diff --git a/docs/architecture/08-crosscutting-concepts.md b/docs/architecture/08-crosscutting-concepts.md index 9e0010b..4bd23c8 100644 --- a/docs/architecture/08-crosscutting-concepts.md +++ b/docs/architecture/08-crosscutting-concepts.md @@ -382,7 +382,7 @@ No person scores the judge. Two automated checks do: bundle it was quoted from, and the report prints the share found per trial. A judge that never opened the code still returns plausible numbers; this is what tells the two apart. -- **The control fixture:** eleven trees built from two pinned applications +- **The control fixture:** twelve trees built from two pinned applications (`tests/efficacy/control/`). Every tree passes the same tests as its application, so only what was changed separates them. Some are damaged, some improved. A primary dimension counts only if it falls on the damaged @@ -417,6 +417,7 @@ application's tests. | `base-1` | the application as one trial generated it, unaltered | | `degraded-1` | the domain merged into one module, `from flask import current_app` used inside `price`, and the package's exceptions reparented off `TariffError` | | `obscured-1` | the pricing algorithm inlined into one long function with abbreviated names, and nothing else: the module boundaries, the error hierarchy and the dispatch are the base's | +| `clarified-1` | the mirror of `obscured-1`: the pricing module rewritten into short functions of one step each, with names that carry the intent, and nothing else changed | | `improved-1` | a rule contract and self-registering kind registry, dispatch on concrete type removed from pricing and persistence, the hardcoded kinds tuple replaced by the registry, a `__class__.__name__` ladder removed from a template, and two stray error classes folded into the package hierarchy | | `improved-2` | `improved-1`, and the store maps a rule's own terms onto its columns with a codec per column, so no module dispatches on a kind | | `improved-3` | `improved-2`, and each kind declares the fields it asks a form for, so the form-building code and the template are derived from the registry and no layer names a kind | @@ -458,7 +459,7 @@ about the instrument: Which tree tests which row matters. `degraded-1` damages structure and leaves every function body alone, so a flat `readability` there says nothing about -the row — that is what `obscured-1` is for. Read each row against the tree +the row — that is what `obscured-1` and `clarified-1` are for. Read each row against the tree built to move it, and treat the others as a check that it is not moving on noise. diff --git a/docs/architecture/10-quality-requirements.md b/docs/architecture/10-quality-requirements.md index 3e1efed..e27352e 100644 --- a/docs/architecture/10-quality-requirements.md +++ b/docs/architecture/10-quality-requirements.md @@ -286,3 +286,55 @@ Every primary falls on the tree built to damage it and rises on one built to improve it, and each row of the second application holds still on the trees built to move another. The 33 judgings used about 1 % of the owner's weekly plan. + +### gpt-6-astra as round 5 registers it, 2026-10-28 + +The judge round 5 registers: `gpt-6-astra` through `codex exec` at effort +`high`, three judgings per tree, under the rubric as it stands. All 33 +judgings took, with evidence found 100 % on every one. Each cell is the mean, +followed by the three scores; a bold cell differs from its application's base +tree. + +| Dimension | base-1 | degraded-1 | obscured-1 | improved-1 | improved-2 | improved-3 | +|---|---|---|---|---|---|---| +| design | 3.00 (333) | **1.00** (111) | 3.00 (333) | **4.00** (444) | **4.00** (444) | **4.00** (444) | +| readability | 3.00 (333) | 3.00 (333) | **1.00** (111) | 3.00 (333) | 3.00 (333) | 3.00 (333) | +| maintainability | 3.00 (333) | **1.33** (121) | 3.00 (333) | 3.33 (433) | 3.67 (434) | **4.00** (444) | + +| Dimension | base-2 | insecure-1 | secured-1 | leaky-1 | protected-1 | +|---|---|---|---|---|---| +| security | 3.00 (333) | **1.00** (111) | **5.00** (555) | 3.00 (333) | 3.00 (333) | +| data_protection | 3.00 (333) | 3.00 (333) | 3.00 (333) | **1.00** (111) | **5.00** (555) | + +Four primaries fall on the tree built to damage them and rise on one built +to improve them. `readability` falls on `obscured-1` but reads 3 on every +improved tree, none of which was built to improve it. So `clarified-1`, the +mirror of `obscured-1`, was added to the control and judged in the same root, +three times: + +| Dimension | base-1 | clarified-1 | +|---|---|---| +| design | 3.00 (333) | 3.00 (333) | +| readability | 3.00 (333) | **3.67** (434) | +| maintainability | 3.00 (333) | 3.00 (333) | + +`readability` rises on the tree built to improve it, and the other two rows +hold still there. With that, every primary falls on the tree built to damage +it and rises on one built to improve it. The rise is the smallest in the +run: one of the three judgings read 3, so a single judging would have missed +it. The second application's rows hold still on the trees built to move +another. + +The re-anchored rubric reads the same under gpt-6-astra as under +claude-opus-5-5, with sharper steps: `design` reaches 4 from `improved-1`, and +the four rows of the second application read 1 or 5 on all three judgings. + +`security` is also read on the first application, where no tree is built to +move it. There its triples spread from 2 to 4, a one-point flip between +judgings of the same bundle, which the three judgings per trial are there to +absorb. + +The first 33 judgings took 70 minutes and used about 11 % of the OpenAI +plan's weekly limit: it read 3 % used before and 14 % after. A block of 75 +trials at three judgings each would take about 75 %. The three judgings of +`clarified-1` came after. diff --git a/docs/journeys/check/check-the-judge.md b/docs/journeys/check/check-the-judge.md index b11a250..67cffd1 100644 --- a/docs/journeys/check/check-the-judge.md +++ b/docs/journeys/check/check-the-judge.md @@ -22,8 +22,8 @@ Assumptions: | 1 | Owner | Runs the control's self test | 2 min | Builds in a temporary directory and checks every mutation landed | | 2 | Owner | Builds the control root | 2 min | Prints one line per entity it changed, read back off the trees | | 3 | Owner | Runs the tests in each built tree | 10 min | Every tree passes, so only structure separates them | -| 4 | Judge | Reads the control root, three times per tree | 30 to 60 min | Eleven trees, 33 judgings | -| 5 | Owner | Reads each primary row: down on `degraded-1`, `obscured-1`, `insecure-1`, `leaky-1`, up on `improved-*`, `secured-1`, `protected-1` | 15 min | A row that does not move cannot decide a round. Results go in [ch. 10.7](../../architecture/10-quality-requirements.md) | +| 4 | Judge | Reads the control root, three times per tree | 75 to 80 min | Twelve trees, 36 judgings | +| 5 | Owner | Reads each primary row: down on `degraded-1`, `obscured-1`, `insecure-1`, `leaky-1`, up on `improved-*`, `clarified-1`, `secured-1`, `protected-1` | 15 min | A row that does not move cannot decide a round. Results go in [ch. 10.7](../../architecture/10-quality-requirements.md) | | | | Total | about 1.5 hours | | ## Commands diff --git a/tests/efficacy/control/control.py b/tests/efficacy/control/control.py index dde35bf..d6d725b 100644 --- a/tests/efficacy/control/control.py +++ b/tests/efficacy/control/control.py @@ -55,7 +55,7 @@ MERGED = ("errors", "models", "rules", "pricing") TRIALS = ("base-1", "degraded-1", "improved-1", "improved-2", - "improved-3", "obscured-1") + "improved-3", "obscured-1", "clarified-1") # The second application's trees: its security and its handling of personal # data, each damaged in one tree and improved in another. @@ -319,6 +319,20 @@ def obscure(tree): os.path.join(tree, "tariff", "pricing.py")) +def clarify(tree): + """Improve what a reader has to hold in their head, and nothing else. + + The mirror of `obscure`: only the pricing module is rewritten, into short + functions that each do one step, with names that carry the intent and no + expression that needs a second reading. The module boundaries, the error + hierarchy and the dispatch on concrete rule classes stay the base's, so + the readability row has something to rise on and every other row has + nothing. + """ + shutil.copy2(os.path.join(OVERLAY, "pricing_clarified.py"), + os.path.join(tree, "tariff", "pricing.py")) + + def edit(tree, rel, *swaps): """Apply `(old, new, where)` swaps to one file of the tree, in order.""" text = read(tree, rel) @@ -484,34 +498,35 @@ def protect(tree): LANDINGS = ( ("tariff/core.py exists", lambda t: os.path.isfile( os.path.join(t, "tariff", "core.py")), - {"base-1": False, "degraded-1": True, "improved-1": False, "improved-2": False, "obscured-1": False, "improved-3": False}), + {"base-1": False, "clarified-1": False, "degraded-1": True, "improved-1": False, "improved-2": False, "obscured-1": False, "improved-3": False}), # Read against the domain alone: the web package imports flask in every # tree, so a whole-tree probe would answer yes whatever was done. ("the domain imports flask", lambda t: "from flask import current_app" - in domain(t), {"base-1": False, "degraded-1": True, + in domain(t), {"base-1": False, "clarified-1": False, "degraded-1": True, "improved-1": False, "improved-2": False, "obscured-1": False, "improved-3": False}), ("ValidationError derives from TariffError", lambda t: "class ValidationError(TariffError):" in whole(t), - {"base-1": True, "degraded-1": False, "improved-1": True, "improved-2": True, "obscured-1": True, "improved-3": True}), + {"base-1": True, "clarified-1": True, "degraded-1": False, "improved-1": True, "improved-2": True, "obscured-1": True, "improved-3": True}), # The damaged tree keeps the ladder: merging the modules moves it into # core.py rather than removing it. Only the improved tree loses it. ("pricing dispatches on concrete type", - lambda t: "isinstance(r, TieredRule)" in whole(t), - {"base-1": True, "degraded-1": True, "improved-1": False, "improved-2": False, "obscured-1": True, "improved-3": False}), + lambda t: ("isinstance(r, TieredRule)" in whole(t) + or "isinstance(rule, TieredRule)" in domain(t)), + {"base-1": True, "clarified-1": True, "degraded-1": True, "improved-1": False, "improved-2": False, "obscured-1": True, "improved-3": False}), ("the rules declare a contract", lambda t: "class Rule(ABC):" in whole(t), - {"base-1": False, "degraded-1": False, "improved-1": True, "improved-2": True, "obscured-1": False, "improved-3": True}), + {"base-1": False, "clarified-1": False, "degraded-1": False, "improved-1": True, "improved-2": True, "obscured-1": False, "improved-3": True}), ("the kinds are hardcoded", lambda t: 'KINDS = ("percentage", "bulk", "tiered", "coupon")' - in whole(t), {"base-1": True, "degraded-1": True, + in whole(t), {"base-1": True, "clarified-1": True, "degraded-1": True, "improved-1": False, "improved-2": False, "obscured-1": True, "improved-3": False}), ("an error class sits outside the hierarchy", lambda t: "class _BadRequest(Exception):" in whole(t), - {"base-1": True, "degraded-1": True, "improved-1": False, "improved-2": False, "obscured-1": True, "improved-3": False}), + {"base-1": True, "clarified-1": True, "degraded-1": True, "improved-1": False, "improved-2": False, "obscured-1": True, "improved-3": False}), ("the template branches on a class name", lambda t: "__class__.__name__" in whole(t), - {"base-1": True, "degraded-1": True, "improved-1": False, "improved-2": False, "obscured-1": True, "improved-3": False}), + {"base-1": True, "clarified-1": True, "degraded-1": True, "improved-1": False, "improved-2": False, "obscured-1": True, "improved-3": False}), # The seed fixture names a kind per sample row in every tree, and has to: # that is data. What this reads is whether the store DISPATCHES on kind, @@ -520,18 +535,24 @@ def protect(tree): lambda t: ('kind == "tiered"' in store(t) or "isinstance(rule, TieredRule)" in store(t) or "_TO_ROW = {" in store(t)), - {"base-1": True, "degraded-1": True, "improved-1": True, + {"base-1": True, "clarified-1": True, "degraded-1": True, "improved-1": True, "improved-2": False, "obscured-1": True, "improved-3": False}), ("the pricing algorithm is broken into named steps", lambda t: "def _price_line(" in whole(t), - {"base-1": True, "degraded-1": True, "improved-1": True, + {"base-1": True, "clarified-1": True, "degraded-1": True, "improved-1": True, "improved-2": True, "obscured-1": False, "improved-3": True}), + ("the invoice's discounts are a step of their own", + lambda t: "def _apply_invoice_rules(" in whole(t), + {"base-1": False, "clarified-1": True, "degraded-1": False, + "improved-1": False, "improved-2": False, "improved-3": False, + "obscured-1": False}), + ("the form names a rule kind", lambda t: ('kind == "percentage"' in form(t) or "Buy (bulk)" in form(t)), - {"base-1": True, "degraded-1": True, "improved-1": True, + {"base-1": True, "clarified-1": True, "degraded-1": True, "improved-1": True, "improved-2": True, "improved-3": False, "obscured-1": True}), ) @@ -697,6 +718,7 @@ def build(root): improve_further(made["improved-2"]) improve_form(made["improved-3"]) obscure(made["obscured-1"]) + clarify(made["clarified-1"]) second = extract(pinned(BASE_2, BASE_2_SHA256), scoring, TRIALS_2) insecure(second["insecure-1"]) diff --git a/tests/efficacy/control/overlay/pricing_clarified.py b/tests/efficacy/control/overlay/pricing_clarified.py new file mode 100644 index 0000000..96e032d --- /dev/null +++ b/tests/efficacy/control/overlay/pricing_clarified.py @@ -0,0 +1,281 @@ +"""The pricing algorithm: price(invoice, rules, jurisdiction) -> PricedInvoice.""" + +from dataclasses import dataclass +from decimal import Decimal, ROUND_DOWN, ROUND_HALF_EVEN + +from .errors import PricingError +from .models import Jurisdiction, Product +from .rules import BulkRule, CouponRule, PercentageRule, TieredRule + +CENT = Decimal("0.01") +ZERO = Decimal("0.00") + +# The order the line rules apply in. Invoice rules apply percentage, then +# coupon, in `_apply_invoice_rules`. +LINE_RULE_KINDS = (TieredRule, BulkRule, PercentageRule) + + +@dataclass +class PricedLine: + product: Product + quantity: int + gross: Decimal + line_discount: Decimal + net: Decimal + invoice_discount: Decimal + taxable: Decimal + tax: Decimal + total: Decimal + applied: list + + +@dataclass +class PricedInvoice: + currency: str + jurisdiction: Jurisdiction + lines: list + subtotal: Decimal + discount_total: Decimal + taxable_total: Decimal + tax_total: Decimal + total: Decimal + applied: list + + +@dataclass +class _DiscountedLine: + """A line after its own rules, before the invoice's discount reaches it.""" + + product: Product + quantity: int + gross: Decimal + line_discount: Decimal + net: Decimal + applied: list + + +def _round_to_cents(amount: Decimal) -> Decimal: + """Round half-even to two decimal places.""" + return amount.quantize(CENT, rounding=ROUND_HALF_EVEN) + + +def _truncate_to_cents(amount: Decimal) -> Decimal: + """Drop everything past the second decimal place.""" + return amount.quantize(CENT, rounding=ROUND_DOWN) + + +def _total(amounts) -> Decimal: + return sum(amounts, ZERO) + + +# One rule, applied to a running amount. + +def _tiered_amount(rule: TieredRule, amount: Decimal, quantity: int) -> Decimal: + """Every unit at the price of the highest tier the quantity reaches. + + Below the first tier the amount is unchanged. + """ + reached_prices = [tier_price for min_quantity, tier_price in rule.tiers + if quantity >= min_quantity] + if not reached_prices: + return amount + return reached_prices[-1] * quantity + + +def _bulk_amount(rule: BulkRule, amount: Decimal, quantity: int) -> Decimal: + """Each complete group of `buy` units charged as `pay` units.""" + complete_groups, leftover_units = divmod(quantity, rule.buy) + chargeable_units = complete_groups * rule.pay + leftover_units + amount_per_unit = amount / quantity + return amount_per_unit * chargeable_units + + +def _percentage_amount(percent: Decimal, amount: Decimal) -> Decimal: + """The amount reduced by `percent`.""" + share_kept = Decimal(1) - percent / Decimal(100) + return amount * share_kept + + +def _coupon_amount(rule: CouponRule, amount: Decimal) -> Decimal: + """The amount reduced by the coupon's percentage, or by its fixed amount. + + A fixed amount larger than the invoice takes it to zero, never below. + """ + if rule.percent is not None: + return _percentage_amount(rule.percent, amount) + return amount - min(rule.amount, amount) + + +def _line_rule_amount(rule, amount: Decimal, quantity: int) -> Decimal: + if isinstance(rule, TieredRule): + return _tiered_amount(rule, amount, quantity) + if isinstance(rule, BulkRule): + return _bulk_amount(rule, amount, quantity) + return _percentage_amount(rule.percent, amount) + + +def _invoice_rule_amount(rule, amount: Decimal) -> Decimal: + """What the invoice would carry after `rule`, rounded to cents.""" + if isinstance(rule, CouponRule): + return _round_to_cents(_coupon_amount(rule, amount)) + return _round_to_cents(_percentage_amount(rule.percent, amount)) + + +# Choosing one rule of a kind. + +def _lowest(outcomes): + """The `(amount, rule)` with the lowest amount; a tie goes to the lower + rule_id.""" + return min(outcomes, key=lambda outcome: (outcome[0], outcome[1].rule_id)) + + +def _line_rules_of_kind(rules, kind, sku): + return [rule for rule in rules if isinstance(rule, kind) and rule.sku == sku] + + +def _invoice_percentage_rules(rules): + return [rule for rule in rules + if isinstance(rule, PercentageRule) and rule.sku is None] + + +def _carried_coupons(rules, coupon_codes): + carried = {code.strip() for code in coupon_codes} + return [rule for rule in rules + if isinstance(rule, CouponRule) and rule.code.strip() in carried] + + +# The algorithm's steps, in the order `price` takes them. + +def _refuse_bad_input(invoice, rules): + """Raise for the inputs pricing refuses before it prices anything.""" + if not invoice.lines: + raise PricingError("invoice has no lines") + + rule_ids = [rule.rule_id for rule in rules] + if len(rule_ids) != len(set(rule_ids)): + raise PricingError("two rules share a rule_id") + + known_codes = {rule.code.strip() for rule in rules + if isinstance(rule, CouponRule)} + for code in invoice.coupon_codes: + if code.strip() not in known_codes: + raise PricingError(f"unknown coupon code {code!r}") + + +def _price_line(line, rules) -> _DiscountedLine: + """Apply the line's own rules, the lowest of each kind, in kind order.""" + if line.quantity < 1: + raise PricingError("line quantity must be at least one") + + gross = line.product.unit_price * line.quantity + amount = gross + applied = [] + for kind in LINE_RULE_KINDS: + candidates = _line_rules_of_kind(rules, kind, line.product.sku) + if not candidates: + continue + outcomes = [(_line_rule_amount(rule, amount, line.quantity), rule) + for rule in candidates] + amount, chosen = _lowest(outcomes) + applied.append(chosen.rule_id) + + net = _round_to_cents(amount) + return _DiscountedLine( + product=line.product, + quantity=line.quantity, + gross=gross, + line_discount=_round_to_cents(gross) - net, + net=net, + applied=applied, + ) + + +def _apply_invoice_rules(subtotal: Decimal, invoice, rules): + """Apply the invoice-wide percentage, then the coupon, rounding after each. + + Returns the discounted subtotal and the rule_ids that applied, in order. + """ + amount = subtotal + applied = [] + stages = (_invoice_percentage_rules(rules), + _carried_coupons(rules, invoice.coupon_codes)) + for candidates in stages: + if not candidates: + continue + outcomes = [(_invoice_rule_amount(rule, amount), rule) + for rule in candidates] + amount, chosen = _lowest(outcomes) + applied.append(chosen.rule_id) + return amount, applied + + +def _allocate(discount_total: Decimal, subtotal: Decimal, nets: list) -> list: + """Split the invoice's discount across the lines pro rata by net. + + Each line takes its exact share truncated to cents. The cents still owed + go one each to the lines that lost most to the truncation, the earlier + line first on a tie, so the shares sum to the discount exactly. + """ + if subtotal == 0: + return [ZERO] * len(nets) + + exact_shares = [discount_total * net / subtotal for net in nets] + shares = [_truncate_to_cents(share) for share in exact_shares] + lost_to_truncation = [exact - share + for exact, share in zip(exact_shares, shares)] + cents_owed = int((discount_total - _total(shares)) / CENT) + + most_lost_first = sorted(range(len(nets)), + key=lambda index: (-lost_to_truncation[index], index)) + for index in most_lost_first[:cents_owed]: + shares[index] += CENT + return shares + + +def _tax_line(line: _DiscountedLine, invoice_discount: Decimal, + jurisdiction: Jurisdiction) -> PricedLine: + """Take the line's share of the invoice discount off, and tax the rest.""" + taxable = line.net - invoice_discount + rate = jurisdiction.rates.get(line.product.tax_category, + jurisdiction.default_rate) + tax = _round_to_cents(taxable * rate) + return PricedLine( + product=line.product, + quantity=line.quantity, + gross=line.gross, + line_discount=line.line_discount, + net=line.net, + invoice_discount=invoice_discount, + taxable=taxable, + tax=tax, + total=taxable + tax, + applied=line.applied, + ) + + +def price(invoice, rules, jurisdiction) -> PricedInvoice: + """Price each line, discount the invoice, spread the discount, tax it.""" + _refuse_bad_input(invoice, rules) + + discounted_lines = [_price_line(line, rules) for line in invoice.lines] + subtotal = _total(line.net for line in discounted_lines) + discounted_subtotal, applied = _apply_invoice_rules(subtotal, invoice, rules) + discount_total = subtotal - discounted_subtotal + + shares = _allocate(discount_total, subtotal, + [line.net for line in discounted_lines]) + priced_lines = [_tax_line(line, share, jurisdiction) + for line, share in zip(discounted_lines, shares)] + tax_total = _total(line.tax for line in priced_lines) + + return PricedInvoice( + currency=invoice.currency, + jurisdiction=jurisdiction, + lines=priced_lines, + subtotal=subtotal, + discount_total=discount_total, + taxable_total=discounted_subtotal, + tax_total=tax_total, + total=discounted_subtotal + tax_total, + applied=applied, + )