From b001fca92490b664eb9aeb9424af1563cf52a05c Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:48:23 +0200 Subject: [PATCH 01/17] feat(efficacy): read each build's reliability, performance and portability - quality.py, beside security.py: a fresh venv per scored trial on Python 3.12, one in-process run through the test client, signed in as the seeded administrator; readings under quality-scores/.json. - Probes: fuzz_robustness, concurrent_writes, latency_p95_ms (two repeats, no threshold yet), capacity_500_lines, n_plus_one, coexistence, and python_portability on Python 3.14. - A probe the build keeps from running is lost and reads failed; one the reader could not run is missing; a stalled run keeps what it read. - Fuzzed integers stay within SQLite's 64-bit range: the spec sets no upper bound on a quantity or an id. - Self-tests plant each fault on a stand-in app; FR-15-01 to FR-15-06, FR-14-01 extended, coverage rows, AGENTS.md, trace.py, building blocks. Refs #119. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- AGENTS.md | 1 + docs/architecture/05-building-block-view.md | 2 + docs/coverage.md | 13 +- docs/requirements.md | 15 +- tests/efficacy/quality.py | 1520 +++++++++++++++++++ tests/efficacy/trace.py | 2 +- 6 files changed, 1550 insertions(+), 3 deletions(-) create mode 100644 tests/efficacy/quality.py diff --git a/AGENTS.md b/AGENTS.md index f851370..eb43239 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,6 +21,7 @@ py tests/efficacy/reuse.py --self-test py tests/efficacy/progress.py --self-test py tests/efficacy/probes.py --self-test py tests/efficacy/security.py --self-test +py tests/efficacy/quality.py --self-test py tests/efficacy/control/control.py --self-test py tests/efficacy/trace.py --self-test py tests/efficacy/trace.py diff --git a/docs/architecture/05-building-block-view.md b/docs/architecture/05-building-block-view.md index 515e447..9112225 100644 --- a/docs/architecture/05-building-block-view.md +++ b/docs/architecture/05-building-block-view.md @@ -22,6 +22,7 @@ dependency with its keyword. | `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/` | | `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 | @@ -72,6 +73,7 @@ are still read. | `tool-lock.txt` | The tool versions every trial is measured with | | `scores/`, `scores-change/` | One score per build trial and per change task | | `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 | | `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/coverage.md b/docs/coverage.md index 01a346e..f2bf018 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -201,5 +201,16 @@ when: | ID | Kind | Checked by | | -- | ---- | ---------- | -| FR-14-01 | Self-test | `score.py` "a live score.py run refuses a second"
`judge.py` "a live judge.py run refuses a second"
`security.py` "a live security.py run refuses a second" | +| FR-14-01 | Self-test | `score.py` "a live score.py run refuses a second"
`judge.py` "a live judge.py run refuses a second"
`security.py` "a live security.py run refuses a second"
`quality.py` "a live quality.py run refuses a second" | | FR-14-02 | Self-test | `harness.py` "an ended run is taken over"
`harness.py` "a live pid that is not the tool is taken over" | + +## 15 Quality probes + +| ID | Kind | Checked by | +| -- | ---- | ---------- | +| FR-15-01 | Self-test | `quality.py` "a sound app passes every probe"
`quality.py` "an app answering 500 on bad input fails fuzz_robustness, and no other probe"
`quality.py` "an app raising out of the client fails fuzz_robustness, and no other probe"
`quality.py` "an app whose writes lock fails concurrent_writes, and no other probe"
`quality.py` "an app dropping an overlapping write fails concurrent_writes, and no other probe"
`quality.py` "the locked write is read as locked"
`quality.py` "an app refusing 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app that cannot show 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app reading each line on its own fails n_plus_one, and no other probe"
`quality.py` "statements are counted per page, and did not grow"
`quality.py` "instances sharing their data fail coexistence, and no other probe"
`quality.py` "an app writing outside its folder fails coexistence, and no other probe"
`quality.py` "the stray file is named" | +| FR-15-02 | Self-test | `quality.py` "a sound app signs in"
`quality.py` "an app that never keeps its sign-in loses every probe, passing none"
`quality.py` "an app answering a malformed request with the sign-in's redirect loses fuzz_robustness, and no other probe"
`quality.py` "the redirect is read as lost, not as an answer" | +| FR-15-03 | Self-test | `quality.py` "an app that will not boot loses every probe"
`quality.py` "a trial that did not install loses every probe"
`quality.py` "no report from the probe is missing, not lost"
`quality.py` "a stalled run keeps what it read and loses the rest"
`quality.py` "a run that stalled booting loses every probe" | +| 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" | diff --git a/docs/requirements.md b/docs/requirements.md index f2fc3c1..5020fb8 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -22,6 +22,8 @@ - **Harness:** `harness.py`, which runs the trials. - **Scorer:** `score.py`, which scores a frozen build. - **Security reader:** `security.py`, which runs the probes. + - **Quality reader:** `quality.py`, which runs the reliability, performance + and portability probes. - **Judge:** `judge.py`, which bundles a build and has a model score it. - **Report:** `report.py`, which reads a round and writes its report. - **Archive:** `archive.py`, which carries a round to the private archive. @@ -209,9 +211,20 @@ | ID | Requirement | Delivered by | | -- | ----------- | ------------ | -| FR-14-01 | The benchmark shall refuse a second scoring, judging or security run that finds a live claim on its root. | Scorer, Judge, Security reader | +| FR-14-01 | The benchmark shall refuse a second scoring, judging, security or quality run that finds a live claim on its root. | Scorer, Judge, Security reader, Quality reader | | FR-14-02 | The benchmark shall take over a claim naming a process that has ended, and say so. | Harness | +### 15 Quality probes + +| ID | Requirement | Delivered by | +| -- | ----------- | ------------ | +| FR-15-01 | The benchmark shall fail each of the fuzz, concurrent-write, 500-line, N+1 and co-existence probes on an app planted with the fault it guards against, and no other probe there, and pass every probe on an app built to pass them. | Quality reader | +| FR-15-02 | The benchmark shall read every quality probe signed in as the seeded administrator, and never measure a page answered with the sign-in's redirect. | Quality reader | +| FR-15-03 | The benchmark shall count as lost, reading failed, a quality probe the trial keeps from running, by not installing, not booting, not signing in or not finishing in time, and as missing one it could not run itself. | Quality reader | +| FR-15-04 | The benchmark shall record the latency as two repeats of the 95th percentile over 30 requests to the main routes, with no pass threshold until one is calibrated. | Quality reader | +| FR-15-05 | The benchmark shall read portability on Python 3.14, the trial installed, booted and serving a signed-in page there, and leave it missing where no Python 3.14 is found. | Quality reader | +| FR-15-06 | The benchmark shall read the quality probes in a fresh environment per trial on the spec's Python, and remove every environment once it is read. | Quality reader | + ## Quality requirements - **Numbering:** characteristics follow ISO/IEC 25010:2023 order, 01 diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py new file mode 100644 index 0000000..9b18591 --- /dev/null +++ b/tests/efficacy/quality.py @@ -0,0 +1,1520 @@ +"""Read scored efficacy trials for reliability, performance and flexibility. + +Seven probes, each read on the application the trial's factory returns: +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. + +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 +this reader could not run is missing, never zero; one the trial kept from +running, by not installing, not booting or not signing in its administrator, +is lost, and reads failed. +""" + +import argparse +import datetime +import io +import json +import os +import shutil +import sys +import tempfile + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import lib # noqa: E402 +from harness import (LiveRunError, canonical, claim_area, # noqa: E402 + claim_refusal_check, release_area, remove_tree, + scoring_area) +from score import (create_venv, pip, python_in, run, # noqa: E402 + venv_version) + +SCRIPT = os.path.basename(__file__) + +# The probes, in the order the reading files them. The latency is a measured +# value; every other probe passes or fails. +PROBES = ("fuzz_robustness", "concurrent_writes", "latency_p95_ms", + "capacity_500_lines", "n_plus_one", "coexistence", + "python_portability") +MEASURED = ("latency_p95_ms",) + +# 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") + +# The interpreter beside the spec's on the owner's machine. Its build has to +# install, boot and serve a signed-in page there too. +OTHER_PYTHON = (3, 14) +OTHER_PYTHON_COMMANDS = (["py", "-%d.%d" % OTHER_PYTHON], + ["python%d.%d" % OTHER_PYTHON]) + +# Long enough for a slow build's 500-line invoice; a run that outlasts it +# keeps what it read and loses the rest to the application. +PROBE_TIMEOUT = 900 + + +# Runs inside the trial's fresh environment, against the application the +# factory returns, through its test client: the specification gives a +# factory, not a server, and counting SQL statements or catching an exception +# needs the application's own process. The first argument is the mode, `all` +# or `portability`; the second is the file the report is written to after +# every probe, so a run that stalls still files what it read; the third is +# where each database's folder is made, outside the workspace, so the +# reader can remove them once the interpreter has let go of their files. +# +# It signs in as the specification has the administrator do: the password +# from the environment, set before the package is imported because the seed +# may run lazily, and the sign-in form's own hidden fields. Every probe reads +# the pages behind that sign-in; one answered with the sign-in's redirect is +# never measured, and the probe is lost. +QUALITY_SCRIPT = r''' +import builtins, html, io, json, logging, math, os, platform, re, sqlite3 +import sys, tempfile, threading, time +from urllib.parse import urlsplit + +PACKAGE = "tariff" +USERNAME = "admin" +PASSWORD = "quality-probe-5b3f-Passphrase" +REDIRECTS = (301, 302, 303, 307, 308) +MODE, PROGRESS, DATABASES = sys.argv[1], sys.argv[2], sys.argv[3] +WORKSPACE = os.path.abspath(os.getcwd()) +os.environ["TARIFF_ADMIN_PASSWORD"] = PASSWORD + +real_open = builtins.open +real_os_open = os.open +report = {"python": platform.python_version(), "probes": {}, + "running": "boot"} + + +def save(): + """The report so far, replaced whole, so a stalled run leaves a whole + file behind.""" + with real_open(PROGRESS + ".part", "w", encoding="utf-8") as handle: + json.dump(report, handle) + os.replace(PROGRESS + ".part", PROGRESS) + + +def finish(): + report.pop("running", None) + save() + print(json.dumps(report)) + raise SystemExit(0) + + +save() + + +# Every statement any connection runs is counted, on every connection the +# application opens: the factory is wrapped before the package is imported, +# so a module that imports `connect` by name gets the wrapped one too. +statements = {"window": 0, "total": 0} + + +def traced(statement): + statements["window"] += 1 + statements["total"] += 1 + + +# Where the application writes while the co-existence probe watches. +watch = {"on": False, "paths": []} + + +def note(path): + if watch["on"] and isinstance(path, (str, bytes, os.PathLike)): + watch["paths"].append(os.path.abspath(os.fsdecode(path))) + + +real_connect = sqlite3.connect + + +def connect(*args, **kwargs): + connection = real_connect(*args, **kwargs) + try: + connection.set_trace_callback(traced) + except Exception: + pass + target = args[0] if args else kwargs.get("database") + if isinstance(target, (str, os.PathLike)): + target = os.fspath(target) + if "mode=memory" in target: + target = "" + if target.startswith("file:"): + target = urlsplit(target).path + if target and target != ":memory:": + note(target) + return connection + + +sqlite3.connect = connect +sqlite3.dbapi2.connect = connect + + +# A file opened to write, by name. Python's own bytecode cache writes through +# the interpreter's internal `open`, so the import machinery is not read. +def watched_open(file, mode="r", *args, **kwargs): + if any(flag in mode for flag in "wax+"): + note(file) + return real_open(file, mode, *args, **kwargs) + + +WRITE_FLAGS = os.O_WRONLY | os.O_RDWR | os.O_CREAT | os.O_APPEND + + +def watched_os_open(path, flags, *args, **kwargs): + if flags & WRITE_FLAGS: + note(path) + return real_os_open(path, flags, *args, **kwargs) + + +builtins.open = io.open = watched_open +os.open = watched_os_open + +# Every record any logger hands to its handlers, with its traceback, so an +# error the application answered 500 for is read even where no page shows it. +records = [] +original_call_handlers = logging.Logger.callHandlers + + +def call_handlers(self, record): + try: + text = record.getMessage() + except Exception: + text = str(record.msg) + if record.exc_info: + text += "\n" + logging.Formatter().formatException(record.exc_info) + records.append(text) + return original_call_handlers(self, record) + + +logging.Logger.callHandlers = call_handlers + + +def folder(): + return tempfile.mkdtemp(prefix="quality-probe-", dir=DATABASES) + + +try: + import importlib + package = importlib.import_module(PACKAGE) + app = package.create_app(os.path.join(folder(), "quality-probe.sqlite")) + client = app.test_client() +except Exception as error: + report["error"] = repr(error)[:300] + finish() + + +class Gated(Exception): + """A page answered with the sign-in's redirect.""" + + +class Raised(Exception): + """The application raised out of the test client.""" + + +def hidden_fields(text): + """Every hidden input in the page, which is where a CSRF token hides.""" + fields = {} + for match in re.finditer(r']*type="hidden"[^>]*>', text, + re.IGNORECASE): + tag = match.group(0) + name = re.search(r'name="([^"]+)"', tag) + value = re.search(r'value="([^"]*)"', tag) + if name: + fields[html.unescape(name.group(1))] = ( + html.unescape(value.group(1)) if value else "") + return fields + + +def gated(response): + """Whether the answer is the redirect to the sign-in form.""" + if response.status_code not in REDIRECTS: + return False + return urlsplit(response.headers.get("Location", "")).path == "/sign-in" + + +def ask(who, method, path, data=None, headers=None): + try: + return who.open(path, method=method, data=data, + headers=headers or {}) + except Exception as error: + raise Raised(repr(error)[:300]) + + +def page(who, path): + """A page behind the sign-in, or Gated.""" + answer = ask(who, "GET", path) + if gated(answer): + raise Gated("%s answered with the sign-in's redirect" % path) + return answer + + +def form_post(who, form, path, body, method="POST", headers=None): + """A post carrying the hidden fields of the form it is sent from, read + afresh, since a token may change between answers.""" + data = dict(body) + for name, value in hidden_fields( + ask(who, "GET", form).get_data(as_text=True)).items(): + data.setdefault(name, value) + return ask(who, method, path, data=data, headers=headers) + + +def held(answer, what): + if gated(answer): + raise Gated("%s answered with the sign-in's redirect" % what) + return answer + + +def sign_in(who): + """Whether the seeded administrator signs in and stays signed in.""" + try: + body = {"username": USERNAME, "password": PASSWORD, "next": "/"} + answer = form_post(who, "/sign-in", "/sign-in", body) + report.setdefault("sign_in_status", answer.status_code) + return not gated(ask(who, "GET", "/")) + except Raised as error: + report.setdefault("sign_in_error", str(error)) + return False + + +def passed(ok, **detail): + detail["passed"] = bool(ok) + return detail + + +def lost(name, reason, **detail): + """A probe the application kept from running: a pass or fail reads + failed, the latency reads no value.""" + detail["lost"] = reason + if name == "latency_p95_ms": + detail["value"] = None + else: + detail["passed"] = False + return detail + + +SKUS = ("WID-1", "GAD-2", "BOK-3", "SRV-4", "SEE-5") +WORKED = (("WID-1", 12), ("SEE-5", 7), ("BOK-3", 2), ("SRV-4", 1)) + + +def builder_body(lines, coupons=""): + return {"jurisdiction": "DE", "currency": "EUR", "customer": "", + "coupon_codes": coupons, "sku": [sku for sku, _ in lines], + "quantity": [str(quantity) for _, quantity in lines]} + + +def saved_page(answer): + """The invoice page a save redirected to, or None.""" + if answer.status_code not in REDIRECTS: + return None + path = urlsplit(answer.headers.get("Location", "")).path + if re.match(r"^/invoices/[^/]+$", path) and path not in ( + "/invoices/new", "/invoices/preview"): + return path + return None + + +def save_invoice(who, lines, coupons=""): + """Save an invoice through the builder; its page, or Gated.""" + answer = held(form_post(who, "/invoices/new", "/invoices", + builder_body(lines, coupons)), "the save") + path = saved_page(answer) + if path is None: + raise Gated("an invoice of %d lines was not saved: it answered %d" + % (len(lines), answer.status_code)) + return path + + +def ok(answer): + return 200 <= answer.status_code < 300 + + +def p95(times): + """The nearest-rank 95th percentile.""" + ordered = sorted(times) + return ordered[max(0, math.ceil(0.95 * len(ordered)) - 1)] + + +ROUTES = ("/", "/products", "/rules", "/jurisdictions", "/customers", + "/invoices/new") + + +def latency_p95_ms(): + """The 95th percentile of 30 requests over the main routes, twice.""" + invoice = save_invoice(client, WORKED, "WELCOME") + requests = ([("GET", path) for path in ROUTES] + + [("GET", invoice), ("GET", invoice + "/export.json"), + ("GET", invoice + "/export.csv"), + ("POST", "/invoices/preview")]) + + def timed(method, path): + data = headers = None + if method == "POST": + data = builder_body(WORKED, "WELCOME") + data.update({name: value for name, value in hidden_fields( + page(client, "/invoices/new").get_data(as_text=True)).items() + if name not in data}) + headers = {"HX-Request": "true"} + start = time.perf_counter() + answer = ask(client, method, path, data=data, headers=headers) + elapsed = (time.perf_counter() - start) * 1000 + held(answer, "%s %s" % (method, path)) + if not ok(answer): + raise Gated("%s %s answered %d, so its time is not the route's" + % (method, path, answer.status_code)) + return elapsed + + # The first answer of each route compiles its templates, which no later + # request pays for. + for method, path in requests: + timed(method, path) + repeats = [] + for _ in range(2): + times = [timed(method, path) for _ in range(3) + for method, path in requests] + repeats.append(round(p95(times), 2)) + return {"value": max(repeats), "repeats": repeats, + "requests": len(times), "routes": [" ".join(request) + for request in requests]} + + +def counted(path): + """The statements one answer ran, and the answer.""" + statements["window"] = 0 + answer = page(client, path) + return statements["window"], answer + + +def n_plus_one(): + """Statements for a 1-line and a 20-line invoice page.""" + one = save_invoice(client, [("WID-1", 1)]) + twenty = save_invoice(client, [(SKUS[index % len(SKUS)], index + 1) + for index in range(20)]) + for path in (one, twenty): + page(client, path) + small, first = counted(one) + large, second = counted(twenty) + if not (ok(first) and ok(second)): + return lost("n_plus_one", "an invoice page answered %d and %d" + % (first.status_code, second.status_code)) + + # A page that runs nothing is read only where the statements are seen + # elsewhere: then the count is real, and it did not grow. + if not statements["total"]: + return {"passed": None, "missing": "no SQL statement was traced on " + "any connection, so none could be counted"} + return passed(large <= small, one_line=small, twenty_lines=large) + + +def capacity_500_lines(): + """An invoice of 500 lines previewed, saved and rendered.""" + lines = [(SKUS[index % len(SKUS)], 1 + index % 7) for index in range(500)] + steps = {} + try: + preview = held(form_post(client, "/invoices/new", "/invoices/preview", + builder_body(lines), + headers={"HX-Request": "true"}), + "the preview") + steps["preview"] = preview.status_code + saved = held(form_post(client, "/invoices/new", "/invoices", + builder_body(lines)), "the save") + steps["save"] = saved.status_code + path = saved_page(saved) + if path is None: + return passed(False, steps=steps, + reason="the save did not redirect to its page") + rendered = page(client, path) + steps["render"] = rendered.status_code + except Raised as error: + return passed(False, steps=steps, raised=str(error)) + return passed(ok(preview) and ok(rendered), steps=steps) + + +LOCKED = re.compile(r"database (table )?is locked", re.IGNORECASE) + + +def concurrent_writes(): + """Two clients, each saving 20 products at once.""" + writers = [app.test_client(), app.test_client()] + if not all(sign_in(writer) for writer in writers): + return lost("concurrent_writes", "a second client could not sign in") + start = threading.Barrier(len(writers)) + outcomes = [[] for _ in writers] + logged = len(records) + + def write(index): + try: + start.wait(timeout=60) + except threading.BrokenBarrierError: + return + for number in range(20): + sku = "QCW-%d-%02d" % (index, number) + entry = {"sku": sku} + try: + answer = form_post(writers[index], "/products", "/products", + {"sku": sku, "name": "Concurrent %s" % sku, + "unit_price": "1.00", + "tax_category": "standard"}) + entry["status"] = answer.status_code + entry["gated"] = gated(answer) + entry["locked"] = bool(LOCKED.search( + answer.get_data(as_text=True))) + except Raised as error: + entry["raised"] = str(error) + entry["locked"] = bool(LOCKED.search(str(error))) + outcomes[index].append(entry) + + threads = [threading.Thread(target=write, args=(index,), daemon=True) + for index in range(len(writers))] + for thread in threads: + thread.start() + for thread in threads: + thread.join(timeout=120) + if any(thread.is_alive() for thread in threads): + return passed(False, reason="the writes did not finish in 120 s") + entries = [entry for outcome in outcomes for entry in outcome] + if any(entry.get("gated") for entry in entries): + return lost("concurrent_writes", "a write answered with the " + "sign-in's redirect") + listing = page(client, "/products").get_data(as_text=True) + unsaved = [entry["sku"] for entry in entries + if entry["sku"] not in listing] + failed = [entry for entry in entries if entry.get("raised") + or (entry.get("status") or 0) >= 500] + locked = (any(entry["locked"] for entry in entries) + or any(LOCKED.search(text) for text in records[logged:])) + return passed(len(entries) == 40 and not unsaved and not failed + and not locked, written=len(entries), unsaved=unsaved, + failed=failed[:5], locked=locked) + + +def inside(path, roots): + path = os.path.normcase(os.path.realpath(path)) + for root in roots: + root = os.path.normcase(os.path.realpath(root)) + try: + if os.path.commonpath([path, root]) == root: + return True + except ValueError: + continue + return False + + +PRODUCT = {"sku": "QCO-1", "name": "Coexistence probe", "unit_price": "2.00", + "tax_category": "standard"} + + +def coexistence(): + """Two instances, each on its own database: a write through one stays + out of the other, and neither writes outside its folder or the + workspace.""" + + # A database's sidecars, its `-wal`, `-shm` and `-journal`, sit in its + # folder, so the two folders admit them. + folders_given = [folder(), folder()] + watch["paths"] = [] + watch["on"] = True + try: + try: + first, second = [ + package.create_app(os.path.join(where, "coexist.sqlite")) + for where in folders_given] + except Exception as error: + return passed(False, reason="a second instance would not boot: " + "%s" % repr(error)[:300]) + one, other = first.test_client(), second.test_client() + if not (sign_in(one) and sign_in(other)): + return lost("coexistence", "an instance's administrator could " + "not sign in") + held(form_post(one, "/products", "/products", PRODUCT), + "the product's post") + stored = PRODUCT["sku"] in page(one, "/products").get_data( + as_text=True) + leaked = PRODUCT["sku"] in page(other, "/products").get_data( + as_text=True) + finally: + watch["on"] = False + if not stored: + return lost("coexistence", "the product written through the first " + "instance was not stored") + stray = sorted(set(path for path in watch["paths"] + if not inside(path, folders_given + [WORKSPACE]))) + return passed(not leaked and not stray, leaked=leaked, stray=stray[:10]) + + +# A number past any bound a price, percentage, rate or tier can have. The +# specification sets no upper bound on a quantity, a group or an id, so one +# past what SQLite stores, or what a Decimal prices to the cent, has no +# answer it defines; those stay at a quintillion, inside both. +HUGE = "9" * 400 +BIG = "1" + "0" * 18 +LONG = "x" * 20000 +GOOD = {"sku": "QFZ-1", "name": "Fuzz", "unit_price": "1.00", + "tax_category": "standard"} + + +def product(**fields): + return dict(GOOD, **fields) + + +def preview(**fields): + body = {"jurisdiction": "DE", "currency": "EUR", "customer": "", + "coupon_codes": "", "sku": "WID-1", "quantity": "1"} + body.update(fields) + return body + + +# Each malformed request: a label, the method, the path, the form whose +# hidden fields it carries (None for none), its body, and whether it is sent +# signed out. Every one is a request the specification defines an answer to: +# a re-rendered form, a 400, a 404 or a 405. +FUZZ = ( + ("POST /products unit_price=abc", "POST", "/products", "/products", + product(unit_price="abc"), False), + ("POST /products unit_price=NaN", "POST", "/products", "/products", + product(sku="QFZ-2", unit_price="NaN"), False), + ("POST /products unit_price=Infinity", "POST", "/products", "/products", + product(sku="QFZ-3", unit_price="Infinity"), False), + ("POST /products unit_price=-1", "POST", "/products", "/products", + product(sku="QFZ-4", unit_price="-1"), False), + ("POST /products unit_price=1e999999", "POST", "/products", "/products", + product(sku="QFZ-5", unit_price="1e999999"), False), + ("POST /products unit_price=<400 digits>", "POST", "/products", + "/products", product(sku="QFZ-6", unit_price=HUGE), False), + ("POST /products unicode", "POST", "/products", "/products", + product(sku="ŠKU-☃-‮", name="名前 \U0001f9fe", + tax_category="stándard"), False), + ("POST /products null bytes", "POST", "/products", "/products", + product(sku="QFZ\x00-7", name="nul\x00name"), False), + ("POST /products 20000-character fields", "POST", "/products", + "/products", product(sku=LONG, name=LONG), False), + ("POST /products no fields", "POST", "/products", "/products", {}, + False), + ("POST /products no unit_price", "POST", "/products", "/products", + {"sku": "QFZ-8", "name": "Fuzz", "tax_category": "standard"}, False), + ("POST /rules kind=bogus", "POST", "/rules", "/rules", + {"rule_id": "qfz-1", "kind": "bogus", "sku": ""}, False), + ("POST /rules percent=abc", "POST", "/rules", "/rules", + {"rule_id": "qfz-2", "kind": "percentage", "sku": "", "percent": "abc"}, + False), + ("POST /rules percent=<400 digits>", "POST", "/rules", "/rules", + {"rule_id": "qfz-3", "kind": "percentage", "sku": "", "percent": HUGE}, + False), + ("POST /rules buy=abc", "POST", "/rules", "/rules", + {"rule_id": "qfz-4", "kind": "bulk", "sku": "WID-1", "buy": "abc", + "pay": "1"}, False), + ("POST /rules buy and pay of 19 digits", "POST", "/rules", "/rules", + {"rule_id": "qfz-5", "kind": "bulk", "sku": "WID-1", "buy": BIG[:-1] + "1", + "pay": BIG}, False), + ("POST /rules tiers=1:,:5,a:b", "POST", "/rules", "/rules", + {"rule_id": "qfz-6", "kind": "tiered", "sku": "WID-1", + "tiers": "1:,:5,a:b"}, False), + ("POST /rules tiers of 400 digits", "POST", "/rules", "/rules", + {"rule_id": "qfz-7", "kind": "tiered", "sku": "WID-1", + "tiers": "%s:1.00" % HUGE}, False), + ("POST /rules amount=abc", "POST", "/rules", "/rules", + {"rule_id": "qfz-8", "kind": "coupon", "sku": "", "code": "QFZ", + "amount": "abc"}, False), + ("POST /rules no fields", "POST", "/rules", "/rules", {}, False), + ("POST /jurisdictions rates=standard==,=0.1,,", "POST", "/jurisdictions", + "/jurisdictions", {"code": "QF", "name": "Fuzz", "default_rate": "0.1", + "rates": "standard==,=0.1,,"}, False), + ("POST /jurisdictions default_rate=abc", "POST", "/jurisdictions", + "/jurisdictions", {"code": "QG", "name": "Fuzz", "default_rate": "abc", + "rates": ""}, False), + ("POST /jurisdictions rate of 400 digits", "POST", "/jurisdictions", + "/jurisdictions", {"code": "QH", "name": "Fuzz", "default_rate": "0.1", + "rates": "standard=%s" % HUGE}, False), + ("POST /customers email=a@@b", "POST", "/customers", "/customers", + {"name": "Fuzz", "email": "a@@b", "address": "1 Fuzz Lane"}, False), + ("POST /customers unicode", "POST", "/customers", "/customers", + {"name": "Zoë ☃", "email": "zoë@exämple.test", + "address": "Straße 1\n‮"}, False), + ("POST /customers no fields", "POST", "/customers", "/customers", {}, + False), + ("POST /invoices/preview quantity=abc", "POST", "/invoices/preview", + "/invoices/new", preview(quantity="abc"), False), + ("POST /invoices/preview quantity=<19 digits>", "POST", + "/invoices/preview", "/invoices/new", preview(quantity=BIG), False), + ("POST /invoices/preview quantity=-5", "POST", "/invoices/preview", + "/invoices/new", preview(quantity="-5"), False), + ("POST /invoices/preview two skus, one quantity", "POST", + "/invoices/preview", "/invoices/new", + preview(sku=["WID-1", "GAD-2"], quantity=["1"]), False), + ("POST /invoices/preview customer=abc", "POST", "/invoices/preview", + "/invoices/new", preview(customer="abc"), False), + ("POST /invoices/preview customer=<19 digits>", "POST", + "/invoices/preview", "/invoices/new", preview(customer=BIG), False), + ("POST /invoices/preview currency=€€€", "POST", + "/invoices/preview", "/invoices/new", preview(currency="€€€"), + False), + ("POST /invoices/preview coupon_codes=,,, ,nul", "POST", + "/invoices/preview", "/invoices/new", + preview(coupon_codes=",,, ,\x00"), False), + ("POST /invoices quantity=abc", "POST", "/invoices", "/invoices/new", + preview(quantity="abc"), False), + ("POST /invoices no fields", "POST", "/invoices", "/invoices/new", {}, + False), + ("GET /invoices/abc", "GET", "/invoices/abc", None, None, False), + ("GET /invoices/<19 digits>", "GET", "/invoices/" + BIG, None, None, + False), + ("GET /invoices/-1/export.csv", "GET", "/invoices/-1/export.csv", None, + None, False), + ("GET /customers/<19 digits>/export.json", "GET", + "/customers/%s/export.json" % BIG, None, None, False), + ("POST /products//delete", "POST", + "/products/%E2%98%83%00/delete", "/products", {}, False), + ("POST /rules//delete", "POST", "/rules/qfz-missing/delete", + "/rules", {}, False), + ("PUT /products", "PUT", "/products", None, product(), False), + ("DELETE /invoices/new", "DELETE", "/invoices/new", None, None, False), + ("GET /invoices/preview", "GET", "/invoices/preview", None, None, False), + ("PATCH /rules", "PATCH", "/rules", None, {}, False), + ("POST /sign-in no fields", "POST", "/sign-in", "/sign-in", {}, True), + ("POST /sign-in unicode and null bytes", "POST", "/sign-in", "/sign-in", + {"username": "ädmin☃", "password": "\x00\x00", + "next": "☃"}, True), +) + + +def fuzz_robustness(): + """Malformed requests to the specification's routes, none answered 500 + and none raising out of the client.""" + stranger = app.test_client() + answers = [] + for label, method, path, form, body, signed_out in FUZZ: + who = stranger if signed_out else client + entry = {"request": label} + try: + answer = (form_post(who, form, path, body, method=method) + if form else ask(who, method, path, data=body)) + entry["status"] = answer.status_code + + # Signed out, the sign-in's own answer may be its redirect. + entry["gated"] = gated(answer) and not signed_out + except Raised as error: + entry["raised"] = str(error) + answers.append(entry) + asked = [entry["request"] for entry in answers if entry.get("gated")] + if asked: + return lost("fuzz_robustness", "%d malformed requests were answered " + "with the sign-in's redirect" % len(asked), asked=asked) + failed = [entry for entry in answers if entry.get("raised") + or (entry.get("status") or 0) >= 500] + return passed(not failed, requests=len(answers), failed=failed) + + +report["signed_in"] = sign_in(client) +if not report["signed_in"] or MODE == "portability": + try: + report["index_status"] = ask(client, "GET", "/").status_code + except Raised as error: + report["index_error"] = str(error) + finish() + +# Fuzzing comes last: what a malformed request stores cannot reach another +# probe's reading. +PROBES = (("latency_p95_ms", latency_p95_ms), ("n_plus_one", n_plus_one), + ("capacity_500_lines", capacity_500_lines), + ("concurrent_writes", concurrent_writes), + ("coexistence", coexistence), + ("fuzz_robustness", fuzz_robustness)) +for name, probe in PROBES: + report["running"] = name + save() + try: + report["probes"][name] = probe() + except Gated as error: + report["probes"][name] = lost(name, str(error)) + except Raised as error: + report["probes"][name] = lost(name, "the application raised: %s" + % error) + except Exception as error: + key = "value" if name == "latency_p95_ms" else "passed" + report["probes"][name] = {key: None, "missing": "the reader failed: " + "%s" % repr(error)[:300]} +finish() +''' + + +def lost_reading(name, reason): + """A probe the trial kept from running: failed, or no latency.""" + if name in MEASURED: + return {"value": None, "lost": reason} + return {"passed": False, "lost": reason} + + +def missing_reading(name, reason): + """A probe this reader could not run: never zero, never passed.""" + if name in MEASURED: + return {"value": None, "missing": reason} + return {"passed": None, "missing": reason} + + +def probe_results(payload, reason=None, lost=False, stalled=None): + """Each in-process probe's reading: its own, lost with the trial's + reason, or missing with ours. + + `reason` is why there is no report, and `lost` says the trial caused it. + `stalled` is why a run that ran out of time stopped: what it read stands, + and the probes it did not reach are lost to the application. + """ + payload = payload or {} + trial = reason if (reason and lost) else None + if not reason: + if "error" in payload: + trial = "the application would not boot: %s" % payload["error"] + elif stalled and "signed_in" not in payload: + trial = stalled + elif not payload.get("signed_in"): + trial = ("the seeded administrator could not sign in; the " + "sign-in answered %s" % payload.get("sign_in_status")) + read = payload.get("probes") or {} + readings = {} + for name in IN_PROCESS: + if reason and not lost: + readings[name] = missing_reading(name, reason) + elif trial: + readings[name] = lost_reading(name, trial) + elif name in read: + readings[name] = read[name] + elif stalled: + readings[name] = lost_reading(name, stalled) + else: + readings[name] = missing_reading( + name, "the in-process probe did not report it") + return readings + + +def write_script(where): + script = os.path.join(where, "quality-probe.py") + with io.open(script, "w", encoding="utf-8") as handle: + handle.write(QUALITY_SCRIPT) + return script + + +def probe_runtime(python, where, mode="all", env=None, timeout=PROBE_TIMEOUT): + """Run the in-process probes; answer the report, why there is none, and + why the run stopped short where it did.""" + script = write_script(where) + progress = os.path.join(where, "quality-probe-%s.json" % mode) + if os.path.exists(progress): + os.remove(progress) + databases = os.path.abspath(where) + "-databases" + remove_tree(databases) + os.makedirs(databases) + try: + outcome = run([python, script, mode, progress, databases], cwd=where, + env=env, timeout=timeout) + finally: + remove_tree(databases) + payload = None + if os.path.isfile(progress): + try: + with io.open(progress, encoding="utf-8") as handle: + payload = json.load(handle) + except ValueError: + payload = None + if payload is None: + return None, ("the quality probe produced no report: %s" + % (outcome["failed"] or outcome["stderr"] + or outcome["stdout"])[-300:]), None + stalled = None + if "running" in payload: + stalled = ("the run stopped during %s: %s" % ( + payload["running"], outcome["failed"] + or "the interpreter exited %s" % outcome["status"])) + return payload, None, stalled + + +def other_interpreter(commands=OTHER_PYTHON_COMMANDS): + """The path of the other Python, or None.""" + probe = "import sys; print(sys.executable); print(*sys.version_info[:2])" + wanted = ["%d" % part for part in OTHER_PYTHON] + for command in commands: + program = shutil.which(command[0]) + if program is None: + continue + outcome = run([program] + list(command[1:]) + ["-c", probe], + timeout=120) + lines = outcome["stdout"].splitlines() + if (outcome["failed"] is None and outcome["status"] == 0 + and len(lines) == 2 and lines[1].split() == wanted): + return lines[0].strip() + return None + + +def portability_reading(installed, payload, reason, version): + """python_portability from the other Python's install and its page. + + On that interpreter the install, the boot and the page are what is + measured, so their failing fails the probe; only a run that filed no + report is missing. + """ + label = "Python %s" % version + if installed["failed"] or installed["status"] != 0: + return {"passed": False, "python": version, + "reason": "the trial did not install on %s: %s" % ( + label, (installed["stderr"] + or installed["stdout"])[-300:])} + if payload is None: + return missing_reading("python_portability", reason) + if "error" in payload: + return {"passed": False, "python": version, + "reason": "the application would not boot on %s: %s" + % (label, payload["error"])} + if not payload.get("signed_in"): + return {"passed": False, "python": version, + "reason": "the administrator could not sign in on %s" + % label} + status = payload.get("index_status") + return {"passed": status == 200, "python": version, "status": status} + + +def read_portability(tree, where, other): + """Install the trial on the other Python and serve one signed-in page.""" + if other is None: + return missing_reading("python_portability", ( + "no Python %d.%d was found" % OTHER_PYTHON)) + venv = os.path.join(where, "venv-other") + remove_tree(venv) + try: + made = run([other, "-m", "venv", venv], timeout=600) + if made["failed"] or made["status"] != 0: + return missing_reading("python_portability", ( + "the other Python's environment was not created: %s" + % (made["stderr"] or made["stdout"])[-300:])) + version = venv_version(venv) + installed = pip(venv, "install", tree, cwd=where) + payload, reason = None, None + if not installed["failed"] and installed["status"] == 0: + payload, reason, _ = probe_runtime(python_in(venv), where, + "portability") + return portability_reading(installed, payload, reason, version) + finally: + + # About 290 MB, and nothing reads it again. + remove_tree(venv) + + +def read_trial(area, name, scores_file, other): + """Every quality probe on one scored trial, read from its score file.""" + with io.open(scores_file, encoding="utf-8") as handle: + scores = json.load(handle) + tree = scores.get("workspace") + result = {"name": name, "read_at": datetime.datetime.now().isoformat( + timespec="seconds")} + where = os.path.join(area, "quality", name) + os.makedirs(where, exist_ok=True) + venv = create_venv(os.path.join(where, "venv")) + try: + result["python"] = venv_version(venv) + installed = pip(venv, "install", tree, cwd=where) + if installed["failed"] or installed["status"] != 0: + reason = ("the trial did not install: %s" + % (installed["stderr"] or installed["stdout"])[-300:]) + probes = probe_results(None, reason, lost=True) + else: + payload, reason, stalled = probe_runtime(python_in(venv), where) + probes = probe_results(payload, reason, stalled=stalled) + finally: + + # About 290 MB a trial, and nothing reads it again. + remove_tree(venv) + + # A build the spec's Python could not install, boot or sign in is lost + # on the other one too: it was never read there. + trial = next((probe["lost"] for probe in probes.values() + if probe.get("lost")), None) + if trial and all(probe.get("lost") == trial for probe in probes.values()): + probes["python_portability"] = lost_reading("python_portability", + trial) + elif all(probe.get("missing") for probe in probes.values()): + probes["python_portability"] = missing_reading( + "python_portability", "the build was not read on the spec's " + "Python") + else: + probes["python_portability"] = read_portability(tree, where, other) + result["probes"] = {name: probes[name] for name in PROBES} + return result + + +# A stand-in application for the in-process probes, importable without +# Flask, on a real SQLite file, so the statement count and the database lock +# are SQLite's own. `sound` passes every probe; each other mode plants the +# fault one probe guards against and nothing else: `fragile` answers 500 on +# a price it cannot parse, `brittle` lets an id it cannot parse raise out of +# the client, `locking` writes without waiting for the lock, `lossy` drops a +# write that overlaps another, `slow` takes 20 ms over every answer, +# `cramped` refuses over 100 lines, `crowded` saves them and will not show +# them, `chatty` reads each invoice line's product on its own, `shared` keeps +# its products in one store for every instance, and `stray` writes a fixed +# file outside its folder. `bouncing` answers a price it cannot parse with +# the sign-in's redirect, `gated` never keeps its sign-in, `broken` will not +# boot, and `unportable` boots on no Python but the one it names. +FAKE_APP = '''import decimal +import json +import logging +import os +import sqlite3 +import sys +import tempfile +import threading +import time + +MODE = "__MODE__" +TOKEN = '' +SKUS = {"WID-1": "10.00", "GAD-2": "24.50", "BOK-3": "12.00", + "SRV-4": "80.00", "SEE-5": "3.75"} +LOG = logging.getLogger("tariff") +SHARED = {} +IN_FLIGHT = [] +GUARD = threading.Lock() +STRAY = os.path.join(tempfile.gettempdir(), "tariff-quality-stray.log") + + +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 listed(value): + if value is None: + return [] + return list(value) if isinstance(value, (list, tuple)) else [value] + + +def number(text): + """An id, or None where it is none or would overflow SQLite.""" + if MODE == "brittle": + return int(text) + if not text.isdigit() or int(text) > 2 ** 63 - 1: + return None + return int(text) + + +class App(object): + def __init__(self, database): + if MODE == "stray": + with open(STRAY, "a") as handle: + handle.write("booted\\n") + self.database = database + self.products = SHARED if MODE == "shared" else None + self.connect().executescript( + "CREATE TABLE IF NOT EXISTS products (sku TEXT PRIMARY KEY, " + "name TEXT, unit_price TEXT);" + "CREATE TABLE IF NOT EXISTS invoices (id INTEGER PRIMARY KEY);" + "CREATE TABLE IF NOT EXISTS lines (invoice INTEGER, position " + "INTEGER, sku TEXT, quantity INTEGER);") + with self.connect() as connection: + for sku, price in SKUS.items(): + connection.execute("INSERT OR IGNORE INTO products VALUES " + "(?, ?, ?)", (sku, sku, price)) + self.password = os.environ.get("TARIFF_ADMIN_PASSWORD") + self.config = {} + + def connect(self, wait=10.0): + return sqlite3.connect(self.database, timeout=wait) + + def test_client(self): + return Client(self) + + def skus(self): + if self.products is not None: + return list(SKUS) + list(self.products) + return [row[0] for row in self.connect().execute( + "SELECT sku FROM products ORDER BY sku")] + + def add_product(self, sku, name, price): + if self.products is not None: + self.products[sku] = (name, price) + return + if MODE == "lossy": + with GUARD: + if IN_FLIGHT: + return + IN_FLIGHT.append(sku) + try: + time.sleep(0.005) + with self.connect() as connection: + connection.execute("INSERT INTO products VALUES " + "(?, ?, ?)", (sku, name, price)) + finally: + IN_FLIGHT.remove(sku) + return + connection = self.connect(0 if MODE == "locking" else 10.0) + connection.isolation_level = None + try: + connection.execute("BEGIN IMMEDIATE") + connection.execute("INSERT INTO products VALUES (?, ?, ?)", + (sku, name, price)) + time.sleep(0.005) + connection.execute("COMMIT") + finally: + if connection.in_transaction: + connection.execute("ROLLBACK") + connection.close() + + +class Client(object): + def __init__(self, app): + self.app = app + self.signed = False + + def get(self, path, **kwargs): + return self.open(path, method="GET", **kwargs) + + def post(self, path, **kwargs): + return self.open(path, method="POST", **kwargs) + + def open(self, path, method="GET", data=None, headers=None, + follow_redirects=False): + if MODE == "slow": + time.sleep(0.02) + try: + return self.dispatch(path.split("?")[0], method, data or {}) + except Exception: + if MODE == "brittle": + raise + LOG.exception("unhandled") + return Response(500, "Internal Server Error") + + def dispatch(self, path, method, data): + if path == "/sign-in": + if method == "GET": + return Response(200, "
" + TOKEN) + if (data.get("csrf_token") == "t" + and data.get("username") == "admin" + and data.get("password") == self.app.password): + self.signed = MODE != "gated" + return Response(302, "", {"Location": "/"}) + return Response(200, "wrong username or password" + TOKEN) + if not self.signed: + return Response(302, "", {"Location": "/sign-in"}) + pages = ("/", "/products", "/rules", "/jurisdictions", "/customers", + "/invoices/new") + posts = ("/products", "/rules", "/jurisdictions", "/customers", + "/invoices/preview", "/invoices") + parts = path.strip("/").split("/") + if method == "GET" and path in pages: + listing = " ".join(self.app.skus()) if path == "/products" else "" + return Response(200, "

%s

%s" % (listing, TOKEN)) + if method == "POST" and (path in posts or path.endswith("/delete") + or path.endswith("/erase")): + if data.get("csrf_token") != "t": + return Response(400, "missing token") + if path.endswith("/delete") or path.endswith("/erase"): + return Response(404, "not found") + if path == "/products": + return self.create_product(data) + if path.startswith("/invoices"): + return self.invoice(path, data) + return Response(200, "the form has an error" + TOKEN) + if method == "GET" and parts[0] in ("invoices", "customers"): + return self.show(parts) + if path in pages or path in posts: + return Response(405, "method not allowed") + return Response(404, "not found") + + def create_product(self, data): + sku = data.get("sku") or "" + name = data.get("name") or "" + if not sku or not name or len(sku) > 64: + return Response(200, "sku or name is invalid" + TOKEN) + if MODE == "fragile": + price = decimal.Decimal(data.get("unit_price")) + else: + try: + price = decimal.Decimal(data.get("unit_price") or "") + except decimal.InvalidOperation: + if MODE == "bouncing": + return Response(302, "", {"Location": "/sign-in"}) + return Response(200, "unit_price is not a number" + TOKEN) + if not price.is_finite() or price < 0 or price > 10 ** 12: + return Response(200, "unit_price is out of range" + TOKEN) + if sku in self.app.skus(): + return Response(200, "sku exists" + TOKEN) + self.app.add_product(sku, name, str(price)) + return Response(302, "", {"Location": "/products"}) + + def invoice(self, path, data): + skus, quantities = listed(data.get("sku")), listed( + data.get("quantity")) + if len(skus) != len(quantities): + return Response(400, "sku and quantity do not pair") + known = self.app.skus() + lines = [] + for sku, quantity in zip(skus, quantities): + if sku not in known or not quantity.isdigit() or int( + quantity) < 1: + return Response(400, "a line is invalid") + lines.append((sku, int(quantity))) + if MODE == "cramped" and len(lines) > 100: + return Response(413, "too many lines") + if path == "/invoices/preview": + return Response(200, "%d lines
" % len(lines)) + if not lines: + return Response(400, "no lines") + with self.app.connect() as connection: + invoice = connection.execute( + "INSERT INTO invoices DEFAULT VALUES").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}) + + def show(self, parts): + if parts[0] != "invoices" or len(parts) > 2 and parts[2] not in ( + "export.json", "export.csv"): + return Response(404, "not found") + invoice = number(parts[1]) if len(parts) > 1 else None + if invoice is None: + return Response(404, "not found") + connection = self.app.connect() + if not connection.execute("SELECT id FROM invoices WHERE id = ?", + (invoice,)).fetchone(): + return Response(404, "not found") + if MODE == "chatty": + rows = [] + for sku, quantity in connection.execute( + "SELECT sku, quantity FROM lines WHERE invoice = ? " + "ORDER BY position", (invoice,)).fetchall(): + rows.append(connection.execute( + "SELECT name, unit_price FROM products WHERE sku = ?", + (sku,)).fetchone() + (quantity,)) + else: + rows = connection.execute( + "SELECT name, unit_price, quantity FROM lines JOIN products " + "USING (sku) WHERE invoice = ? ORDER BY position", + (invoice,)).fetchall() + if MODE == "crowded" and len(rows) > 100: + return Response(413, "too many lines to show") + return Response(200, json.dumps(rows)) + + +def create_app(database): + if MODE == "broken": + raise RuntimeError("no factory today") + if MODE == "unportable" and sys.version_info[:2] != (2, 7): + raise RuntimeError("written for Python 2.7 only") + return App(database) +''' + +FAULTS = {"fragile": "fuzz_robustness", "brittle": "fuzz_robustness", + "locking": "concurrent_writes", "lossy": "concurrent_writes", + "cramped": "capacity_500_lines", "crowded": "capacity_500_lines", + "bouncing": "fuzz_robustness", "chatty": "n_plus_one", + "shared": "coexistence", "stray": "coexistence"} + + +def fake_readings(scratch, modes, mode_arg="all"): + """Run the in-process probes against the stand-in in each mode.""" + readings = {} + for mode in modes: + where = os.path.join(scratch, "%s-%s" % (mode_arg, mode)) + package = os.path.join(where, "site", "tariff") + os.makedirs(package) + with io.open(os.path.join(package, "__init__.py"), "w", + encoding="utf-8") as handle: + handle.write(FAKE_APP.replace("__MODE__", mode)) + env = dict(os.environ, PYTHONPATH=os.path.join(where, "site")) + readings[mode] = probe_runtime(sys.executable, where, mode_arg, + env=env, timeout=300) + return readings + + +def failing(probes): + """The pass/fail probes a reading fails, in order.""" + return [name for name in IN_PROCESS + if name not in MEASURED and probes[name].get("passed") is not True] + + +def runtime_self_checks(scratch): + """Each planted fault fails its own probe and no other; an app that + keeps the probes from running loses them.""" + modes = ["sound", "slow", "gated", "broken"] + sorted(FAULTS) + readings = fake_readings(scratch, modes) + probes = {mode: probe_results(*readings[mode]) for mode in modes} + sound = probes["sound"] + latency = sound["latency_p95_ms"] + checks = [ + ("a sound app signs in", (readings["sound"][0] or {}).get( + "signed_in") is True), + ("a sound app passes every probe", failing(sound) == []), + ("the latency is two repeats of 30 requests each", + latency.get("requests") == 30 + and len(latency.get("repeats") or []) == 2 + and all(value > 0 for value in latency["repeats"]) + and latency["value"] == max(latency["repeats"])), + ("a slowed app reads slower by its delay", + failing(probes["slow"]) == [] + and (probes["slow"]["latency_p95_ms"].get("value") or 0) >= 20 + and probes["slow"]["latency_p95_ms"]["value"] > latency["value"]), + ("statements are counted per page, and did not grow", + sound["n_plus_one"].get("one_line", 0) > 0 + and sound["n_plus_one"]["twenty_lines"] + == sound["n_plus_one"]["one_line"]), + ] + labels = { + "fragile": "an app answering 500 on bad input fails fuzz_robustness", + "brittle": "an app raising out of the client fails fuzz_robustness", + "locking": "an app whose writes lock fails concurrent_writes", + "lossy": "an app dropping an overlapping write fails " + "concurrent_writes", + "cramped": "an app refusing 500 lines fails capacity_500_lines", + "crowded": "an app that cannot show 500 lines fails " + "capacity_500_lines", + "bouncing": "an app answering a malformed request with the sign-in's " + "redirect loses fuzz_robustness", + "chatty": "an app reading each line on its own fails n_plus_one", + "shared": "instances sharing their data fail coexistence", + "stray": "an app writing outside its folder fails coexistence", + } + for mode, label in sorted(labels.items()): + checks.append(("%s, and no other probe" % label, + failing(probes[mode]) == [FAULTS[mode]])) + checks.extend([ + ("the redirect is read as lost, not as an answer", + "sign-in's redirect" in probes["bouncing"]["fuzz_robustness"].get( + "lost", "")), + ("the locked write is read as locked", + probes["locking"]["concurrent_writes"].get("locked") is True), + ("the stray file is named", + any(path.endswith("tariff-quality-stray.log") for path in + probes["stray"]["coexistence"].get("stray", []))), + ("an app that never keeps its sign-in loses every probe, passing " + "none", all(probe.get("lost") and not probe.get("passed") + and probe.get("value") is None + for probe in probes["gated"].values()) + and all("could not sign in" in probe["lost"] + for probe in probes["gated"].values())), + ("an app that will not boot loses every probe", + all("would not boot" in probe.get("lost", "") + for probe in probes["broken"].values())), + ]) + stray = os.path.join(tempfile.gettempdir(), "tariff-quality-stray.log") + if os.path.exists(stray): + os.remove(stray) + return checks + + +def reading_self_checks(): + """A missing report is missing, and a stalled run keeps what it read.""" + no_report = probe_results(None, "the quality probe produced no report") + stalled = probe_results( + {"signed_in": True, "running": "n_plus_one", + "probes": {"latency_p95_ms": {"value": 3.0, "repeats": [3.0, 2.0]}}}, + stalled="the run stopped during n_plus_one: timed out after 900s") + hung_boot = probe_results({"running": "boot", "probes": {}}, + stalled="the run stopped during boot") + return [ + ("no report from the probe is missing, not lost", + all(probe.get("missing") and probe.get("passed") is None + and probe.get("value") is None and not probe.get("lost") + for probe in no_report.values())), + ("a stalled run keeps what it read and loses the rest", + stalled["latency_p95_ms"]["value"] == 3.0 + and all("stopped during n_plus_one" in stalled[name].get("lost", "") + for name in IN_PROCESS if name != "latency_p95_ms")), + ("a run that stalled booting loses every probe", + all("during boot" in probe.get("lost", "") + for probe in hung_boot.values())), + ] + + +def portability_self_checks(scratch): + """The other Python's install, boot and page decide portability.""" + readings = fake_readings(scratch, ["sound", "unportable", "gated"], + "portability") + good = {"failed": None, "status": 0, "stdout": "", "stderr": ""} + refused = {"failed": None, "status": 1, "stdout": "", + "stderr": "ERROR: Package 'tariff' requires a different " + "Python: 3.14.0 not in '<3.13,>=3.12'"} + + def reading(mode, installed=good): + payload, reason, _ = readings[mode] + return portability_reading(installed, payload, reason, "3.14.0") + + return [ + ("a build that serves its page on the other Python passes " + "portability", reading("sound")["passed"] is True), + ("a build that boots on its own Python only fails portability", + reading("unportable")["passed"] is False + and "would not boot" in reading("unportable")["reason"]), + ("a build whose sign-in fails on the other Python fails " + "portability", reading("gated")["passed"] is False), + ("a build the other Python will not install fails portability", + reading("sound", refused)["passed"] is False + and "did not install" in reading("sound", refused)["reason"]), + ("no other Python is missing, not passed", + read_portability(scratch, scratch, None)["passed"] is None + and "no Python" in read_portability(scratch, scratch, + None)["missing"]), + ] + + +def claim_self_checks(scratch): + """A reading run refuses while another holds the area, and installs + nothing.""" + root = os.path.join(scratch, "claimed") + area = scoring_area(root) + os.makedirs(os.path.join(area, "scores")) + with io.open(os.path.join(area, "scores", "none-1.json"), "w", + encoding="utf-8") as handle: + handle.write("{}") + label, refused = claim_refusal_check(SCRIPT, main, root) + return [(label, refused + and not os.path.exists(os.path.join(area, "quality")))] + + +def leftover_self_checks(scratch): + """A reading leaves no environment behind, and a trial that did not + install loses every probe, portability too.""" + area = os.path.join(scratch, "leftover") + tree = os.path.join(area, "tree") + os.makedirs(tree) + scores_file = os.path.join(area, "none-1.json") + with io.open(scores_file, "w", encoding="utf-8") as handle: + json.dump({"workspace": tree}, handle) + result = read_trial(area, "none-1", scores_file, None) + where = os.path.join(area, "quality", "none-1") + return [ + ("a reading's environment is gone once it is read", + not os.path.exists(os.path.join(where, "venv")) + and not os.path.exists(os.path.join(where, "venv-other"))), + ("a trial that did not install loses every probe", + sorted(result["probes"]) == sorted(PROBES) + and all("did not install" in probe.get("lost", "") + for probe in result["probes"].values())), + ] + + +def self_test(): + """Prove each probe fails the fault it guards against, records missing + as missing, and that a live run refuses a second.""" + scratch = os.path.join(tempfile.gettempdir(), "efficacy-quality-self-test") + remove_tree(scratch) + os.makedirs(scratch) + checks = (runtime_self_checks(scratch) + reading_self_checks() + + portability_self_checks(scratch) + claim_self_checks(scratch) + + leftover_self_checks(scratch)) + for label, ok in checks: + print(" %-52s %s" % (label, "ok" if ok else "FAILED")) + remove_tree(scratch) + passed = sum(1 for _, ok in checks if ok) + lib.print_verdict(passed == len(checks), + "%d/%d self-test checks passed" % (passed, len(checks))) + return 0 if passed == len(checks) else 1 + + +def existing_file(directory, name): + """The JSON file a trial's reading is filed under, or None.""" + path = os.path.join(directory, "%s.json" % canonical(name)) + return path if os.path.isfile(path) else None + + +def parse_args(argv): + parser = argparse.ArgumentParser( + description="Read scored efficacy trials for reliability, " + "performance and flexibility.") + parser.add_argument("--root", help="the harness's run root") + parser.add_argument("--trial", action="append", default=[], + help="read only this trial, as none-1; repeatable") + parser.add_argument("--reread", action="store_true", + help="read a trial already read; by default such a " + "trial is skipped") + parser.add_argument("--self-test", action="store_true", + help="prove every probe against a planted app; read " + "no trial") + return parser.parse_args(argv) + + +def main(argv): + options = parse_args(argv) + if options.self_test: + return self_test() + if not options.root: + 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")} + 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)) + return 2 + + # A run clears each trial's environment before rebuilding it, so a second + # run against the area deletes the one a live run is installing into. + try: + claim = claim_area(area, SCRIPT) + except LiveRunError as error: + print("refused: %s" % error) + return 2 + try: + return read_trials(options, area, scored, wanted) + finally: + release_area(claim) + + +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") + done = [] + if not options.reread: + for name in wanted: + written = existing_file(target, name) + if written: + print("%s already read at %s; --reread to read it again" + % (name, written)) + done.append(name) + wanted = [name for name in wanted if name not in done] + if not wanted: + lib.print_verdict(True, "0 trial(s) read, %d already read" + % len(done)) + return 0 + other = other_interpreter() + os.makedirs(target, exist_ok=True) + for name in wanted: + print("%s reading for quality" % name) + result = read_trial(area, name, scored[name], other) + 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) + print(" " + ", ".join( + "%s %s" % (key, shown(probe)) + for key, probe in result["probes"].items())) + lib.print_verdict(True, "%d trial(s) read, %d already read" + % (len(wanted), len(done))) + return 0 + + +def shown(probe): + """One probe's reading in a word or a number.""" + if probe.get("missing"): + return "missing" + if probe.get("lost"): + return "lost" + if "value" in probe: + return "%s ms" % probe["value"] + return "passed" if probe["passed"] else "failed" + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/tests/efficacy/trace.py b/tests/efficacy/trace.py index 939434d..46f76e5 100644 --- a/tests/efficacy/trace.py +++ b/tests/efficacy/trace.py @@ -31,7 +31,7 @@ # is looked up only in the output of the module its row names. MODULES = ("harness.py", "generate_arm.py", "score.py", "judge.py", "report.py", "archive.py", "reuse.py", "progress.py", "probes.py", - "security.py", "control/control.py") + "security.py", "quality.py", "control/control.py") ROW = re.compile(r"^\| (FR-(\d{2})-(\d{2})) \| (.+?) \| (.+?) \|$") TOPIC = re.compile(r"^#{2,3} (\d{2}) ") From 41d917b485bf42e86b810b26e50e4e7f18a7cf7e Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:37:43 +0200 Subject: [PATCH 02/17] fix(efficacy): the quality reader signs in on a 200 and counts every line Codex round 1 on the quality reader: - Hidden fields are read with an HTML parser, so a single-quoted CSRF token signs in. - The sign-in holds only where the dashboard then answers 200; a 401, or a 403 to a request carrying its token, is the sign-in turning it away, like its redirect, and the probe is lost. - The 500-line probe passes only where the export holds all 500 lines and the preview and the page show every line and the export's total. - Stand-in modes: single-quoted sign-in, `refusing` (401), `forbidding` (403 on bad input), `truncating` (keeps 100 lines). Refs #119. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 4 +- docs/requirements.md | 4 +- tests/efficacy/quality.py | 195 +++++++++++++++++++++++++++++--------- 3 files changed, 153 insertions(+), 50 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index f2bf018..c8d4050 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -208,8 +208,8 @@ when: | ID | Kind | Checked by | | -- | ---- | ---------- | -| FR-15-01 | Self-test | `quality.py` "a sound app passes every probe"
`quality.py` "an app answering 500 on bad input fails fuzz_robustness, and no other probe"
`quality.py` "an app raising out of the client fails fuzz_robustness, and no other probe"
`quality.py` "an app whose writes lock fails concurrent_writes, and no other probe"
`quality.py` "an app dropping an overlapping write fails concurrent_writes, and no other probe"
`quality.py` "the locked write is read as locked"
`quality.py` "an app refusing 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app that cannot show 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app reading each line on its own fails n_plus_one, and no other probe"
`quality.py` "statements are counted per page, and did not grow"
`quality.py` "instances sharing their data fail coexistence, and no other probe"
`quality.py` "an app writing outside its folder fails coexistence, and no other probe"
`quality.py` "the stray file is named" | -| FR-15-02 | Self-test | `quality.py` "a sound app signs in"
`quality.py` "an app that never keeps its sign-in loses every probe, passing none"
`quality.py` "an app answering a malformed request with the sign-in's redirect loses fuzz_robustness, and no other probe"
`quality.py` "the redirect is read as lost, not as an answer" | +| FR-15-01 | Self-test | `quality.py` "a sound app passes every probe"
`quality.py` "an app answering 500 on bad input fails fuzz_robustness, and no other probe"
`quality.py` "an app raising out of the client fails fuzz_robustness, and no other probe"
`quality.py` "an app whose writes lock fails concurrent_writes, and no other probe"
`quality.py` "an app dropping an overlapping write fails concurrent_writes, and no other probe"
`quality.py` "the locked write is read as locked"
`quality.py` "an app refusing 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app that cannot show 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app keeping 100 of 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app reading each line on its own fails n_plus_one, and no other probe"
`quality.py` "statements are counted per page, and did not grow"
`quality.py` "instances sharing their data fail coexistence, and no other probe"
`quality.py` "an app writing outside its folder fails coexistence, and no other probe"
`quality.py` "the stray file is named" | +| FR-15-02 | Self-test | `quality.py` "a sound app signs in"
`quality.py` "a sign-in form quoted with single quotes signs in"
`quality.py` "an app answering 401 until signed in, and never signing in, loses every probe"
`quality.py` "an app answering 403 to a malformed request loses fuzz_robustness, and no other probe"
`quality.py` "an app that never keeps its sign-in loses every probe, passing none"
`quality.py` "an app answering a malformed request with the sign-in's redirect loses fuzz_robustness, and no other probe"
`quality.py` "the redirect is read as lost, not as an answer" | | FR-15-03 | Self-test | `quality.py` "an app that will not boot loses every probe"
`quality.py` "a trial that did not install loses every probe"
`quality.py` "no report from the probe is missing, not lost"
`quality.py` "a stalled run keeps what it read and loses the rest"
`quality.py` "a run that stalled booting loses every probe" | | 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" | diff --git a/docs/requirements.md b/docs/requirements.md index 5020fb8..b4e4827 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -218,8 +218,8 @@ | ID | Requirement | Delivered by | | -- | ----------- | ------------ | -| FR-15-01 | The benchmark shall fail each of the fuzz, concurrent-write, 500-line, N+1 and co-existence probes on an app planted with the fault it guards against, and no other probe there, and pass every probe on an app built to pass them. | Quality reader | -| FR-15-02 | The benchmark shall read every quality probe signed in as the seeded administrator, and never measure a page answered with the sign-in's redirect. | Quality reader | +| FR-15-01 | The benchmark shall fail each of the fuzz, concurrent-write, 500-line, N+1 and co-existence probes on an app planted with the fault it guards against, and no other probe there, and pass every probe on an app built to pass them; the 500-line probe passes only where the preview, the saved invoice and its page keep every line. | Quality reader | +| FR-15-02 | The benchmark shall read every quality probe signed in as the seeded administrator, through the sign-in form's hidden fields however they are quoted, the sign-in holding only where the dashboard then answers 200, and never measure a request the sign-in turns away with its redirect, a 401, or a 403 to a request that carried its token. | Quality reader | | FR-15-03 | The benchmark shall count as lost, reading failed, a quality probe the trial keeps from running, by not installing, not booting, not signing in or not finishing in time, and as missing one it could not run itself. | Quality reader | | FR-15-04 | The benchmark shall record the latency as two repeats of the 95th percentile over 30 requests to the main routes, with no pass threshold until one is calibrated. | Quality reader | | 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 | diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index 9b18591..7562022 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -66,12 +66,15 @@ # # It signs in as the specification has the administrator do: the password # from the environment, set before the package is imported because the seed -# may run lazily, and the sign-in form's own hidden fields. Every probe reads -# the pages behind that sign-in; one answered with the sign-in's redirect is -# never measured, and the probe is lost. +# may run lazily, and the sign-in form's own hidden fields. The sign-in holds +# only where the dashboard then answers 200. Every probe reads the pages +# behind that sign-in; a request it turns away, with its redirect, a 401 or +# a 403, is never measured, and the probe is lost. QUALITY_SCRIPT = r''' -import builtins, html, io, json, logging, math, os, platform, re, sqlite3 +import builtins, io, json, logging, math, os, platform, re, sqlite3 import sys, tempfile, threading, time +from decimal import Decimal, InvalidOperation +from html.parser import HTMLParser from urllib.parse import urlsplit PACKAGE = "tariff" @@ -206,29 +209,42 @@ def folder(): class Gated(Exception): - """A page answered with the sign-in's redirect.""" + """A request the sign-in turned away.""" class Raised(Exception): """The application raised out of the test client.""" +class Hidden(HTMLParser): + """Collects every hidden input, however its attributes are quoted.""" + + def __init__(self): + HTMLParser.__init__(self) + self.fields = {} + + def handle_starttag(self, tag, attrs): + attributes = dict(attrs) + if (tag == "input" and (attributes.get("type") or "").lower() + == "hidden" and attributes.get("name")): + self.fields[attributes["name"]] = attributes.get("value") or "" + + def hidden_fields(text): """Every hidden input in the page, which is where a CSRF token hides.""" - fields = {} - for match in re.finditer(r']*type="hidden"[^>]*>', text, - re.IGNORECASE): - tag = match.group(0) - name = re.search(r'name="([^"]+)"', tag) - value = re.search(r'value="([^"]*)"', tag) - if name: - fields[html.unescape(name.group(1))] = ( - html.unescape(value.group(1)) if value else "") - return fields - - -def gated(response): - """Whether the answer is the redirect to the sign-in form.""" + parser = Hidden() + parser.feed(text) + return parser.fields + + +# A request the sign-in turns away: its redirect, a 401, or a 403 to a +# request that carried its form's token, which no CSRF check refuses. A +# request sent without a token may be refused 403 as a forgery, as the +# specification allows. +def gated(response, token=True): + """Whether the answer refuses the request for want of a sign-in.""" + if response.status_code == 401 or (token and response.status_code == 403): + return True if response.status_code not in REDIRECTS: return False return urlsplit(response.headers.get("Location", "")).path == "/sign-in" @@ -246,7 +262,8 @@ def page(who, path): """A page behind the sign-in, or Gated.""" answer = ask(who, "GET", path) if gated(answer): - raise Gated("%s answered with the sign-in's redirect" % path) + raise Gated("%s was turned away by the sign-in: %d" + % (path, answer.status_code)) return answer @@ -262,17 +279,21 @@ def form_post(who, form, path, body, method="POST", headers=None): def held(answer, what): if gated(answer): - raise Gated("%s answered with the sign-in's redirect" % what) + raise Gated("%s was turned away by the sign-in: %d" + % (what, answer.status_code)) return answer def sign_in(who): - """Whether the seeded administrator signs in and stays signed in.""" + """Whether the seeded administrator signs in: the dashboard, which + only a signed-in administrator is shown, then answers 200.""" try: body = {"username": USERNAME, "password": PASSWORD, "next": "/"} answer = form_post(who, "/sign-in", "/sign-in", body) report.setdefault("sign_in_status", answer.status_code) - return not gated(ask(who, "GET", "/")) + home = ask(who, "GET", "/") + report.setdefault("home_status", home.status_code) + return home.status_code == 200 except Raised as error: report.setdefault("sign_in_error", str(error)) return False @@ -407,8 +428,32 @@ def n_plus_one(): return passed(large <= small, one_line=small, twenty_lines=large) +def exported(path): + """The saved invoice's JSON export: its lines and its total, or None.""" + try: + export = json.loads(page(client, path + "/export.json").get_data( + as_text=True)) + Decimal(export["total"]) + return list(export["lines"]), str(export["total"]) + except (ValueError, KeyError, TypeError, InvalidOperation): + return None + + +def shows_all(answer, lines, total): + """Whether a page shows every line, by each sku's count, and the total + that only every line gives, read with any thousands separator.""" + text = re.sub(r"(?<=\d)[,\u00a0\u202f ](?=\d{3}\b)", "", + answer.get_data(as_text=True)) + counts = {} + for sku, _ in lines: + counts[sku] = counts.get(sku, 0) + 1 + return (all(text.count(sku) >= count for sku, count in counts.items()) + and total in text) + + def capacity_500_lines(): - """An invoice of 500 lines previewed, saved and rendered.""" + """An invoice of 500 lines previewed, saved and rendered, every line + kept in all three.""" lines = [(SKUS[index % len(SKUS)], 1 + index % 7) for index in range(500)] steps = {} try: @@ -426,9 +471,25 @@ def capacity_500_lines(): reason="the save did not redirect to its page") rendered = page(client, path) steps["render"] = rendered.status_code + export = exported(path) except Raised as error: return passed(False, steps=steps, raised=str(error)) - return passed(ok(preview) and ok(rendered), steps=steps) + if not (ok(preview) and ok(rendered)): + return passed(False, steps=steps) + + # A build that quietly keeps fewer lines answers 2xx on all three, so + # the lines are counted: the export's, the spec's fixed form, then the + # preview's and the page's against it. + if export is None: + return passed(False, steps=steps, + reason="the saved invoice's JSON export did not read") + kept = {"saved": len(export[0]) == len(lines) + and [(line.get("sku"), line.get("quantity")) for line in export[0]] + == lines, + "preview": shows_all(preview, lines, export[1]), + "render": shows_all(rendered, lines, export[1])} + return passed(all(kept.values()), steps=steps, kept=kept, + saved_lines=len(export[0])) LOCKED = re.compile(r"database (table )?is locked", re.IGNORECASE) @@ -475,8 +536,8 @@ def write(index): return passed(False, reason="the writes did not finish in 120 s") entries = [entry for outcome in outcomes for entry in outcome] if any(entry.get("gated") for entry in entries): - return lost("concurrent_writes", "a write answered with the " - "sign-in's redirect") + return lost("concurrent_writes", "a write was turned away by the " + "sign-in") listing = page(client, "/products").get_data(as_text=True) unsaved = [entry["sku"] for entry in entries if entry["sku"] not in listing] @@ -692,14 +753,15 @@ def fuzz_robustness(): entry["status"] = answer.status_code # Signed out, the sign-in's own answer may be its redirect. - entry["gated"] = gated(answer) and not signed_out + entry["gated"] = not signed_out and gated( + answer, token=method == "GET" or form is not None) except Raised as error: entry["raised"] = str(error) answers.append(entry) asked = [entry["request"] for entry in answers if entry.get("gated")] if asked: - return lost("fuzz_robustness", "%d malformed requests were answered " - "with the sign-in's redirect" % len(asked), asked=asked) + return lost("fuzz_robustness", "%d malformed requests were turned " + "away by the sign-in" % len(asked), asked=asked) failed = [entry for entry in answers if entry.get("raised") or (entry.get("status") or 0) >= 500] return passed(not failed, requests=len(answers), failed=failed) @@ -769,7 +831,9 @@ def probe_results(payload, reason=None, lost=False, stalled=None): trial = stalled elif not payload.get("signed_in"): trial = ("the seeded administrator could not sign in; the " - "sign-in answered %s" % payload.get("sign_in_status")) + "sign-in answered %s and / %s" + % (payload.get("sign_in_status"), + payload.get("home_status"))) read = payload.get("probes") or {} readings = {} for name in IN_PROCESS: @@ -949,10 +1013,14 @@ def read_trial(area, name, scores_file, other): # write that overlaps another, `slow` takes 20 ms over every answer, # `cramped` refuses over 100 lines, `crowded` saves them and will not show # them, `chatty` reads each invoice line's product on its own, `shared` keeps -# its products in one store for every instance, and `stray` writes a fixed -# file outside its folder. `bouncing` answers a price it cannot parse with -# the sign-in's redirect, `gated` never keeps its sign-in, `broken` will not -# boot, and `unportable` boots on no Python but the one it names. +# its products in one store for every instance, `stray` writes a fixed file +# outside its folder, and `truncating` keeps the first 100 lines of an +# invoice, answering as if it kept them all. `bouncing` answers a price it +# cannot parse with the sign-in's redirect and `forbidding` with a 403; +# `gated` never keeps its sign-in, and `refusing` neither keeps it nor +# redirects, answering 401; `broken` will not boot, and `unportable` boots +# on no Python but the one it names. Every mode's sign-in form quotes its +# attributes with single quotes. FAKE_APP = '''import decimal import json import logging @@ -965,6 +1033,7 @@ def read_trial(area, name, scores_file, other): MODE = "__MODE__" TOKEN = '' +SIGN_IN = "" SKUS = {"WID-1": "10.00", "GAD-2": "24.50", "BOK-3": "12.00", "SRV-4": "80.00", "SEE-5": "3.75"} LOG = logging.getLogger("tariff") @@ -990,6 +1059,17 @@ def listed(value): return list(value) if isinstance(value, (list, tuple)) else [value] +def table(rows): + """Each line's sku and quantity, and the total, from (sku, unit price, + quantity) rows.""" + total = sum((decimal.Decimal(price) * quantity + for _, price, quantity in rows), decimal.Decimal("0")) + total = str(total.quantize(decimal.Decimal("0.01"))) + return total, "%s

Total %s

" % ("".join( + "%s%d" % (sku, quantity) + for sku, _, quantity in rows), total) + + def number(text): """An id, or None where it is none or would overflow SQLite.""" if MODE == "brittle": @@ -1088,13 +1168,15 @@ def open(self, path, method="GET", data=None, headers=None, def dispatch(self, path, method, data): if path == "/sign-in": if method == "GET": - return Response(200, "" + TOKEN) + return Response(200, SIGN_IN) if (data.get("csrf_token") == "t" and data.get("username") == "admin" and data.get("password") == self.app.password): - self.signed = MODE != "gated" + self.signed = MODE not in ("gated", "refusing") return Response(302, "", {"Location": "/"}) - return Response(200, "wrong username or password" + TOKEN) + return Response(200, "wrong username or password" + SIGN_IN) + if not self.signed and MODE == "refusing": + return Response(401, "sign in first") if not self.signed: return Response(302, "", {"Location": "/sign-in"}) pages = ("/", "/products", "/rules", "/jurisdictions", "/customers", @@ -1135,6 +1217,8 @@ def create_product(self, data): except decimal.InvalidOperation: if MODE == "bouncing": return Response(302, "", {"Location": "/sign-in"}) + if MODE == "forbidding": + return Response(403, "forbidden") return Response(200, "unit_price is not a number" + TOKEN) if not price.is_finite() or price < 0 or price > 10 ** 12: return Response(200, "unit_price is out of range" + TOKEN) @@ -1157,8 +1241,11 @@ def invoice(self, path, data): lines.append((sku, int(quantity))) if MODE == "cramped" and len(lines) > 100: return Response(413, "too many lines") + if MODE == "truncating": + lines = lines[:100] if path == "/invoices/preview": - return Response(200, "%d lines
" % len(lines)) + return Response(200, table([(sku, SKUS.get(sku, "1.00"), quantity) + for sku, quantity in lines])[1]) if not lines: return Response(400, "no lines") with self.app.connect() as connection: @@ -1187,16 +1274,21 @@ def show(self, parts): "SELECT sku, quantity FROM lines WHERE invoice = ? " "ORDER BY position", (invoice,)).fetchall(): rows.append(connection.execute( - "SELECT name, unit_price FROM products WHERE sku = ?", + "SELECT sku, unit_price FROM products WHERE sku = ?", (sku,)).fetchone() + (quantity,)) else: rows = connection.execute( - "SELECT name, unit_price, quantity FROM lines JOIN products " + "SELECT sku, unit_price, quantity FROM lines JOIN products " "USING (sku) WHERE invoice = ? ORDER BY position", (invoice,)).fetchall() if MODE == "crowded" and len(rows) > 100: return Response(413, "too many lines to show") - return Response(200, json.dumps(rows)) + total, shown = table(rows) + if parts[-1] == "export.json": + return Response(200, json.dumps({"lines": [ + {"sku": sku, "quantity": quantity} + for sku, _, quantity in rows], "total": total})) + return Response(200, shown) def create_app(database): @@ -1210,7 +1302,8 @@ def create_app(database): FAULTS = {"fragile": "fuzz_robustness", "brittle": "fuzz_robustness", "locking": "concurrent_writes", "lossy": "concurrent_writes", "cramped": "capacity_500_lines", "crowded": "capacity_500_lines", - "bouncing": "fuzz_robustness", "chatty": "n_plus_one", + "truncating": "capacity_500_lines", "bouncing": "fuzz_robustness", + "forbidding": "fuzz_robustness", "chatty": "n_plus_one", "shared": "coexistence", "stray": "coexistence"} @@ -1239,7 +1332,7 @@ def failing(probes): def runtime_self_checks(scratch): """Each planted fault fails its own probe and no other; an app that keeps the probes from running loses them.""" - modes = ["sound", "slow", "gated", "broken"] + sorted(FAULTS) + modes = ["sound", "slow", "gated", "refusing", "broken"] + sorted(FAULTS) readings = fake_readings(scratch, modes) probes = {mode: probe_results(*readings[mode]) for mode in modes} sound = probes["sound"] @@ -1247,6 +1340,9 @@ def runtime_self_checks(scratch): checks = [ ("a sound app signs in", (readings["sound"][0] or {}).get( "signed_in") is True), + ("a sign-in form quoted with single quotes signs in", + (readings["sound"][0] or {}).get("signed_in") is True + and "type='hidden'" in FAKE_APP), ("a sound app passes every probe", failing(sound) == []), ("the latency is two repeats of 30 requests each", latency.get("requests") == 30 @@ -1273,6 +1369,10 @@ def runtime_self_checks(scratch): "capacity_500_lines", "bouncing": "an app answering a malformed request with the sign-in's " "redirect loses fuzz_robustness", + "forbidding": "an app answering 403 to a malformed request loses " + "fuzz_robustness", + "truncating": "an app keeping 100 of 500 lines fails " + "capacity_500_lines", "chatty": "an app reading each line on its own fails n_plus_one", "shared": "instances sharing their data fail coexistence", "stray": "an app writing outside its folder fails coexistence", @@ -1282,8 +1382,11 @@ def runtime_self_checks(scratch): failing(probes[mode]) == [FAULTS[mode]])) checks.extend([ ("the redirect is read as lost, not as an answer", - "sign-in's redirect" in probes["bouncing"]["fuzz_robustness"].get( - "lost", "")), + "turned away by the sign-in" in probes["bouncing"][ + "fuzz_robustness"].get("lost", "")), + ("an app answering 401 until signed in, and never signing in, loses " + "every probe", all("could not sign in" in probe.get("lost", "") + for probe in probes["refusing"].values())), ("the locked write is read as locked", probes["locking"]["concurrent_writes"].get("locked") is True), ("the stray file is named", From 57fc90b2aa95e7a8de34d0bf0f1cb5a81618a14f Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:03:35 +0200 Subject: [PATCH 03/17] fix(efficacy): the 500-line probe reads the export's lines and the total Codex round 2 on the quality reader: - The export must list all 500 lines in order, each a record with a sku and an integer quantity; a null or malformed line fails, never missing. - The preview and the page are read by the invoice's total alone, matched however it is grouped and beside any currency sign; row counting in HTML is dropped, so a page that paginates its rows passes. - A fault mode's check now needs its probe failed, not merely unpassed. - Stand-in modes: `paginating` (passes), `miscounting`, `nulling`; pages write grouped amounts beside the euro's sign. Refs #119. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 2 +- docs/requirements.md | 2 +- tests/efficacy/quality.py | 142 ++++++++++++++++++++++++++------------ 3 files changed, 100 insertions(+), 46 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index 2b152cd..cad44d6 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -208,7 +208,7 @@ when: | ID | Kind | Checked by | | -- | ---- | ---------- | -| FR-15-01 | Self-test | `quality.py` "a sound app passes every probe"
`quality.py` "an app answering 500 on bad input fails fuzz_robustness, and no other probe"
`quality.py` "an app raising out of the client fails fuzz_robustness, and no other probe"
`quality.py` "an app whose writes lock fails concurrent_writes, and no other probe"
`quality.py` "an app dropping an overlapping write fails concurrent_writes, and no other probe"
`quality.py` "the locked write is read as locked"
`quality.py` "an app refusing 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app that cannot show 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app keeping 100 of 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app reading each line on its own fails n_plus_one, and no other probe"
`quality.py` "statements are counted per page, and did not grow"
`quality.py` "instances sharing their data fail coexistence, and no other probe"
`quality.py` "an app writing outside its folder fails coexistence, and no other probe"
`quality.py` "the stray file is named" | +| FR-15-01 | Self-test | `quality.py` "a sound app passes every probe"
`quality.py` "an app answering 500 on bad input fails fuzz_robustness, and no other probe"
`quality.py` "an app raising out of the client fails fuzz_robustness, and no other probe"
`quality.py` "an app whose writes lock fails concurrent_writes, and no other probe"
`quality.py` "an app dropping an overlapping write fails concurrent_writes, and no other probe"
`quality.py` "the locked write is read as locked"
`quality.py` "an app refusing 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app that cannot show 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app keeping 100 of 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "a page showing a total other than the export's fails capacity_500_lines, and no other probe"
`quality.py` "an export with a null line fails capacity_500_lines, and no other probe"
`quality.py` "a page showing fewer rows but the whole total passes capacity_500_lines"
`quality.py` "a total grouped by thousands beside a currency sign is read"
`quality.py` "an app reading each line on its own fails n_plus_one, and no other probe"
`quality.py` "statements are counted per page, and did not grow"
`quality.py` "instances sharing their data fail coexistence, and no other probe"
`quality.py` "an app writing outside its folder fails coexistence, and no other probe"
`quality.py` "the stray file is named" | | FR-15-02 | Self-test | `quality.py` "a sound app signs in"
`quality.py` "a sign-in form quoted with single quotes signs in"
`quality.py` "an app answering 401 until signed in, and never signing in, loses every probe"
`quality.py` "an app answering 403 to a malformed request loses fuzz_robustness, and no other probe"
`quality.py` "an app that never keeps its sign-in loses every probe, passing none"
`quality.py` "an app answering a malformed request with the sign-in's redirect loses fuzz_robustness, and no other probe"
`quality.py` "the redirect is read as lost, not as an answer" | | FR-15-03 | Self-test | `quality.py` "an app that will not boot loses every probe"
`quality.py` "a trial that did not install loses every probe"
`quality.py` "no report from the probe is missing, not lost"
`quality.py` "a stalled run keeps what it read and loses the rest"
`quality.py` "a run that stalled booting loses every probe" | | 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" | diff --git a/docs/requirements.md b/docs/requirements.md index b4e4827..4721be5 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -218,7 +218,7 @@ | ID | Requirement | Delivered by | | -- | ----------- | ------------ | -| FR-15-01 | The benchmark shall fail each of the fuzz, concurrent-write, 500-line, N+1 and co-existence probes on an app planted with the fault it guards against, and no other probe there, and pass every probe on an app built to pass them; the 500-line probe passes only where the preview, the saved invoice and its page keep every line. | Quality reader | +| FR-15-01 | The benchmark shall fail each of the fuzz, concurrent-write, 500-line, N+1 and co-existence probes on an app planted with the fault it guards against, and no other probe there, and pass every probe on an app built to pass them; the 500-line probe passes only where the JSON export lists all 500 lines in order, each a well-formed record, and the preview and the page each answer 2xx and show the invoice's total, which only every line gives, however it is grouped and whatever currency sign it carries. A page that paginates its rows but shows that total passes. | Quality reader | | FR-15-02 | The benchmark shall read every quality probe signed in as the seeded administrator, through the sign-in form's hidden fields however they are quoted, the sign-in holding only where the dashboard then answers 200, and never measure a request the sign-in turns away with its redirect, a 401, or a 403 to a request that carried its token. | Quality reader | | FR-15-03 | The benchmark shall count as lost, reading failed, a quality probe the trial keeps from running, by not installing, not booting, not signing in or not finishing in time, and as missing one it could not run itself. | Quality reader | | FR-15-04 | The benchmark shall record the latency as two repeats of the 95th percentile over 30 requests to the main routes, with no pass threshold until one is calibrated. | Quality reader | diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index 7562022..3d6ae39 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -428,27 +428,46 @@ def n_plus_one(): return passed(large <= small, one_line=small, twenty_lines=large) -def exported(path): - """The saved invoice's JSON export: its lines and its total, or None.""" +def exported(path, lines): + """The saved invoice's JSON export read against the lines saved: its + total, or None and why it does not hold them.""" try: export = json.loads(page(client, path + "/export.json").get_data( as_text=True)) - Decimal(export["total"]) - return list(export["lines"]), str(export["total"]) - except (ValueError, KeyError, TypeError, InvalidOperation): - return None + except ValueError: + return None, "the saved invoice's JSON export is not JSON" + if not isinstance(export, dict) or not isinstance(export.get("lines"), + list): + return None, "the saved invoice's JSON export lists no lines" + records = export["lines"] + malformed = [index for index, line in enumerate(records) + if not isinstance(line, dict) + or not isinstance(line.get("sku"), str) + or type(line.get("quantity")) is not int] + if malformed: + return None, ("the export's line %d is not a record with a sku and " + "an integer quantity" % (malformed[0] + 1)) + if [(line["sku"], line["quantity"]) for line in records] != lines: + return None, ("the export holds %d lines, not the %d saved in order" + % (len(records), len(lines))) + try: + return Decimal(str(export.get("total"))), None + except InvalidOperation: + return None, "the export's total is not a number" + + +# An amount as a page may write it: grouped by thousands with a comma, a +# point, a space or an apostrophe, and two decimals after a point or a comma. +AMOUNT = re.compile(r"(?= count for sku, count in counts.items()) - and total in text) +def shows_total(answer, total): + """Whether a page shows the amount `total`, however it is grouped and + whatever currency sign stands beside it.""" + return any(Decimal(re.sub(r"\D", "", whole) + "." + cents) == total + for whole, cents in AMOUNT.findall( + answer.get_data(as_text=True))) def capacity_500_lines(): @@ -471,25 +490,26 @@ def capacity_500_lines(): reason="the save did not redirect to its page") rendered = page(client, path) steps["render"] = rendered.status_code - export = exported(path) + total, reason = exported(path, lines) except Raised as error: return passed(False, steps=steps, raised=str(error)) if not (ok(preview) and ok(rendered)): return passed(False, steps=steps) - # A build that quietly keeps fewer lines answers 2xx on all three, so - # the lines are counted: the export's, the spec's fixed form, then the - # preview's and the page's against it. - if export is None: - return passed(False, steps=steps, - reason="the saved invoice's JSON export did not read") - kept = {"saved": len(export[0]) == len(lines) - and [(line.get("sku"), line.get("quantity")) for line in export[0]] - == lines, - "preview": shows_all(preview, lines, export[1]), - "render": shows_all(rendered, lines, export[1])} + # A build that quietly keeps fewer lines answers 2xx on all three. The + # export, in the spec's fixed form, must list every line saved, each a + # well-formed record; a malformed one is the build's output, so it fails. + if reason: + return passed(False, steps=steps, reason=reason) + + # The preview and the page are read by their total alone, which only all + # 500 lines give, since every line adds to it. A page that paginates its + # rows but shows the whole invoice's total keeps every line, so it is no + # capacity failure; counting rows in HTML is left alone. + kept = {"preview": shows_total(preview, total), + "render": shows_total(rendered, total)} return passed(all(kept.values()), steps=steps, kept=kept, - saved_lines=len(export[0])) + total=str(total)) LOCKED = re.compile(r"database (table )?is locked", re.IGNORECASE) @@ -1014,8 +1034,11 @@ def read_trial(area, name, scores_file, other): # `cramped` refuses over 100 lines, `crowded` saves them and will not show # them, `chatty` reads each invoice line's product on its own, `shared` keeps # its products in one store for every instance, `stray` writes a fixed file -# outside its folder, and `truncating` keeps the first 100 lines of an -# invoice, answering as if it kept them all. `bouncing` answers a price it +# outside its folder, `truncating` keeps the first 100 lines of an invoice, +# answering as if it kept them all, `miscounting` shows a total of 100 of +# them, and `nulling` exports one line as null. `paginating` shows 100 rows +# and the whole total, which is no fault. Pages write amounts grouped by +# thousands beside the euro's sign. `bouncing` answers a price it # cannot parse with the sign-in's redirect and `forbidding` with a 403; # `gated` never keeps its sign-in, and `refusing` neither keeps it nor # redirects, answering 401; `broken` will not boot, and `unportable` boots @@ -1059,15 +1082,31 @@ def listed(value): return list(value) if isinstance(value, (list, tuple)) else [value] -def table(rows): - """Each line's sku and quantity, and the total, from (sku, unit price, - quantity) rows.""" +def summed(rows): total = sum((decimal.Decimal(price) * quantity for _, price, quantity in rows), decimal.Decimal("0")) - total = str(total.quantize(decimal.Decimal("0.01"))) + return str(total.quantize(decimal.Decimal("0.01"))) + + +def written(amount, style): + """An amount as a page writes it: `12,345.67 EUR` grouped by commas in + English, `12.345,67 EUR` by points otherwise, with the euro's sign.""" + whole, cents = amount.split(".") + grouped = format(int(whole), ",") + if style == "en": + return "\u20ac" + grouped + "." + cents + return grouped.replace(",", ".") + "," + cents + "\u00a0\u20ac" + + +def table(rows, style): + """The export's total, and the page: each line's sku and quantity, and + the total, from (sku, unit price, quantity) rows.""" + total = summed(rows) + shown = rows[:100] if MODE in ("paginating", "miscounting") else rows + page_total = summed(shown) if MODE == "miscounting" else total return total, "%s

Total %s

" % ("".join( "%s%d" % (sku, quantity) - for sku, _, quantity in rows), total) + for sku, _, quantity in shown), written(page_total, style)) def number(text): @@ -1245,7 +1284,7 @@ def invoice(self, path, data): lines = lines[:100] if path == "/invoices/preview": return Response(200, table([(sku, SKUS.get(sku, "1.00"), quantity) - for sku, quantity in lines])[1]) + for sku, quantity in lines], "eu")[1]) if not lines: return Response(400, "no lines") with self.app.connect() as connection: @@ -1283,11 +1322,14 @@ def show(self, parts): (invoice,)).fetchall() if MODE == "crowded" and len(rows) > 100: return Response(413, "too many lines to show") - total, shown = table(rows) + total, shown = table(rows, "en") if parts[-1] == "export.json": - return Response(200, json.dumps({"lines": [ - {"sku": sku, "quantity": quantity} - for sku, _, quantity in rows], "total": total})) + records = [{"sku": sku, "quantity": quantity} + for sku, _, quantity in rows] + if MODE == "nulling" and len(records) > 100: + records[100] = None + return Response(200, json.dumps({"lines": records, + "total": total})) return Response(200, shown) @@ -1302,7 +1344,9 @@ def create_app(database): FAULTS = {"fragile": "fuzz_robustness", "brittle": "fuzz_robustness", "locking": "concurrent_writes", "lossy": "concurrent_writes", "cramped": "capacity_500_lines", "crowded": "capacity_500_lines", - "truncating": "capacity_500_lines", "bouncing": "fuzz_robustness", + "truncating": "capacity_500_lines", + "miscounting": "capacity_500_lines", + "nulling": "capacity_500_lines", "bouncing": "fuzz_robustness", "forbidding": "fuzz_robustness", "chatty": "n_plus_one", "shared": "coexistence", "stray": "coexistence"} @@ -1332,7 +1376,8 @@ def failing(probes): def runtime_self_checks(scratch): """Each planted fault fails its own probe and no other; an app that keeps the probes from running loses them.""" - modes = ["sound", "slow", "gated", "refusing", "broken"] + sorted(FAULTS) + modes = (["sound", "slow", "paginating", "gated", "refusing", "broken"] + + sorted(FAULTS)) readings = fake_readings(scratch, modes) probes = {mode: probe_results(*readings[mode]) for mode in modes} sound = probes["sound"] @@ -1344,6 +1389,11 @@ def runtime_self_checks(scratch): (readings["sound"][0] or {}).get("signed_in") is True and "type='hidden'" in FAKE_APP), ("a sound app passes every probe", failing(sound) == []), + ("a total grouped by thousands beside a currency sign is read", + sound["capacity_500_lines"].get("passed") is True + and "€" in FAKE_APP and 'format(int(whole), ",")' in FAKE_APP), + ("a page showing fewer rows but the whole total passes " + "capacity_500_lines", failing(probes["paginating"]) == []), ("the latency is two repeats of 30 requests each", latency.get("requests") == 30 and len(latency.get("repeats") or []) == 2 @@ -1373,13 +1423,17 @@ def runtime_self_checks(scratch): "fuzz_robustness", "truncating": "an app keeping 100 of 500 lines fails " "capacity_500_lines", + "miscounting": "a page showing a total other than the export's " + "fails capacity_500_lines", + "nulling": "an export with a null line fails capacity_500_lines", "chatty": "an app reading each line on its own fails n_plus_one", "shared": "instances sharing their data fail coexistence", "stray": "an app writing outside its folder fails coexistence", } for mode, label in sorted(labels.items()): checks.append(("%s, and no other probe" % label, - failing(probes[mode]) == [FAULTS[mode]])) + failing(probes[mode]) == [FAULTS[mode]] + and probes[mode][FAULTS[mode]].get("passed") is False)) checks.extend([ ("the redirect is read as lost, not as an answer", "turned away by the sign-in" in probes["bouncing"][ From 49c439bec3db0e8d37489f3c8a978659577d5ac5 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:19:37 +0200 Subject: [PATCH 04/17] fix(efficacy): CI runs the quality self-test, and 500 lines cost five times 100 Codex round 3 on the quality reader: - The CI loop runs quality.py's self-test, so the trace finds its output; trace.py's self-test checks the loop covers every module it reads. - Totals are matched with character references resolved, so ` ` and ` ` group thousands. - The 500 lines are SEE-5 at multiples of 6: zero-rated, priced per line, each net a whole 15.00, so the price is linear; the first 100 priced alone must cost a fifth of the 500-line total, within a cent. - Stand-in mode `capped` prices 100 lines while exporting 500; the preview writes its total with ` `. Refs #119. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- .github/workflows/self-tests.yml | 2 +- docs/coverage.md | 2 +- docs/requirements.md | 2 +- tests/efficacy/quality.py | 77 +++++++++++++++++++++++--------- tests/efficacy/trace.py | 17 +++++++ 5 files changed, 76 insertions(+), 24 deletions(-) diff --git a/.github/workflows/self-tests.yml b/.github/workflows/self-tests.yml index b440b5f..721db6c 100644 --- a/.github/workflows/self-tests.yml +++ b/.github/workflows/self-tests.yml @@ -76,7 +76,7 @@ jobs: outputs="$RUNNER_TEMP/self-tests" mkdir -p "$outputs" for module in harness generate_arm score judge report archive reuse \ - progress probes security control/control trace; do + progress probes security quality control/control trace; do echo "::group::$module" python "tests/efficacy/$module.py" --self-test \ | tee "$outputs/$(basename "$module").txt" diff --git a/docs/coverage.md b/docs/coverage.md index cad44d6..a96208a 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -208,7 +208,7 @@ when: | ID | Kind | Checked by | | -- | ---- | ---------- | -| FR-15-01 | Self-test | `quality.py` "a sound app passes every probe"
`quality.py` "an app answering 500 on bad input fails fuzz_robustness, and no other probe"
`quality.py` "an app raising out of the client fails fuzz_robustness, and no other probe"
`quality.py` "an app whose writes lock fails concurrent_writes, and no other probe"
`quality.py` "an app dropping an overlapping write fails concurrent_writes, and no other probe"
`quality.py` "the locked write is read as locked"
`quality.py` "an app refusing 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app that cannot show 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app keeping 100 of 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "a page showing a total other than the export's fails capacity_500_lines, and no other probe"
`quality.py` "an export with a null line fails capacity_500_lines, and no other probe"
`quality.py` "a page showing fewer rows but the whole total passes capacity_500_lines"
`quality.py` "a total grouped by thousands beside a currency sign is read"
`quality.py` "an app reading each line on its own fails n_plus_one, and no other probe"
`quality.py` "statements are counted per page, and did not grow"
`quality.py` "instances sharing their data fail coexistence, and no other probe"
`quality.py` "an app writing outside its folder fails coexistence, and no other probe"
`quality.py` "the stray file is named" | +| FR-15-01 | Self-test | `quality.py` "a sound app passes every probe"
`quality.py` "an app answering 500 on bad input fails fuzz_robustness, and no other probe"
`quality.py` "an app raising out of the client fails fuzz_robustness, and no other probe"
`quality.py` "an app whose writes lock fails concurrent_writes, and no other probe"
`quality.py` "an app dropping an overlapping write fails concurrent_writes, and no other probe"
`quality.py` "the locked write is read as locked"
`quality.py` "an app refusing 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app that cannot show 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app keeping 100 of 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "a page showing a total other than the export's fails capacity_500_lines, and no other probe"
`quality.py` "an export with a null line fails capacity_500_lines, and no other probe"
`quality.py` "a page showing fewer rows but the whole total passes capacity_500_lines"
`quality.py` "a total grouped by thousands beside a currency sign is read"
`quality.py` "a total grouped by no-break-space references, with a decimal comma, is read"
`quality.py` "a total over the first 100 of 500 exported lines fails capacity_500_lines, and no other probe"
`quality.py` "an app reading each line on its own fails n_plus_one, and no other probe"
`quality.py` "statements are counted per page, and did not grow"
`quality.py` "instances sharing their data fail coexistence, and no other probe"
`quality.py` "an app writing outside its folder fails coexistence, and no other probe"
`quality.py` "the stray file is named" | | FR-15-02 | Self-test | `quality.py` "a sound app signs in"
`quality.py` "a sign-in form quoted with single quotes signs in"
`quality.py` "an app answering 401 until signed in, and never signing in, loses every probe"
`quality.py` "an app answering 403 to a malformed request loses fuzz_robustness, and no other probe"
`quality.py` "an app that never keeps its sign-in loses every probe, passing none"
`quality.py` "an app answering a malformed request with the sign-in's redirect loses fuzz_robustness, and no other probe"
`quality.py` "the redirect is read as lost, not as an answer" | | FR-15-03 | Self-test | `quality.py` "an app that will not boot loses every probe"
`quality.py` "a trial that did not install loses every probe"
`quality.py` "no report from the probe is missing, not lost"
`quality.py` "a stalled run keeps what it read and loses the rest"
`quality.py` "a run that stalled booting loses every probe" | | 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" | diff --git a/docs/requirements.md b/docs/requirements.md index 4721be5..da32220 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -218,7 +218,7 @@ | ID | Requirement | Delivered by | | -- | ----------- | ------------ | -| FR-15-01 | The benchmark shall fail each of the fuzz, concurrent-write, 500-line, N+1 and co-existence probes on an app planted with the fault it guards against, and no other probe there, and pass every probe on an app built to pass them; the 500-line probe passes only where the JSON export lists all 500 lines in order, each a well-formed record, and the preview and the page each answer 2xx and show the invoice's total, which only every line gives, however it is grouped and whatever currency sign it carries. A page that paginates its rows but shows that total passes. | Quality reader | +| FR-15-01 | The benchmark shall fail each of the fuzz, concurrent-write, 500-line, N+1 and co-existence probes on an app planted with the fault it guards against, and no other probe there, and pass every probe on an app built to pass them; the 500-line probe passes only where the JSON export lists all 500 lines in order, each a well-formed record, and the preview and the page each answer 2xx and show the invoice's total, which only every line gives, however it is grouped, with its character references resolved, and whatever currency sign it carries; and its first 100 lines, priced alone, cost a fifth of it within a cent. A page that paginates its rows but shows that total passes. | Quality reader | | FR-15-02 | The benchmark shall read every quality probe signed in as the seeded administrator, through the sign-in form's hidden fields however they are quoted, the sign-in holding only where the dashboard then answers 200, and never measure a request the sign-in turns away with its redirect, a 401, or a 403 to a request that carried its token. | Quality reader | | FR-15-03 | The benchmark shall count as lost, reading failed, a quality probe the trial keeps from running, by not installing, not booting, not signing in or not finishing in time, and as missing one it could not run itself. | Quality reader | | FR-15-04 | The benchmark shall record the latency as two repeats of the 95th percentile over 30 requests to the main routes, with no pass threshold until one is calibrated. | Quality reader | diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index 3d6ae39..ca63260 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -71,7 +71,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, html, io, json, logging, math, os, platform, re, sqlite3 import sys, tempfile, threading, time from decimal import Decimal, InvalidOperation from html.parser import HTMLParser @@ -457,23 +457,37 @@ def exported(path, lines): # An amount as a page may write it: grouped by thousands with a comma, a -# point, a space or an apostrophe, and two decimals after a point or a comma. +# point, a space, a no-break or narrow no-break space, or an apostrophe, and +# two decimals after a point or a comma. The page is read with its character +# references resolved, so ` ` and ` ` group as the characters do. AMOUNT = re.compile(r"(?%s

Total %s

" % ("".join( @@ -1346,7 +1374,8 @@ def create_app(database): "cramped": "capacity_500_lines", "crowded": "capacity_500_lines", "truncating": "capacity_500_lines", "miscounting": "capacity_500_lines", - "nulling": "capacity_500_lines", "bouncing": "fuzz_robustness", + "nulling": "capacity_500_lines", "capped": "capacity_500_lines", + "bouncing": "fuzz_robustness", "forbidding": "fuzz_robustness", "chatty": "n_plus_one", "shared": "coexistence", "stray": "coexistence"} @@ -1392,6 +1421,10 @@ def runtime_self_checks(scratch): ("a total grouped by thousands beside a currency sign is read", sound["capacity_500_lines"].get("passed") is True and "€" in FAKE_APP and 'format(int(whole), ",")' in FAKE_APP), + ("a total grouped by no-break-space references, with a decimal " + "comma, is read", + sound["capacity_500_lines"].get("kept", {}).get("preview") is True + and " " in FAKE_APP), ("a page showing fewer rows but the whole total passes " "capacity_500_lines", failing(probes["paginating"]) == []), ("the latency is two repeats of 30 requests each", @@ -1426,6 +1459,8 @@ def runtime_self_checks(scratch): "miscounting": "a page showing a total other than the export's " "fails capacity_500_lines", "nulling": "an export with a null line fails capacity_500_lines", + "capped": "a total over the first 100 of 500 exported lines fails " + "capacity_500_lines", "chatty": "an app reading each line on its own fails n_plus_one", "shared": "instances sharing their data fail coexistence", "stray": "an app writing outside its folder fails coexistence", diff --git a/tests/efficacy/trace.py b/tests/efficacy/trace.py index 46f76e5..0c3a140 100644 --- a/tests/efficacy/trace.py +++ b/tests/efficacy/trace.py @@ -26,6 +26,7 @@ REQUIREMENTS = os.path.join(ROOT, "docs", "requirements.md") COVERAGE = os.path.join(ROOT, "docs", "coverage.md") +WORKFLOW = os.path.join(ROOT, ".github", "workflows", "self-tests.yml") # Every module with a self-test, by its path under tests/efficacy/. A label # is looked up only in the output of the module its row names. @@ -179,6 +180,15 @@ def trace(requirements, coverage, outputs): return problems, counts +def workflow_modules(text): + """The modules a workflow's self-test loop runs, as paths under + tests/efficacy/.""" + loop = re.search(r"for module in (.*?); do", text, re.DOTALL) + if not loop: + return set() + return {word + ".py" for word in loop.group(1).replace("\\", " ").split()} + + def run_self_tests(): """Each module's self-test output, by module, running each in turn.""" outputs = {} @@ -242,7 +252,14 @@ def one(*covering): return len(problems_of(*covering, *good[len(covering):])) == 1 found, counts = trace(document(*stated), document(*good), outputs) + + # CI saves each module's output for the trace to read; a module its loop + # leaves out has no output there, and every label it prints goes unseen. + with io.open(WORKFLOW, encoding="utf-8") as handle: + unrun = sorted(set(MODULES) - workflow_modules(handle.read())) checks = [ + ("the CI workflow runs every module the trace reads", unrun == [], + unrun), ("every rule accounted for passes", found == [], found), ("each kind of row is counted", counts == {"Self-test": 2, "Untestable": 1, "Missing": 1}, counts), From 75b34fe5afa5976d5dc2a687a485985a9faeeeac Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:36:07 +0200 Subject: [PATCH 05/17] fix(efficacy): a post carries its own form's token, and a NaN total fails Codex round 4 on the quality reader: - Hidden fields are read per form: a post carries the fields of the first form whose action resolves to its path, else the page's first of each name; `formaction` is not read, by design. - An export total that is not a finite amount, NaN or Infinity, fails the 500-line probe as malformed output, never reads missing. - Stand-in pages carry a sign-out form with another token, before the main form on the products page and after it elsewhere; mode `unpriced` exports its total as NaN. Refs #119. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 4 +- docs/requirements.md | 4 +- tests/efficacy/quality.py | 101 +++++++++++++++++++++++++++++++------- 3 files changed, 86 insertions(+), 23 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index a96208a..21983b6 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -208,8 +208,8 @@ when: | ID | Kind | Checked by | | -- | ---- | ---------- | -| FR-15-01 | Self-test | `quality.py` "a sound app passes every probe"
`quality.py` "an app answering 500 on bad input fails fuzz_robustness, and no other probe"
`quality.py` "an app raising out of the client fails fuzz_robustness, and no other probe"
`quality.py` "an app whose writes lock fails concurrent_writes, and no other probe"
`quality.py` "an app dropping an overlapping write fails concurrent_writes, and no other probe"
`quality.py` "the locked write is read as locked"
`quality.py` "an app refusing 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app that cannot show 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app keeping 100 of 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "a page showing a total other than the export's fails capacity_500_lines, and no other probe"
`quality.py` "an export with a null line fails capacity_500_lines, and no other probe"
`quality.py` "a page showing fewer rows but the whole total passes capacity_500_lines"
`quality.py` "a total grouped by thousands beside a currency sign is read"
`quality.py` "a total grouped by no-break-space references, with a decimal comma, is read"
`quality.py` "a total over the first 100 of 500 exported lines fails capacity_500_lines, and no other probe"
`quality.py` "an app reading each line on its own fails n_plus_one, and no other probe"
`quality.py` "statements are counted per page, and did not grow"
`quality.py` "instances sharing their data fail coexistence, and no other probe"
`quality.py` "an app writing outside its folder fails coexistence, and no other probe"
`quality.py` "the stray file is named" | -| FR-15-02 | Self-test | `quality.py` "a sound app signs in"
`quality.py` "a sign-in form quoted with single quotes signs in"
`quality.py` "an app answering 401 until signed in, and never signing in, loses every probe"
`quality.py` "an app answering 403 to a malformed request loses fuzz_robustness, and no other probe"
`quality.py` "an app that never keeps its sign-in loses every probe, passing none"
`quality.py` "an app answering a malformed request with the sign-in's redirect loses fuzz_robustness, and no other probe"
`quality.py` "the redirect is read as lost, not as an answer" | +| FR-15-01 | Self-test | `quality.py` "a sound app passes every probe"
`quality.py` "an app answering 500 on bad input fails fuzz_robustness, and no other probe"
`quality.py` "an app raising out of the client fails fuzz_robustness, and no other probe"
`quality.py` "an app whose writes lock fails concurrent_writes, and no other probe"
`quality.py` "an app dropping an overlapping write fails concurrent_writes, and no other probe"
`quality.py` "the locked write is read as locked"
`quality.py` "an app refusing 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app that cannot show 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app keeping 100 of 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "a page showing a total other than the export's fails capacity_500_lines, and no other probe"
`quality.py` "an export with a null line fails capacity_500_lines, and no other probe"
`quality.py` "an export whose total is NaN fails capacity_500_lines, and no other probe"
`quality.py` "a page showing fewer rows but the whole total passes capacity_500_lines"
`quality.py` "a total grouped by thousands beside a currency sign is read"
`quality.py` "a total grouped by no-break-space references, with a decimal comma, is read"
`quality.py` "a total over the first 100 of 500 exported lines fails capacity_500_lines, and no other probe"
`quality.py` "an app reading each line on its own fails n_plus_one, and no other probe"
`quality.py` "statements are counted per page, and did not grow"
`quality.py` "instances sharing their data fail coexistence, and no other probe"
`quality.py` "an app writing outside its folder fails coexistence, and no other probe"
`quality.py` "the stray file is named" | +| FR-15-02 | Self-test | `quality.py` "a sound app signs in"
`quality.py` "a sign-in form quoted with single quotes signs in"
`quality.py` "a form's own token is posted, not one from a form before it"
`quality.py` "a post no form's action names carries the page's first token"
`quality.py` "an app answering 401 until signed in, and never signing in, loses every probe"
`quality.py` "an app answering 403 to a malformed request loses fuzz_robustness, and no other probe"
`quality.py` "an app that never keeps its sign-in loses every probe, passing none"
`quality.py` "an app answering a malformed request with the sign-in's redirect loses fuzz_robustness, and no other probe"
`quality.py` "the redirect is read as lost, not as an answer" | | FR-15-03 | Self-test | `quality.py` "an app that will not boot loses every probe"
`quality.py` "a trial that did not install loses every probe"
`quality.py` "no report from the probe is missing, not lost"
`quality.py` "a stalled run keeps what it read and loses the rest"
`quality.py` "a run that stalled booting loses every probe" | | 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" | diff --git a/docs/requirements.md b/docs/requirements.md index da32220..cd82648 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -218,8 +218,8 @@ | ID | Requirement | Delivered by | | -- | ----------- | ------------ | -| FR-15-01 | The benchmark shall fail each of the fuzz, concurrent-write, 500-line, N+1 and co-existence probes on an app planted with the fault it guards against, and no other probe there, and pass every probe on an app built to pass them; the 500-line probe passes only where the JSON export lists all 500 lines in order, each a well-formed record, and the preview and the page each answer 2xx and show the invoice's total, which only every line gives, however it is grouped, with its character references resolved, and whatever currency sign it carries; and its first 100 lines, priced alone, cost a fifth of it within a cent. A page that paginates its rows but shows that total passes. | Quality reader | -| FR-15-02 | The benchmark shall read every quality probe signed in as the seeded administrator, through the sign-in form's hidden fields however they are quoted, the sign-in holding only where the dashboard then answers 200, and never measure a request the sign-in turns away with its redirect, a 401, or a 403 to a request that carried its token. | Quality reader | +| FR-15-01 | The benchmark shall fail each of the fuzz, concurrent-write, 500-line, N+1 and co-existence probes on an app planted with the fault it guards against, and no other probe there, and pass every probe on an app built to pass them; the 500-line probe passes only where the JSON export lists all 500 lines in order, each a well-formed record, with a finite total, and the preview and the page each answer 2xx and show the invoice's total, which only every line gives, however it is grouped, with its character references resolved, and whatever currency sign it carries; and its first 100 lines, priced alone, cost a fifth of it within a cent. A page that paginates its rows but shows that total passes. | Quality reader | +| FR-15-02 | The benchmark shall read every quality probe signed in as the seeded administrator, through the sign-in form's hidden fields however they are quoted, each post carrying the hidden fields of the form whose action it is sent to, or else the page's first of each name, the sign-in holding only where the dashboard then answers 200, and never measure a request the sign-in turns away with its redirect, a 401, or a 403 to a request that carried its token. | Quality reader | | FR-15-03 | The benchmark shall count as lost, reading failed, a quality probe the trial keeps from running, by not installing, not booting, not signing in or not finishing in time, and as missing one it could not run itself. | Quality reader | | FR-15-04 | The benchmark shall record the latency as two repeats of the 95th percentile over 30 requests to the main routes, with no pass threshold until one is calibrated. | Quality reader | | 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 | diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index ca63260..fb66666 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -75,7 +75,7 @@ import sys, tempfile, threading, time from decimal import Decimal, InvalidOperation from html.parser import HTMLParser -from urllib.parse import urlsplit +from urllib.parse import urljoin, urlsplit PACKAGE = "tariff" USERNAME = "admin" @@ -217,24 +217,55 @@ class Raised(Exception): class Hidden(HTMLParser): - """Collects every hidden input, however its attributes are quoted.""" + """Collects every hidden input, however its attributes are quoted, in + page order, with the action of the form it sits in.""" def __init__(self): HTMLParser.__init__(self) - self.fields = {} + self.inputs = [] + self.forms = [] + self.form = None def handle_starttag(self, tag, attrs): attributes = dict(attrs) - if (tag == "input" and (attributes.get("type") or "").lower() + if tag == "form": + self.form = len(self.forms) + self.forms.append(attributes.get("action") or "") + elif (tag == "input" and (attributes.get("type") or "").lower() == "hidden" and attributes.get("name")): - self.fields[attributes["name"]] = attributes.get("value") or "" - - -def hidden_fields(text): - """Every hidden input in the page, which is where a CSRF token hides.""" + self.inputs.append((self.form, attributes["name"], + attributes.get("value") or "")) + + def handle_endtag(self, tag): + if tag == "form": + self.form = None + + +# A page may hold several forms, each with its own token, such as a sign-out +# form beside the one being sent. The fields sent are those of the first form +# whose action is the path posted to, read as the browser resolves it, its +# query ignored, an empty action being the page's own path. A post no form's +# action names takes every hidden field on the page, the first of each name. +# A save control's `formaction` is not read: the builder's save is sent with +# the builder form's fields by that fallback, which is how a browser sends it. +def hidden_fields(text, page_path, target): + """The hidden fields a post to `target` carries from the page at + `page_path`.""" parser = Hidden() parser.feed(text) - return parser.fields + base = "http://localhost" + page_path + wanted = urlsplit(target).path + for form, action in enumerate(parser.forms): + if urlsplit(urljoin(base, action or page_path)).path == wanted: + fields = {} + for owner, name, value in parser.inputs: + if owner == form: + fields.setdefault(name, value) + return fields + fields = {} + for _, name, value in parser.inputs: + fields.setdefault(name, value) + return fields # A request the sign-in turns away: its redirect, a 401, or a 403 to a @@ -272,7 +303,8 @@ def form_post(who, form, path, body, method="POST", headers=None): afresh, since a token may change between answers.""" data = dict(body) for name, value in hidden_fields( - ask(who, "GET", form).get_data(as_text=True)).items(): + ask(who, "GET", form).get_data(as_text=True), form, + path).items(): data.setdefault(name, value) return ask(who, method, path, data=data, headers=headers) @@ -374,8 +406,8 @@ def timed(method, path): if method == "POST": data = builder_body(WORKED, "WELCOME") data.update({name: value for name, value in hidden_fields( - page(client, "/invoices/new").get_data(as_text=True)).items() - if name not in data}) + page(client, "/invoices/new").get_data(as_text=True), + "/invoices/new", path).items() if name not in data}) headers = {"HX-Request": "true"} start = time.perf_counter() answer = ask(client, method, path, data=data, headers=headers) @@ -450,10 +482,16 @@ def exported(path, lines): if [(line["sku"], line["quantity"]) for line in records] != lines: return None, ("the export holds %d lines, not the %d saved in order" % (len(records), len(lines))) + # A total that is no finite amount, NaN or Infinity among them, is the + # build's malformed output, so it fails rather than goes unread. try: - return Decimal(str(export.get("total"))), None + total = Decimal(str(export.get("total"))) except InvalidOperation: - return None, "the export's total is not a number" + total = None + if total is None or not total.is_finite(): + return None, ("the export's total, %r, is not a finite amount" + % (export.get("total"),)) + return total, None # An amount as a page may write it: grouped by thousands with a comma, a @@ -1062,7 +1100,8 @@ def read_trial(area, name, scores_file, other): # outside its folder, `truncating` keeps the first 100 lines of an invoice, # answering as if it kept them all, `miscounting` shows a total of 100 of # them, `nulling` exports one line as null, and `capped` prices the first -# 100 lines alone wherever it prices them, while it keeps and exports all. +# 100 lines alone wherever it prices them, while it keeps and exports all; +# `unpriced` exports its total as NaN. # `paginating` shows 100 rows and the whole total, which is no fault. Pages # write amounts grouped by thousands beside the euro's sign, the preview's # with ` `. `bouncing` answers a price it cannot parse with the @@ -1084,6 +1123,19 @@ def read_trial(area, name, scores_file, other): MODE = "__MODE__" TOKEN = '' SIGN_IN = "" +SIGN_OUT = ('') + + +def form_page(path, body): + """A page whose main form posts to its own route, the builder's to its + preview, with a sign-out form carrying another token beside it: before + the main form on the products page, after it everywhere else.""" + action = "/invoices/preview" if path == "/invoices/new" else path + main = '
%s
' % (action, TOKEN) + if path == "/products": + return SIGN_OUT + body + main + return body + main + SIGN_OUT SKUS = {"WID-1": "10.00", "GAD-2": "24.50", "BOK-3": "12.00", "SRV-4": "80.00", "SEE-5": "3.75"} LOG = logging.getLogger("tariff") @@ -1253,7 +1305,7 @@ def dispatch(self, path, method, data): parts = path.strip("/").split("/") if method == "GET" and path in pages: listing = " ".join(self.app.skus()) if path == "/products" else "" - return Response(200, "

%s

%s" % (listing, TOKEN)) + return Response(200, form_page(path, "

%s

" % listing)) if method == "POST" and (path in posts or path.endswith("/delete") or path.endswith("/erase")): if data.get("csrf_token") != "t": @@ -1356,8 +1408,9 @@ def show(self, parts): for sku, _, quantity in rows] if MODE == "nulling" and len(records) > 100: records[100] = None - return Response(200, json.dumps({"lines": records, - "total": total})) + return Response(200, json.dumps({ + "lines": records, + "total": "NaN" if MODE == "unpriced" else total})) return Response(200, shown) @@ -1375,6 +1428,7 @@ def create_app(database): "truncating": "capacity_500_lines", "miscounting": "capacity_500_lines", "nulling": "capacity_500_lines", "capped": "capacity_500_lines", + "unpriced": "capacity_500_lines", "bouncing": "fuzz_robustness", "forbidding": "fuzz_robustness", "chatty": "n_plus_one", "shared": "coexistence", "stray": "coexistence"} @@ -1418,6 +1472,14 @@ def runtime_self_checks(scratch): (readings["sound"][0] or {}).get("signed_in") is True and "type='hidden'" in FAKE_APP), ("a sound app passes every probe", failing(sound) == []), + ("a form's own token is posted, not one from a form before it", + sound["concurrent_writes"].get("passed") is True + and sound["coexistence"].get("passed") is True + and "return SIGN_OUT + body + main" in FAKE_APP), + ("a post no form's action names carries the page's first token", + sound["n_plus_one"].get("passed") is True + and sound["capacity_500_lines"].get("passed") is True + and "return body + main + SIGN_OUT" in FAKE_APP), ("a total grouped by thousands beside a currency sign is read", sound["capacity_500_lines"].get("passed") is True and "€" in FAKE_APP and 'format(int(whole), ",")' in FAKE_APP), @@ -1459,6 +1521,7 @@ def runtime_self_checks(scratch): "miscounting": "a page showing a total other than the export's " "fails capacity_500_lines", "nulling": "an export with a null line fails capacity_500_lines", + "unpriced": "an export whose total is NaN fails capacity_500_lines", "capped": "a total over the first 100 of 500 exported lines fails " "capacity_500_lines", "chatty": "an app reading each line on its own fails n_plus_one", From 504a0f1b6b7172a4e8a9e529f58a2cdfe319193a Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:16:37 +0200 Subject: [PATCH 06/17] fix(efficacy): a file URI names its own database, and a zero total fails Codex round 5 on the quality reader: - A database opened by a `file:` URI is read back to the path it names, its query dropped, its escapes undone, `/C:/...` read as a drive, so an isolated build no longer reads as writing outside its folder. - The 500-line total must be positive before it is scaled: every line is a Seed pack at six or more, which costs more than nothing. - Stand-in modes open their databases by URI with `?mode=rwc`; mode `free` prices every line at nothing while exporting all 500. Refs #119. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 2 +- docs/requirements.md | 2 +- tests/efficacy/quality.py | 55 +++++++++++++++++++++++++++++++-------- 3 files changed, 46 insertions(+), 13 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index 21983b6..b8f1668 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -208,7 +208,7 @@ when: | ID | Kind | Checked by | | -- | ---- | ---------- | -| FR-15-01 | Self-test | `quality.py` "a sound app passes every probe"
`quality.py` "an app answering 500 on bad input fails fuzz_robustness, and no other probe"
`quality.py` "an app raising out of the client fails fuzz_robustness, and no other probe"
`quality.py` "an app whose writes lock fails concurrent_writes, and no other probe"
`quality.py` "an app dropping an overlapping write fails concurrent_writes, and no other probe"
`quality.py` "the locked write is read as locked"
`quality.py` "an app refusing 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app that cannot show 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app keeping 100 of 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "a page showing a total other than the export's fails capacity_500_lines, and no other probe"
`quality.py` "an export with a null line fails capacity_500_lines, and no other probe"
`quality.py` "an export whose total is NaN fails capacity_500_lines, and no other probe"
`quality.py` "a page showing fewer rows but the whole total passes capacity_500_lines"
`quality.py` "a total grouped by thousands beside a currency sign is read"
`quality.py` "a total grouped by no-break-space references, with a decimal comma, is read"
`quality.py` "a total over the first 100 of 500 exported lines fails capacity_500_lines, and no other probe"
`quality.py` "an app reading each line on its own fails n_plus_one, and no other probe"
`quality.py` "statements are counted per page, and did not grow"
`quality.py` "instances sharing their data fail coexistence, and no other probe"
`quality.py` "an app writing outside its folder fails coexistence, and no other probe"
`quality.py` "the stray file is named" | +| FR-15-01 | Self-test | `quality.py` "a sound app passes every probe"
`quality.py` "an app answering 500 on bad input fails fuzz_robustness, and no other probe"
`quality.py` "an app raising out of the client fails fuzz_robustness, and no other probe"
`quality.py` "an app whose writes lock fails concurrent_writes, and no other probe"
`quality.py` "an app dropping an overlapping write fails concurrent_writes, and no other probe"
`quality.py` "the locked write is read as locked"
`quality.py` "an app refusing 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app that cannot show 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app keeping 100 of 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "a page showing a total other than the export's fails capacity_500_lines, and no other probe"
`quality.py` "an export with a null line fails capacity_500_lines, and no other probe"
`quality.py` "an export whose total is NaN fails capacity_500_lines, and no other probe"
`quality.py` "an app pricing every line at nothing fails capacity_500_lines, and no other probe"
`quality.py` "a database opened by a file URI with a query stays in its folder"
`quality.py` "a page showing fewer rows but the whole total passes capacity_500_lines"
`quality.py` "a total grouped by thousands beside a currency sign is read"
`quality.py` "a total grouped by no-break-space references, with a decimal comma, is read"
`quality.py` "a total over the first 100 of 500 exported lines fails capacity_500_lines, and no other probe"
`quality.py` "an app reading each line on its own fails n_plus_one, and no other probe"
`quality.py` "statements are counted per page, and did not grow"
`quality.py` "instances sharing their data fail coexistence, and no other probe"
`quality.py` "an app writing outside its folder fails coexistence, and no other probe"
`quality.py` "the stray file is named" | | FR-15-02 | Self-test | `quality.py` "a sound app signs in"
`quality.py` "a sign-in form quoted with single quotes signs in"
`quality.py` "a form's own token is posted, not one from a form before it"
`quality.py` "a post no form's action names carries the page's first token"
`quality.py` "an app answering 401 until signed in, and never signing in, loses every probe"
`quality.py` "an app answering 403 to a malformed request loses fuzz_robustness, and no other probe"
`quality.py` "an app that never keeps its sign-in loses every probe, passing none"
`quality.py` "an app answering a malformed request with the sign-in's redirect loses fuzz_robustness, and no other probe"
`quality.py` "the redirect is read as lost, not as an answer" | | FR-15-03 | Self-test | `quality.py` "an app that will not boot loses every probe"
`quality.py` "a trial that did not install loses every probe"
`quality.py` "no report from the probe is missing, not lost"
`quality.py` "a stalled run keeps what it read and loses the rest"
`quality.py` "a run that stalled booting loses every probe" | | 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" | diff --git a/docs/requirements.md b/docs/requirements.md index cd82648..25ee8ca 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -218,7 +218,7 @@ | ID | Requirement | Delivered by | | -- | ----------- | ------------ | -| FR-15-01 | The benchmark shall fail each of the fuzz, concurrent-write, 500-line, N+1 and co-existence probes on an app planted with the fault it guards against, and no other probe there, and pass every probe on an app built to pass them; the 500-line probe passes only where the JSON export lists all 500 lines in order, each a well-formed record, with a finite total, and the preview and the page each answer 2xx and show the invoice's total, which only every line gives, however it is grouped, with its character references resolved, and whatever currency sign it carries; and its first 100 lines, priced alone, cost a fifth of it within a cent. A page that paginates its rows but shows that total passes. | Quality reader | +| FR-15-01 | The benchmark shall fail each of the fuzz, concurrent-write, 500-line, N+1 and co-existence probes on an app planted with the fault it guards against, and no other probe there, and pass every probe on an app built to pass them; the 500-line probe passes only where the JSON export lists all 500 lines in order, each a well-formed record, with a finite total, and the preview and the page each answer 2xx and show the invoice's total, which only every line gives, however it is grouped, with its character references resolved, and whatever currency sign it carries; and that total is positive and its first 100 lines, priced alone, cost a fifth of it within a cent; and the co-existence probe reads a database opened by a `file:` URI as the file it names. A page that paginates its rows but shows that total passes. | Quality reader | | FR-15-02 | The benchmark shall read every quality probe signed in as the seeded administrator, through the sign-in form's hidden fields however they are quoted, each post carrying the hidden fields of the form whose action it is sent to, or else the page's first of each name, the sign-in holding only where the dashboard then answers 200, and never measure a request the sign-in turns away with its redirect, a 401, or a 403 to a request that carried its token. | Quality reader | | FR-15-03 | The benchmark shall count as lost, reading failed, a quality probe the trial keeps from running, by not installing, not booting, not signing in or not finishing in time, and as missing one it could not run itself. | Quality reader | | FR-15-04 | The benchmark shall record the latency as two repeats of the 95th percentile over 30 requests to the main routes, with no pass threshold until one is calibrated. | Quality reader | diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index fb66666..9dde650 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -76,6 +76,7 @@ from decimal import Decimal, InvalidOperation from html.parser import HTMLParser from urllib.parse import urljoin, urlsplit +from urllib.request import url2pathname PACKAGE = "tariff" USERNAME = "admin" @@ -132,6 +133,24 @@ def note(path): real_connect = sqlite3.connect +# A database named by a `file:` URI, as `Path.as_uri()` writes one with +# `uri=True`, is read back to the path it names: its query, such as +# `?mode=rwc`, dropped, its escapes undone, and `/C:/...` read as a drive. +def database_file(target): + """The file a connection opens, or None for a database in memory.""" + if target.startswith("file:"): + parts = urlsplit(target) + if "mode=memory" in parts.query: + return None + path = parts.path + if parts.netloc and parts.netloc != "localhost": + path = "//" + parts.netloc + path + target = url2pathname(path) if path else "" + if target in ("", ":memory:"): + return None + return target + + def connect(*args, **kwargs): connection = real_connect(*args, **kwargs) try: @@ -139,14 +158,10 @@ def connect(*args, **kwargs): except Exception: pass target = args[0] if args else kwargs.get("database") - if isinstance(target, (str, os.PathLike)): - target = os.fspath(target) - if "mode=memory" in target: - target = "" - if target.startswith("file:"): - target = urlsplit(target).path - if target and target != ":memory:": - note(target) + if isinstance(target, (str, bytes, os.PathLike)): + path = database_file(os.fsdecode(target)) + if path: + note(path) return connection @@ -569,6 +584,13 @@ def capacity_500_lines(): # The total the export states is the build's own, so a calculation that # reads only the first 100 lines would agree with itself everywhere. The # first 100 lines priced alone must cost a fifth of it. + # Every line is a Seed pack at a quantity of six or more, which costs + # more than nothing under the seed's rules, so the invoice's total is + # positive; a total of nothing scales with any count of lines. + if total <= 0: + return passed(False, steps=steps, kept=kept, total=str(total), + reason="500 lines that each cost more than nothing " + "were priced at %s" % total) share = total * SAMPLE / len(lines) kept["scales"] = shows_total(sample, share, CENT_PER_SAMPLE) return passed(all(kept.values()), steps=steps, kept=kept, @@ -1101,7 +1123,8 @@ def read_trial(area, name, scores_file, other): # answering as if it kept them all, `miscounting` shows a total of 100 of # them, `nulling` exports one line as null, and `capped` prices the first # 100 lines alone wherever it prices them, while it keeps and exports all; -# `unpriced` exports its total as NaN. +# `unpriced` exports its total as NaN, and `free` prices every line at +# nothing. Every mode opens its database by a `file:` URI with a query. # `paginating` shows 100 rows and the whole total, which is no fault. Pages # write amounts grouped by thousands beside the euro's sign, the preview's # with ` `. `bouncing` answers a price it cannot parse with the @@ -1114,6 +1137,7 @@ def read_trial(area, name, scores_file, other): import json import logging import os +import pathlib import sqlite3 import sys import tempfile @@ -1162,6 +1186,8 @@ def listed(value): def summed(rows): + if MODE == "free": + rows = [] total = sum((decimal.Decimal(price) * quantity for _, price, quantity in rows), decimal.Decimal("0")) return str(total.quantize(decimal.Decimal("0.01"))) @@ -1219,7 +1245,8 @@ def __init__(self, database): self.config = {} def connect(self, wait=10.0): - return sqlite3.connect(self.database, timeout=wait) + uri = pathlib.Path(self.database).as_uri() + "?mode=rwc" + return sqlite3.connect(uri, uri=True, timeout=wait) def test_client(self): return Client(self) @@ -1428,7 +1455,7 @@ def create_app(database): "truncating": "capacity_500_lines", "miscounting": "capacity_500_lines", "nulling": "capacity_500_lines", "capped": "capacity_500_lines", - "unpriced": "capacity_500_lines", + "unpriced": "capacity_500_lines", "free": "capacity_500_lines", "bouncing": "fuzz_robustness", "forbidding": "fuzz_robustness", "chatty": "n_plus_one", "shared": "coexistence", "stray": "coexistence"} @@ -1472,6 +1499,10 @@ def runtime_self_checks(scratch): (readings["sound"][0] or {}).get("signed_in") is True and "type='hidden'" in FAKE_APP), ("a sound app passes every probe", failing(sound) == []), + ("a database opened by a file URI with a query stays in its folder", + sound["coexistence"].get("passed") is True + and sound["coexistence"].get("stray") == [] + and '.as_uri() + "?mode=rwc"' in FAKE_APP), ("a form's own token is posted, not one from a form before it", sound["concurrent_writes"].get("passed") is True and sound["coexistence"].get("passed") is True @@ -1522,6 +1553,8 @@ def runtime_self_checks(scratch): "fails capacity_500_lines", "nulling": "an export with a null line fails capacity_500_lines", "unpriced": "an export whose total is NaN fails capacity_500_lines", + "free": "an app pricing every line at nothing fails " + "capacity_500_lines", "capped": "a total over the first 100 of 500 exported lines fails " "capacity_500_lines", "chatty": "an app reading each line on its own fails n_plus_one", From 93a0609f93f9d8b3933038eb5ff7632966661a26 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:50:05 +0200 Subject: [PATCH 07/17] fix(efficacy): capacity reads exports only; concurrent writes run last Codex round 6 on the quality reader: - Capacity reads no amount from HTML: the 500-line invoice previews, saves and renders 2xx; its export lists every line with a finite, positive total; a 100-line invoice of its first lines, saved alone, exports a fifth of that total within a cent. - The separator parser and the page-total stand-ins go. - Concurrent writes run last, on a fresh instance of their own: a writer the build hangs fails them and stops the run, every reading before it kept; no product fuzzing stored reaches them. - Stand-in modes `hanging` and `poisoned`; the self-test waits 5 s for a writer. Refs #119. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 2 +- docs/requirements.md | 2 +- tests/efficacy/quality.py | 228 ++++++++++++++++++++------------------ 3 files changed, 122 insertions(+), 110 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index b8f1668..d404d73 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -208,7 +208,7 @@ when: | ID | Kind | Checked by | | -- | ---- | ---------- | -| FR-15-01 | Self-test | `quality.py` "a sound app passes every probe"
`quality.py` "an app answering 500 on bad input fails fuzz_robustness, and no other probe"
`quality.py` "an app raising out of the client fails fuzz_robustness, and no other probe"
`quality.py` "an app whose writes lock fails concurrent_writes, and no other probe"
`quality.py` "an app dropping an overlapping write fails concurrent_writes, and no other probe"
`quality.py` "the locked write is read as locked"
`quality.py` "an app refusing 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app that cannot show 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app keeping 100 of 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "a page showing a total other than the export's fails capacity_500_lines, and no other probe"
`quality.py` "an export with a null line fails capacity_500_lines, and no other probe"
`quality.py` "an export whose total is NaN fails capacity_500_lines, and no other probe"
`quality.py` "an app pricing every line at nothing fails capacity_500_lines, and no other probe"
`quality.py` "a database opened by a file URI with a query stays in its folder"
`quality.py` "a page showing fewer rows but the whole total passes capacity_500_lines"
`quality.py` "a total grouped by thousands beside a currency sign is read"
`quality.py` "a total grouped by no-break-space references, with a decimal comma, is read"
`quality.py` "a total over the first 100 of 500 exported lines fails capacity_500_lines, and no other probe"
`quality.py` "an app reading each line on its own fails n_plus_one, and no other probe"
`quality.py` "statements are counted per page, and did not grow"
`quality.py` "instances sharing their data fail coexistence, and no other probe"
`quality.py` "an app writing outside its folder fails coexistence, and no other probe"
`quality.py` "the stray file is named" | +| FR-15-01 | Self-test | `quality.py` "a sound app passes every probe"
`quality.py` "an app answering 500 on bad input fails fuzz_robustness, and no other probe"
`quality.py` "an app raising out of the client fails fuzz_robustness, and no other probe"
`quality.py` "an app whose writes lock fails concurrent_writes, and no other probe"
`quality.py` "an app dropping an overlapping write fails concurrent_writes, and no other probe"
`quality.py` "the locked write is read as locked"
`quality.py` "a writer the app hangs fails concurrent_writes, and no other probe"
`quality.py` "a hung writer stops the run, every reading before it kept"
`quality.py` "a product a malformed request stored does not reach the concurrent writes"
`quality.py` "an app refusing 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app that cannot show 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app keeping 100 of 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an export with a null line fails capacity_500_lines, and no other probe"
`quality.py` "an export whose total is NaN fails capacity_500_lines, and no other probe"
`quality.py` "an app pricing every line at nothing fails capacity_500_lines, and no other probe"
`quality.py` "a database opened by a file URI with a query stays in its folder"
`quality.py` "a total over the first 100 of 500 exported lines fails capacity_500_lines, and no other probe"
`quality.py` "an app reading each line on its own fails n_plus_one, and no other probe"
`quality.py` "statements are counted per page, and did not grow"
`quality.py` "instances sharing their data fail coexistence, and no other probe"
`quality.py` "an app writing outside its folder fails coexistence, and no other probe"
`quality.py` "the stray file is named" | | FR-15-02 | Self-test | `quality.py` "a sound app signs in"
`quality.py` "a sign-in form quoted with single quotes signs in"
`quality.py` "a form's own token is posted, not one from a form before it"
`quality.py` "a post no form's action names carries the page's first token"
`quality.py` "an app answering 401 until signed in, and never signing in, loses every probe"
`quality.py` "an app answering 403 to a malformed request loses fuzz_robustness, and no other probe"
`quality.py` "an app that never keeps its sign-in loses every probe, passing none"
`quality.py` "an app answering a malformed request with the sign-in's redirect loses fuzz_robustness, and no other probe"
`quality.py` "the redirect is read as lost, not as an answer" | | FR-15-03 | Self-test | `quality.py` "an app that will not boot loses every probe"
`quality.py` "a trial that did not install loses every probe"
`quality.py` "no report from the probe is missing, not lost"
`quality.py` "a stalled run keeps what it read and loses the rest"
`quality.py` "a run that stalled booting loses every probe" | | 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" | diff --git a/docs/requirements.md b/docs/requirements.md index 25ee8ca..574486b 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -218,7 +218,7 @@ | ID | Requirement | Delivered by | | -- | ----------- | ------------ | -| FR-15-01 | The benchmark shall fail each of the fuzz, concurrent-write, 500-line, N+1 and co-existence probes on an app planted with the fault it guards against, and no other probe there, and pass every probe on an app built to pass them; the 500-line probe passes only where the JSON export lists all 500 lines in order, each a well-formed record, with a finite total, and the preview and the page each answer 2xx and show the invoice's total, which only every line gives, however it is grouped, with its character references resolved, and whatever currency sign it carries; and that total is positive and its first 100 lines, priced alone, cost a fifth of it within a cent; and the co-existence probe reads a database opened by a `file:` URI as the file it names. A page that paginates its rows but shows that total passes. | Quality reader | +| FR-15-01 | The benchmark shall fail each of the fuzz, concurrent-write, 500-line, N+1 and co-existence probes on an app planted with the fault it guards against, and no other probe there, and pass every probe on an app built to pass them; the 500-line probe passes only where the invoice previews 2xx, saves and renders 2xx, its JSON export lists all 500 lines in order, each a well-formed record, with a finite, positive total, and its first 100 lines, saved alone, export a total a fifth of it within a cent; pages are read for answering, never for the amounts they show; the co-existence probe reads a database opened by a `file:` URI as the file it names; and the concurrent writes run last, on a fresh instance of their own, a writer the app hangs failing them and stopping the run there, every reading before it kept. | Quality reader | | FR-15-02 | The benchmark shall read every quality probe signed in as the seeded administrator, through the sign-in form's hidden fields however they are quoted, each post carrying the hidden fields of the form whose action it is sent to, or else the page's first of each name, the sign-in holding only where the dashboard then answers 200, and never measure a request the sign-in turns away with its redirect, a 401, or a 403 to a request that carried its token. | Quality reader | | FR-15-03 | The benchmark shall count as lost, reading failed, a quality probe the trial keeps from running, by not installing, not booting, not signing in or not finishing in time, and as missing one it could not run itself. | Quality reader | | FR-15-04 | The benchmark shall record the latency as two repeats of the 95th percentile over 30 requests to the main routes, with no pass threshold until one is calibrated. | Quality reader | diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index 9dde650..ec23b10 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -71,7 +71,7 @@ # behind that sign-in; a request it turns away, with its redirect, a 401 or # a 403, is never measured, and the probe is lost. QUALITY_SCRIPT = r''' -import builtins, html, io, json, logging, math, os, platform, re, sqlite3 +import builtins, io, json, logging, math, os, platform, re, sqlite3 import sys, tempfile, threading, time from decimal import Decimal, InvalidOperation from html.parser import HTMLParser @@ -509,37 +509,35 @@ def exported(path, lines): return total, None -# An amount as a page may write it: grouped by thousands with a comma, a -# point, a space, a no-break or narrow no-break space, or an apostrophe, and -# two decimals after a point or a comma. The page is read with its character -# references resolved, so ` ` and ` ` group as the characters do. -AMOUNT = re.compile(r"(?%s

Total %s

" % ("".join( "%s%d" % (sku, quantity) - for sku, _, quantity in shown), written(page_total, style)) + for sku, _, quantity in rows), total) def number(text): @@ -1251,6 +1250,13 @@ def connect(self, wait=10.0): def test_client(self): return Client(self) + def prices(self): + """Every product's price to the cent, which no price past a + Decimal's precision survives.""" + return [decimal.Decimal(row[0]).quantize(decimal.Decimal("0.01")) + for row in self.connect().execute( + "SELECT unit_price FROM products")] + def skus(self): if self.products is not None: return list(SKUS) + list(self.products) @@ -1274,13 +1280,15 @@ def add_product(self, sku, name, price): finally: IN_FLIGHT.remove(sku) return - connection = self.connect(0 if MODE == "locking" else 10.0) + hangs = MODE == "hanging" and sku == "QCW-1-00" + wait = {"locking": 0, "hanging": 0.1}.get(MODE, 10.0) + connection = self.connect(10.0 if hangs else wait) connection.isolation_level = None try: connection.execute("BEGIN IMMEDIATE") connection.execute("INSERT INTO products VALUES (?, ?, ?)", (sku, name, price)) - time.sleep(0.005) + time.sleep(60 if hangs else 0.005) connection.execute("COMMIT") finally: if connection.in_transaction: @@ -1332,6 +1340,8 @@ def dispatch(self, path, method, data): parts = path.strip("/").split("/") if method == "GET" and path in pages: listing = " ".join(self.app.skus()) if path == "/products" else "" + if path == "/products" and MODE == "poisoned": + self.app.prices() return Response(200, form_page(path, "

%s

" % listing)) if method == "POST" and (path in posts or path.endswith("/delete") or path.endswith("/erase")): @@ -1366,7 +1376,8 @@ def create_product(self, data): if MODE == "forbidding": return Response(403, "forbidden") return Response(200, "unit_price is not a number" + TOKEN) - if not price.is_finite() or price < 0 or price > 10 ** 12: + if not price.is_finite() or price < 0 or ( + price > 10 ** 12 and MODE != "poisoned"): return Response(200, "unit_price is out of range" + TOKEN) if sku in self.app.skus(): return Response(200, "sku exists" + TOKEN) @@ -1391,7 +1402,7 @@ def invoice(self, path, data): lines = lines[:100] if path == "/invoices/preview": return Response(200, table([(sku, SKUS.get(sku, "1.00"), quantity) - for sku, quantity in lines], "eu")[1]) + for sku, quantity in lines])[1]) if not lines: return Response(400, "no lines") with self.app.connect() as connection: @@ -1429,7 +1440,7 @@ def show(self, parts): (invoice,)).fetchall() if MODE == "crowded" and len(rows) > 100: return Response(413, "too many lines to show") - total, shown = table(rows, "en") + total, shown = table(rows) if parts[-1] == "export.json": records = [{"sku": sku, "quantity": quantity} for sku, _, quantity in rows] @@ -1453,7 +1464,7 @@ def create_app(database): "locking": "concurrent_writes", "lossy": "concurrent_writes", "cramped": "capacity_500_lines", "crowded": "capacity_500_lines", "truncating": "capacity_500_lines", - "miscounting": "capacity_500_lines", + "hanging": "concurrent_writes", "nulling": "capacity_500_lines", "capped": "capacity_500_lines", "unpriced": "capacity_500_lines", "free": "capacity_500_lines", "bouncing": "fuzz_robustness", @@ -1471,7 +1482,8 @@ def fake_readings(scratch, modes, mode_arg="all"): with io.open(os.path.join(package, "__init__.py"), "w", encoding="utf-8") as handle: handle.write(FAKE_APP.replace("__MODE__", mode)) - env = dict(os.environ, PYTHONPATH=os.path.join(where, "site")) + env = dict(os.environ, PYTHONPATH=os.path.join(where, "site"), + QUALITY_PROBE_WRITE_SECONDS="5") readings[mode] = probe_runtime(sys.executable, where, mode_arg, env=env, timeout=300) return readings @@ -1486,7 +1498,7 @@ def failing(probes): def runtime_self_checks(scratch): """Each planted fault fails its own probe and no other; an app that keeps the probes from running loses them.""" - modes = (["sound", "slow", "paginating", "gated", "refusing", "broken"] + modes = (["sound", "slow", "poisoned", "gated", "refusing", "broken"] + sorted(FAULTS)) readings = fake_readings(scratch, modes) probes = {mode: probe_results(*readings[mode]) for mode in modes} @@ -1511,15 +1523,6 @@ def runtime_self_checks(scratch): sound["n_plus_one"].get("passed") is True and sound["capacity_500_lines"].get("passed") is True and "return body + main + SIGN_OUT" in FAKE_APP), - ("a total grouped by thousands beside a currency sign is read", - sound["capacity_500_lines"].get("passed") is True - and "€" in FAKE_APP and 'format(int(whole), ",")' in FAKE_APP), - ("a total grouped by no-break-space references, with a decimal " - "comma, is read", - sound["capacity_500_lines"].get("kept", {}).get("preview") is True - and " " in FAKE_APP), - ("a page showing fewer rows but the whole total passes " - "capacity_500_lines", failing(probes["paginating"]) == []), ("the latency is two repeats of 30 requests each", latency.get("requests") == 30 and len(latency.get("repeats") or []) == 2 @@ -1549,8 +1552,7 @@ def runtime_self_checks(scratch): "fuzz_robustness", "truncating": "an app keeping 100 of 500 lines fails " "capacity_500_lines", - "miscounting": "a page showing a total other than the export's " - "fails capacity_500_lines", + "hanging": "a writer the app hangs fails concurrent_writes", "nulling": "an export with a null line fails capacity_500_lines", "unpriced": "an export whose total is NaN fails capacity_500_lines", "free": "an app pricing every line at nothing fails " @@ -1566,6 +1568,16 @@ def runtime_self_checks(scratch): failing(probes[mode]) == [FAULTS[mode]] and probes[mode][FAULTS[mode]].get("passed") is False)) checks.extend([ + ("a product a malformed request stored does not reach the " + "concurrent writes", failing(probes["poisoned"]) == []), + ("a hung writer stops the run, every reading before it kept", + "hung it" in probes["hanging"]["concurrent_writes"].get( + "reason", "") + and {name: probe.get("passed") + for name, probe in probes["hanging"].items() + if name != "concurrent_writes"} + == {name: probe.get("passed") for name, probe in sound.items() + if name != "concurrent_writes"}), ("the redirect is read as lost, not as an answer", "turned away by the sign-in" in probes["bouncing"][ "fuzz_robustness"].get("lost", "")), From 906548ff08d756c94df634f1c1a34a09b20f123f Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:52:00 +0200 Subject: [PATCH 08/17] docs(efficacy): say what the fuzz probe does not read, and why - The comment above the fuzz rule states that only the malformed requests' own answers are read, never a later page after one stored an extreme value: the spec bounds no price's size, so it defines no answer. Refs #119. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- tests/efficacy/quality.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index ec23b10..257c7f2 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -742,7 +742,11 @@ def preview(**fields): # Each malformed request: a label, the method, the path, the form whose # hidden fields it carries (None for none), its body, and whether it is sent # signed out. Every one is a request the specification defines an answer to: -# a re-rendered form, a 400, a 404 or a 405. +# a re-rendered form, a 400, a 404 or a 405. Only these answers are read, +# never a later page after one stored an extreme value, such as a price of +# `1e999999`: the specification bounds no price's size, so it defines no +# answer for such a page, and reading one would measure that gap, not the +# build. FUZZ = ( ("POST /products unit_price=abc", "POST", "/products", "/products", product(unit_price="abc"), False), From 7d04ebe9398c41f99211bddf4ada5272d61481b8 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:22:26 +0200 Subject: [PATCH 09/17] fix(efficacy): each fuzz case runs on its own instance and reaches its form Codex round 7 on the quality reader: - Each malformed request goes to a fresh instance on its own database, signed in afresh, so no case meets what another stored. - A case sent with its form's token whose form page does not answer 200 fails as its form not reached, never as a handled refusal. - Stand-in mode `unformed` answers 500 on its rules page; `poisoned` now passes fuzzing with every case reaching its route. - On the reference, fuzzing takes about 22 s, 0.47 s a case. Refs #119. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 2 +- docs/requirements.md | 2 +- tests/efficacy/quality.py | 89 +++++++++++++++++++++++++++++++-------- 3 files changed, 73 insertions(+), 20 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index d404d73..c244693 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -208,7 +208,7 @@ when: | ID | Kind | Checked by | | -- | ---- | ---------- | -| FR-15-01 | Self-test | `quality.py` "a sound app passes every probe"
`quality.py` "an app answering 500 on bad input fails fuzz_robustness, and no other probe"
`quality.py` "an app raising out of the client fails fuzz_robustness, and no other probe"
`quality.py` "an app whose writes lock fails concurrent_writes, and no other probe"
`quality.py` "an app dropping an overlapping write fails concurrent_writes, and no other probe"
`quality.py` "the locked write is read as locked"
`quality.py` "a writer the app hangs fails concurrent_writes, and no other probe"
`quality.py` "a hung writer stops the run, every reading before it kept"
`quality.py` "a product a malformed request stored does not reach the concurrent writes"
`quality.py` "an app refusing 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app that cannot show 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app keeping 100 of 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an export with a null line fails capacity_500_lines, and no other probe"
`quality.py` "an export whose total is NaN fails capacity_500_lines, and no other probe"
`quality.py` "an app pricing every line at nothing fails capacity_500_lines, and no other probe"
`quality.py` "a database opened by a file URI with a query stays in its folder"
`quality.py` "a total over the first 100 of 500 exported lines fails capacity_500_lines, and no other probe"
`quality.py` "an app reading each line on its own fails n_plus_one, and no other probe"
`quality.py` "statements are counted per page, and did not grow"
`quality.py` "instances sharing their data fail coexistence, and no other probe"
`quality.py` "an app writing outside its folder fails coexistence, and no other probe"
`quality.py` "the stray file is named" | +| FR-15-01 | Self-test | `quality.py` "a sound app passes every probe"
`quality.py` "an app answering 500 on bad input fails fuzz_robustness, and no other probe"
`quality.py` "an app raising out of the client fails fuzz_robustness, and no other probe"
`quality.py` "an app whose form page answers 500 fails fuzz_robustness, and no other probe"
`quality.py` "a form that cannot be reached is no handled request"
`quality.py` "a value one malformed request stored reaches no other case"
`quality.py` "an app whose writes lock fails concurrent_writes, and no other probe"
`quality.py` "an app dropping an overlapping write fails concurrent_writes, and no other probe"
`quality.py` "the locked write is read as locked"
`quality.py` "a writer the app hangs fails concurrent_writes, and no other probe"
`quality.py` "a hung writer stops the run, every reading before it kept"
`quality.py` "a product a malformed request stored does not reach the concurrent writes"
`quality.py` "an app refusing 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app that cannot show 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app keeping 100 of 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an export with a null line fails capacity_500_lines, and no other probe"
`quality.py` "an export whose total is NaN fails capacity_500_lines, and no other probe"
`quality.py` "an app pricing every line at nothing fails capacity_500_lines, and no other probe"
`quality.py` "a database opened by a file URI with a query stays in its folder"
`quality.py` "a total over the first 100 of 500 exported lines fails capacity_500_lines, and no other probe"
`quality.py` "an app reading each line on its own fails n_plus_one, and no other probe"
`quality.py` "statements are counted per page, and did not grow"
`quality.py` "instances sharing their data fail coexistence, and no other probe"
`quality.py` "an app writing outside its folder fails coexistence, and no other probe"
`quality.py` "the stray file is named" | | FR-15-02 | Self-test | `quality.py` "a sound app signs in"
`quality.py` "a sign-in form quoted with single quotes signs in"
`quality.py` "a form's own token is posted, not one from a form before it"
`quality.py` "a post no form's action names carries the page's first token"
`quality.py` "an app answering 401 until signed in, and never signing in, loses every probe"
`quality.py` "an app answering 403 to a malformed request loses fuzz_robustness, and no other probe"
`quality.py` "an app that never keeps its sign-in loses every probe, passing none"
`quality.py` "an app answering a malformed request with the sign-in's redirect loses fuzz_robustness, and no other probe"
`quality.py` "the redirect is read as lost, not as an answer" | | FR-15-03 | Self-test | `quality.py` "an app that will not boot loses every probe"
`quality.py` "a trial that did not install loses every probe"
`quality.py` "no report from the probe is missing, not lost"
`quality.py` "a stalled run keeps what it read and loses the rest"
`quality.py` "a run that stalled booting loses every probe" | | 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" | diff --git a/docs/requirements.md b/docs/requirements.md index 574486b..eed2538 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -218,7 +218,7 @@ | ID | Requirement | Delivered by | | -- | ----------- | ------------ | -| FR-15-01 | The benchmark shall fail each of the fuzz, concurrent-write, 500-line, N+1 and co-existence probes on an app planted with the fault it guards against, and no other probe there, and pass every probe on an app built to pass them; the 500-line probe passes only where the invoice previews 2xx, saves and renders 2xx, its JSON export lists all 500 lines in order, each a well-formed record, with a finite, positive total, and its first 100 lines, saved alone, export a total a fifth of it within a cent; pages are read for answering, never for the amounts they show; the co-existence probe reads a database opened by a `file:` URI as the file it names; and the concurrent writes run last, on a fresh instance of their own, a writer the app hangs failing them and stopping the run there, every reading before it kept. | Quality reader | +| FR-15-01 | The benchmark shall fail each of the fuzz, concurrent-write, 500-line, N+1 and co-existence probes on an app planted with the fault it guards against, and no other probe there, and pass every probe on an app built to pass them; the 500-line probe passes only where the invoice previews 2xx, saves and renders 2xx, its JSON export lists all 500 lines in order, each a well-formed record, with a finite, positive total, and its first 100 lines, saved alone, export a total a fifth of it within a cent; pages are read for answering, never for the amounts they show; the co-existence probe reads a database opened by a `file:` URI as the file it names; each malformed request is sent to a fresh instance of its own, signed in afresh, and one whose form page does not answer 200 fails as unreached; and the concurrent writes run last, on a fresh instance of their own, a writer the app hangs failing them and stopping the run there, every reading before it kept. | Quality reader | | FR-15-02 | The benchmark shall read every quality probe signed in as the seeded administrator, through the sign-in form's hidden fields however they are quoted, each post carrying the hidden fields of the form whose action it is sent to, or else the page's first of each name, the sign-in holding only where the dashboard then answers 200, and never measure a request the sign-in turns away with its redirect, a 401, or a 403 to a request that carried its token. | Quality reader | | FR-15-03 | The benchmark shall count as lost, reading failed, a quality probe the trial keeps from running, by not installing, not booting, not signing in or not finishing in time, and as missing one it could not run itself. | Quality reader | | FR-15-04 | The benchmark shall record the latency as two repeats of the 95th percentile over 30 requests to the main routes, with no pass threshold until one is calibrated. | Quality reader | diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index 257c7f2..1d448e3 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -856,32 +856,68 @@ def preview(**fields): ) +# Each case is sent to an instance of its own, on a fresh database and +# signed in afresh, so no case meets what another stored. A case sent with +# its form's token needs that form first: a form page that does not answer +# 200 gives no token, and a refusal for want of one would read as handled, +# so the case fails as its form not reached. A case sent without a token on +# purpose fetches no form. +def fuzz_case(method, path, form, body, signed_out): + """One malformed request's outcome, on a fresh instance.""" + entry = {} + try: + own = package.create_app(os.path.join(folder(), "fuzz.sqlite")) + except Exception as error: + entry["reason"] = "a fresh instance would not boot: %s" % ( + repr(error)[:200]) + return entry + who = own.test_client() + if not signed_out and not sign_in(who): + entry["gated"] = True + return entry + try: + data = body + if form: + sent_from = ask(who, "GET", form) + if not signed_out and gated(sent_from): + entry["gated"] = True + return entry + if sent_from.status_code != 200: + entry["reason"] = ("the form could not be reached: %s " + "answered %d" + % (form, sent_from.status_code)) + return entry + data = dict(body) + for name, value in hidden_fields( + sent_from.get_data(as_text=True), form, path).items(): + data.setdefault(name, value) + answer = ask(who, method, path, data=data) + entry["status"] = answer.status_code + + # Signed out, the sign-in's own answer may be its redirect. + entry["gated"] = not signed_out and gated( + answer, token=method == "GET" or form is not None) + except Raised as error: + entry["raised"] = str(error) + return entry + + def fuzz_robustness(): - """Malformed requests to the specification's routes, none answered 500 - and none raising out of the client.""" - stranger = app.test_client() + """Malformed requests to the specification's routes, each reaching + its route, none answered 500 and none raising out of the client.""" answers = [] for label, method, path, form, body, signed_out in FUZZ: - who = stranger if signed_out else client entry = {"request": label} - try: - answer = (form_post(who, form, path, body, method=method) - if form else ask(who, method, path, data=body)) - entry["status"] = answer.status_code - - # Signed out, the sign-in's own answer may be its redirect. - entry["gated"] = not signed_out and gated( - answer, token=method == "GET" or form is not None) - except Raised as error: - entry["raised"] = str(error) + entry.update(fuzz_case(method, path, form, body, signed_out)) answers.append(entry) asked = [entry["request"] for entry in answers if entry.get("gated")] if asked: return lost("fuzz_robustness", "%d malformed requests were turned " "away by the sign-in" % len(asked), asked=asked) failed = [entry for entry in answers if entry.get("raised") - or (entry.get("status") or 0) >= 500] - return passed(not failed, requests=len(answers), failed=failed) + or entry.get("reason") or (entry.get("status") or 0) >= 500] + return passed(not failed, requests=len(answers), failed=failed, + statuses=[entry.get("status") for entry in answers]) report["signed_in"] = sign_in(client) @@ -1141,7 +1177,8 @@ def read_trial(area, name, scores_file, other): # it keeps and exports all; `unpriced` exports its total as NaN, `free` # prices every line at nothing, `poisoned` stores a price it cannot then # list, so its products page answers 500 once fuzzing has stored one, which -# is no fault of any probe's, and `hanging` holds one concurrent write, +# is no fault of any probe's, `unformed` answers 500 on its rules page, and +# `hanging` holds one concurrent write, # and its lock, for a minute. Every mode opens its database by a `file:` URI # with a query. `bouncing` answers a price it cannot parse with the # sign-in's redirect and `forbidding` with a 403; @@ -1346,6 +1383,8 @@ def dispatch(self, path, method, data): listing = " ".join(self.app.skus()) if path == "/products" else "" if path == "/products" and MODE == "poisoned": self.app.prices() + if path == "/rules" and MODE == "unformed": + raise RuntimeError("the rules page is broken") return Response(200, form_page(path, "

%s

" % listing)) if method == "POST" and (path in posts or path.endswith("/delete") or path.endswith("/erase")): @@ -1468,7 +1507,7 @@ def create_app(database): "locking": "concurrent_writes", "lossy": "concurrent_writes", "cramped": "capacity_500_lines", "crowded": "capacity_500_lines", "truncating": "capacity_500_lines", - "hanging": "concurrent_writes", + "hanging": "concurrent_writes", "unformed": "fuzz_robustness", "nulling": "capacity_500_lines", "capped": "capacity_500_lines", "unpriced": "capacity_500_lines", "free": "capacity_500_lines", "bouncing": "fuzz_robustness", @@ -1557,6 +1596,8 @@ def runtime_self_checks(scratch): "truncating": "an app keeping 100 of 500 lines fails " "capacity_500_lines", "hanging": "a writer the app hangs fails concurrent_writes", + "unformed": "an app whose form page answers 500 fails " + "fuzz_robustness", "nulling": "an export with a null line fails capacity_500_lines", "unpriced": "an export whose total is NaN fails capacity_500_lines", "free": "an app pricing every line at nothing fails " @@ -1574,6 +1615,18 @@ def runtime_self_checks(scratch): checks.extend([ ("a product a malformed request stored does not reach the " "concurrent writes", failing(probes["poisoned"]) == []), + ("a value one malformed request stored reaches no other case", + probes["poisoned"]["fuzz_robustness"].get("passed") is True + and len(sound["fuzz_robustness"].get("statuses") or []) + == sound["fuzz_robustness"].get("requests", 0) > 0 + and [index for index, (poisoned, clean) in enumerate(zip( + probes["poisoned"]["fuzz_robustness"].get("statuses") or [], + sound["fuzz_robustness"]["statuses"])) + if poisoned == 400 and clean != 400] == []), + ("a form that cannot be reached is no handled request", + any("could not be reached" in entry.get("reason", "") + for entry in probes["unformed"]["fuzz_robustness"].get( + "failed", []))), ("a hung writer stops the run, every reading before it kept", "hung it" in probes["hanging"]["concurrent_writes"].get( "reason", "") From be75b63b4505ee605f3e452abbf4c0e12c691efe Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:52:59 +0200 Subject: [PATCH 10/17] feat(efficacy): archive and reuse carry quality readings; a failed export fails Codex round 8 on the quality reader: - archive.py keeps quality-scores/ among its readings, hashed into the stamp, refuses to run beside a live quality.py claim, and drops the quality reader's leftover environments. - reuse.py copies a trial's quality reading with it. - The 500-line probe needs a 2xx export, for both invoices, before it reads the lines and the total; stand-in mode `unexported` answers 500 with valid JSON. Refs #119. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 10 +++++----- docs/requirements.md | 2 +- tests/efficacy/archive.py | 20 +++++++++++++++----- tests/efficacy/quality.py | 17 ++++++++++++----- tests/efficacy/reuse.py | 6 +++++- 5 files changed, 38 insertions(+), 17 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index c244693..a920a8c 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -166,7 +166,7 @@ when: | ID | Kind | Checked by | | -- | ---- | ---------- | | FR-12-01 | Self-test | `report.py` "a contrast crossing rounds carries no verdict and counts nowhere"
`report.py` "a comparison across rounds reads as not given, not too few runs" | -| FR-12-02 | Self-test | `report.py` "a contrast across rounds is unpaired, with a verdict"
`report.py` "a round-5d run reads H4 against a reused `none`, unpaired"
`report.py` "an unpaired contrast leaves out two trials, not blocks"
`report.py` "a contrast crosses rounds where its arms ran in different roots, reused or not"
`reuse.py` "a trial copied on keeps the root it ran in as its origin" | +| FR-12-02 | Self-test | `report.py` "a contrast across rounds is unpaired, with a verdict"
`report.py` "a round-5d run reads H4 against a reused `none`, unpaired"
`report.py` "an unpaired contrast leaves out two trials, not blocks"
`report.py` "a contrast crosses rounds where its arms ran in different roots, reused or not"
`reuse.py` "a trial copied on keeps the root it ran in as its origin"
`reuse.py` "a quality reading comes along with its trial" | | FR-12-03 | Self-test | `report.py` "it prints every declared contrast its arms ran"
`report.py` "a three-arm run prints only its own contrasts" | | FR-12-04 | Self-test | `report.py` "round 5 reports the files it supersedes without a verdict" | | FR-12-05 | Self-test | `report.py` "the report links its appendix, and the appendix the record"
`report.py` "the appendix holds what produced the results, the radar's axes and the verdict vector, and nothing else" | @@ -188,8 +188,8 @@ when: | -- | ---- | ---------- | | FR-13-01 | Self-test | `harness.py` "the record is written as every trial starts and ends"
`harness.py` "every trial records the CLI's version, read as it starts" | | FR-13-02 | Self-test | `generate_arm.py` "every built arm's file has its generation record beside it"
`report.py` "a pilot arm no script builds keeps its record for the report, and its vendored templates" | -| FR-13-03 | Self-test | `archive.py` "readings, judgings, map and lock come; bundles do not"
`archive.py` "the original tarball's hash is recorded"
`archive.py` "the revisions are recorded"
`archive.py` "a reading changed in the archive fails the verify" | -| FR-13-04 | Self-test | `archive.py` "a reading changed after the stamp is a problem"
`archive.py` "the report refuses docs/reports/ without a current stamp"
`report.py` "a report into any docs/reports needs the stamp" | +| FR-13-03 | Self-test | `archive.py` "readings, judgings, map and lock come; bundles do not"
`archive.py` "the original tarball's hash is recorded"
`archive.py` "the revisions are recorded"
`archive.py` "a reading changed in the archive fails the verify"
`archive.py` "an archived round drops its trees and environments" | +| FR-13-04 | Self-test | `archive.py` "a reading changed after the stamp is a problem"
`archive.py` "a quality reading changed after the stamp is a problem"
`archive.py` "the report refuses docs/reports/ without a current stamp"
`report.py` "a report into any docs/reports needs the stamp" | | FR-13-05 | Self-test | `archive.py` "the restored root reads as the original does"
`archive.py` "a restored record points at the restored tarball and void"
`archive.py` "a restored transcript keeps its time" | | FR-13-06 | Self-test | `generate_arm.py` "the two map arms name the same moments in the chain's order"
`generate_arm.py` "the reading map names every template of the chain once, under docs/solid-ai-templates/"
`generate_arm.py` "each template skill is its template verbatim, named by the manifest"
`generate_arm.py` "a chain file the manifest does not describe is refused" | | FR-13-07 | Self-test | `generate_arm.py` "every built root opens with the brief, verbatim, the emitted ones too"
`generate_arm.py` "every committed arm's root opens with the brief, verbatim"
`generate_arm.py` "the brief and the facts name the stack and no tooling" | @@ -201,14 +201,14 @@ when: | ID | Kind | Checked by | | -- | ---- | ---------- | -| FR-14-01 | Self-test | `score.py` "a live score.py run refuses a second"
`judge.py` "a live judge.py run refuses a second"
`security.py` "a live security.py run refuses a second"
`quality.py` "a live quality.py run refuses a second" | +| FR-14-01 | Self-test | `score.py` "a live score.py run refuses a second"
`judge.py` "a live judge.py run refuses a second"
`security.py` "a live security.py run refuses a second"
`quality.py` "a live quality.py run refuses a second"
`archive.py` "a live quality.py run refuses a second" | | FR-14-02 | Self-test | `harness.py` "an ended run is taken over"
`harness.py` "a live pid that is not the tool is taken over" | ## 15 Quality probes | ID | Kind | Checked by | | -- | ---- | ---------- | -| FR-15-01 | Self-test | `quality.py` "a sound app passes every probe"
`quality.py` "an app answering 500 on bad input fails fuzz_robustness, and no other probe"
`quality.py` "an app raising out of the client fails fuzz_robustness, and no other probe"
`quality.py` "an app whose form page answers 500 fails fuzz_robustness, and no other probe"
`quality.py` "a form that cannot be reached is no handled request"
`quality.py` "a value one malformed request stored reaches no other case"
`quality.py` "an app whose writes lock fails concurrent_writes, and no other probe"
`quality.py` "an app dropping an overlapping write fails concurrent_writes, and no other probe"
`quality.py` "the locked write is read as locked"
`quality.py` "a writer the app hangs fails concurrent_writes, and no other probe"
`quality.py` "a hung writer stops the run, every reading before it kept"
`quality.py` "a product a malformed request stored does not reach the concurrent writes"
`quality.py` "an app refusing 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app that cannot show 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app keeping 100 of 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an export with a null line fails capacity_500_lines, and no other probe"
`quality.py` "an export whose total is NaN fails capacity_500_lines, and no other probe"
`quality.py` "an app pricing every line at nothing fails capacity_500_lines, and no other probe"
`quality.py` "a database opened by a file URI with a query stays in its folder"
`quality.py` "a total over the first 100 of 500 exported lines fails capacity_500_lines, and no other probe"
`quality.py` "an app reading each line on its own fails n_plus_one, and no other probe"
`quality.py` "statements are counted per page, and did not grow"
`quality.py` "instances sharing their data fail coexistence, and no other probe"
`quality.py` "an app writing outside its folder fails coexistence, and no other probe"
`quality.py` "the stray file is named" | +| FR-15-01 | Self-test | `quality.py` "a sound app passes every probe"
`quality.py` "an app answering 500 on bad input fails fuzz_robustness, and no other probe"
`quality.py` "an app raising out of the client fails fuzz_robustness, and no other probe"
`quality.py` "an app whose form page answers 500 fails fuzz_robustness, and no other probe"
`quality.py` "a form that cannot be reached is no handled request"
`quality.py` "a value one malformed request stored reaches no other case"
`quality.py` "an app whose writes lock fails concurrent_writes, and no other probe"
`quality.py` "an app dropping an overlapping write fails concurrent_writes, and no other probe"
`quality.py` "the locked write is read as locked"
`quality.py` "a writer the app hangs fails concurrent_writes, and no other probe"
`quality.py` "a hung writer stops the run, every reading before it kept"
`quality.py` "a product a malformed request stored does not reach the concurrent writes"
`quality.py` "an app refusing 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app that cannot show 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app keeping 100 of 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an export with a null line fails capacity_500_lines, and no other probe"
`quality.py` "an export whose total is NaN fails capacity_500_lines, and no other probe"
`quality.py` "an export answered 500 fails capacity_500_lines, and no other probe"
`quality.py` "an app pricing every line at nothing fails capacity_500_lines, and no other probe"
`quality.py` "a database opened by a file URI with a query stays in its folder"
`quality.py` "a total over the first 100 of 500 exported lines fails capacity_500_lines, and no other probe"
`quality.py` "an app reading each line on its own fails n_plus_one, and no other probe"
`quality.py` "statements are counted per page, and did not grow"
`quality.py` "instances sharing their data fail coexistence, and no other probe"
`quality.py` "an app writing outside its folder fails coexistence, and no other probe"
`quality.py` "the stray file is named" | | FR-15-02 | Self-test | `quality.py` "a sound app signs in"
`quality.py` "a sign-in form quoted with single quotes signs in"
`quality.py` "a form's own token is posted, not one from a form before it"
`quality.py` "a post no form's action names carries the page's first token"
`quality.py` "an app answering 401 until signed in, and never signing in, loses every probe"
`quality.py` "an app answering 403 to a malformed request loses fuzz_robustness, and no other probe"
`quality.py` "an app that never keeps its sign-in loses every probe, passing none"
`quality.py` "an app answering a malformed request with the sign-in's redirect loses fuzz_robustness, and no other probe"
`quality.py` "the redirect is read as lost, not as an answer" | | FR-15-03 | Self-test | `quality.py` "an app that will not boot loses every probe"
`quality.py` "a trial that did not install loses every probe"
`quality.py` "no report from the probe is missing, not lost"
`quality.py` "a stalled run keeps what it read and loses the rest"
`quality.py` "a run that stalled booting loses every probe" | | 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" | diff --git a/docs/requirements.md b/docs/requirements.md index eed2538..0507603 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -218,7 +218,7 @@ | ID | Requirement | Delivered by | | -- | ----------- | ------------ | -| FR-15-01 | The benchmark shall fail each of the fuzz, concurrent-write, 500-line, N+1 and co-existence probes on an app planted with the fault it guards against, and no other probe there, and pass every probe on an app built to pass them; the 500-line probe passes only where the invoice previews 2xx, saves and renders 2xx, its JSON export lists all 500 lines in order, each a well-formed record, with a finite, positive total, and its first 100 lines, saved alone, export a total a fifth of it within a cent; pages are read for answering, never for the amounts they show; the co-existence probe reads a database opened by a `file:` URI as the file it names; each malformed request is sent to a fresh instance of its own, signed in afresh, and one whose form page does not answer 200 fails as unreached; and the concurrent writes run last, on a fresh instance of their own, a writer the app hangs failing them and stopping the run there, every reading before it kept. | Quality reader | +| FR-15-01 | The benchmark shall fail each of the fuzz, concurrent-write, 500-line, N+1 and co-existence probes on an app planted with the fault it guards against, and no other probe there, and pass every probe on an app built to pass them; the 500-line probe passes only where the invoice previews 2xx, saves and renders 2xx, its JSON export answers 2xx and lists all 500 lines in order, each a well-formed record, with a finite, positive total, and its first 100 lines, saved alone, export a total a fifth of it within a cent; pages are read for answering, never for the amounts they show; the co-existence probe reads a database opened by a `file:` URI as the file it names; each malformed request is sent to a fresh instance of its own, signed in afresh, and one whose form page does not answer 200 fails as unreached; and the concurrent writes run last, on a fresh instance of their own, a writer the app hangs failing them and stopping the run there, every reading before it kept. | Quality reader | | FR-15-02 | The benchmark shall read every quality probe signed in as the seeded administrator, through the sign-in form's hidden fields however they are quoted, each post carrying the hidden fields of the form whose action it is sent to, or else the page's first of each name, the sign-in holding only where the dashboard then answers 200, and never measure a request the sign-in turns away with its redirect, a 401, or a 403 to a request that carried its token. | Quality reader | | FR-15-03 | The benchmark shall count as lost, reading failed, a quality probe the trial keeps from running, by not installing, not booting, not signing in or not finishing in time, and as missing one it could not run itself. | Quality reader | | FR-15-04 | The benchmark shall record the latency as two repeats of the 95th percentile over 30 requests to the main routes, with no pass threshold until one is calibrated. | Quality reader | diff --git a/tests/efficacy/archive.py b/tests/efficacy/archive.py index 29d1a3e..fb454de 100644 --- a/tests/efficacy/archive.py +++ b/tests/efficacy/archive.py @@ -35,7 +35,7 @@ # The scoring area's per-trial readings the report aggregates, each a JSON # file named for its trial. -READINGS = ("scores", "scores-change", "security-scores") +READINGS = ("scores", "scores-change", "security-scores", "quality-scores") # What a frozen workspace holds that no reading needs and any scoring # rebuilds: tool caches, compiled bytecode, and every virtual environment, @@ -330,7 +330,7 @@ def stamp(root, into): # The tools that read and write a scoring area while they run, each under a # claim of its own. -AREA_TOOLS = ("score.py", "security.py", "judge.py") +AREA_TOOLS = ("score.py", "security.py", "quality.py", "judge.py") def live_run_problem(root): @@ -357,6 +357,7 @@ def drop_trees(root): 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 folder in folders: remove_tree(folder) return len(folders) @@ -487,6 +488,7 @@ def self_test(): and not any("credentials" in key for key in files)), ("readings, judgings, map and lock come; bundles do not", {"scoring/scores/none-1.json", "scoring/security-scores/hybrid-1.json", + "scoring/quality-scores/hybrid-1.json", "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)), @@ -546,12 +548,13 @@ def self_test(): checks.append(("a stamped round has none", stamp_problem(root) is None)) # What scoring leaves: a trial's tree and environment, a change task's, - # and a security reading's environment. + # and a security and a quality reading's environment. area = scoring_area(root) leftovers = [os.path.join(area, "scoring", "none-1", "tree"), os.path.join(area, "scoring", "none-1", "venv"), os.path.join(area, "scoring-change", "none-1", "tree"), - os.path.join(area, "security", "hybrid-1", "venv")] + os.path.join(area, "security", "hybrid-1", "venv"), + os.path.join(area, "quality", "hybrid-1", "venv")] for folder in leftovers: os.makedirs(folder, exist_ok=True) with io.open(os.path.join(folder, "left.txt"), "w") as handle: @@ -566,6 +569,11 @@ def self_test(): dump_json(score, dict(load_json(score), planted=True)) checks.append(("a reading changed after the stamp is a problem", "scores/none-1.json" in (stamp_problem(root) or ""))) + quality = os.path.join(scoring_area(root), "quality-scores", "none-1.json") + if os.path.isfile(quality): + dump_json(quality, dict(load_json(quality), planted=True)) + checks.append(("a quality reading changed after the stamp is a problem", + "quality-scores/none-1.json" in (stamp_problem(root) or ""))) out = os.path.join(scratch, "draft") checks.append(("the report refuses docs/reports/ without a current stamp", report.main(["--root", root]) == 2)) @@ -573,7 +581,9 @@ def self_test(): report.main(["--root", root, "--out-dir", out]) == 0 and bool(os.listdir(out)))) - for tool in AREA_TOOLS: + # Named, not read from the list the archive keeps, so a tool missing + # from that list shows as an archive made beside its live run. + for tool in ("score.py", "security.py", "quality.py", "judge.py"): checks.append(claim_refusal_check( tool, main, root, "--into", os.path.join(scratch, "runs", "live-" + tool))) diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index 1d448e3..924fbf8 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -478,9 +478,12 @@ def n_plus_one(): def exported(path, lines): """The saved invoice's JSON export read against the lines saved: its total, or None and why it does not hold them.""" + answer = page(client, path + "/export.json") + if not ok(answer): + return None, ("the saved invoice's JSON export answered %d" + % answer.status_code) try: - export = json.loads(page(client, path + "/export.json").get_data( - as_text=True)) + export = json.loads(answer.get_data(as_text=True)) except ValueError: return None, "the saved invoice's JSON export is not JSON" if not isinstance(export, dict) or not isinstance(export.get("lines"), @@ -1177,7 +1180,8 @@ def read_trial(area, name, scores_file, other): # it keeps and exports all; `unpriced` exports its total as NaN, `free` # prices every line at nothing, `poisoned` stores a price it cannot then # list, so its products page answers 500 once fuzzing has stored one, which -# is no fault of any probe's, `unformed` answers 500 on its rules page, and +# is no fault of any probe's, `unformed` answers 500 on its rules page, +# `unexported` answers its export with a 500 and the JSON all the same, and # `hanging` holds one concurrent write, # and its lock, for a minute. Every mode opens its database by a `file:` URI # with a query. `bouncing` answers a price it cannot parse with the @@ -1489,9 +1493,10 @@ def show(self, parts): for sku, _, quantity in rows] if MODE == "nulling" and len(records) > 100: records[100] = None - return Response(200, json.dumps({ + export = json.dumps({ "lines": records, - "total": "NaN" if MODE == "unpriced" else total})) + "total": "NaN" if MODE == "unpriced" else total}) + return Response(500 if MODE == "unexported" else 200, export) return Response(200, shown) @@ -1508,6 +1513,7 @@ def create_app(database): "cramped": "capacity_500_lines", "crowded": "capacity_500_lines", "truncating": "capacity_500_lines", "hanging": "concurrent_writes", "unformed": "fuzz_robustness", + "unexported": "capacity_500_lines", "nulling": "capacity_500_lines", "capped": "capacity_500_lines", "unpriced": "capacity_500_lines", "free": "capacity_500_lines", "bouncing": "fuzz_robustness", @@ -1598,6 +1604,7 @@ def runtime_self_checks(scratch): "hanging": "a writer the app hangs fails concurrent_writes", "unformed": "an app whose form page answers 500 fails " "fuzz_robustness", + "unexported": "an export answered 500 fails capacity_500_lines", "nulling": "an export with a null line fails capacity_500_lines", "unpriced": "an export whose total is NaN fails capacity_500_lines", "free": "an app pricing every line at nothing fails " diff --git a/tests/efficacy/reuse.py b/tests/efficacy/reuse.py index 7e9a4f2..1f40b6c 100644 --- a/tests/efficacy/reuse.py +++ b/tests/efficacy/reuse.py @@ -30,7 +30,7 @@ # 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") +READINGS = ("scores", "security-scores", "quality-scores") def existing_file(directory, name): @@ -305,6 +305,10 @@ def loaded(*parts): and not os.path.exists(os.path.join(area, "judge", "T3.json")) and loaded(area, "judge", "map.json")["blind"] == {"inline-1": "T2", "hand-1": "T1"}), + ("a quality reading comes along with its trial", + os.path.isfile(os.path.join(area, "quality-scores", "inline-1.json")) + and loaded(area, "quality-scores", "inline-1.json")["reused_from"][ + "name"] == "inline-1"), ("the earlier round's tool lock comes along", io.open(os.path.join(area, "tool-lock.txt"), encoding="utf-8").read() == "ruler==1.0\n"), From abdda5ef0e3da975a6709c6a8c86483d4288cc19 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:26:28 +0200 Subject: [PATCH 11/17] fix(efficacy): a save control's formaction picks its form; every write counts Codex round 9 on the quality reader: - A post carries the fields of the form that sends it there: by its action, or by a submit control's `formaction`, a control outside the form linked by its `form` id included. - Every file opened to write is recorded from before the package's import; co-existence fails on any outside the workspace and the reader's database root, read again as the run ends. - The temporary folder is asked for before the watch, so the standard library's own scratch-file test is not read as the build's. - Stand-ins put the sign-out form before the main form; `detached` and `plain-save` pass; `stray` writes through a handle opened at import. Refs #119. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 2 +- docs/requirements.md | 4 +- tests/efficacy/quality.py | 205 ++++++++++++++++++++++++-------------- 3 files changed, 135 insertions(+), 76 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index a920a8c..70093dd 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -209,7 +209,7 @@ when: | ID | Kind | Checked by | | -- | ---- | ---------- | | FR-15-01 | Self-test | `quality.py` "a sound app passes every probe"
`quality.py` "an app answering 500 on bad input fails fuzz_robustness, and no other probe"
`quality.py` "an app raising out of the client fails fuzz_robustness, and no other probe"
`quality.py` "an app whose form page answers 500 fails fuzz_robustness, and no other probe"
`quality.py` "a form that cannot be reached is no handled request"
`quality.py` "a value one malformed request stored reaches no other case"
`quality.py` "an app whose writes lock fails concurrent_writes, and no other probe"
`quality.py` "an app dropping an overlapping write fails concurrent_writes, and no other probe"
`quality.py` "the locked write is read as locked"
`quality.py` "a writer the app hangs fails concurrent_writes, and no other probe"
`quality.py` "a hung writer stops the run, every reading before it kept"
`quality.py` "a product a malformed request stored does not reach the concurrent writes"
`quality.py` "an app refusing 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app that cannot show 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app keeping 100 of 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an export with a null line fails capacity_500_lines, and no other probe"
`quality.py` "an export whose total is NaN fails capacity_500_lines, and no other probe"
`quality.py` "an export answered 500 fails capacity_500_lines, and no other probe"
`quality.py` "an app pricing every line at nothing fails capacity_500_lines, and no other probe"
`quality.py` "a database opened by a file URI with a query stays in its folder"
`quality.py` "a total over the first 100 of 500 exported lines fails capacity_500_lines, and no other probe"
`quality.py` "an app reading each line on its own fails n_plus_one, and no other probe"
`quality.py` "statements are counted per page, and did not grow"
`quality.py` "instances sharing their data fail coexistence, and no other probe"
`quality.py` "an app writing outside its folder fails coexistence, and no other probe"
`quality.py` "the stray file is named" | -| FR-15-02 | Self-test | `quality.py` "a sound app signs in"
`quality.py` "a sign-in form quoted with single quotes signs in"
`quality.py` "a form's own token is posted, not one from a form before it"
`quality.py` "a post no form's action names carries the page's first token"
`quality.py` "an app answering 401 until signed in, and never signing in, loses every probe"
`quality.py` "an app answering 403 to a malformed request loses fuzz_robustness, and no other probe"
`quality.py` "an app that never keeps its sign-in loses every probe, passing none"
`quality.py` "an app answering a malformed request with the sign-in's redirect loses fuzz_robustness, and no other probe"
`quality.py` "the redirect is read as lost, not as an answer" | +| FR-15-02 | Self-test | `quality.py` "a sound app signs in"
`quality.py` "a sign-in form quoted with single quotes signs in"
`quality.py` "a form's own token is posted, not one from a form before it"
`quality.py` "a post no form's action names carries the page's first token"
`quality.py` "a save sent by its control's formaction carries its form's token"
`quality.py` "a save control outside its form, linked by its id, carries that form's token"
`quality.py` "an app answering 401 until signed in, and never signing in, loses every probe"
`quality.py` "an app answering 403 to a malformed request loses fuzz_robustness, and no other probe"
`quality.py` "an app that never keeps its sign-in loses every probe, passing none"
`quality.py` "an app answering a malformed request with the sign-in's redirect loses fuzz_robustness, and no other probe"
`quality.py` "the redirect is read as lost, not as an answer" | | FR-15-03 | Self-test | `quality.py` "an app that will not boot loses every probe"
`quality.py` "a trial that did not install loses every probe"
`quality.py` "no report from the probe is missing, not lost"
`quality.py` "a stalled run keeps what it read and loses the rest"
`quality.py` "a run that stalled booting loses every probe" | | 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" | diff --git a/docs/requirements.md b/docs/requirements.md index 0507603..be484c8 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -218,8 +218,8 @@ | ID | Requirement | Delivered by | | -- | ----------- | ------------ | -| FR-15-01 | The benchmark shall fail each of the fuzz, concurrent-write, 500-line, N+1 and co-existence probes on an app planted with the fault it guards against, and no other probe there, and pass every probe on an app built to pass them; the 500-line probe passes only where the invoice previews 2xx, saves and renders 2xx, its JSON export answers 2xx and lists all 500 lines in order, each a well-formed record, with a finite, positive total, and its first 100 lines, saved alone, export a total a fifth of it within a cent; pages are read for answering, never for the amounts they show; the co-existence probe reads a database opened by a `file:` URI as the file it names; each malformed request is sent to a fresh instance of its own, signed in afresh, and one whose form page does not answer 200 fails as unreached; and the concurrent writes run last, on a fresh instance of their own, a writer the app hangs failing them and stopping the run there, every reading before it kept. | Quality reader | -| FR-15-02 | The benchmark shall read every quality probe signed in as the seeded administrator, through the sign-in form's hidden fields however they are quoted, each post carrying the hidden fields of the form whose action it is sent to, or else the page's first of each name, the sign-in holding only where the dashboard then answers 200, and never measure a request the sign-in turns away with its redirect, a 401, or a 403 to a request that carried its token. | Quality reader | +| FR-15-01 | The benchmark shall fail each of the fuzz, concurrent-write, 500-line, N+1 and co-existence probes on an app planted with the fault it guards against, and no other probe there, and pass every probe on an app built to pass them; the 500-line probe passes only where the invoice previews 2xx, saves and renders 2xx, its JSON export answers 2xx and lists all 500 lines in order, each a well-formed record, with a finite, positive total, and its first 100 lines, saved alone, export a total a fifth of it within a cent; pages are read for answering, never for the amounts they show; the co-existence probe reads a database opened by a `file:` URI as the file it names, and fails a build that, at any time in the run, opens to write a file outside the workspace and the reader's own database root; each malformed request is sent to a fresh instance of its own, signed in afresh, and one whose form page does not answer 200 fails as unreached; and the concurrent writes run last, on a fresh instance of their own, a writer the app hangs failing them and stopping the run there, every reading before it kept. | Quality reader | +| FR-15-02 | The benchmark shall read every quality probe signed in as the seeded administrator, through the sign-in form's hidden fields however they are quoted, each post carrying the hidden fields of the form whose action, or one of whose submit controls' `formaction`, it is sent to, or else the page's first of each name, the sign-in holding only where the dashboard then answers 200, and never measure a request the sign-in turns away with its redirect, a 401, or a 403 to a request that carried its token. | Quality reader | | FR-15-03 | The benchmark shall count as lost, reading failed, a quality probe the trial keeps from running, by not installing, not booting, not signing in or not finishing in time, and as missing one it could not run itself. | Quality reader | | FR-15-04 | The benchmark shall record the latency as two repeats of the 95th percentile over 30 requests to the main routes, with no pass threshold until one is calibrated. | Quality reader | | 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 | diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index 924fbf8..90bb6ba 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -86,6 +86,11 @@ WORKSPACE = os.path.abspath(os.getcwd()) os.environ["TARIFF_ADMIN_PASSWORD"] = PASSWORD +# The standard library tries its temporary folder with a scratch file the +# first time any code asks for it; asked here, before the watch below, that +# try is not read as the build's write. +tempfile.gettempdir() + real_open = builtins.open real_os_open = os.open report = {"python": platform.python_version(), "probes": {}, @@ -102,6 +107,8 @@ def save(): def finish(): report.pop("running", None) + if "leaked" in report["probes"].get("coexistence", {}): + settle_coexistence(report["probes"]["coexistence"]) save() print(json.dumps(report)) raise SystemExit(0) @@ -121,13 +128,15 @@ def traced(statement): statements["total"] += 1 -# Where the application writes while the co-existence probe watches. -watch = {"on": False, "paths": []} +# Every file the application opens to write, by name, for the whole run. +# The watch is in place before the package is imported, so a handle opened +# at import and written to later is seen. +written = [] def note(path): - if watch["on"] and isinstance(path, (str, bytes, os.PathLike)): - watch["paths"].append(os.path.abspath(os.fsdecode(path))) + if isinstance(path, (str, bytes, os.PathLike)): + written.append(os.path.abspath(os.fsdecode(path))) real_connect = sqlite3.connect @@ -232,37 +241,59 @@ class Raised(Exception): class Hidden(HTMLParser): - """Collects every hidden input, however its attributes are quoted, in - page order, with the action of the form it sits in.""" + """Collects every form's action and id, every hidden input and every + submit control's `formaction`, however their attributes are quoted, in + page order, each with the form it belongs to.""" def __init__(self): HTMLParser.__init__(self) - self.inputs = [] self.forms = [] + self.inputs = [] + self.controls = [] self.form = None + def owner(self, attributes): + """The form a control belongs to: the one its `form` attribute names + by id, else the one it sits in.""" + named = attributes.get("form") + return ("id", named) if named else self.form + def handle_starttag(self, tag, attrs): attributes = dict(attrs) + kind = (attributes.get("type") or "").lower() if tag == "form": self.form = len(self.forms) - self.forms.append(attributes.get("action") or "") - elif (tag == "input" and (attributes.get("type") or "").lower() - == "hidden" and attributes.get("name")): - self.inputs.append((self.form, attributes["name"], + self.forms.append((attributes.get("action") or "", + attributes.get("id"))) + elif tag == "input" and kind == "hidden" and attributes.get("name"): + self.inputs.append((self.owner(attributes), attributes["name"], attributes.get("value") or "")) + if ((tag == "button" and kind in ("", "submit")) + or (tag == "input" and kind in ("submit", "image"))) \ + and attributes.get("formaction") is not None: + self.controls.append((self.owner(attributes), + attributes["formaction"])) def handle_endtag(self, tag): if tag == "form": self.form = None + def resolved(self, owner): + """A form's index from an owner, an index or an id.""" + if isinstance(owner, tuple): + return next((index for index, (_, ident) in enumerate(self.forms) + if ident == owner[1]), None) + return owner + # A page may hold several forms, each with its own token, such as a sign-out # form beside the one being sent. The fields sent are those of the first form -# whose action is the path posted to, read as the browser resolves it, its -# query ignored, an empty action being the page's own path. A post no form's -# action names takes every hidden field on the page, the first of each name. -# A save control's `formaction` is not read: the builder's save is sent with -# the builder form's fields by that fallback, which is how a browser sends it. +# that posts to the path posted to: by its action, or by a submit control's +# `formaction`, as the builder's save sends the builder form to `/invoices`; +# a control outside the form, linked by its `form` attribute, counts too. +# Each is read as the browser resolves it, its query ignored, an empty one +# being the page's own path. A post no form sends takes every hidden field +# on the page, the first of each name. def hidden_fields(text, page_path, target): """The hidden fields a post to `target` carries from the page at `page_path`.""" @@ -270,11 +301,18 @@ def hidden_fields(text, page_path, target): parser.feed(text) base = "http://localhost" + page_path wanted = urlsplit(target).path - for form, action in enumerate(parser.forms): - if urlsplit(urljoin(base, action or page_path)).path == wanted: + + def path_of(address): + return urlsplit(urljoin(base, address or page_path)).path + + for form, (action, _) in enumerate(parser.forms): + sends = {path_of(action)} | { + path_of(address) for owner, address in parser.controls + if parser.resolved(owner) == form} + if wanted in sends: fields = {} for owner, name, value in parser.inputs: - if owner == form: + if parser.resolved(owner) == form: fields.setdefault(name, value) return fields fields = {} @@ -687,37 +725,41 @@ def coexistence(): out of the other, and neither writes outside its folder or the workspace.""" - # A database's sidecars, its `-wal`, `-shm` and `-journal`, sit in its - # folder, so the two folders admit them. folders_given = [folder(), folder()] - watch["paths"] = [] - watch["on"] = True try: - try: - first, second = [ - package.create_app(os.path.join(where, "coexist.sqlite")) - for where in folders_given] - except Exception as error: - return passed(False, reason="a second instance would not boot: " - "%s" % repr(error)[:300]) - one, other = first.test_client(), second.test_client() - if not (sign_in(one) and sign_in(other)): - return lost("coexistence", "an instance's administrator could " - "not sign in") - held(form_post(one, "/products", "/products", PRODUCT), - "the product's post") - stored = PRODUCT["sku"] in page(one, "/products").get_data( - as_text=True) - leaked = PRODUCT["sku"] in page(other, "/products").get_data( - as_text=True) - finally: - watch["on"] = False + first, second = [ + package.create_app(os.path.join(where, "coexist.sqlite")) + for where in folders_given] + except Exception as error: + return passed(False, reason="a second instance would not boot: " + "%s" % repr(error)[:300]) + one, other = first.test_client(), second.test_client() + if not (sign_in(one) and sign_in(other)): + return lost("coexistence", "an instance's administrator could not " + "sign in") + held(form_post(one, "/products", "/products", PRODUCT), + "the product's post") + stored = PRODUCT["sku"] in page(one, "/products").get_data(as_text=True) + leaked = PRODUCT["sku"] in page(other, "/products").get_data( + as_text=True) if not stored: return lost("coexistence", "the product written through the first " "instance was not stored") - stray = sorted(set(path for path in watch["paths"] - if not inside(path, folders_given + [WORKSPACE]))) - return passed(not leaked and not stray, leaked=leaked, stray=stray[:10]) + return settle_coexistence({"leaked": leaked}) + + +# Every database of every probe sits in a folder under the reader's own +# root, so the workspace and that root are the only places a build may +# write; a database's sidecars, its `-wal`, `-shm` and `-journal`, sit +# beside it. Read again as the run ends, so a write after the probe counts. +def settle_coexistence(reading): + """The co-existence reading with every write so far read against the + places a build may write.""" + stray = sorted(set(path for path in written + if not inside(path, [DATABASES, WORKSPACE]))) + reading["stray"] = stray[:10] + reading["passed"] = not reading["leaked"] and not stray + return reading # A number past any bound a price, percentage, rate or tier can have. The @@ -1174,22 +1216,24 @@ def read_trial(area, name, scores_file, other): # `cramped` refuses over 100 lines, `crowded` saves them and will not show # them, `chatty` reads each invoice line's product on its own, `shared` keeps # its products in one store for every instance, `stray` writes a fixed file -# outside its folder, `truncating` keeps the first 100 lines of an invoice, -# answering as if it kept them all, `nulling` exports one line as null, and -# `capped` prices the first 100 lines alone wherever it prices them, while -# it keeps and exports all; `unpriced` exports its total as NaN, `free` -# prices every line at nothing, `poisoned` stores a price it cannot then -# list, so its products page answers 500 once fuzzing has stored one, which -# is no fault of any probe's, `unformed` answers 500 on its rules page, -# `unexported` answers its export with a 500 and the JSON all the same, and -# `hanging` holds one concurrent write, -# and its lock, for a minute. Every mode opens its database by a `file:` URI -# with a query. `bouncing` answers a price it cannot parse with the -# sign-in's redirect and `forbidding` with a 403; -# `gated` never keeps its sign-in, and `refusing` neither keeps it nor -# redirects, answering 401; `broken` will not boot, and `unportable` boots -# on no Python but the one it names. Every mode's sign-in form quotes its -# attributes with single quotes. +# outside its folder through a handle opened at import, `truncating` keeps +# the first 100 lines of an invoice, answering as if it kept them all, +# `nulling` exports one line as null, `capped` prices the first 100 lines +# alone wherever it prices them while it keeps and exports all, `unpriced` +# exports its total as NaN, `free` prices every line at nothing, +# `unexported` answers its export with a 500 and the JSON all the same, +# `unformed` answers 500 on its rules page, and `hanging` holds one +# concurrent write, and its lock, for a minute. `poisoned` stores a price it +# cannot then list, so its products page answers 500 once fuzzing has stored +# one, which is no fault of any probe's; `detached` and `plain-save` place +# the builder's save control and the sign-out form otherwise, which is none +# either. Every mode opens its database by a `file:` URI with a query, and +# puts a sign-out form carrying another token on its pages. `bouncing` +# answers a price it cannot parse with the sign-in's redirect and +# `forbidding` with a 403; `gated` never keeps its sign-in, and `refusing` +# neither keeps it nor redirects, answering 401; `broken` will not boot, and +# `unportable` boots on no Python but the one it names. Every mode's sign-in +# form quotes its attributes with single quotes. FAKE_APP = '''import decimal import json import logging @@ -1210,13 +1254,22 @@ def read_trial(area, name, scores_file, other): def form_page(path, body): """A page whose main form posts to its own route, the builder's to its - preview, with a sign-out form carrying another token beside it: before - the main form on the products page, after it everywhere else.""" + preview with a save control sending it to `/invoices`, and a sign-out + form carrying another token before it. `plain-save` has no save control + and puts the sign-out form after; `detached` puts the save control + after the builder form, linked to it by its id.""" action = "/invoices/preview" if path == "/invoices/new" else path - main = '
%s
' % (action, TOKEN) - if path == "/products": - return SIGN_OUT + body + main - return body + main + SIGN_OUT + save = control = "" + if path == "/invoices/new" and MODE == "detached": + control = ('') + elif path == "/invoices/new" and MODE != "plain-save": + save = '' + main = ('
%s%s
%s' + % (action, TOKEN, save, control)) + if MODE == "plain-save": + return body + main + SIGN_OUT + return SIGN_OUT + body + main SKUS = {"WID-1": "10.00", "GAD-2": "24.50", "BOK-3": "12.00", "SRV-4": "80.00", "SEE-5": "3.75"} LOG = logging.getLogger("tariff") @@ -1224,6 +1277,7 @@ def form_page(path, body): IN_FLIGHT = [] GUARD = threading.Lock() STRAY = os.path.join(tempfile.gettempdir(), "tariff-quality-stray.log") +HANDLE = open(STRAY, "a") if MODE == "stray" else None class Response(object): @@ -1270,9 +1324,9 @@ def number(text): class App(object): def __init__(self, database): - if MODE == "stray": - with open(STRAY, "a") as handle: - handle.write("booted\\n") + if HANDLE is not None: + HANDLE.write("booted\\n") + HANDLE.flush() self.database = database self.products = SHARED if MODE == "shared" else None self.connect().executescript( @@ -1547,7 +1601,8 @@ def failing(probes): def runtime_self_checks(scratch): """Each planted fault fails its own probe and no other; an app that keeps the probes from running loses them.""" - modes = (["sound", "slow", "poisoned", "gated", "refusing", "broken"] + modes = (["sound", "slow", "poisoned", "detached", "plain-save", "gated", + "refusing", "broken"] + sorted(FAULTS)) readings = fake_readings(scratch, modes) probes = {mode: probe_results(*readings[mode]) for mode in modes} @@ -1568,10 +1623,14 @@ def runtime_self_checks(scratch): sound["concurrent_writes"].get("passed") is True and sound["coexistence"].get("passed") is True and "return SIGN_OUT + body + main" in FAKE_APP), - ("a post no form's action names carries the page's first token", + ("a save sent by its control's formaction carries its form's token", sound["n_plus_one"].get("passed") is True and sound["capacity_500_lines"].get("passed") is True - and "return body + main + SIGN_OUT" in FAKE_APP), + and 'formaction="/invoices"' in FAKE_APP), + ("a save control outside its form, linked by its id, carries that " + "form's token", failing(probes["detached"]) == []), + ("a post no form's action names carries the page's first token", + failing(probes["plain-save"]) == []), ("the latency is two repeats of 30 requests each", latency.get("requests") == 30 and len(latency.get("repeats") or []) == 2 From 41aca9175c2e8e72513daca27a4b1ce720b82137 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Mon, 16 Nov 2026 07:56:41 +0200 Subject: [PATCH 12/17] fix(efficacy): co-existence reads both lists, and a stray write is filed at once Codex round 10 on the quality reader: - Co-existence needs a 2xx product list from both instances before it compares them; a list that does not answer fails the probe. - A write outside the workspace and the reader's database root is filed to the report the moment it is seen, and the reader folds it into co-existence, so a run killed later keeps it. - Stand-in modes `unlisted` (the second instance's list answers 500) and `late-stray` (writes outside on its first malformed request, then hangs). Refs #119. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 2 +- docs/requirements.md | 2 +- tests/efficacy/quality.py | 146 ++++++++++++++++++++++++++------------ 3 files changed, 102 insertions(+), 48 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index 70093dd..e3653d4 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -208,7 +208,7 @@ when: | ID | Kind | Checked by | | -- | ---- | ---------- | -| FR-15-01 | Self-test | `quality.py` "a sound app passes every probe"
`quality.py` "an app answering 500 on bad input fails fuzz_robustness, and no other probe"
`quality.py` "an app raising out of the client fails fuzz_robustness, and no other probe"
`quality.py` "an app whose form page answers 500 fails fuzz_robustness, and no other probe"
`quality.py` "a form that cannot be reached is no handled request"
`quality.py` "a value one malformed request stored reaches no other case"
`quality.py` "an app whose writes lock fails concurrent_writes, and no other probe"
`quality.py` "an app dropping an overlapping write fails concurrent_writes, and no other probe"
`quality.py` "the locked write is read as locked"
`quality.py` "a writer the app hangs fails concurrent_writes, and no other probe"
`quality.py` "a hung writer stops the run, every reading before it kept"
`quality.py` "a product a malformed request stored does not reach the concurrent writes"
`quality.py` "an app refusing 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app that cannot show 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app keeping 100 of 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an export with a null line fails capacity_500_lines, and no other probe"
`quality.py` "an export whose total is NaN fails capacity_500_lines, and no other probe"
`quality.py` "an export answered 500 fails capacity_500_lines, and no other probe"
`quality.py` "an app pricing every line at nothing fails capacity_500_lines, and no other probe"
`quality.py` "a database opened by a file URI with a query stays in its folder"
`quality.py` "a total over the first 100 of 500 exported lines fails capacity_500_lines, and no other probe"
`quality.py` "an app reading each line on its own fails n_plus_one, and no other probe"
`quality.py` "statements are counted per page, and did not grow"
`quality.py` "instances sharing their data fail coexistence, and no other probe"
`quality.py` "an app writing outside its folder fails coexistence, and no other probe"
`quality.py` "the stray file is named" | +| FR-15-01 | Self-test | `quality.py` "a sound app passes every probe"
`quality.py` "an app answering 500 on bad input fails fuzz_robustness, and no other probe"
`quality.py` "an app raising out of the client fails fuzz_robustness, and no other probe"
`quality.py` "an app whose form page answers 500 fails fuzz_robustness, and no other probe"
`quality.py` "a form that cannot be reached is no handled request"
`quality.py` "a value one malformed request stored reaches no other case"
`quality.py` "an app whose writes lock fails concurrent_writes, and no other probe"
`quality.py` "an app dropping an overlapping write fails concurrent_writes, and no other probe"
`quality.py` "the locked write is read as locked"
`quality.py` "a writer the app hangs fails concurrent_writes, and no other probe"
`quality.py` "a hung writer stops the run, every reading before it kept"
`quality.py` "a product a malformed request stored does not reach the concurrent writes"
`quality.py` "an app refusing 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app that cannot show 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app keeping 100 of 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an export with a null line fails capacity_500_lines, and no other probe"
`quality.py` "an export whose total is NaN fails capacity_500_lines, and no other probe"
`quality.py` "an export answered 500 fails capacity_500_lines, and no other probe"
`quality.py` "an app pricing every line at nothing fails capacity_500_lines, and no other probe"
`quality.py` "a database opened by a file URI with a query stays in its folder"
`quality.py` "a total over the first 100 of 500 exported lines fails capacity_500_lines, and no other probe"
`quality.py` "an app reading each line on its own fails n_plus_one, and no other probe"
`quality.py` "statements are counted per page, and did not grow"
`quality.py` "instances sharing their data fail coexistence, and no other probe"
`quality.py` "an app writing outside its folder fails coexistence, and no other probe"
`quality.py` "the stray file is named"
`quality.py` "a second instance whose product list answers 500 fails coexistence, and no other probe"
`quality.py` "a write outside before a hang still fails coexistence, the path kept" | | FR-15-02 | Self-test | `quality.py` "a sound app signs in"
`quality.py` "a sign-in form quoted with single quotes signs in"
`quality.py` "a form's own token is posted, not one from a form before it"
`quality.py` "a post no form's action names carries the page's first token"
`quality.py` "a save sent by its control's formaction carries its form's token"
`quality.py` "a save control outside its form, linked by its id, carries that form's token"
`quality.py` "an app answering 401 until signed in, and never signing in, loses every probe"
`quality.py` "an app answering 403 to a malformed request loses fuzz_robustness, and no other probe"
`quality.py` "an app that never keeps its sign-in loses every probe, passing none"
`quality.py` "an app answering a malformed request with the sign-in's redirect loses fuzz_robustness, and no other probe"
`quality.py` "the redirect is read as lost, not as an answer" | | FR-15-03 | Self-test | `quality.py` "an app that will not boot loses every probe"
`quality.py` "a trial that did not install loses every probe"
`quality.py` "no report from the probe is missing, not lost"
`quality.py` "a stalled run keeps what it read and loses the rest"
`quality.py` "a run that stalled booting loses every probe" | | 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" | diff --git a/docs/requirements.md b/docs/requirements.md index be484c8..5aff355 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -218,7 +218,7 @@ | ID | Requirement | Delivered by | | -- | ----------- | ------------ | -| FR-15-01 | The benchmark shall fail each of the fuzz, concurrent-write, 500-line, N+1 and co-existence probes on an app planted with the fault it guards against, and no other probe there, and pass every probe on an app built to pass them; the 500-line probe passes only where the invoice previews 2xx, saves and renders 2xx, its JSON export answers 2xx and lists all 500 lines in order, each a well-formed record, with a finite, positive total, and its first 100 lines, saved alone, export a total a fifth of it within a cent; pages are read for answering, never for the amounts they show; the co-existence probe reads a database opened by a `file:` URI as the file it names, and fails a build that, at any time in the run, opens to write a file outside the workspace and the reader's own database root; each malformed request is sent to a fresh instance of its own, signed in afresh, and one whose form page does not answer 200 fails as unreached; and the concurrent writes run last, on a fresh instance of their own, a writer the app hangs failing them and stopping the run there, every reading before it kept. | Quality reader | +| FR-15-01 | The benchmark shall fail each of the fuzz, concurrent-write, 500-line, N+1 and co-existence probes on an app planted with the fault it guards against, and no other probe there, and pass every probe on an app built to pass them; the 500-line probe passes only where the invoice previews 2xx, saves and renders 2xx, its JSON export answers 2xx and lists all 500 lines in order, each a well-formed record, with a finite, positive total, and its first 100 lines, saved alone, export a total a fifth of it within a cent; pages are read for answering, never for the amounts they show; the co-existence probe reads a database opened by a `file:` URI as the file it names, fails where either instance's product list does not answer 2xx, and fails a build that, at any time in the run, opens to write a file outside the workspace and the reader's own database root, each such write filed as it happens so a run killed later keeps it; each malformed request is sent to a fresh instance of its own, signed in afresh, and one whose form page does not answer 200 fails as unreached; and the concurrent writes run last, on a fresh instance of their own, a writer the app hangs failing them and stopping the run there, every reading before it kept. | Quality reader | | FR-15-02 | The benchmark shall read every quality probe signed in as the seeded administrator, through the sign-in form's hidden fields however they are quoted, each post carrying the hidden fields of the form whose action, or one of whose submit controls' `formaction`, it is sent to, or else the page's first of each name, the sign-in holding only where the dashboard then answers 200, and never measure a request the sign-in turns away with its redirect, a 401, or a 403 to a request that carried its token. | Quality reader | | FR-15-03 | The benchmark shall count as lost, reading failed, a quality probe the trial keeps from running, by not installing, not booting, not signing in or not finishing in time, and as missing one it could not run itself. | Quality reader | | FR-15-04 | The benchmark shall record the latency as two repeats of the 95th percentile over 30 requests to the main routes, with no pass threshold until one is calibrated. | Quality reader | diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index 90bb6ba..aa7c277 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -97,12 +97,16 @@ "running": "boot"} +SAVING = threading.Lock() + + def save(): """The report so far, replaced whole, so a stalled run leaves a whole file behind.""" - with real_open(PROGRESS + ".part", "w", encoding="utf-8") as handle: - json.dump(report, handle) - os.replace(PROGRESS + ".part", PROGRESS) + with SAVING: + with real_open(PROGRESS + ".part", "w", encoding="utf-8") as handle: + json.dump(report, handle) + os.replace(PROGRESS + ".part", PROGRESS) def finish(): @@ -128,15 +132,33 @@ def traced(statement): statements["total"] += 1 -# Every file the application opens to write, by name, for the whole run. -# The watch is in place before the package is imported, so a handle opened -# at import and written to later is seen. -written = [] +def inside(path, roots): + path = os.path.normcase(os.path.realpath(path)) + for root in roots: + root = os.path.normcase(os.path.realpath(root)) + try: + if os.path.commonpath([path, root]) == root: + return True + except ValueError: + continue + return False +# Every file the application opens to write, by name, for the whole run. +# The watch is in place before the package is imported, so a handle opened +# at import and written to later is seen. Every database of every probe sits +# in a folder under the reader's own root, so the workspace and that root +# are the only places a build may write; a database's sidecars, its `-wal`, +# `-shm` and `-journal`, sit beside it. A write anywhere else is filed the +# moment it is seen, so a run killed later cannot lose it. def note(path): - if isinstance(path, (str, bytes, os.PathLike)): - written.append(os.path.abspath(os.fsdecode(path))) + if not isinstance(path, (str, bytes, os.PathLike)): + return + path = os.path.abspath(os.fsdecode(path)) + stray = report.setdefault("stray", []) + if not inside(path, [DATABASES, WORKSPACE]) and path not in stray: + stray.append(path) + save() real_connect = sqlite3.connect @@ -704,18 +726,6 @@ def write(index): failed=failed[:5], locked=locked) -def inside(path, roots): - path = os.path.normcase(os.path.realpath(path)) - for root in roots: - root = os.path.normcase(os.path.realpath(root)) - try: - if os.path.commonpath([path, root]) == root: - return True - except ValueError: - continue - return False - - PRODUCT = {"sku": "QCO-1", "name": "Coexistence probe", "unit_price": "2.00", "tax_category": "standard"} @@ -739,25 +749,28 @@ def coexistence(): "sign in") held(form_post(one, "/products", "/products", PRODUCT), "the product's post") - stored = PRODUCT["sku"] in page(one, "/products").get_data(as_text=True) - leaked = PRODUCT["sku"] in page(other, "/products").get_data( - as_text=True) + listed, other_listed = page(one, "/products"), page(other, "/products") + + # A list that does not answer cannot show the product, so its absence + # there says nothing about isolation. + if not (ok(listed) and ok(other_listed)): + return passed(False, reason=( + "the instances' product lists answered %d and %d, so neither's " + "contents could be read" % (listed.status_code, + other_listed.status_code))) + stored = PRODUCT["sku"] in listed.get_data(as_text=True) + leaked = PRODUCT["sku"] in other_listed.get_data(as_text=True) if not stored: return lost("coexistence", "the product written through the first " "instance was not stored") return settle_coexistence({"leaked": leaked}) -# Every database of every probe sits in a folder under the reader's own -# root, so the workspace and that root are the only places a build may -# write; a database's sidecars, its `-wal`, `-shm` and `-journal`, sit -# beside it. Read again as the run ends, so a write after the probe counts. def settle_coexistence(reading): - """The co-existence reading with every write so far read against the - places a build may write.""" - stray = sorted(set(path for path in written - if not inside(path, [DATABASES, WORKSPACE]))) - reading["stray"] = stray[:10] + """The co-existence reading with every write outside the places a build + may write, so far.""" + stray = report.get("stray") or [] + reading["stray"] = sorted(stray)[:10] reading["passed"] = not reading["leaked"] and not stray return reading @@ -1002,6 +1015,15 @@ def fuzz_robustness(): ''' +# The stray writes are filed apart from the probe that reads them, so a run +# killed after one keeps it; the reader folds them into co-existence again. +def stray_read(reading, stray): + """A co-existence reading with `stray` writes counted against it.""" + reading["stray"] = sorted(stray)[:10] + reading["passed"] = not reading["leaked"] and not stray + return reading + + def lost_reading(name, reason): """A probe the trial kept from running: failed, or no latency.""" if name in MEASURED: @@ -1050,6 +1072,8 @@ def probe_results(payload, reason=None, lost=False, stalled=None): else: readings[name] = missing_reading( name, "the in-process probe did not report it") + if payload.get("stray") and "leaked" in readings["coexistence"]: + stray_read(readings["coexistence"], payload["stray"]) return readings @@ -1222,13 +1246,16 @@ def read_trial(area, name, scores_file, other): # alone wherever it prices them while it keeps and exports all, `unpriced` # exports its total as NaN, `free` prices every line at nothing, # `unexported` answers its export with a 500 and the JSON all the same, -# `unformed` answers 500 on its rules page, and `hanging` holds one -# concurrent write, and its lock, for a minute. `poisoned` stores a price it -# cannot then list, so its products page answers 500 once fuzzing has stored -# one, which is no fault of any probe's; `detached` and `plain-save` place -# the builder's save control and the sign-out form otherwise, which is none -# either. Every mode opens its database by a `file:` URI with a query, and -# puts a sign-out form carrying another token on its pages. `bouncing` +# `unformed` answers 500 on its rules page, `unlisted` answers 500 on the +# product list of the third instance made, the second co-existence's, and +# `hanging` holds one concurrent write, and its lock, for a minute; +# `late-stray` writes outside on its first malformed request, then hangs. +# `poisoned` stores a price it cannot then list, so its products page +# answers 500 once fuzzing has stored one, which is no fault of any probe's; +# `detached` and `plain-save` place the builder's save control and the +# sign-out form otherwise, which is none either. Every mode opens its +# database by a `file:` URI with a query, and puts a sign-out form carrying +# another token on its pages. `bouncing` # answers a price it cannot parse with the sign-in's redirect and # `forbidding` with a 403; `gated` never keeps its sign-in, and `refusing` # neither keeps it nor redirects, answering 401; `broken` will not boot, and @@ -1278,6 +1305,8 @@ def form_page(path, body): GUARD = threading.Lock() STRAY = os.path.join(tempfile.gettempdir(), "tariff-quality-stray.log") HANDLE = open(STRAY, "a") if MODE == "stray" else None +LATE = os.path.join(tempfile.gettempdir(), "tariff-quality-late.log") +INSTANCES = [] class Response(object): @@ -1324,6 +1353,8 @@ def number(text): class App(object): def __init__(self, database): + INSTANCES.append(self) + self.number = len(INSTANCES) if HANDLE is not None: HANDLE.write("booted\\n") HANDLE.flush() @@ -1439,6 +1470,9 @@ def dispatch(self, path, method, data): parts = path.strip("/").split("/") if method == "GET" and path in pages: listing = " ".join(self.app.skus()) if path == "/products" else "" + if (path == "/products" and MODE == "unlisted" + and self.app.number == 3): + raise RuntimeError("the second instance's list is broken") if path == "/products" and MODE == "poisoned": self.app.prices() if path == "/rules" and MODE == "unformed": @@ -1476,6 +1510,10 @@ def create_product(self, data): return Response(302, "", {"Location": "/sign-in"}) if MODE == "forbidding": return Response(403, "forbidden") + if MODE == "late-stray": + with open(LATE, "a") as handle: + handle.write("late\\n") + time.sleep(600) return Response(200, "unit_price is not a number" + TOKEN) if not price.is_finite() or price < 0 or ( price > 10 ** 12 and MODE != "poisoned"): @@ -1567,7 +1605,7 @@ def create_app(database): "cramped": "capacity_500_lines", "crowded": "capacity_500_lines", "truncating": "capacity_500_lines", "hanging": "concurrent_writes", "unformed": "fuzz_robustness", - "unexported": "capacity_500_lines", + "unexported": "capacity_500_lines", "unlisted": "coexistence", "nulling": "capacity_500_lines", "capped": "capacity_500_lines", "unpriced": "capacity_500_lines", "free": "capacity_500_lines", "bouncing": "fuzz_robustness", @@ -1575,7 +1613,7 @@ def create_app(database): "shared": "coexistence", "stray": "coexistence"} -def fake_readings(scratch, modes, mode_arg="all"): +def fake_readings(scratch, modes, mode_arg="all", timeout=300): """Run the in-process probes against the stand-in in each mode.""" readings = {} for mode in modes: @@ -1588,7 +1626,7 @@ def fake_readings(scratch, modes, mode_arg="all"): env = dict(os.environ, PYTHONPATH=os.path.join(where, "site"), QUALITY_PROBE_WRITE_SECONDS="5") readings[mode] = probe_runtime(sys.executable, where, mode_arg, - env=env, timeout=300) + env=env, timeout=timeout) return readings @@ -1664,6 +1702,8 @@ def runtime_self_checks(scratch): "unformed": "an app whose form page answers 500 fails " "fuzz_robustness", "unexported": "an export answered 500 fails capacity_500_lines", + "unlisted": "a second instance whose product list answers 500 fails " + "coexistence", "nulling": "an export with a null line fails capacity_500_lines", "unpriced": "an export whose total is NaN fails capacity_500_lines", "free": "an app pricing every line at nothing fails " @@ -1722,9 +1762,23 @@ def runtime_self_checks(scratch): all("would not boot" in probe.get("lost", "") for probe in probes["broken"].values())), ]) - stray = os.path.join(tempfile.gettempdir(), "tariff-quality-stray.log") - if os.path.exists(stray): - os.remove(stray) + + # The first malformed request writes outside and then hangs, so the run + # is killed in its fuzzing, long after co-existence passed. + payload, reason, stalled = fake_readings(scratch, ["late-stray"], + timeout=40)["late-stray"] + late = probe_results(payload, reason, stalled=stalled) + checks.append(( + "a write outside before a hang still fails coexistence, the path kept", + late["coexistence"].get("passed") is False + and any(path.endswith("tariff-quality-late.log") + for path in late["coexistence"].get("stray", [])) + and "stopped during fuzz_robustness" in late["fuzz_robustness"].get( + "lost", ""))) + for name in ("tariff-quality-stray.log", "tariff-quality-late.log"): + path = os.path.join(tempfile.gettempdir(), name) + if os.path.exists(path): + os.remove(path) return checks From ab0c9c8773598e4c54ff9cb1eedeeb81e62ea247 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:33:17 +0200 Subject: [PATCH 13/17] fix(efficacy): a dropped tree is not measured, and a read-only database is no write Codex round 11 on the quality reader: - A trial whose source tree is not present, as an archived round leaves it, has every probe missing with "source tree not present"; nothing is installed and the tree is not restored. - A database opened by a `file:` URI with `mode=ro` is traced but not read as a write, so it is no stray for co-existence. - Stand-in mode `reader` reads a database outside its folder read-only and passes. Refs #119. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 4 +-- docs/requirements.md | 4 +-- tests/efficacy/quality.py | 61 +++++++++++++++++++++++++++++++++++---- 3 files changed, 59 insertions(+), 10 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index e3653d4..5d44a54 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -208,9 +208,9 @@ when: | ID | Kind | Checked by | | -- | ---- | ---------- | -| FR-15-01 | Self-test | `quality.py` "a sound app passes every probe"
`quality.py` "an app answering 500 on bad input fails fuzz_robustness, and no other probe"
`quality.py` "an app raising out of the client fails fuzz_robustness, and no other probe"
`quality.py` "an app whose form page answers 500 fails fuzz_robustness, and no other probe"
`quality.py` "a form that cannot be reached is no handled request"
`quality.py` "a value one malformed request stored reaches no other case"
`quality.py` "an app whose writes lock fails concurrent_writes, and no other probe"
`quality.py` "an app dropping an overlapping write fails concurrent_writes, and no other probe"
`quality.py` "the locked write is read as locked"
`quality.py` "a writer the app hangs fails concurrent_writes, and no other probe"
`quality.py` "a hung writer stops the run, every reading before it kept"
`quality.py` "a product a malformed request stored does not reach the concurrent writes"
`quality.py` "an app refusing 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app that cannot show 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app keeping 100 of 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an export with a null line fails capacity_500_lines, and no other probe"
`quality.py` "an export whose total is NaN fails capacity_500_lines, and no other probe"
`quality.py` "an export answered 500 fails capacity_500_lines, and no other probe"
`quality.py` "an app pricing every line at nothing fails capacity_500_lines, and no other probe"
`quality.py` "a database opened by a file URI with a query stays in its folder"
`quality.py` "a total over the first 100 of 500 exported lines fails capacity_500_lines, and no other probe"
`quality.py` "an app reading each line on its own fails n_plus_one, and no other probe"
`quality.py` "statements are counted per page, and did not grow"
`quality.py` "instances sharing their data fail coexistence, and no other probe"
`quality.py` "an app writing outside its folder fails coexistence, and no other probe"
`quality.py` "the stray file is named"
`quality.py` "a second instance whose product list answers 500 fails coexistence, and no other probe"
`quality.py` "a write outside before a hang still fails coexistence, the path kept" | +| FR-15-01 | Self-test | `quality.py` "a sound app passes every probe"
`quality.py` "an app answering 500 on bad input fails fuzz_robustness, and no other probe"
`quality.py` "an app raising out of the client fails fuzz_robustness, and no other probe"
`quality.py` "an app whose form page answers 500 fails fuzz_robustness, and no other probe"
`quality.py` "a form that cannot be reached is no handled request"
`quality.py` "a value one malformed request stored reaches no other case"
`quality.py` "an app whose writes lock fails concurrent_writes, and no other probe"
`quality.py` "an app dropping an overlapping write fails concurrent_writes, and no other probe"
`quality.py` "the locked write is read as locked"
`quality.py` "a writer the app hangs fails concurrent_writes, and no other probe"
`quality.py` "a hung writer stops the run, every reading before it kept"
`quality.py` "a product a malformed request stored does not reach the concurrent writes"
`quality.py` "an app refusing 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app that cannot show 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app keeping 100 of 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an export with a null line fails capacity_500_lines, and no other probe"
`quality.py` "an export whose total is NaN fails capacity_500_lines, and no other probe"
`quality.py` "an export answered 500 fails capacity_500_lines, and no other probe"
`quality.py` "an app pricing every line at nothing fails capacity_500_lines, and no other probe"
`quality.py` "a database opened by a file URI with a query stays in its folder"
`quality.py` "a total over the first 100 of 500 exported lines fails capacity_500_lines, and no other probe"
`quality.py` "an app reading each line on its own fails n_plus_one, and no other probe"
`quality.py` "statements are counted per page, and did not grow"
`quality.py` "instances sharing their data fail coexistence, and no other probe"
`quality.py` "an app writing outside its folder fails coexistence, and no other probe"
`quality.py` "the stray file is named"
`quality.py` "a second instance whose product list answers 500 fails coexistence, and no other probe"
`quality.py` "a write outside before a hang still fails coexistence, the path kept"
`quality.py` "a database outside, opened read-only, is no stray write" | | FR-15-02 | Self-test | `quality.py` "a sound app signs in"
`quality.py` "a sign-in form quoted with single quotes signs in"
`quality.py` "a form's own token is posted, not one from a form before it"
`quality.py` "a post no form's action names carries the page's first token"
`quality.py` "a save sent by its control's formaction carries its form's token"
`quality.py` "a save control outside its form, linked by its id, carries that form's token"
`quality.py` "an app answering 401 until signed in, and never signing in, loses every probe"
`quality.py` "an app answering 403 to a malformed request loses fuzz_robustness, and no other probe"
`quality.py` "an app that never keeps its sign-in loses every probe, passing none"
`quality.py` "an app answering a malformed request with the sign-in's redirect loses fuzz_robustness, and no other probe"
`quality.py` "the redirect is read as lost, not as an answer" | | FR-15-03 | Self-test | `quality.py` "an app that will not boot loses every probe"
`quality.py` "a trial that did not install loses every probe"
`quality.py` "no report from the probe is missing, not lost"
`quality.py` "a stalled run keeps what it read and loses the rest"
`quality.py` "a run that stalled booting loses every probe" | | 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" | +| 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" | diff --git a/docs/requirements.md b/docs/requirements.md index 5aff355..a7ea5eb 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -218,12 +218,12 @@ | ID | Requirement | Delivered by | | -- | ----------- | ------------ | -| FR-15-01 | The benchmark shall fail each of the fuzz, concurrent-write, 500-line, N+1 and co-existence probes on an app planted with the fault it guards against, and no other probe there, and pass every probe on an app built to pass them; the 500-line probe passes only where the invoice previews 2xx, saves and renders 2xx, its JSON export answers 2xx and lists all 500 lines in order, each a well-formed record, with a finite, positive total, and its first 100 lines, saved alone, export a total a fifth of it within a cent; pages are read for answering, never for the amounts they show; the co-existence probe reads a database opened by a `file:` URI as the file it names, fails where either instance's product list does not answer 2xx, and fails a build that, at any time in the run, opens to write a file outside the workspace and the reader's own database root, each such write filed as it happens so a run killed later keeps it; each malformed request is sent to a fresh instance of its own, signed in afresh, and one whose form page does not answer 200 fails as unreached; and the concurrent writes run last, on a fresh instance of their own, a writer the app hangs failing them and stopping the run there, every reading before it kept. | Quality reader | +| FR-15-01 | The benchmark shall fail each of the fuzz, concurrent-write, 500-line, N+1 and co-existence probes on an app planted with the fault it guards against, and no other probe there, and pass every probe on an app built to pass them; the 500-line probe passes only where the invoice previews 2xx, saves and renders 2xx, its JSON export answers 2xx and lists all 500 lines in order, each a well-formed record, with a finite, positive total, and its first 100 lines, saved alone, export a total a fifth of it within a cent; pages are read for answering, never for the amounts they show; the co-existence probe reads a database opened by a `file:` URI as the file it names, fails where either instance's product list does not answer 2xx, and fails a build that, at any time in the run, opens to write a file outside the workspace and the reader's own database root, a database opened read-only by a `mode=ro` URI being no write, each such write filed as it happens so a run killed later keeps it; each malformed request is sent to a fresh instance of its own, signed in afresh, and one whose form page does not answer 200 fails as unreached; and the concurrent writes run last, on a fresh instance of their own, a writer the app hangs failing them and stopping the run there, every reading before it kept. | Quality reader | | FR-15-02 | The benchmark shall read every quality probe signed in as the seeded administrator, through the sign-in form's hidden fields however they are quoted, each post carrying the hidden fields of the form whose action, or one of whose submit controls' `formaction`, it is sent to, or else the page's first of each name, the sign-in holding only where the dashboard then answers 200, and never measure a request the sign-in turns away with its redirect, a 401, or a 403 to a request that carried its token. | Quality reader | | FR-15-03 | The benchmark shall count as lost, reading failed, a quality probe the trial keeps from running, by not installing, not booting, not signing in or not finishing in time, and as missing one it could not run itself. | Quality reader | | FR-15-04 | The benchmark shall record the latency as two repeats of the 95th percentile over 30 requests to the main routes, with no pass threshold until one is calibrated. | Quality reader | | FR-15-05 | The benchmark shall read portability on Python 3.14, the trial installed, booted and serving a signed-in page there, and leave it missing where no Python 3.14 is found. | Quality reader | -| FR-15-06 | The benchmark shall read the quality probes in a fresh environment per trial on the spec's Python, and remove every environment once it is read. | Quality reader | +| 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 | ## Quality requirements diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index aa7c277..38161c5 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -19,6 +19,7 @@ import json import os import shutil +import sqlite3 import sys import tempfile @@ -75,7 +76,7 @@ import sys, tempfile, threading, time from decimal import Decimal, InvalidOperation from html.parser import HTMLParser -from urllib.parse import urljoin, urlsplit +from urllib.parse import parse_qs, urljoin, urlsplit from urllib.request import url2pathname PACKAGE = "tariff" @@ -167,11 +168,14 @@ def note(path): # A database named by a `file:` URI, as `Path.as_uri()` writes one with # `uri=True`, is read back to the path it names: its query, such as # `?mode=rwc`, dropped, its escapes undone, and `/C:/...` read as a drive. +# Opened with `mode=ro`, it is read and never written, so it is no write. def database_file(target): - """The file a connection opens, or None for a database in memory.""" + """The file a connection may write, or None for a database in memory + or one opened read-only.""" if target.startswith("file:"): parts = urlsplit(target) - if "mode=memory" in parts.query: + mode = parse_qs(parts.query).get("mode", [""])[-1] + if mode in ("memory", "ro"): return None path = parts.path if parts.netloc and parts.netloc != "localhost": @@ -1195,6 +1199,15 @@ def read_trial(area, name, scores_file, other): tree = scores.get("workspace") result = {"name": name, "read_at": datetime.datetime.now().isoformat( timespec="seconds")} + + # An archived round drops its extracted trees. With no tree there is + # nothing to install, which is no fault of the build's, so nothing is + # measured; the tree is not restored here. + if not tree or not os.path.isdir(tree): + reason = "source tree not present: %s" % tree + result["probes"] = {probe: missing_reading(probe, reason) + for probe in PROBES} + return result where = os.path.join(area, "quality", name) os.makedirs(where, exist_ok=True) venv = create_venv(os.path.join(where, "venv")) @@ -1250,6 +1263,8 @@ def read_trial(area, name, scores_file, other): # product list of the third instance made, the second co-existence's, and # `hanging` holds one concurrent write, and its lock, for a minute; # `late-stray` writes outside on its first malformed request, then hangs. +# `reader` reads a database outside its folder, opened read-only, which is +# no fault. # `poisoned` stores a price it cannot then list, so its products page # answers 500 once fuzzing has stored one, which is no fault of any probe's; # `detached` and `plain-save` place the builder's save control and the @@ -1306,6 +1321,8 @@ def form_page(path, body): STRAY = os.path.join(tempfile.gettempdir(), "tariff-quality-stray.log") HANDLE = open(STRAY, "a") if MODE == "stray" else None LATE = os.path.join(tempfile.gettempdir(), "tariff-quality-late.log") +REFERENCE = os.path.join(tempfile.gettempdir(), + "tariff-quality-reference.sqlite") INSTANCES = [] @@ -1355,6 +1372,10 @@ class App(object): def __init__(self, database): INSTANCES.append(self) self.number = len(INSTANCES) + if MODE == "reader": + uri = pathlib.Path(REFERENCE).as_uri() + "?mode=ro" + sqlite3.connect(uri, uri=True).execute( + "SELECT COUNT(*) FROM rates").fetchone() if HANDLE is not None: HANDLE.write("booted\\n") HANDLE.flush() @@ -1639,8 +1660,14 @@ def failing(probes): def runtime_self_checks(scratch): """Each planted fault fails its own probe and no other; an app that keeps the probes from running loses them.""" - modes = (["sound", "slow", "poisoned", "detached", "plain-save", "gated", - "refusing", "broken"] + reference = os.path.join(tempfile.gettempdir(), + "tariff-quality-reference.sqlite") + connection = sqlite3.connect(reference) + connection.execute("CREATE TABLE IF NOT EXISTS rates (code TEXT)") + connection.commit() + connection.close() + modes = (["sound", "slow", "poisoned", "detached", "plain-save", "reader", + "gated", "refusing", "broken"] + sorted(FAULTS)) readings = fake_readings(scratch, modes) probes = {mode: probe_results(*readings[mode]) for mode in modes} @@ -1733,6 +1760,9 @@ def runtime_self_checks(scratch): any("could not be reached" in entry.get("reason", "") for entry in probes["unformed"]["fuzz_robustness"].get( "failed", []))), + ("a database outside, opened read-only, is no stray write", + failing(probes["reader"]) == [] + and probes["reader"]["coexistence"].get("stray") == []), ("a hung writer stops the run, every reading before it kept", "hung it" in probes["hanging"]["concurrent_writes"].get( "reason", "") @@ -1775,7 +1805,8 @@ def runtime_self_checks(scratch): for path in late["coexistence"].get("stray", [])) and "stopped during fuzz_robustness" in late["fuzz_robustness"].get( "lost", ""))) - for name in ("tariff-quality-stray.log", "tariff-quality-late.log"): + for name in ("tariff-quality-stray.log", "tariff-quality-late.log", + "tariff-quality-reference.sqlite"): path = os.path.join(tempfile.gettempdir(), name) if os.path.exists(path): os.remove(path) @@ -1851,6 +1882,23 @@ def claim_self_checks(scratch): and not os.path.exists(os.path.join(area, "quality")))] +def absent_tree_self_checks(scratch): + """A trial whose tree is gone has nothing measured, and installs + nothing.""" + area = os.path.join(scratch, "absent") + os.makedirs(area) + scores_file = os.path.join(area, "none-1.json") + with io.open(scores_file, "w", encoding="utf-8") as handle: + json.dump({"workspace": os.path.join(area, "dropped")}, handle) + result = read_trial(area, "none-1", scores_file, None) + return [("a trial whose source tree is gone is missing, not lost", + sorted(result["probes"]) == sorted(PROBES) + and all("source tree not present" in (probe.get("missing") or "") + and not probe.get("lost") + for probe in result["probes"].values()) + and not os.path.exists(os.path.join(area, "quality")))] + + def leftover_self_checks(scratch): """A reading leaves no environment behind, and a trial that did not install loses every probe, portability too.""" @@ -1881,6 +1929,7 @@ def self_test(): os.makedirs(scratch) 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)) for label, ok in checks: print(" %-52s %s" % (label, "ok" if ok else "FAILED")) From 9d82672da161d5638c56aae87d4703afde6277a4 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:47:41 +0200 Subject: [PATCH 14/17] test(efficacy): the slowed stand-in's latency is read against its delay alone - "a slowed app reads slower by its delay" now needs each repeat's p95 of the 20 ms-delayed stand-in to be at least 20 ms, and no longer compares it with the sound run's, which read the machine's load. Refs #119. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- tests/efficacy/quality.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index 38161c5..c13a248 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -1701,10 +1701,13 @@ def runtime_self_checks(scratch): and len(latency.get("repeats") or []) == 2 and all(value > 0 for value in latency["repeats"]) and latency["value"] == max(latency["repeats"])), + # Each answer is delayed 20 ms, so each repeat's p95 is at least + # that whatever the machine's load; a comparison with the sound + # run's would read the load instead. ("a slowed app reads slower by its delay", failing(probes["slow"]) == [] - and (probes["slow"]["latency_p95_ms"].get("value") or 0) >= 20 - and probes["slow"]["latency_p95_ms"]["value"] > latency["value"]), + and len(probes["slow"]["latency_p95_ms"].get("repeats") or []) == 2 + and min(probes["slow"]["latency_p95_ms"]["repeats"]) >= 20), ("statements are counted per page, and did not grow", sound["n_plus_one"].get("one_line", 0) > 0 and sound["n_plus_one"]["twenty_lines"] From 70e575529cadea6c46a32be1013afe742d94e1b4 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:39:03 +0200 Subject: [PATCH 15/17] fix(efficacy): a redirect's location is resolved against its request Codex round 12 on the quality reader: - Every redirect's `Location` is resolved against the path the answer was asked on, with `urljoin`, before it is matched or fetched, so a relative `invoices/1` after `POST /invoices` names the invoice page; the sign-in's redirect is read the same way. - Stand-in mode `relative` answers a save with that relative form and reads as the sound app on capacity, N+1 and latency. Refs #119. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 2 +- docs/requirements.md | 2 +- tests/efficacy/quality.py | 36 +++++++++++++++++++++++++++++------- 3 files changed, 31 insertions(+), 9 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index 5d44a54..cff7034 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -209,7 +209,7 @@ when: | ID | Kind | Checked by | | -- | ---- | ---------- | | FR-15-01 | Self-test | `quality.py` "a sound app passes every probe"
`quality.py` "an app answering 500 on bad input fails fuzz_robustness, and no other probe"
`quality.py` "an app raising out of the client fails fuzz_robustness, and no other probe"
`quality.py` "an app whose form page answers 500 fails fuzz_robustness, and no other probe"
`quality.py` "a form that cannot be reached is no handled request"
`quality.py` "a value one malformed request stored reaches no other case"
`quality.py` "an app whose writes lock fails concurrent_writes, and no other probe"
`quality.py` "an app dropping an overlapping write fails concurrent_writes, and no other probe"
`quality.py` "the locked write is read as locked"
`quality.py` "a writer the app hangs fails concurrent_writes, and no other probe"
`quality.py` "a hung writer stops the run, every reading before it kept"
`quality.py` "a product a malformed request stored does not reach the concurrent writes"
`quality.py` "an app refusing 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app that cannot show 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an app keeping 100 of 500 lines fails capacity_500_lines, and no other probe"
`quality.py` "an export with a null line fails capacity_500_lines, and no other probe"
`quality.py` "an export whose total is NaN fails capacity_500_lines, and no other probe"
`quality.py` "an export answered 500 fails capacity_500_lines, and no other probe"
`quality.py` "an app pricing every line at nothing fails capacity_500_lines, and no other probe"
`quality.py` "a database opened by a file URI with a query stays in its folder"
`quality.py` "a total over the first 100 of 500 exported lines fails capacity_500_lines, and no other probe"
`quality.py` "an app reading each line on its own fails n_plus_one, and no other probe"
`quality.py` "statements are counted per page, and did not grow"
`quality.py` "instances sharing their data fail coexistence, and no other probe"
`quality.py` "an app writing outside its folder fails coexistence, and no other probe"
`quality.py` "the stray file is named"
`quality.py` "a second instance whose product list answers 500 fails coexistence, and no other probe"
`quality.py` "a write outside before a hang still fails coexistence, the path kept"
`quality.py` "a database outside, opened read-only, is no stray write" | -| FR-15-02 | Self-test | `quality.py` "a sound app signs in"
`quality.py` "a sign-in form quoted with single quotes signs in"
`quality.py` "a form's own token is posted, not one from a form before it"
`quality.py` "a post no form's action names carries the page's first token"
`quality.py` "a save sent by its control's formaction carries its form's token"
`quality.py` "a save control outside its form, linked by its id, carries that form's token"
`quality.py` "an app answering 401 until signed in, and never signing in, loses every probe"
`quality.py` "an app answering 403 to a malformed request loses fuzz_robustness, and no other probe"
`quality.py` "an app that never keeps its sign-in loses every probe, passing none"
`quality.py` "an app answering a malformed request with the sign-in's redirect loses fuzz_robustness, and no other probe"
`quality.py` "the redirect is read as lost, not as an answer" | +| FR-15-02 | Self-test | `quality.py` "a sound app signs in"
`quality.py` "a sign-in form quoted with single quotes signs in"
`quality.py` "a form's own token is posted, not one from a form before it"
`quality.py` "a post no form's action names carries the page's first token"
`quality.py` "a save sent by its control's formaction carries its form's token"
`quality.py` "a save control outside its form, linked by its id, carries that form's token"
`quality.py` "a save redirected to a relative location reads as the sound app's"
`quality.py` "an app answering 401 until signed in, and never signing in, loses every probe"
`quality.py` "an app answering 403 to a malformed request loses fuzz_robustness, and no other probe"
`quality.py` "an app that never keeps its sign-in loses every probe, passing none"
`quality.py` "an app answering a malformed request with the sign-in's redirect loses fuzz_robustness, and no other probe"
`quality.py` "the redirect is read as lost, not as an answer" | | FR-15-03 | Self-test | `quality.py` "an app that will not boot loses every probe"
`quality.py` "a trial that did not install loses every probe"
`quality.py` "no report from the probe is missing, not lost"
`quality.py` "a stalled run keeps what it read and loses the rest"
`quality.py` "a run that stalled booting loses every probe" | | 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" | diff --git a/docs/requirements.md b/docs/requirements.md index a7ea5eb..ca48bf7 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -219,7 +219,7 @@ | ID | Requirement | Delivered by | | -- | ----------- | ------------ | | FR-15-01 | The benchmark shall fail each of the fuzz, concurrent-write, 500-line, N+1 and co-existence probes on an app planted with the fault it guards against, and no other probe there, and pass every probe on an app built to pass them; the 500-line probe passes only where the invoice previews 2xx, saves and renders 2xx, its JSON export answers 2xx and lists all 500 lines in order, each a well-formed record, with a finite, positive total, and its first 100 lines, saved alone, export a total a fifth of it within a cent; pages are read for answering, never for the amounts they show; the co-existence probe reads a database opened by a `file:` URI as the file it names, fails where either instance's product list does not answer 2xx, and fails a build that, at any time in the run, opens to write a file outside the workspace and the reader's own database root, a database opened read-only by a `mode=ro` URI being no write, each such write filed as it happens so a run killed later keeps it; each malformed request is sent to a fresh instance of its own, signed in afresh, and one whose form page does not answer 200 fails as unreached; and the concurrent writes run last, on a fresh instance of their own, a writer the app hangs failing them and stopping the run there, every reading before it kept. | Quality reader | -| FR-15-02 | The benchmark shall read every quality probe signed in as the seeded administrator, through the sign-in form's hidden fields however they are quoted, each post carrying the hidden fields of the form whose action, or one of whose submit controls' `formaction`, it is sent to, or else the page's first of each name, the sign-in holding only where the dashboard then answers 200, and never measure a request the sign-in turns away with its redirect, a 401, or a 403 to a request that carried its token. | Quality reader | +| FR-15-02 | The benchmark shall read every quality probe signed in as the seeded administrator, through the sign-in form's hidden fields however they are quoted, each post carrying the hidden fields of the form whose action, or one of whose submit controls' `formaction`, it is sent to, or else the page's first of each name, every redirect resolved against its request as a browser resolves it, the sign-in holding only where the dashboard then answers 200, and never measure a request the sign-in turns away with its redirect, a 401, or a 403 to a request that carried its token. | Quality reader | | FR-15-03 | The benchmark shall count as lost, reading failed, a quality probe the trial keeps from running, by not installing, not booting, not signing in or not finishing in time, and as missing one it could not run itself. | Quality reader | | FR-15-04 | The benchmark shall record the latency as two repeats of the 95th percentile over 30 requests to the main routes, with no pass threshold until one is calibrated. | Quality reader | | 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 | diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index c13a248..58d8cc9 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -357,15 +357,27 @@ def gated(response, token=True): return True if response.status_code not in REDIRECTS: return False - return urlsplit(response.headers.get("Location", "")).path == "/sign-in" + return location(response) == "/sign-in" + + +# A redirect may name its target relative to the request, as `invoices/1` +# after a post to `/invoices`; it is resolved against the path the answer +# was asked on, as a browser resolves it. +def location(response): + """The path a redirect sends to, resolved against its request's.""" + asked = getattr(response, "asked_path", None) or "/" + return urlsplit(urljoin("http://localhost" + asked, + response.headers.get("Location", ""))).path def ask(who, method, path, data=None, headers=None): try: - return who.open(path, method=method, data=data, - headers=headers or {}) + answer = who.open(path, method=method, data=data, + headers=headers or {}) except Exception as error: raise Raised(repr(error)[:300]) + answer.asked_path = urlsplit(path).path + return answer def page(who, path): @@ -440,7 +452,7 @@ def saved_page(answer): """The invoice page a save redirected to, or None.""" if answer.status_code not in REDIRECTS: return None - path = urlsplit(answer.headers.get("Location", "")).path + path = location(answer) if re.match(r"^/invoices/[^/]+$", path) and path not in ( "/invoices/new", "/invoices/preview"): return path @@ -1263,8 +1275,9 @@ def read_trial(area, name, scores_file, other): # product list of the third instance made, the second co-existence's, and # `hanging` holds one concurrent write, and its lock, for a minute; # `late-stray` writes outside on its first malformed request, then hangs. -# `reader` reads a database outside its folder, opened read-only, which is -# no fault. +# `reader` reads a database outside its folder, opened read-only, and +# `relative` answers a save with a location relative to `/invoices`, which +# are no faults. # `poisoned` stores a price it cannot then list, so its products page # answers 500 once fuzzing has stored one, which is no fault of any probe's; # `detached` and `plain-save` place the builder's save control and the @@ -1572,7 +1585,9 @@ def invoice(self, path, data): "INSERT INTO lines VALUES (?, ?, ?, ?)", [(invoice, position, sku, quantity) for position, (sku, quantity) in enumerate(lines)]) - return Response(302, "", {"Location": "/invoices/%d" % invoice}) + target = ("invoices/%d" if MODE == "relative" + else "/invoices/%d") % invoice + return Response(302, "", {"Location": target}) def show(self, parts): if parts[0] != "invoices" or len(parts) > 2 and parts[2] not in ( @@ -1667,6 +1682,7 @@ def runtime_self_checks(scratch): connection.commit() connection.close() modes = (["sound", "slow", "poisoned", "detached", "plain-save", "reader", + "relative", "gated", "refusing", "broken"] + sorted(FAULTS)) readings = fake_readings(scratch, modes) @@ -1763,6 +1779,12 @@ def runtime_self_checks(scratch): any("could not be reached" in entry.get("reason", "") for entry in probes["unformed"]["fuzz_robustness"].get( "failed", []))), + ("a save redirected to a relative location reads as the sound " + "app's", failing(probes["relative"]) == [] + and probes["relative"]["latency_p95_ms"].get("value") is not None + and all(probes["relative"][name].get("passed") + is sound[name].get("passed") is True + for name in ("capacity_500_lines", "n_plus_one"))), ("a database outside, opened read-only, is no stray write", failing(probes["reader"]) == [] and probes["reader"]["coexistence"].get("stray") == []), From 297da26c290cf0ec0bfb2e81828d3d4e3e0114d9 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:25:30 +0200 Subject: [PATCH 16/17] test(efficacy): only the hung writer's stand-in waits 5 s for its writers - The self-test shortened the reader's wait for concurrent writers to 5 s for every stand-in mode; under load a sound stand-in's 40 writes could outlast it, read as hung, and fail a mode's "no other probe" check. The short wait now applies to the `hanging` mode alone; every other mode keeps the reader's own 120 s. Refs #119. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- tests/efficacy/quality.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index 58d8cc9..87c406c 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -1659,8 +1659,13 @@ def fake_readings(scratch, modes, mode_arg="all", timeout=300): with io.open(os.path.join(package, "__init__.py"), "w", encoding="utf-8") as handle: handle.write(FAKE_APP.replace("__MODE__", mode)) - env = dict(os.environ, PYTHONPATH=os.path.join(where, "site"), - QUALITY_PROBE_WRITE_SECONDS="5") + env = dict(os.environ, PYTHONPATH=os.path.join(where, "site")) + + # Only the hung writer's run waits a short 5 s for its writers: a + # build's writes on a loaded machine can outlast that, so every + # other mode keeps the reader's own wait. + if mode == "hanging": + env["QUALITY_PROBE_WRITE_SECONDS"] = "5" readings[mode] = probe_runtime(sys.executable, where, mode_arg, env=env, timeout=timeout) return readings From 1e06346e598924ee3e64c72333b6d8d051596174 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:37:50 +0200 Subject: [PATCH 17/17] test(efficacy): the late stray write's run is killed at 120 s, not 40 s - The `late-stray` check kills its run in fuzzing to prove a stray write survives the kill. At 40 s a slow or loaded runner could be killed before co-existence ran, so the check would read the machine; at 120 s it has ample margin. What the check asserts is unchanged. Refs #119. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- tests/efficacy/quality.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/efficacy/quality.py b/tests/efficacy/quality.py index 87c406c..529d364 100644 --- a/tests/efficacy/quality.py +++ b/tests/efficacy/quality.py @@ -1824,9 +1824,12 @@ def runtime_self_checks(scratch): ]) # The first malformed request writes outside and then hangs, so the run - # is killed in its fuzzing, long after co-existence passed. + # is killed in its fuzzing, long after co-existence passed. The kill + # comes at 120 s, well past what the probes before fuzzing take on a + # slow or loaded machine: killed sooner, the run would stop before + # co-existence and the check would read the machine, not the rule. payload, reason, stalled = fake_readings(scratch, ["late-stray"], - timeout=40)["late-stray"] + timeout=120)["late-stray"] late = probe_results(payload, reason, stalled=stalled) checks.append(( "a write outside before a hang still fails coexistence, the path kept",