diff --git a/README.md b/README.md index defa5591a5..591d159f2c 100644 --- a/README.md +++ b/README.md @@ -663,6 +663,24 @@ reference and the stored-input verdict (`stored_inputs`), so a waiver ships with the release it waives, and a `gate_evidence` block that says of each verdict whether it is bound, skipped by flag or never evaluated. +The QRF tail gate checks a sparse QRF output only when it has 500 or more +carriers, the records with positive weighted absolute mass, and reports one +with fewer as thin. It fails a checked column whose top 100 records carry +more than 75% of its weighted absolute mass, unless the run's register +(`--qrf-tail-concentration-exclusions`) lists the column with a reason. That +test cannot see one record carrying a fifth of a column: in #1259's seed-0 +rerun of the #1251 chain, one tax unit of weight 644.7 carried 21.7% of line +32's weighted absolute mass at initial weights, while the top 100 of its +16,001 carriers carried 45.1%. +`qrf_tail_concentration.json` therefore also reports, for every numeric QRF +output, dense and thin ones included, the largest single record's share of +the weighted absolute mass and that record's weight, beside the top-100 share +(`surface.single_record_concentration`). These numbers never change the +gate's verdict: the release tool measures after the gate runs and lists an +output it cannot measure under `unmeasured` with the reason. A column with no +mass reports no share. The dry run reports the same two numbers at base weights, +and the post-export probe compares the block, unmeasured reasons included. + A US release may not store a column that looks like a policyengine-us variable (lowercase snake_case) unless the engine it is certified against defines that variable or `microcosm.data.stored_inputs.US_STORED_NON_VARIABLE_COLUMNS` diff --git a/changelog.d/us-qrf-tail-single-record-share.added.md b/changelog.d/us-qrf-tail-single-record-share.added.md new file mode 100644 index 0000000000..bf67113238 --- /dev/null +++ b/changelog.d/us-qrf-tail-single-record-share.added.md @@ -0,0 +1 @@ +The US release's QRF tail evidence now reports each QRF output's largest single record. The tail gate tests the top 100 records' share of a column's weighted absolute mass, so one record can carry a fifth of a column and pass: in #1259's seed-0 rerun of the #1251 chain, one tax unit of weight 644.7 carried 21.7% of line 32's weighted absolute mass at initial weights, while the top 100 of its 16,001 carriers carried 45.1%. `microcosm.build.gates.single_record_concentration` measures a column's top-1 share, the weight of that record, the top-k share (on a column the gate checks whose total mass is finite, the gate's own share capped at 1) and the carrier count, on the gate's own population. `qrf_tail_concentration.json` records it for every numeric QRF output, dense and thin ones included, under `surface.single_record_concentration`. The measurement adds no threshold and changes neither the gate's verdict nor its details. It runs after the gate, and an output it cannot measure goes under `unmeasured` with the reason rather than failing the run. A column with no mass, or a mass beyond the float range, reports no share. The release dry run carries the share and the weight on each row at base weights, and the post-export probe compares the block, unmeasured reasons included, with a release that recorded it. diff --git a/experiments/1268-us-qrf-tail-top1-share/README.md b/experiments/1268-us-qrf-tail-top1-share/README.md new file mode 100644 index 0000000000..5a1d94d47d --- /dev/null +++ b/experiments/1268-us-qrf-tail-top1-share/README.md @@ -0,0 +1,244 @@ +# Largest single record of each QRF output (#1268): receipts + +Pull request: PolicyEngine/microcosm#1268. It adds +`microcosm.build.gates.single_record_concentration` and the +`surface.single_record_concentration` block of `qrf_tail_concentration.json`. +This folder holds the scripts and logs behind the numbers that pull request +quotes. + +## What the scripts measure + +For every numeric QRF-imputed output of one certified US release: + +- the largest single record's share of the column's weighted absolute mass + (`|value| × weight`), the top-1 share; +- that record's weight; +- the top-100 share, the number the QRF tail gate grades on the columns it + checks; +- and the number of carriers, the records with positive mass. + +`route_a_top1.py` takes these once at the release's calibrated household +weights and once at the initial weights in its calibration sidecar. + +## Release and commit + +| Item | Value | +|---|---| +| Release | `populace-us-2024-0fb05b6-4b57d15a287c-20260930T150401Z` (Route A) | +| `populace_us_2024.h5`, sha256 | `417d23aed4d044de2e657a7b5d856136975d25739dbdb4ddd72866f841de1559` | +| Recorded `qrf_tail_concentration.json`, sha256 | `8311943453d524a5b1a286cd440e40ea56a5909da0aa9971d065da9cc72cdc58` | +| Commit that ran the measurement | `a6644d62b2f7b6d4e2afbd91212e8f25dd82ac1d` | + +On 2026-11-11 the Hugging Face dataset repository `policyengine/populace-us` +was public and ungated. Its revision +`07db2a23ca6598abb837c154a085655eeeefca73` holds this release: +`populace_us_2024.h5` (the sha256 above) and +`populace_us_2024_calibration.npz` (sha256 +`d1403f75c549f030dcc13c2df3c2e4f7365b67105caa1bb0440e9ab8683f2d55`) at the top +level, and `release_manifest.json` and `qrf_tail_concentration.json` under +`releases//`. + +`route_a_top1.py` loads the release tool and the post-export probe from a +checkout. It reads the H5's QRF columns with the probe's loader and runs the +release tool's `_qrf_tail_concentration_gate` on them. At `a6644d62b` the +source manifest lists 106 QRF outputs, and the H5 carries 68 of them as +numeric columns. + +Before it reports anything, the script checks its own inputs and stops on any +difference: + +- the H5 and the recorded `qrf_tail_concentration.json` hash to the sha256s + in the release manifest; +- at calibrated weights, the gate's verdict, its details after a JSON round + trip and the four surface lists (checked, dense, absent and non-numeric + columns) equal the recorded file's, and the probe's `compare_qrf_tail` + finds no difference across the 33 columns with a top-100 share; +- the sidecar's `household_weight` equals the H5's household weights element + for element, so `initial_household_weight` aligns by row. + +`route_a_top1.log` records the outcome of each check. + +## Files + +| File | What it holds | +|---|---| +| `route_a_top1.py` | The Route A measurement. | +| `route_a_top1.md` | Its table: all 68 measured columns, sorted by top-1 share at final weights. | +| `route_a_top1.log` | Its printed summary: hashes, commit, the checks above and the columns above 5% and 10%. | +| `calibration_weight_stats.py`, `.log` | Household weights before and after calibration. | +| `shared_largest_records.py` | Which columns above 5% share a largest record or a household. | +| `minimize.py`, `.log` | Inputs whose gate share passes 1 under every legal arrangement of the partition. | +| `monotone_k.py`, `.log` | Whether a larger `top_k` can lower the top-k share. | + +Two outputs stay out of the repository because they name records: +`route_a_top1.json`, which `route_a_top1.py` writes beside the table and which +gives each column's largest record by `record_id` and `household_id`, and the +printed output of `shared_largest_records.py`. + +This folder's copies differ from the scripts that ran in form only. `ruff +format` reflowed them, three lines gained a `# noqa` comment, and +`shared_largest_records.py` lost an unused `numpy` import. With that import +set aside, each copy parses to the same syntax tree as the script that ran. + +## How to rerun + +`minimize.py` and `monotone_k.py` need only numpy: + +```bash +python minimize.py > minimize.log +python monotone_k.py . > monotone_k.log # the argument: the folder that holds minimize.py +``` + +A rerun on 2026-11-11 (numpy 2.4.6, macOS arm64) printed both committed logs +byte for byte. Two lines of `minimize.log` describe the machine that ran it: +the line that prints numpy's own partition, and the last line, which prints +the numpy version and the platform. Every other line comes from sums the +script arranges itself. + +The other three scripts need the release's files. Download the four files +named above at that revision and lay them out as `route_a_top1.py` reads them: + +```text +populace-us-2024-0fb05b6-4b57d15a287c-20260930T150401Z/ + artifacts/populace_us_2024.h5 + artifacts/populace_us_2024_calibration.npz + releases/populace-us-2024-0fb05b6-4b57d15a287c-20260930T150401Z/release_manifest.json + releases/populace-us-2024-0fb05b6-4b57d15a287c-20260930T150401Z/qrf_tail_concentration.json +``` + +Then run: + +```bash +python route_a_top1.py +python calibration_weight_stats.py +python shared_largest_records.py /route_a_top1.json +``` + +`route_a_top1.py` needs a Python environment with the checkout's packages +installed; the other two need h5py and numpy. On 2026-11-11, reruns on that +revision's files gave the same results: `calibration_weight_stats.py` printed +the committed log byte for byte, and `shared_largest_records.py` printed the +shared records and households that +[Largest records that columns share](#largest-records-that-columns-share) +reports. + +Run `route_a_top1.py` against a checkout of `a6644d62b`. The script stops +unless the absent QRF outputs equal the recorded ones, and the source manifest +has since gained eight QRF outputs that this H5 does not carry +(`detailed_industry_recode`, `federal_parent_plus_loan_balance`, +`federal_student_loan_balance`, `federal_student_loan_graduate_share`, +`is_income_based_repayment_new_borrower`, `major_industry_recode`, +`passive_partnership_s_corp_income` and `worked_last_year`). + +## Results + +### Top-1 shares in the release + +`route_a_top1.md` lists all 68 columns. Four carry no mass (`s_corp_income` +and the three second-home mortgage columns), so 64 have a share. + +| Weights | Columns above 5% | Columns above 10% | +|---|---:|---:| +| Final (calibrated) | 17 | 7 | +| Initial | 13 | 8 | + +The table's "largest record" cell prints the record's signed value, and the +mass beside it is `|value| × weight`: `farm_rent_income` reads +`$-288,692 × 3,896.9 = $1.12B`. + +### Calibration weights + +From `calibration_weight_stats.log`, over the release's 352,932 households: + +| Statistic | Initial | Final | +|---|---:|---:| +| Total weight | 138,098,416.6 | 138,098,416.6 | +| Median | 378.04 | 117.78 | +| 99th percentile | 1,021.20 | 3,730.77 | +| Minimum | 0.1028 | 0.0207 | +| Maximum | 2,371.62 | 9,740.07 | + +The final-to-initial ratio runs from 0.014248 to 5.0000 across households, +and no household starts at weight 0. + +### Largest records that columns share + +`shared_largest_records.py` maps each largest record to its household for the +17 columns above 5% at final weights: + +- One person's record is the largest record of both W-2 wage columns, + `sstb_w2_wages_from_qualified_business` and + `w2_wages_from_qualified_business`. +- One household holds three columns' largest records. One of its members + holds the largest record of `sstb_self_employment_income_before_lsr` and of + `sstb_unadjusted_basis_qualified_property`, and a tax unit in that household + holds the largest record of `unrecaptured_section_1250_gain`. +- The other 12 columns have their largest records in 12 different households. + +So 14 households hold the largest records of these 17 columns. The script +prints each record's household and not its tax unit. A separate lookup in the +H5's person table found that the person in the second finding belongs to the +tax unit named there. + +### The gate's share can pass 1 + +`tail_concentration_gate` sums its tail in the order `np.partition` leaves it +and its total in record order. `minimize.py` sums the tail in every legal +arrangement of a partition: + +- The nine-record input + `[2, 3, 2, 1, 1e16, 7, 1e15, 1, 0.5]` at `top_k = 8` gives a share of + 0.9999999999999998, 1.0 or 1.0000000000000002, depending on the tail's + order. +- With `top_k` of 1 or 2, no input of three to five records from the script's + ten-value grid gives a share above 1.0 in any legal arrangement. +- With four records and `top_k = 3`, 81 grid inputs give a share above 1 in + every legal arrangement. One of them is `[2**53 + 2, 3, 1, 0.5]`: the + record-order total is `2**53 + 4`, and the two legal tails give + 1.0000000000000002 and 1.0000000000000004, while the exact share rounds to + 1.0. + +`single_record_concentration` therefore caps `top_k_share` at 1. + +### A larger top-k can lower the share + +`monotone_k.py` searches every four- and five-record input from an eight-value +grid, at every `top_k` below the record count. It compares shares capped at 1, +as `single_record_concentration` reports them: + +- For 2,651 pairs of an input and a `top_k`, some legal arrangement at `top_k` + gives a larger share than some legal arrangement at `top_k + 1`. For example + `[0.5, 0.5, 0.5, 0.5, 2**53 + 2]` can give 1.0 at `top_k = 3` and + 0.9999999999999998 at `top_k = 4`. +- For no pair does every arrangement at `top_k` give more than every + arrangement at `top_k + 1`. + +So a larger `top_k` can lower `top_k_share` under some arrangement of the +partition, and on this grid never under all of them. The function's test +module pins one such input, `[0.5, 1, 2**53, 0.5, 0.5]`, with the arrangement +fixed. + +### Mutation run + +At commit `3ccae300a`, a run applied fourteen mutants to +`single_record_concentration`, one at a time, and the function's test module +(`test_single_record_concentration.py`) failed on every one. The mutants: + +1. the smallest weight among tied records, in place of the largest; +2. no cap on `top_k_share`; +3. a cap one rounding step too loose; +4. `carriers < top_k` for `carriers <= top_k`; +5. no shortcut when every carrier sits in the top `top_k`; +6. a tail one record short; +7. the tail summed in sorted order; +8. no check that the total is finite; +9. zero-mass records counted as carriers; +10. weights left out of the finite filter; +11. signed mass in place of absolute mass; +12. the median mass in place of the largest; +13. the top-1 mass over the tail in place of the total; +14. overflow left to warn. + +That run's script patched a checkout in place, so this folder does not hold +it. The pull request's description reports a later mutation pass, and this +folder holds no log of either run. diff --git a/experiments/1268-us-qrf-tail-top1-share/calibration_weight_stats.log b/experiments/1268-us-qrf-tail-top1-share/calibration_weight_stats.log new file mode 100644 index 0000000000..59487cc336 --- /dev/null +++ b/experiments/1268-us-qrf-tail-top1-share/calibration_weight_stats.log @@ -0,0 +1,5 @@ +sidecar keys: ['final_estimates', 'household_weight', 'initial_estimates', 'initial_household_weight', 'registry_version', 'relative_errors', 'target_names', 'target_values'] +households: 352,932 +initial total 138,098,416.6 median 378.04 p99 1,021.20 min 0.1028 max 2,371.62 +final total 138,098,416.6 median 117.78 p99 3,730.77 min 0.0207 max 9,740.07 +final/initial ratio: max 5.0000 min 0.014248 households with initial weight 0: 0 diff --git a/experiments/1268-us-qrf-tail-top1-share/calibration_weight_stats.py b/experiments/1268-us-qrf-tail-top1-share/calibration_weight_stats.py new file mode 100644 index 0000000000..ba067099a7 --- /dev/null +++ b/experiments/1268-us-qrf-tail-top1-share/calibration_weight_stats.py @@ -0,0 +1,34 @@ +"""S2: household weight statistics before and after Route A calibration, engine-free. + +Usage: calibration_weight_stats.py +The sidecar's household_weight must equal the H5's household weights row for row, +so its initial_household_weight aligns by row (route_a_top1.py checks the same). +""" + +import sys + +import h5py +import numpy as np + +with h5py.File(sys.argv[1], "r") as f: + h5_final = ( + f["household/table"] + .fields(["household_weight"])[:]["household_weight"] + .astype(np.float64) + ) +sidecar = np.load(sys.argv[2]) +print("sidecar keys:", sorted(sidecar.files)) +final = sidecar["household_weight"].astype(np.float64) +initial = sidecar["initial_household_weight"].astype(np.float64) +assert np.array_equal(final, h5_final), "sidecar final weights differ from the H5's" +print(f"households: {final.size:,}") +for label, w in (("initial", initial), ("final", final)): + q = np.quantile(w, [0.5, 0.99]) + print( + f"{label:8s} total {w.sum():,.1f} median {q[0]:,.2f} p99 {q[1]:,.2f} min {w.min():,.4f} max {w.max():,.2f}" + ) +positive = initial > 0 +ratio = final[positive] / initial[positive] +print( + f"final/initial ratio: max {ratio.max():.4f} min {ratio.min():.6f} households with initial weight 0: {(~positive).sum()}" +) diff --git a/experiments/1268-us-qrf-tail-top1-share/minimize.log b/experiments/1268-us-qrf-tail-top1-share/minimize.log new file mode 100644 index 0000000000..c28adb6007 --- /dev/null +++ b/experiments/1268-us-qrf-tail-top1-share/minimize.log @@ -0,0 +1,21 @@ +CI input: values=[2.0, 3.0, 2.0, 1.0, 1e+16, 7.0, 1000000000000000.0, 1.0, 0.5] top_k=8 + array-order total 1.1000000000000016e+16; exact share rounds to 1.0 + share 0.9999999999999998 e.g. tail order [1.0, 2.0, 3.0, 1000000000000000.0, 1.0, 1e+16, 2.0, 7.0] + share 1.0 e.g. tail order [1.0, 1.0, 2.0, 2.0, 3.0, 7.0, 1000000000000000.0, 1e+16] + share 1.0000000000000002 e.g. tail order [1.0, 1.0, 2.0, 2.0, 3.0, 1000000000000000.0, 7.0, 1e+16] + introselect (macOS arm64) tail: [1.0, 2.0, 3.0, 1e+16, 7.0, 1000000000000000.0, 1.0, 2.0] -> share 1.0000000000000002 + sorted tail (x86-simd-sort base case): [1.0, 1.0, 2.0, 2.0, 3.0, 7.0, 1000000000000000.0, 1e+16] -> share 1.0 +top_k=1: largest share over every grid input of 3-5 records and every legal tail: 1.0 +top_k=2: largest share over every grid input of 3-5 records and every legal tail: 1.0 +4-record inputs, top_k=3, overshooting in every legal arrangement: 81 + [0.5, 9007199254740994.0, 3.0, 1.0] + [3.0, 9007199254740994.0, 0.5, 1.0] + [3.0, 9007199254740994.0, 1.0, 0.5] + [9007199254740994.0, 0.5, 3.0, 1.0] + [9007199254740994.0, 3.0, 0.5, 1.0] + [9007199254740994.0, 3.0, 1.0, 0.5] +minimized: values=[9007199254740994.0, 3.0, 1.0, 0.5] top_k=3 + array-order total 9007199254740996.0; exact share rounds to 1.0 + share 1.0000000000000002 e.g. tail order [1.0, 3.0, 9007199254740994.0] + share 1.0000000000000004 e.g. tail order [1.0, 9007199254740994.0, 3.0] +numpy 2.4.6 darwin diff --git a/experiments/1268-us-qrf-tail-top1-share/minimize.py b/experiments/1268-us-qrf-tail-top1-share/minimize.py new file mode 100644 index 0000000000..c957c7476b --- /dev/null +++ b/experiments/1268-us-qrf-tail-top1-share/minimize.py @@ -0,0 +1,92 @@ +"""Minimize the CI counterexample of microcosm#1268's rounding test, engine-free. + +The gate and ``single_record_concentration`` sum their tail as +``np.partition(mass, -top_k)[-top_k:].sum()``. numpy fixes the summation order +of a contiguous slice (pairwise_sum in loops_utils.h.src) but leaves the order +of elements inside a partition undefined. A partition is legal when position +``kth = n - top_k`` holds the kth-smallest value, nothing before it is larger +and nothing after it smaller. This script sums the tail in every legal +arrangement, so its results hold on every platform. +""" + +from __future__ import annotations + +import itertools +import sys +from fractions import Fraction + +import numpy as np + + +def legal_tails(mass: np.ndarray, top_k: int): + """Every distinct tail ``np.partition(mass, -top_k)[-top_k:]`` may return.""" + ordered = np.sort(mass) + kth = mass.size - top_k + first, rest = ordered[kth], ordered[kth + 1 :] + for order in sorted(set(itertools.permutations(rest.tolist()))): + yield np.array([first, *order]) + + +def shares(values, top_k): + mass = np.abs(np.asarray(values, dtype=np.float64)) + total = float(mass.sum()) # array order, fixed on every platform + out = {} + for tail in legal_tails(mass, top_k): + out.setdefault(float(tail.sum()) / total, tail.tolist()) + exact = sum(map(Fraction, sorted(mass.tolist())[-top_k:])) / sum( + map(Fraction, mass.tolist()) + ) + return total, out, float(exact) + + +def show(label, values, top_k): + total, out, exact = shares(values, top_k) + print(f"{label}: values={values} top_k={top_k}") + print(f" array-order total {total!r}; exact share rounds to {exact!r}") + for share in sorted(out): + print(f" share {share!r:<22} e.g. tail order {out[share]}") + return out + + +if __name__ == "__main__": + ci = [2.0, 3.0, 2.0, 1.0, 1e16, 7.0, 1e15, 1.0, 0.5] + out = show("CI input", ci, 8) + print( + " introselect (macOS arm64) tail:", + np.partition(np.array(ci), -8)[-8:].tolist(), + "-> share", + repr(float(np.partition(np.array(ci), -8)[-8:].sum()) / float(np.sum(ci))), + ) + print( + " sorted tail (x86-simd-sort base case):", + np.sort(ci)[-8:].tolist(), + "-> share", + repr(float(np.sort(ci)[-8:].sum()) / float(np.sum(ci))), + ) + + # top_k <= 2 never overshoots: search a grid that does overshoot at top_k = 3. + alphabet = [0.5, 1.0, 2.0, 3.0, 7.0, 2.0**53, 2.0**53 + 2, 2.0**53 + 4, 1e15, 1e16] + for top_k in (1, 2): + worst = 0.0 + for n in range(top_k + 1, 6): + for combo in itertools.product(alphabet, repeat=n): + _, out, _ = shares(list(combo), top_k) + worst = max(worst, max(out)) + print( + f"top_k={top_k}: largest share over every grid input of 3-5 records and every legal tail: {worst!r}" + ) + + # Smallest gate-checkable input (top_k = 3, four carriers) whose every legal tail overshoots. + found = [] + for combo in itertools.product(alphabet, repeat=4): + _, out, _ = shares(list(combo), 3) + if min(out) > 1.0: + found.append(combo) + print( + f"4-record inputs, top_k=3, overshooting in every legal arrangement: {len(found)}" + ) + key = lambda c: (sum(v > 1e6 for v in c), sorted(c), c) # noqa: E731 + for combo in sorted(found, key=key)[:6]: + print(" ", list(combo)) + show("minimized", [2.0**53 + 2, 3.0, 1.0, 0.5], 3) + print("numpy", np.__version__, sys.platform) diff --git a/experiments/1268-us-qrf-tail-top1-share/monotone_k.log b/experiments/1268-us-qrf-tail-top1-share/monotone_k.log new file mode 100644 index 0000000000..515efd015a --- /dev/null +++ b/experiments/1268-us-qrf-tail-top1-share/monotone_k.log @@ -0,0 +1,7 @@ +drops possible under some legal arrangement: 2651 + ex [0.5, 0.5, 0.5, 0.5, 9007199254740994.0] k 3 1.0 -> 0.9999999999999998 + ex [0.5, 0.5, 0.5, 1.0, 9007199254740992.0] k 3 1.0 -> 0.9999999999999998 + ex [0.5, 0.5, 0.5, 1.0, 9007199254740996.0] k 3 1.0 -> 0.9999999999999998 + ex [0.5, 0.5, 0.5, 3.0, 9007199254740994.0] k 3 1.0 -> 0.9999999999999998 + ex [0.5, 0.5, 0.5, 9007199254740992.0, 1.0] k 3 0.9999999999999998 -> 0.9999999999999996 +drops under every legal arrangement: 0 diff --git a/experiments/1268-us-qrf-tail-top1-share/monotone_k.py b/experiments/1268-us-qrf-tail-top1-share/monotone_k.py new file mode 100644 index 0000000000..b38946b552 --- /dev/null +++ b/experiments/1268-us-qrf-tail-top1-share/monotone_k.py @@ -0,0 +1,48 @@ +"""Is top_k_share exactly non-decreasing in k? Search legal partition arrangements, engine-free. + +measure(k) = min(fl-sum(legal tail of k) / fl-sum(array), 1), with the carriers > k +partition path; k >= carriers returns exactly 1. Reports inputs where some legal +arrangement at k gives more than some legal arrangement at k + 1 (possible +somewhere), and inputs where every arrangement at k gives more than every +arrangement at k + 1 (so every platform shows the drop). +""" + +from __future__ import annotations + +import itertools +import sys + +import numpy as np + +sys.path.insert(0, sys.argv[1]) +from minimize import legal_tails # noqa: E402 + + +def possible(values, k): + mass = np.abs(np.asarray(values, dtype=np.float64)) + if mass.size <= k: + return {1.0} + total = float(mass.sum()) + return {min(float(t.sum()) / total, 1.0) for t in legal_tails(mass, k)} + + +alphabet = [0.5, 1.0, 2.0, 3.0, 2.0**53, 2.0**53 + 2, 2.0**53 + 4, 2.0**54 + 4] +somewhere, everywhere = [], [] +for n in (4, 5): + for combo in itertools.product(alphabet, repeat=n): + for k in range(1, n): + low, high = possible(combo, k), possible(combo, k + 1) + if max(low) > min(high): + somewhere.append((combo, k, max(low), min(high))) + if min(low) > max(high): + everywhere.append((combo, k, min(low), max(high))) +print("drops possible under some legal arrangement:", len(somewhere)) +for row in sorted( + somewhere, key=lambda r: (len(r[0]), sum(v > 1e6 for v in r[0]), r[0]) +)[:5]: + print(" ex", [*row[0]], "k", row[1], repr(row[2]), "->", repr(row[3])) +print("drops under every legal arrangement:", len(everywhere)) +for row in sorted( + everywhere, key=lambda r: (len(r[0]), sum(v > 1e6 for v in r[0]), r[0]) +)[:5]: + print(" ex", [*row[0]], "k", row[1], repr(row[2]), "->", repr(row[3])) diff --git a/experiments/1268-us-qrf-tail-top1-share/route_a_top1.log b/experiments/1268-us-qrf-tail-top1-share/route_a_top1.log new file mode 100644 index 0000000000..05278951a5 --- /dev/null +++ b/experiments/1268-us-qrf-tail-top1-share/route_a_top1.log @@ -0,0 +1,74 @@ +{ + "release_id": "populace-us-2024-0fb05b6-4b57d15a287c-20260930T150401Z", + "h5_sha256": "417d23aed4d044de2e657a7b5d856136975d25739dbdb4ddd72866f841de1559", + "qrf_tail_concentration_sha256": "8311943453d524a5b1a286cd440e40ea56a5909da0aa9971d065da9cc72cdc58", + "branch_commit": "a6644d62b2f7b6d4e2afbd91212e8f25dd82ac1d", + "fidelity": { + "gate_details_equal_recorded": true, + "verdict_equal_recorded": true, + "checked_sparse_columns_equal_recorded": true, + "dense_columns_equal_recorded": true, + "absent_columns_equal_recorded": true, + "non_numeric_columns_equal_recorded": true, + "probe_compare_differences": [], + "probe_columns_compared": 33, + "sidecar_final_weights_equal_h5": true + }, + "qrf_outputs": 106, + "measured_columns": 68, + "over": { + "final_weights_over_5pct": [ + "long_term_capital_gains_on_collectibles", + "investment_income_elected_form_4952", + "farm_income", + "casualty_loss", + "sstb_w2_wages_from_qualified_business", + "investment_interest_expense", + "bond_assets", + "estate_income", + "w2_wages_from_qualified_business", + "sstb_self_employment_income_before_lsr", + "unadjusted_basis_qualified_property", + "qualified_bdc_income", + "charitable_non_cash_donations", + "unrecaptured_section_1250_gain", + "sstb_unadjusted_basis_qualified_property", + "tax_exempt_interest_income", + "farm_rent_income" + ], + "final_weights_over_10pct": [ + "long_term_capital_gains_on_collectibles", + "investment_income_elected_form_4952", + "farm_income", + "casualty_loss", + "sstb_w2_wages_from_qualified_business", + "investment_interest_expense", + "bond_assets" + ], + "initial_weights_over_5pct": [ + "investment_income_elected_form_4952", + "farm_income", + "estate_income", + "domestic_production_ald", + "sstb_w2_wages_from_qualified_business", + "unrecaptured_section_1250_gain", + "long_term_capital_gains_on_collectibles", + "w2_wages_from_qualified_business", + "investment_interest_expense", + "casualty_loss", + "charitable_non_cash_donations", + "stock_assets", + "partnership_income" + ], + "initial_weights_over_10pct": [ + "investment_income_elected_form_4952", + "farm_income", + "estate_income", + "domestic_production_ald", + "sstb_w2_wages_from_qualified_business", + "unrecaptured_section_1250_gain", + "long_term_capital_gains_on_collectibles", + "w2_wages_from_qualified_business" + ] + } +} diff --git a/experiments/1268-us-qrf-tail-top1-share/route_a_top1.md b/experiments/1268-us-qrf-tail-top1-share/route_a_top1.md new file mode 100644 index 0000000000..3fb481022c --- /dev/null +++ b/experiments/1268-us-qrf-tail-top1-share/route_a_top1.md @@ -0,0 +1,81 @@ +# Route A single-record concentration (populace-us-2024-0fb05b6-4b57d15a287c-20260930T150401Z) + +H5 sha256 `417d23aed4d044de2e657a7b5d856136975d25739dbdb4ddd72866f841de1559`; recorded tail evidence `8311943453d524a5b1a286cd440e40ea56a5909da0aa9971d065da9cc72cdc58`. + +| column | class | waived | carriers | top-1 final | top-1 weight final | top-100 final | largest record final (value × weight) | top-1 initial | top-1 weight initial | +|---|---|---|---:|---:|---:|---:|---|---:|---:| +| `long_term_capital_gains_on_collectibles` | checked | yes | 1,138 | 48.1% | 1,757.8 | 93.3% | $6,761,367 × 1,757.8 = $11.89B | 13.9% | 351.6 | +| `investment_income_elected_form_4952` | thin | | 394 | 44.1% | 1,989.2 | 98.2% | $6,715,619 × 1,989.2 = $13.36B | 23.7% | 408.0 | +| `farm_income` | thin | | 445 | 43.5% | 4,673.2 | 96.8% | $3,804,933 × 4,673.2 = $17.78B | 22.1% | 934.6 | +| `casualty_loss` | thin | | 138 | 18.7% | 2,418.8 | 99.8% | $618,387 × 2,418.8 = $1.50B | 7.5% | 483.8 | +| `sstb_w2_wages_from_qualified_business` | thin | | 480 | 18.4% | 3,675.7 | 94.7% | $9,294,781 × 3,675.7 = $34.16B | 20.4% | 265.2 | +| `investment_interest_expense` | dense | | 64,778 | 17.5% | 2,120.1 | 65.0% | $3,681,182 × 2,120.1 = $7.80B | 7.6% | 424.0 | +| `bond_assets` | checked | yes | 8,887 | 14.9% | 5,381.4 | 77.3% | $20,590,000 × 5,381.4 = $110.80B | 4.4% | 1,114.8 | +| `estate_income` | checked | yes | 2,567 | 8.5% | 176.1 | 79.2% | $27,594,578 × 176.1 = $4.86B | 21.6% | 610.4 | +| `w2_wages_from_qualified_business` | checked | yes | 1,563 | 7.8% | 3,675.7 | 77.3% | $9,294,781 × 3,675.7 = $34.16B | 10.4% | 610.4 | +| `sstb_self_employment_income_before_lsr` | checked | | 11,696 | 6.6% | 2,353.0 | 52.4% | $10,162,242 × 2,353.0 = $23.91B | 2.9% | 470.6 | +| `unadjusted_basis_qualified_property` | checked | | 24,729 | 6.6% | 1,701.6 | 47.2% | $119,257,711 × 1,701.6 = $202.93B | 3.6% | 520.4 | +| `qualified_bdc_income` | checked | | 5,276 | 6.6% | 2,509.2 | 69.0% | $2,747 × 2,509.2 = $0.01B | 4.2% | 598.1 | +| `charitable_non_cash_donations` | checked | | 45,215 | 6.6% | 973.7 | 65.3% | $7,753,602 × 973.7 = $7.55B | 7.4% | 497.9 | +| `unrecaptured_section_1250_gain` | checked | | 6,310 | 6.3% | 2,353.0 | 58.9% | $1,349,338 × 2,353.0 = $3.18B | 16.7% | 943.0 | +| `sstb_unadjusted_basis_qualified_property` | checked | | 5,378 | 6.1% | 2,353.0 | 72.3% | $23,399,794 × 2,353.0 = $55.06B | 4.2% | 670.9 | +| `tax_exempt_interest_income` | checked | | 16,664 | 5.5% | 1,115.9 | 51.5% | $3,078,364 × 1,115.9 = $3.44B | 2.6% | 467.3 | +| `farm_rent_income` | checked | | 2,063 | 5.1% | 3,896.9 | 74.8% | $-288,692 × 3,896.9 = $1.12B | 1.7% | 925.7 | +| `miscellaneous_income` | checked | | 9,681 | 4.9% | 1,115.9 | 61.3% | $-4,523,612 × 1,115.9 = $5.05B | 4.9% | 776.5 | +| `alimony_expense` | checked | | 890 | 3.9% | 5,174.9 | 74.6% | $96,865 × 5,174.9 = $0.50B | 1.3% | 1,035.0 | +| `long_term_capital_gains_before_response` | dense | | 66,419 | 3.9% | 1,757.8 | 28.5% | $27,110,918 × 1,757.8 = $47.66B | 2.1% | 408.0 | +| `salt_refund_income` | checked | | 36,023 | 3.9% | 3,162.3 | 33.0% | $561,281 × 3,162.3 = $1.77B | 3.3% | 610.4 | +| `domestic_production_ald` | checked | | 1,326 | 3.4% | 4,422.5 | 70.3% | $188,999 × 4,422.5 = $0.84B | 21.2% | 610.4 | +| `qualified_reit_and_ptp_income` | checked | | 35,094 | 3.0% | 2,186.8 | 61.5% | $133,125 × 2,186.8 = $0.29B | 2.7% | 746.3 | +| `partnership_self_employment_net_earnings` | checked | | 5,905 | 2.9% | 3,016.0 | 41.0% | $-2,253,004 × 3,016.0 = $6.80B | 1.4% | 806.7 | +| `charitable_cash_donations` | dense | | 68,778 | 2.9% | 3,162.3 | 24.4% | $2,280,264 × 3,162.3 = $7.21B | 1.7% | 776.5 | +| `alimony_income` | checked | | 886 | 2.9% | 4,889.9 | 74.5% | $88,007 × 4,889.9 = $0.43B | 1.5% | 696.6 | +| `farm_operations_income` | checked | | 7,198 | 2.9% | 5,100.2 | 55.8% | $420,000 × 5,100.2 = $2.14B | 2.0% | 753.5 | +| `non_sch_d_capital_gains` | checked | | 10,393 | 2.8% | 4,180.8 | 50.5% | $67,269 × 4,180.8 = $0.28B | 0.6% | 836.2 | +| `qualified_dividend_income` | dense | | 121,248 | 2.3% | 1,989.2 | 33.3% | $3,983,369 × 1,989.2 = $7.92B | 1.9% | 742.0 | +| `first_home_mortgage_interest` | dense | | 64,774 | 2.1% | 3,042.3 | 18.3% | $2,610,229 × 3,042.3 = $7.94B | 0.8% | 494.6 | +| `partnership_income` | checked | | 14,598 | 2.0% | 3,675.7 | 32.4% | $6,780,061 × 3,675.7 = $24.92B | 5.3% | 610.4 | +| `stock_assets` | dense | | 97,956 | 2.0% | 4,757.7 | 33.3% | $57,940,000 × 4,757.7 = $275.66B | 5.3% | 408.0 | +| `self_employment_income_before_lsr` | checked | | 37,329 | 1.8% | 3,162.3 | 13.6% | $2,850,620 × 3,162.3 = $9.01B | 1.2% | 744.8 | +| `home_mortgage_interest` | dense | | 64,779 | 1.7% | 3,042.3 | 17.7% | $2,025,703 × 3,042.3 = $6.16B | 0.7% | 494.6 | +| `rental_income` | checked | | 40,644 | 1.6% | 884.7 | 36.2% | $7,675,311 × 884.7 = $6.79B | 2.2% | 876.4 | +| `short_term_capital_gains` | dense | | 54,715 | 1.6% | 2,784.4 | 39.0% | $1,052,437 × 2,784.4 = $2.93B | 1.5% | 465.3 | +| `unreimbursed_business_employee_expenses` | dense | | 56,404 | 1.4% | 2,189.1 | 20.4% | $1,279,521 × 2,189.1 = $2.80B | 1.1% | 776.5 | +| `taxable_interest_income` | dense | | 187,724 | 1.3% | 1,989.2 | 19.6% | $1,838,201 × 1,989.2 = $3.66B | 0.2% | 397.8 | +| `non_qualified_dividend_income` | dense | | 125,479 | 1.2% | 3,620.4 | 26.8% | $386,400 × 3,620.4 = $1.40B | 1.3% | 610.4 | +| `bank_account_assets` | dense | | 320,613 | 1.0% | 1,678.7 | 10.1% | $38,700,000 × 1,678.7 = $64.96B | 0.3% | 481.6 | +| `first_home_mortgage_balance` | dense | | 64,784 | 0.9% | 4,028.2 | 8.0% | $21,705,976 × 4,028.2 = $87.44B | 0.3% | 805.6 | +| `qualified_tuition_expenses` | checked | | 2,564 | 0.7% | 5,039.6 | 36.2% | $5,424 × 5,039.6 = $0.03B | 0.2% | 1,267.1 | +| `employment_income_before_lsr` | dense | | 436,418 | 0.6% | 1,989.2 | 4.9% | $34,235,367 × 1,989.2 = $68.10B | 0.1% | 397.8 | +| `net_worth` | dense | | 351,713 | 0.6% | 2,105.6 | 14.2% | $471,040,000 × 2,105.6 = $991.81B | 0.2% | 662.9 | +| `health_savings_account_ald` | checked | | 2,839 | 0.6% | 4,470.2 | 35.4% | $10,373 × 4,470.2 = $0.05B | 0.3% | 1,235.4 | +| `self_employed_pension_contributions_desired` | checked | | 6,972 | 0.5% | 5,217.2 | 22.9% | $1,403 × 5,217.2 = $0.01B | 0.2% | 1,217.8 | +| `taxable_ira_distributions` | checked | | 40,741 | 0.5% | 3,253.4 | 14.2% | $679,139 × 3,253.4 = $2.21B | 0.3% | 898.1 | +| `real_estate_taxes` | dense | | 77,380 | 0.4% | 1,935.5 | 7.9% | $429,180 × 1,935.5 = $0.83B | 0.1% | 387.1 | +| `social_security_survivors` | checked | | 23,302 | 0.3% | 3,652.2 | 11.7% | $149,557 × 3,652.2 = $0.55B | 0.1% | 730.4 | +| `traditional_ira_contributions_desired` | dense | | 153,591 | 0.3% | 4,361.9 | 4.0% | $10,097 × 4,361.9 = $0.04B | 0.1% | 966.7 | +| `fsla_overtime_premium` | dense | | 72,063 | 0.3% | 4,197.4 | 7.3% | $101,816 × 4,197.4 = $0.43B | 0.1% | 396.2 | +| `educator_expense` | checked | | 10,489 | 0.3% | 7,196.6 | 14.6% | $339 × 7,196.6 = $0.00B | 0.1% | 835.3 | +| `taxable_private_pension_income` | dense | | 86,717 | 0.2% | 1,909.7 | 7.3% | $1,180,309 × 1,909.7 = $2.25B | 0.1% | 831.3 | +| `hourly_wage` | dense | | 435,721 | 0.2% | 6,141.8 | 4.5% | $2,120 × 6,141.8 = $0.01B | 0.0% | 1,256.9 | +| `social_security_dependents` | checked | | 22,539 | 0.2% | 3,767.7 | 10.2% | $28,690 × 3,767.7 = $0.11B | 0.1% | 910.0 | +| `social_security_disability` | checked | | 33,193 | 0.2% | 4,651.7 | 9.4% | $61,070 × 4,651.7 = $0.28B | 0.1% | 818.1 | +| `student_loan_interest` | checked | | 19,544 | 0.2% | 6,544.7 | 9.9% | $3,390 × 6,544.7 = $0.02B | 0.0% | 1,583.1 | +| `auto_loan_balance` | dense | | 115,154 | 0.1% | 4,352.4 | 2.8% | $252,000 × 4,352.4 = $1.10B | 0.0% | 1,104.2 | +| `auto_loan_interest` | dense | | 109,643 | 0.1% | 5,383.6 | 4.6% | $12,361 × 5,383.6 = $0.07B | 0.0% | 1,681.3 | +| `qualified_passenger_vehicle_loan_interest` | dense | | 109,643 | 0.1% | 5,383.6 | 4.6% | $1,799 × 5,383.6 = $0.01B | 0.0% | 1,681.3 | +| `social_security_retirement` | dense | | 131,652 | 0.0% | 6,956.1 | 2.1% | $57,373 × 6,956.1 = $0.40B | 0.0% | 2,054.3 | +| `first_home_mortgage_origination_year` | dense | | 64,782 | 0.0% | 9,740.1 | 2.0% | $2,021 × 9,740.1 = $0.02B | 0.0% | 2,242.3 | +| `cps_race` | dense | | 907,863 | 0.0% | 5,685.9 | 0.9% | $24 × 5,685.9 = $0.00B | 0.0% | 1,348.2 | +| `detailed_occupation_recode` | dense | | 725,628 | 0.0% | 8,574.1 | 0.3% | $53 × 8,574.1 = $0.00B | 0.0% | 2,371.6 | +| `s_corp_income` | thin | | 0 | n/a | n/a | n/a | n/a | n/a | n/a | +| `second_home_mortgage_balance` | thin | | 0 | n/a | n/a | n/a | n/a | n/a | n/a | +| `second_home_mortgage_interest` | thin | | 0 | n/a | n/a | n/a | n/a | n/a | n/a | +| `second_home_mortgage_origination_year` | thin | | 0 | n/a | n/a | n/a | n/a | n/a | n/a | + +## Over the thresholds + +- **final_weights_over_5pct** (17): `long_term_capital_gains_on_collectibles`, `investment_income_elected_form_4952`, `farm_income`, `casualty_loss`, `sstb_w2_wages_from_qualified_business`, `investment_interest_expense`, `bond_assets`, `estate_income`, `w2_wages_from_qualified_business`, `sstb_self_employment_income_before_lsr`, `unadjusted_basis_qualified_property`, `qualified_bdc_income`, `charitable_non_cash_donations`, `unrecaptured_section_1250_gain`, `sstb_unadjusted_basis_qualified_property`, `tax_exempt_interest_income`, `farm_rent_income` +- **final_weights_over_10pct** (7): `long_term_capital_gains_on_collectibles`, `investment_income_elected_form_4952`, `farm_income`, `casualty_loss`, `sstb_w2_wages_from_qualified_business`, `investment_interest_expense`, `bond_assets` +- **initial_weights_over_5pct** (13): `investment_income_elected_form_4952`, `farm_income`, `estate_income`, `domestic_production_ald`, `sstb_w2_wages_from_qualified_business`, `unrecaptured_section_1250_gain`, `long_term_capital_gains_on_collectibles`, `w2_wages_from_qualified_business`, `investment_interest_expense`, `casualty_loss`, `charitable_non_cash_donations`, `stock_assets`, `partnership_income` +- **initial_weights_over_10pct** (8): `investment_income_elected_form_4952`, `farm_income`, `estate_income`, `domestic_production_ald`, `sstb_w2_wages_from_qualified_business`, `unrecaptured_section_1250_gain`, `long_term_capital_gains_on_collectibles`, `w2_wages_from_qualified_business` diff --git a/experiments/1268-us-qrf-tail-top1-share/route_a_top1.py b/experiments/1268-us-qrf-tail-top1-share/route_a_top1.py new file mode 100644 index 0000000000..35684ae84a --- /dev/null +++ b/experiments/1268-us-qrf-tail-top1-share/route_a_top1.py @@ -0,0 +1,272 @@ +"""Top-1 share of every QRF output in the certified Route A release. + +Runs the PR branch's own ``_qrf_tail_concentration_gate`` on the release's +published H5 (QRF columns only, read with the post-export probe's loader), +first at the release's calibrated household weights, then at the initial +weights from the release's calibration sidecar. + +Fidelity checks before anything is reported: + +* the H5 and the recorded ``qrf_tail_concentration.json`` hash to the + release manifest's sha256s; +* at calibrated weights the branch's gate reproduces the recorded tail + evidence exactly: verdict, surface buckets, and the gate's details + (every top-100 share and carrier count) after a JSON round trip, and the + probe's ``compare_qrf_tail`` finds no difference; +* the sidecar's ``household_weight`` equals the H5's household weights + element for element, so its ``initial_household_weight`` aligns by row. + +Usage: route_a_top1.py +""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import sys +from pathlib import Path + +import numpy as np + +ROOT = Path(sys.argv[1]) +RELEASE_OUT = Path(sys.argv[2]) +OUT = Path(sys.argv[3]) +RELEASE_ID = RELEASE_OUT.name +RELEASE_DIR = RELEASE_OUT / "releases" / RELEASE_ID +H5 = RELEASE_OUT / "artifacts" / "populace_us_2024.h5" +SIDECAR = RELEASE_OUT / "artifacts" / "populace_us_2024_calibration.npz" +THRESHOLDS = (0.05, 0.10) + + +def _load(name: str, filename: str): + spec = importlib.util.spec_from_file_location(name, ROOT / "tools" / filename) + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + return module + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1 << 24), b""): + digest.update(block) + return digest.hexdigest() + + +builder = _load("build_us_fiscal_refresh_release", "build_us_fiscal_refresh_release.py") +probe = _load("probe_us_post_export", "probe_us_post_export.py") +sampler = probe.load_sampler() +from microcosm.frame import Frame, WeightKind, Weights # noqa: E402 +from microcosm.frame.units import US_SCHEMA # noqa: E402 + +manifest = json.loads((RELEASE_DIR / "release_manifest.json").read_text()) +artifacts = manifest["artifacts"] +h5_sha = _sha256(H5) +tail_sha = _sha256(RELEASE_DIR / "qrf_tail_concentration.json") +assert h5_sha == artifacts["populace_us_2024"]["sha256"], h5_sha +assert tail_sha == artifacts["qrf_tail_concentration"]["sha256"], tail_sha + +recorded = json.loads((RELEASE_DIR / "qrf_tail_concentration.json").read_text()) +register = dict(recorded["surface"]["reviewed_exclusions"]) +qrf_outputs = sorted(builder._qrf_imputed_source_outputs()) +frame = probe.source_columns_frame( + H5, qrf_outputs, sampler=sampler, chunk_bytes=sampler.DEFAULT_CHUNK_BYTES +) + +# --- Fidelity at the release's calibrated weights ------------------------ +gate, surface = builder._qrf_tail_concentration_gate( + frame, reviewed_exclusions=register +) +fidelity: dict[str, object] = {} +roundtrip = json.loads(json.dumps(dict(gate.details))) +fidelity["gate_details_equal_recorded"] = ( + roundtrip == recorded["tail_concentration"]["details"] +) +fidelity["verdict_equal_recorded"] = ( + gate.passed == recorded["tail_concentration"]["passed"] +) +for bucket in ( + "checked_sparse_columns", + "dense_columns", + "absent_columns", + "non_numeric_columns", +): + fidelity[f"{bucket}_equal_recorded"] = sorted(surface[bucket]) == sorted( + recorded["surface"][bucket] + ) +comparison = probe.compare_qrf_tail( + {"passed": gate.passed, "surface": surface, "details": dict(gate.details)}, + recorded, +) +fidelity["probe_compare_differences"] = comparison["differences"] +fidelity["probe_columns_compared"] = comparison["columns_compared"] +assert all(v is True for k, v in fidelity.items() if k.endswith("_recorded")), fidelity +assert not comparison["differences"], comparison +block = surface["single_record_concentration"] +assert block["unmeasured"] == {}, block["unmeasured"] +for column, share in gate.details["top_share"].items(): + assert block["columns"][column]["top_k_share"] == min(share, 1.0), column + +# --- Initial weights from the calibration sidecar ------------------------ +with np.load(SIDECAR, allow_pickle=False) as sidecar: + final_weights = sidecar["household_weight"] + initial_weights = sidecar["initial_household_weight"] +h5_weights = np.asarray(frame.resolve_weights("household").values, dtype=np.float64) +fidelity["sidecar_final_weights_equal_h5"] = bool( + np.array_equal(final_weights, h5_weights) +) +assert fidelity["sidecar_final_weights_equal_h5"] +initial_frame = Frame( + {entity: frame.table(entity) for entity in sampler.US_ENTITIES}, + US_SCHEMA, + {"household": Weights(initial_weights, WeightKind.DESIGN)}, +) +initial_gate, initial_surface = builder._qrf_tail_concentration_gate( + initial_frame, reviewed_exclusions=register +) +initial_block = initial_surface["single_record_concentration"] + + +# --- The largest record itself, for the report ---------------------------- +def largest_record(frame_: Frame, column: str) -> dict[str, float] | None: + entity = frame_.column_entity(column) + values = frame_.table(entity)[column].to_numpy(dtype=np.float64) + weights = np.asarray(frame_.resolve_weights(entity).values, dtype=np.float64) + finite = np.isfinite(values) & np.isfinite(weights) + mass = np.where(finite, np.abs(values) * weights, 0.0) + mass = np.where(mass > 0.0, mass, 0.0) + if not mass.any(): + return None + index = int(np.argmax(mass)) + table = frame_.table(entity) + household = ( + table["person_household_id"].iloc[index] + if entity == "person" + else table["household_id"].iloc[index] + if entity == "household" + else None + ) + return { + "entity": entity, + "record_id": int(table[f"{entity}_id"].iloc[index]), + "household_id": None if household is None else int(household), + "value": float(values[index]), + "weight": float(weights[index]), + "mass": float(mass[index]), + "column_absolute_mass": float(mass.sum()), + } + + +def classify(column: str, surface_: dict, details: dict) -> str: + if column in surface_["dense_columns"]: + return "dense" + if column in details["thin_columns"]: + return "thin" + return "checked" + + +rows = [] +for column in sorted(block["columns"]): + final = block["columns"][column] + initial = initial_block["columns"][column] + record = largest_record(frame, column) + initial_record = largest_record(initial_frame, column) + if record is not None: + assert record["weight"] == final["top_1_weight"] or np.isclose( + record["mass"] / record["column_absolute_mass"], final["top_1_share"] + ), column + rows.append( + { + "column": column, + "class": classify(column, surface, gate.details), + "waived": column in register, + "entity": None if record is None else record["entity"], + "carriers": final["carriers"], + "final": final, + "initial": initial, + "final_largest_record": record, + "initial_largest_record": initial_record, + } + ) + + +def over(threshold: float, key: str) -> list[str]: + return [ + row["column"] + for row in sorted(rows, key=lambda r: -(r[key]["top_1_share"] or 0.0)) + if (row[key]["top_1_share"] or 0.0) > threshold + ] + + +summary = { + "release_id": RELEASE_ID, + "h5_sha256": h5_sha, + "qrf_tail_concentration_sha256": tail_sha, + "branch_commit": __import__("subprocess") + .run(["git", "-C", str(ROOT), "rev-parse", "HEAD"], capture_output=True, text=True) + .stdout.strip(), + "fidelity": fidelity, + "qrf_outputs": len(qrf_outputs), + "measured_columns": len(rows), + "over": { + f"{key}_weights_over_{int(t * 100)}pct": over(t, key) + for key in ("final", "initial") + for t in THRESHOLDS + }, + "rows": rows, +} +OUT.mkdir(parents=True, exist_ok=True) +(OUT / "route_a_top1.json").write_text(json.dumps(summary, indent=2, sort_keys=True)) + + +def pct(value): + return "n/a" if value is None else f"{100 * value:.1f}%" + + +def money(value): + return "n/a" if value is None else f"${value / 1e9:,.2f}B" + + +lines = [ + f"# Route A single-record concentration ({RELEASE_ID})", + "", + f"H5 sha256 `{h5_sha}`; recorded tail evidence `{tail_sha}`.", + "", + "| column | class | waived | carriers | top-1 final | top-1 weight final " + "| top-100 final | largest record final (value × weight) | top-1 initial " + "| top-1 weight initial |", + "|---|---|---|---:|---:|---:|---:|---|---:|---:|", +] + + +def weight(value): + return "n/a" if value is None else f"{value:,.1f}" + + +def described(record): + if record is None: + return "n/a" + return ( + f"${record['value']:,.0f} × {record['weight']:,.1f} = {money(record['mass'])}" + ) + + +for row in sorted(rows, key=lambda r: -(r["final"]["top_1_share"] or 0.0)): + lines.append( + f"| `{row['column']}` | {row['class']} | {'yes' if row['waived'] else ''} " + f"| {row['carriers']:,} | {pct(row['final']['top_1_share'])} " + f"| {weight(row['final']['top_1_weight'])} " + f"| {pct(row['final']['top_k_share'])} " + f"| {described(row['final_largest_record'])} " + f"| {pct(row['initial']['top_1_share'])} " + f"| {weight(row['initial']['top_1_weight'])} |" + ) +lines += ["", "## Over the thresholds", ""] +for key, columns in summary["over"].items(): + lines.append( + f"- **{key}** ({len(columns)}): " + ", ".join(f"`{c}`" for c in columns) + ) +(OUT / "route_a_top1.md").write_text("\n".join(lines) + "\n") +print(json.dumps({k: v for k, v in summary.items() if k != "rows"}, indent=2)) diff --git a/experiments/1268-us-qrf-tail-top1-share/shared_largest_records.py b/experiments/1268-us-qrf-tail-top1-share/shared_largest_records.py new file mode 100644 index 0000000000..75cdd455a9 --- /dev/null +++ b/experiments/1268-us-qrf-tail-top1-share/shared_largest_records.py @@ -0,0 +1,61 @@ +"""S3: which Route A QRF columns above 5% top-1 share a largest record or a household? + +Reads route_a_top1.json (the PR's evidence) for each column's largest record at +final weights, and the release H5's person table (pandas HDFStore, read with +h5py, engine-free) to map tax units and persons to households. + +Usage: shared_largest_records.py +""" + +import json +import sys +from collections import defaultdict + +import h5py + +evidence = json.load(open(sys.argv[1])) +with h5py.File(sys.argv[2], "r") as f: + person = f["person/table"].fields( + ["person_id", "person_tax_unit_id", "person_household_id"] + )[:] +tax_unit_households = defaultdict(set) +for tax_unit, household in zip( # noqa: B905 + person["person_tax_unit_id"].tolist(), person["person_household_id"].tolist() +): + tax_unit_households[tax_unit].add(household) +person_household = dict( + zip(person["person_id"].tolist(), person["person_household_id"].tolist()) # noqa: B905 +) +assert all(len(h) == 1 for h in tax_unit_households.values()), ( + "a tax unit spans households" +) + +over = evidence["over"]["final_weights_over_5pct"] +rows = {row["column"]: row for row in evidence["rows"]} +by_record, by_household = defaultdict(list), defaultdict(list) +print(f"{'column':45s} {'share':>6s} entity record household weight") +for column in over: + row = rows[column] + largest = row["final_largest_record"] + entity, record = largest["entity"], largest["record_id"] + if entity == "person": + household = person_household[record] + assert largest["household_id"] in (None, household), column + elif entity == "tax_unit": + (household,) = tax_unit_households[record] + else: + household = record if entity == "household" else None + by_record[(entity, record)].append(column) + by_household[household].append(column) + print( + f"{column:45s} {row['final']['top_1_share']:6.3f} {entity:9s} {record:8d} {household!s:>10s} {largest['weight']!r}" + ) +print() +print( + "largest records shared by columns:", + {f"{e} {r}": c for (e, r), c in by_record.items() if len(c) > 1}, +) +print( + "households holding more than one column's largest record:", + {h: c for h, c in by_household.items() if len(c) > 1}, +) diff --git a/packages/microcosm-build/src/microcosm/build/gates.py b/packages/microcosm-build/src/microcosm/build/gates.py index 0eb163e912..85fc8e8f07 100644 --- a/packages/microcosm-build/src/microcosm/build/gates.py +++ b/packages/microcosm-build/src/microcosm/build/gates.py @@ -78,6 +78,7 @@ "source_coverage_gate", "source_stage_input_coverage_gate", "tail_concentration_gate", + "single_record_concentration", "target_fit_gate", "target_profile_coverage_gate", "TargetCoverageRequirement", @@ -3475,3 +3476,120 @@ def tail_concentration_gate( "dormant_exclusions": dormant_exclusions, }, ) + + +def single_record_concentration( + values: Iterable[float], + weights: Iterable[float], + *, + top_k: int = 100, +) -> dict[str, float | int | None]: + """One column's largest single record, as a share of its weighted mass. + + The measurement :func:`tail_concentration_gate` does not make. That gate + asks whether the ``top_k`` records together carry too much of a column, so + one record can carry a fifth of it and pass. In microcosm#1259's seed-0 + rerun of the microcosm#1251 chain, one tax unit of weight 644.7 drew a + $218.9M Schedule E line-32 value. At initial weights it carried 21.7% of + the column's weighted absolute mass, while the top 100 of its 16,001 + carriers carried 45.1%, under the gate's 0.75. + + Reporting only: this returns measurements, with no verdict and no + threshold. After microcosm#1259's draw bound, the worst single-draw share + in a 12-seed sweep was still 33% for collectibles gains. + + The population is the gate's: records whose value and weight are finite + and whose weighted absolute mass ``|value| * weight`` is positive. This + skips no column for being thin, so a column with at most ``top_k`` + carriers reports a ``top_k_share`` of exactly 1. + + Args: + values: The column's per-record values. This takes a signed column's + absolute mass. + weights: Per-record weights, aligned with ``values``. + top_k: How many of the largest records ``top_k_share`` covers + (default 100, the gate's tail). + + Returns: + ``carriers``, the number of records with positive mass, and three + measurements: + + * ``top_1_share``: the largest record's mass over the column's total + mass, which this sums in record order. + * ``top_1_weight``: that record's weight. Among records tied for the + largest mass it is the largest weight, so record order never + changes it. + * ``top_k_share``: the ``top_k`` largest records' share. This sums + the tail as the gate does and caps the ratio at 1. On a column + the gate checks whose total mass is finite, it equals + ``min(top_share, 1)`` for the gate's ``top_share``. The gate sums + its tail in the order ``np.partition`` leaves it, which numpy + leaves undefined and which differs across platforms, and its total + in record order; when the records outside the tail hold less mass + than one rounding step, its share can pass 1 by a rounding step or + two (the tests record 1.0000000000000002 and 1.0000000000000004). + + The three are ``None`` when the column has no share to report: its + total mass is zero (no carriers) or not finite. Otherwise, exactly in + float64, ``0 < top_1_share <= top_k_share <= 1``, and with + ``top_k = 1`` the two shares are the same number. Raising ``top_k`` + never lowers ``top_k_share`` by more than float rounding; each + ``top_k`` sums its own partition, so near a share of 1 it can fall by + a rounding step, an intended drop that keeps ``top_k_share`` the + gate's own number. + + Scaling every weight by a power of two scales ``top_1_weight`` by it + and leaves both shares unchanged, exactly, as long as no product or + sum overflows or underflows (a property pins factors from ``2**-20`` + to ``2**20``). Under the same condition, any other positive factor + can round each mass differently: it leaves both shares unchanged to + float rounding (a property pins 1e-9 relative for factors from 1e-3 + to 1e3) and can move ``top_1_weight`` to another record whose mass + ties the largest to within rounding. + + Raises: + ValueError: If ``top_k`` falls below 1 or the values and weights do + not align. + """ + if top_k < 1: + raise ValueError(f"top_k must be at least 1, got {top_k!r}.") + value_vector = np.asarray(values, dtype=np.float64).reshape(-1) + weight_vector = np.asarray(weights, dtype=np.float64).reshape(-1) + if value_vector.shape[0] != weight_vector.shape[0]: + raise ValueError( + "values and weights must align, got " + f"{value_vector.shape[0]} values vs {weight_vector.shape[0]} weights." + ) + finite = np.isfinite(value_vector) & np.isfinite(weight_vector) + carrier_weights = weight_vector[finite] + # This reports a product or a sum past the float64 range as a column with + # no share, never as a warning or a NaN. + with np.errstate(over="ignore"): + mass = np.abs(value_vector[finite]) * carrier_weights + carrying = mass > 0.0 + mass = mass[carrying] + carriers = int(mass.size) + total = float(mass.sum()) + if not carriers or not math.isfinite(total): + return { + "carriers": carriers, + "top_1_share": None, + "top_1_weight": None, + "top_k_share": None, + } + top = float(mass.max()) + # With at most top_k carriers the tail is the whole column. Above + # that, this sums the tail as the gate does, in an order numpy's + # partition leaves undefined; that sum can pass the record-order + # total by a rounding step or two, hence the cap. + tail = ( + total + if carriers <= top_k + else float(np.partition(mass, -top_k)[-top_k:].sum()) + ) + return { + "carriers": carriers, + "top_1_share": top / total, + "top_1_weight": float(carrier_weights[carrying][mass == top].max()), + "top_k_share": min(tail / total, 1.0), + } diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/release_gate_dry_run.py b/packages/microcosm-build/src/microcosm/build/us_runtime/release_gate_dry_run.py index 439bfd38e8..951c5c604d 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/release_gate_dry_run.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/release_gate_dry_run.py @@ -94,7 +94,7 @@ import math from collections.abc import Callable, Iterable, Mapping, Sequence -from dataclasses import dataclass +from dataclasses import dataclass, replace from typing import Any, Literal, get_args from microcosm.build.us_runtime.release_gate_preflight import PreflightReport @@ -485,6 +485,9 @@ class TailColumnDryRun: top_share: float | None = None nonzero_share: float | None = None carriers: int | None = None + # Reported only: no class or verdict reads the largest record's share. + top_1_share: float | None = None + top_1_weight: float | None = None @property def status(self) -> PreflightStatus: @@ -514,6 +517,8 @@ def to_row(self) -> dict[str, Any]: "top_share_at_base_weights": self.top_share, "nonzero_share": self.nonzero_share, "carriers_at_base_weights": self.carriers, + "top_1_share_at_base_weights": self.top_1_share, + "top_1_weight_at_base_weights": self.top_1_weight, } @@ -749,7 +754,10 @@ def qrf_tail_register_check( qrf_outputs: ``_qrf_imputed_source_outputs()``. register: The loaded per-run register (column -> reason). surface: The surface dict from ``_qrf_tail_concentration_gate``, which - must carry ``nonzero_shares`` and ``nonzero_records``. + must carry ``nonzero_shares`` and ``nonzero_records``. Its + ``single_record_concentration`` block, when present, gives each + row the largest single record's share and weight at base weights. + No class or verdict reads them. gate_details: That call's gate details. release_lines_at_base_weights: The lines the release would append at these weights. @@ -787,6 +795,9 @@ def qrf_tail_register_check( str(k): int(v) for k, v in dict(gate_details["thin_columns"]).items() } top_share = {str(k): float(v) for k, v in gate_details["top_share"].items()} + single_record = dict( + dict(surface.get("single_record_concentration", {})).get("columns", {}) + ) rows: list[TailColumnDryRun] = [] owners: dict[str, str] = {} @@ -797,21 +808,26 @@ def qrf_tail_register_check( owner = evidence_owner(column) if evidence_owner is not None else None if owner is not None: owners[column] = owner + measured = dict(single_record.get(column, {})) rows.append( - classify_tail_column( - column, - base_class=base_class, - in_register=column in register, - allow_concentration=allow_concentration, - top_share=top_share.get(column), - nonzero_share=nonzero_shares.get(column), - carriers=carriers, - support_fixed=support_fixed, - margins=margins, - max_top_share=float(gate["max_top_share"]), - sparse_nonzero_share_max=float(gate["sparse_nonzero_share_max"]), - min_nonzero_records=int(gate["min_nonzero_records"]), - evidence_owned=owner is not None, + replace( + classify_tail_column( + column, + base_class=base_class, + in_register=column in register, + allow_concentration=allow_concentration, + top_share=top_share.get(column), + nonzero_share=nonzero_shares.get(column), + carriers=carriers, + support_fixed=support_fixed, + margins=margins, + max_top_share=float(gate["max_top_share"]), + sparse_nonzero_share_max=float(gate["sparse_nonzero_share_max"]), + min_nonzero_records=int(gate["min_nonzero_records"]), + evidence_owned=owner is not None, + ), + top_1_share=measured.get("top_1_share"), + top_1_weight=measured.get("top_1_weight"), ) ) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_single_record_concentration.py b/packages/microcosm-build/tests/engine_free/shared/test_single_record_concentration.py new file mode 100644 index 0000000000..ded332a8c6 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_single_record_concentration.py @@ -0,0 +1,786 @@ +"""``single_record_concentration``: one column's largest record, as a share. + +These tests pin eleven invariants, each for every input the strategies +reach. "Exactly" means in float64, with no tolerance. + +1. **Bounds.** A measured column has ``0 < top_1_share <= top_k_share <= 1`` + exactly. Every carrier's mass is positive, and a rounded sum of + non-negative masses never falls below any one of them, so the total and + the tail sum each reach at least the largest mass. The cap keeps + ``top_k_share`` at most 1. +2. **No rounding step lifts a share past 1.** The measurement sums the tail + in the order a partition leaves it and the total in record order, so their + ratio can pass 1 when the records outside the tail hold less mass than one + rounding step: for ``[2**53 + 2, 3, 1, 0.5]`` at ``top_k = 3`` the gate + reports 1.0000000000000002 or 1.0000000000000004, whatever the platform. + ``top_k_share`` is ``min(ratio, 1)`` under every arrangement numpy may + return. +3. **One record.** With ``top_k = 1``, ``top_k_share`` is ``top_1_share``, + and both are the largest mass over the total mass, exactly. +4. **Monotone in ``top_k``, to rounding.** A larger ``top_k`` never lowers + ``top_k_share`` by more than float rounding. It can lower it by a + rounding step, because each ``top_k`` sums its own partition: + ``[0.5, 1, 2**53, 0.5, 0.5]`` gives 1.0 at ``top_k = 3`` and + 0.9999999999999998 at ``top_k = 4`` on macOS arm64. That one-step drop + is an intended violation of exact monotonicity: it keeps ``top_k_share`` + the gate's own number, bit for bit (invariant 6). With at most ``top_k`` + carriers, ``top_k_share`` is exactly 1. +5. **Pigeonhole floor.** The largest of ``n`` positive masses is at least + their mean, so ``top_1_share >= 1 / carriers``, and + ``top_k_share >= min(top_k, carriers) / carriers``, to float rounding. +6. **Differential, against the gate.** On every column + ``tail_concentration_gate`` checks whose total mass is finite, + ``top_k_share`` is ``min(top_share, 1)`` for the gate's ``top_share``, + exactly, under every partition arrangement, and ``carriers`` is its + carrier count; on a thin column ``carriers`` is the gate's thin count. +7. **Differential, against exact arithmetic.** Both shares equal the ratios of + the same float masses summed as exact rationals, to float rounding. +8. **Scale-free, exactly for a power of two.** Multiplying every weight by a + power of two leaves the carrier count and both shares unchanged and + multiplies ``top_1_weight`` by the factor, exactly. Multiplying every + value by a power of two changes nothing, and neither does negating every + value, since the measurement takes a signed column's absolute mass. Any + other positive factor can round each mass differently. On the weights, it + leaves the carrier count unchanged and both shares unchanged to float + rounding; a property pins 1e-9 relative for factors from 1e-3 to 1e3. On + the weights or on the values, it can move ``top_1_weight`` to another + record whose mass ties the largest to within rounding: ``[1, 10]`` at + weights ``[1, 0.1]`` reports weight 1, and at three times those weights + it reports 0.30000000000000004, not 3. That move is intended: the + measurement compares float masses with no tolerance, so rounding decides + a near-tie. +9. **Total.** Any float64 values and weights (NaN, infinities, zeros, + negative weights, products past the float64 range) give a report that is + valid JSON without NaN, and numpy warns about nothing. A column with no + carriers, or with a total mass that is not finite, reports its three + measurements as ``None``: the measurement reports zero mass and never + divides by it. +10. **Order-free.** Permuting the records leaves ``carriers`` and + ``top_1_weight`` unchanged and the shares unchanged to float rounding. + Records tied for the largest mass report the largest of their weights. +11. **Monotone in the largest record, to rounding.** Raising the largest + record's value never lowers ``top_1_share`` by more than float rounding; + a property pins 1e-12 relative for lifts of up to 1,000 times. It can + lower it by one float step, because the total is a rounded sum: + ``[2**53, 2**51 + 1]`` sums to ``5 * 2**51``, a share of 0.8, and + ``[2**53 + 2, 2**51 + 1]`` sums to ``5 * 2**51 + 4``, a share of + 0.7999999999999999, the float just below 0.8. That one-step drop is an + intended violation of exact monotonicity: the measurement divides by the + float total it sums in record order, as the gate divides by its own. + +numpy leaves the order of the elements on each side of a partition undefined, +and the order differs across CPUs. numpy 2.4 partitions float64 with +x86-simd-sort on x86-64 CPUs at the X86_V3 (AVX2) level or above, and that +library sorts a small array outright. Elsewhere, macOS arm64 among them, +numpy uses introselect. Tests whose sums depend on that order fix it with +:func:`_partition_arranged`, so they pass the same way on every platform. +""" + +from __future__ import annotations + +import contextlib +import itertools +import json +import math +import operator +import warnings +from collections.abc import Iterator, Sequence +from fractions import Fraction +from unittest import mock + +import numpy as np +import pytest +from hypothesis import assume, given, settings, target +from hypothesis import strategies as st + +import microcosm.build.gates as gates +from microcosm.build.gates import ( + single_record_concentration, + tail_concentration_gate, +) + +PROPERTY = settings(max_examples=300, deadline=None, database=None) +_ROUNDING = 1e-12 + +# Dollar-like magnitudes: no product or sum leaves the float64 range, and no +# positive mass rounds to zero. The totality property drops these bounds. +_VALUE = st.one_of( + st.just(0.0), + st.floats(min_value=1e-3, max_value=1e12), + st.floats(min_value=-1e12, max_value=-1e-3), +) +_WEIGHT = st.one_of(st.just(0.0), st.floats(min_value=1e-3, max_value=1e6)) +_RECORDS = st.lists(st.tuples(_VALUE, _WEIGHT), min_size=0, max_size=40) +_TOP_K = st.integers(min_value=1, max_value=12) +_ANY_FLOAT = st.floats(allow_nan=True, allow_infinity=True) +_ANY_RECORDS = st.lists(st.tuples(_ANY_FLOAT, _ANY_FLOAT), min_size=0, max_size=40) +_MEASUREMENTS = ("top_1_share", "top_1_weight", "top_k_share") + +# Values near 2**53, where float64's spacing is 2, beside small multiples of +# one half, at power-of-two weights so every product is exact. The records +# outside a tail can then hold less mass than one rounding step, so the +# tail's sum and the total can round past each other: the inputs that reach +# the cap in invariant 2. Every record carries mass. +_NEAR_TIE_VALUE = st.one_of( + st.integers(min_value=2**53, max_value=2**53 + 64).map(float), + st.integers(min_value=1, max_value=16).map(lambda halves: halves / 2.0), +) +_NEAR_TIE_RECORDS = st.lists( + st.tuples(_NEAR_TIE_VALUE, st.sampled_from([0.5, 1.0, 2.0])), + min_size=2, + max_size=16, +) + + +class _NumpyWithLegalPartition: + """numpy as ``microcosm.build.gates`` sees it, with one chosen partition. + + ``partition(array, kth)`` returns a legal partition: the kth smallest + value at ``kth``, the smaller values sorted before it, and the larger + values after it in ``tail_order``, an order of ``range`` of their count. + Every other attribute is numpy's. + """ + + def __init__(self, tail_order: Sequence[int]) -> None: + self._tail_order = list(tail_order) + + def __getattr__(self, name: str): + return getattr(np, name) + + def partition(self, array, kth) -> np.ndarray: + ordered = np.sort(np.asarray(array)) + kth = operator.index(kth) % ordered.size + larger = ordered[kth + 1 :] + assert sorted(self._tail_order) == list(range(larger.size)) + return np.concatenate([ordered[: kth + 1], larger[self._tail_order]]) + + +@contextlib.contextmanager +def _partition_arranged(tail_order: Sequence[int]) -> Iterator[None]: + """Run the gate and the measurement on one legal partition arrangement.""" + with mock.patch.object(gates, "np", _NumpyWithLegalPartition(tail_order)): + yield + + +def _split(records) -> tuple[list[float], list[float]]: + return [value for value, _ in records], [weight for _, weight in records] + + +def _measure(records, top_k: int = 100) -> dict[str, float | int | None]: + values, weights = _split(records) + return single_record_concentration(values, weights, top_k=top_k) + + +def _carrying(records) -> list[tuple[float, float]]: + return [(value, weight) for value, weight in records if abs(value) * weight > 0.0] + + +def _masses(records) -> np.ndarray: + """The gate's population: positive ``|value| * weight`` of finite records, + in record order.""" + values, weights = _split(records) + value_vector = np.asarray(values, dtype=np.float64) + weight_vector = np.asarray(weights, dtype=np.float64) + finite = np.isfinite(value_vector) & np.isfinite(weight_vector) + with np.errstate(over="ignore"): + mass = np.abs(value_vector[finite]) * weight_vector[finite] + return mass[mass > 0.0] + + +def _exact_top_k_share(records, top_k: int) -> float: + masses = sorted((Fraction(mass) for mass in _masses(records)), reverse=True) + return float(sum(masses[:top_k]) / sum(masses)) + + +@PROPERTY +@given(records=_RECORDS, top_k=_TOP_K) +def test_share_chain(records, top_k) -> None: + result = _measure(records, top_k) + carriers = len(_carrying(records)) + + assert result["carriers"] == carriers + if not carriers: + assert all(result[key] is None for key in _MEASUREMENTS) + return + assert 0.0 < result["top_1_share"] <= result["top_k_share"] <= 1.0 + assert result["top_1_weight"] > 0.0 + if carriers <= top_k: + assert result["top_k_share"] == 1.0 + # The pigeonhole floors, to the rounding of one float sum. + assert result["top_1_share"] >= (1.0 / carriers) * (1.0 - _ROUNDING) + assert result["top_k_share"] >= (min(top_k, carriers) / carriers) * ( + 1.0 - _ROUNDING + ) + + +@PROPERTY +@given(records=_NEAR_TIE_RECORDS, data=st.data()) +def test_no_legal_partition_lifts_a_share_past_1(records, data) -> None: + """Invariants 1, 2 and 6, in any arrangement numpy may return.""" + values, weights = _split(records) + top_k = data.draw(st.integers(min_value=1, max_value=len(records) - 1)) + tail_order = data.draw(st.permutations(range(top_k - 1))) + + with _partition_arranged(tail_order): + result = single_record_concentration(values, weights, top_k=top_k) + gate = tail_concentration_gate( + {"column": values}, + {"column": weights}, + top_k=top_k, + min_nonzero_records=top_k + 1, + ) + + ratio = gate.details["top_share"]["column"] + target(ratio, label="the gate's uncapped top-k share") + assert result["carriers"] == gate.details["carrier_counts"]["column"] + assert 0.0 < result["top_1_share"] <= result["top_k_share"] <= 1.0 + assert result["top_k_share"] == min(ratio, 1.0) + assert result["top_k_share"] == pytest.approx( + _exact_top_k_share(records, top_k), rel=_ROUNDING, abs=0.0 + ) + + +@PROPERTY +@given(records=st.one_of(_RECORDS, _NEAR_TIE_RECORDS, _ANY_RECORDS)) +def test_top_k_of_one_is_the_largest_mass_over_the_total(records) -> None: + result = _measure(records, top_k=1) + + assert result["top_k_share"] == result["top_1_share"] + if result["top_1_share"] is not None: + masses = _masses(records) + assert result["top_1_share"] == float(masses.max()) / float(masses.sum()) + + +@PROPERTY +@given(records=_RECORDS, top_k=_TOP_K, exponent=st.integers(-20, 20)) +def test_scaling_weights_by_a_power_of_two_is_exact(records, top_k, exponent) -> None: + factor = math.ldexp(1.0, exponent) + values, weights = _split(records) + base = single_record_concentration(values, weights, top_k=top_k) + + scaled = single_record_concentration( + values, [weight * factor for weight in weights], top_k=top_k + ) + + assert scaled["carriers"] == base["carriers"] + assert scaled["top_1_share"] == base["top_1_share"] + assert scaled["top_k_share"] == base["top_k_share"] + if base["top_1_weight"] is None: + assert scaled["top_1_weight"] is None + else: + assert scaled["top_1_weight"] == base["top_1_weight"] * factor + + +@PROPERTY +@given( + records=_RECORDS, + top_k=_TOP_K, + factor=st.floats(min_value=1e-3, max_value=1e3), +) +def test_shares_are_scale_free_in_the_weights(records, top_k, factor) -> None: + values, weights = _split(records) + base = single_record_concentration(values, weights, top_k=top_k) + + scaled = single_record_concentration( + values, [weight * factor for weight in weights], top_k=top_k + ) + + assert scaled["carriers"] == base["carriers"] + for key in ("top_1_share", "top_k_share"): + if base[key] is None: + assert scaled[key] is None + else: + assert scaled[key] == pytest.approx(base[key], rel=1e-9, abs=0.0) + + +@PROPERTY +@given( + records=_RECORDS, + top_k=_TOP_K, + exponent=st.integers(-10, 10), + negate=st.booleans(), +) +def test_scaling_or_negating_values_changes_nothing( + records, top_k, exponent, negate +) -> None: + factor = math.ldexp(-1.0 if negate else 1.0, exponent) + values, weights = _split(records) + + assert single_record_concentration( + [value * factor for value in values], weights, top_k=top_k + ) == single_record_concentration(values, weights, top_k=top_k) + + +@PROPERTY +@given(records=_ANY_RECORDS, top_k=_TOP_K) +def test_any_floats_give_a_finite_report(records, top_k) -> None: + # Any numpy warning (overflow, invalid, divide) fails the test. + with warnings.catch_warnings(): + warnings.simplefilter("error") + result = _measure(records, top_k) + + # allow_nan=False refuses NaN and both infinities. + json.dumps(result, allow_nan=False) + assert set(result) == {"carriers", *_MEASUREMENTS} + assert isinstance(result["carriers"], int) and result["carriers"] >= 0 + measured = [result[key] is not None for key in _MEASUREMENTS] + assert all(measured) or not any(measured) + if not result["carriers"]: + assert not any(measured) + if all(measured): + assert 0.0 < result["top_1_share"] <= result["top_k_share"] <= 1.0 + assert result["top_1_weight"] > 0.0 + + +@PROPERTY +@given(records=_RECORDS, top_k=_TOP_K, seed=st.integers(0, 2**32 - 1)) +def test_record_order_does_not_matter(records, top_k, seed) -> None: + order = np.random.default_rng(seed).permutation(len(records)) + base = _measure(records, top_k) + + shuffled = _measure([records[index] for index in order], top_k) + + assert shuffled["carriers"] == base["carriers"] + assert shuffled["top_1_weight"] == base["top_1_weight"] + for key in ("top_1_share", "top_k_share"): + if base[key] is None: + assert shuffled[key] is None + else: + assert shuffled[key] == pytest.approx(base[key], rel=_ROUNDING, abs=0.0) + + +@PROPERTY +@given( + records=_RECORDS, + top_k=_TOP_K, + lift=st.floats(min_value=1.0, max_value=1e3), +) +def test_a_larger_top_record_never_lowers_the_top_1_share(records, top_k, lift) -> None: + carrying = _carrying(records) + assume(carrying) + top = max(range(len(records)), key=lambda i: abs(records[i][0]) * records[i][1]) + lifted = list(records) + lifted[top] = (records[top][0] * lift, records[top][1]) + + assert _measure(lifted, top_k)["top_1_share"] >= _measure(records, top_k)[ + "top_1_share" + ] * (1.0 - _ROUNDING) + + +@PROPERTY +@given( + records=st.one_of(_RECORDS, _NEAR_TIE_RECORDS), + top_k=_TOP_K, + data=st.data(), +) +def test_a_larger_top_k_never_lowers_the_top_k_share_past_rounding( + records, top_k, data +) -> None: + """Invariant 4, with each ``top_k`` in any arrangement numpy may return.""" + assume(_carrying(records)) + smaller_order = data.draw(st.permutations(range(top_k - 1))) + larger_order = data.draw(st.permutations(range(top_k))) + + with _partition_arranged(smaller_order): + smaller = _measure(records, top_k)["top_k_share"] + with _partition_arranged(larger_order): + larger = _measure(records, top_k + 1)["top_k_share"] + + assert larger >= smaller * (1.0 - _ROUNDING) + + +@PROPERTY +@given( + columns=st.dictionaries( + st.sampled_from(["a", "b", "c", "d"]), _RECORDS, min_size=1, max_size=4 + ), + top_k=st.integers(min_value=1, max_value=6), + extra=st.integers(min_value=1, max_value=6), +) +def test_agrees_with_the_tail_concentration_gate(columns, top_k, extra) -> None: + """The gate's own share and counts, on every column it checks or calls thin.""" + values = {column: _split(records)[0] for column, records in columns.items()} + weights = {column: _split(records)[1] for column, records in columns.items()} + + gate = tail_concentration_gate( + values, weights, top_k=top_k, min_nonzero_records=top_k + extra + ) + + checked = gate.details["top_share"] + thin = gate.details["thin_columns"] + assert set(checked) | set(thin) == set(columns) + for column in columns: + result = single_record_concentration( + values[column], weights[column], top_k=top_k + ) + if column in thin: + assert result["carriers"] == thin[column] + continue + assert result["carriers"] == gate.details["carrier_counts"][column] + # The gate sums its tail and its total in different orders, so its + # share can pass 1 by a rounding step or two; the measurement caps it. + assert result["top_k_share"] == min(checked[column], 1.0) + + +@PROPERTY +@given(records=_RECORDS, top_k=_TOP_K) +def test_agrees_with_exact_rational_arithmetic(records, top_k) -> None: + masses = sorted( + (Fraction(abs(value) * weight) for value, weight in _carrying(records)), + reverse=True, + ) + assume(masses) + total = sum(masses) + result = _measure(records, top_k) + + assert result["top_1_share"] == pytest.approx( + float(masses[0] / total), rel=_ROUNDING, abs=0.0 + ) + assert result["top_k_share"] == pytest.approx( + float(sum(masses[:top_k]) / total), rel=_ROUNDING, abs=0.0 + ) + top_weights = [ + weight + for value, weight in _carrying(records) + if Fraction(abs(value) * weight) == masses[0] + ] + assert result["top_1_weight"] == max(top_weights) + + +class TestExamples: + def test_the_1251_line_32_draw(self) -> None: + """One weight-644.7 tax unit draws $218.9M: $141.1B, 21.7% of the column. + + The test spreads the other 16,000 carriers so the top 100 hold about + 0.43, near microcosm#1259's seed-0 rerun of the #1251 chain at initial + weights (16,001 carriers, top 100 at 0.451) and well under the gate's + 0.75: the gate passes, and only the single-record share shows the draw. + """ + rng = np.random.default_rng(1251) + body_values = rng.lognormal(mean=10.0, sigma=1.8, size=16_000) + body_weights = rng.uniform(100.0, 900.0, size=16_000) + draw_mass = 218.9e6 * 644.7 + # Scale the body so the draw is 21.7% of the column's mass. + body_values *= (draw_mass * (1 - 0.217) / 0.217) / float( + body_values @ body_weights + ) + values = np.concatenate([body_values, [218.9e6]]) + weights = np.concatenate([body_weights, [644.7]]) + + result = single_record_concentration(values, weights) + gate = tail_concentration_gate( + {"partnership_income": values}, {"partnership_income": weights} + ) + + assert gate.passed + assert result["carriers"] == 16_001 + assert result["top_1_share"] == pytest.approx(0.217, abs=1e-9) + assert result["top_1_weight"] == 644.7 + assert result["top_k_share"] == gate.details["top_share"]["partnership_income"] + assert 0.40 < result["top_k_share"] < 0.50 + assert result["top_1_share"] < result["top_k_share"] < 0.75 + + def test_a_signed_column_is_measured_on_absolute_mass(self) -> None: + result = single_record_concentration([-60.0, 30.0, 10.0], [1.0, 1.0, 1.0]) + + assert result == { + "carriers": 3, + "top_1_share": 0.6, + "top_1_weight": 1.0, + "top_k_share": 1.0, + } + + def test_the_weight_decides_the_largest_record(self) -> None: + # The smaller value on the heavier record carries more mass. + result = single_record_concentration([100.0, 30.0], [1.0, 10.0]) + + assert result["top_1_share"] == pytest.approx(300.0 / 400.0) + assert result["top_1_weight"] == 10.0 + + def test_tied_records_report_the_largest_weight(self) -> None: + # Masses 6, 6 and 6 from weights 3, 2 and 6, in any order. + for values, weights in ( + ([2.0, 3.0, 1.0], [3.0, 2.0, 6.0]), + ([1.0, 2.0, 3.0], [6.0, 3.0, 2.0]), + ): + result = single_record_concentration(values, weights) + + assert result["top_1_share"] == pytest.approx(1.0 / 3.0) + assert result["top_1_weight"] == 6.0 + + def test_top_k_share_counts_only_the_top_k(self) -> None: + values = np.concatenate([np.full(4, 10.0), np.full(6, 1.0)]) + + result = single_record_concentration(values, np.ones(10), top_k=4) + + assert result["top_1_share"] == pytest.approx(10.0 / 46.0) + assert result["top_k_share"] == pytest.approx(40.0 / 46.0) + + @pytest.mark.parametrize( + ("values", "weights"), + [ + ([], []), + ([0.0, 0.0, 0.0], [1.0, 2.0, 3.0]), + ([5.0, 7.0], [0.0, 0.0]), + ([float("nan"), float("inf")], [1.0, 1.0]), + ([5.0], [float("nan")]), + ([5.0, 7.0], [-1.0, -2.0]), + ], + ) + def test_a_zero_mass_column_is_reported_not_divided(self, values, weights) -> None: + assert single_record_concentration(values, weights) == { + "carriers": 0, + "top_1_share": None, + "top_1_weight": None, + "top_k_share": None, + } + + @pytest.mark.parametrize( + ("values", "weights"), + [ + # One product past the float64 range. + ([1e200, 1.0], [1e200, 1.0]), + # Finite products whose sum is past it. + ([1.5e308, 1.5e308], [1.0, 1.0]), + ], + ) + def test_a_mass_past_the_float_range_is_reported_without_a_share( + self, values, weights + ) -> None: + with np.errstate(over="raise"): + result = single_record_concentration(values, weights) + + assert result == { + "carriers": 2, + "top_1_share": None, + "top_1_weight": None, + "top_k_share": None, + } + + def test_non_finite_records_are_dropped_like_the_gate_drops_them(self) -> None: + result = single_record_concentration( + [float("nan"), float("inf"), 3.0, 1.0], [1.0, 1.0, 2.0, float("inf")] + ) + + assert result == { + "carriers": 1, + "top_1_share": 1.0, + "top_1_weight": 2.0, + "top_k_share": 1.0, + } + + def test_a_rounding_step_never_lifts_the_top_k_share_past_1(self) -> None: + """The smallest input whose gate share passes 1 on every platform. + + ``[2**53 + 2, 3, 1, 0.5]`` at ``top_k = 3``, where float64's spacing + is 2. Summed in record order, all three additions round down and the + total comes to ``2**53 + 4``. The two legal tails, + ``[1, 3, 2**53 + 2]`` and ``[1, 2**53 + 2, 3]``, sum to ``2**53 + 6`` + and ``2**53 + 8``. The exact share, ``(2**53 + 6) / (2**53 + 6.5)``, + rounds to 1. Rounding is monotone, so a record-order sum of + non-negative masses never falls below the rounded sum of any two of + them, and a tail of one or two records cannot pass 1. The gate checks + only columns with more carriers than ``top_k``, so four records at + ``top_k = 3`` make the smallest input whose gate share can pass 1. + """ + values = [2.0**53 + 2, 3.0, 1.0, 0.5] + weights = [1.0] * len(values) + + def measure() -> tuple[float, dict[str, float | int | None]]: + gate = tail_concentration_gate( + {"column": values}, + {"column": weights}, + top_k=3, + min_nonzero_records=4, + ) + result = single_record_concentration(values, weights, top_k=3) + return gate.details["top_share"]["column"], result + + # numpy's own partition, in whatever order this platform leaves it. + ratio, result = measure() + assert ratio > 1.0 + assert result["top_k_share"] == 1.0 + + ratios = set() + for tail_order in itertools.permutations(range(2)): + with _partition_arranged(tail_order): + ratio, result = measure() + ratios.add(ratio) + assert result["top_k_share"] == 1.0 + assert ratios == {1.0000000000000002, 1.0000000000000004} + assert _exact_top_k_share(list(zip(values, weights, strict=True)), 3) == 1.0 + + def test_the_partition_order_moves_the_gate_share_and_not_past_the_cap( + self, + ) -> None: + """The input CI failed on, in every arrangement numpy may return. + + At ``top_k = 8`` the record outside the tail holds 0.5 of a total near + 1.1e16, below one rounding step, so the exact share rounds to 1. The + tail's order decides the gate's share: 1.0000000000000002 in the + order introselect returns (macOS arm64); exactly 1.0 sorted, the order + x86-simd-sort's base case leaves and the share CI's x86-64 runners + reported; and 0.9999999999999998 in some other legal orders. The + measurement reports ``min(share, 1)`` in each. + """ + values = [2.0, 3.0, 2.0, 1.0, 1e16, 7.0, 1e15, 1.0, 0.5] + weights = [1.0] * len(values) + + def measure(tail_order) -> tuple[float, float]: + with _partition_arranged(tail_order): + gate = tail_concentration_gate( + {"column": values}, + {"column": weights}, + top_k=8, + min_nonzero_records=9, + ) + result = single_record_concentration(values, weights, top_k=8) + return gate.details["top_share"]["column"], result["top_k_share"] + + # The tail's seven values after its smallest, 1.0, sorted: 1.0, 2.0, + # 2.0, 3.0, 7.0, 1e15 and 1e16. Introselect leaves the tail as 1.0, + # 2.0, 3.0, 1e16, 7.0, 1e15, 1.0, 2.0. + introselect = (1, 3, 6, 4, 5, 0, 2) + assert measure(introselect) == (1.0000000000000002, 1.0) + assert measure(range(7)) == (1.0, 1.0) + + ratios = set() + for tail_order in itertools.permutations(range(7)): + ratio, share = measure(tail_order) + ratios.add(ratio) + assert share == min(ratio, 1.0) + assert ratios == {0.9999999999999998, 1.0, 1.0000000000000002} + assert _exact_top_k_share(list(zip(values, weights, strict=True)), 8) == 1.0 + + def test_a_larger_top_k_can_lower_the_share_by_a_rounding_step(self) -> None: + """Intended: each ``top_k`` sums its own partition, as the gate does. + + ``[0.5, 1, 2**53, 0.5, 0.5]`` sums to ``2**53 + 2`` in record order. + The top-3 tail ``[0.5, 1, 2**53]`` sums to that too, a share of 1.0; + the top-4 tail ``[0.5, 2**53, 1, 0.5]`` loses each value after + ``2**53`` to rounding and sums to ``2**53``, a share of + 0.9999999999999998. numpy's own partition leaves these two orders on + macOS arm64. Both shares are within a rounding step of the exact ones. + """ + records = [(value, 1.0) for value in [0.5, 1.0, 2.0**53, 0.5, 0.5]] + + with _partition_arranged((0, 1)): + top_3 = _measure(records, top_k=3)["top_k_share"] + with _partition_arranged((2, 1, 0)): + top_4 = _measure(records, top_k=4)["top_k_share"] + + assert (top_3, top_4) == (1.0, 0.9999999999999998) + for top_k, share in ((3, top_3), (4, top_4)): + assert share == pytest.approx( + _exact_top_k_share(records, top_k), rel=_ROUNDING, abs=0.0 + ) + + def test_a_factor_that_is_not_a_power_of_two_can_move_the_largest_record( + self, + ) -> None: + """Intended: such a factor rounds each mass anew, and rounding decides. + + ``[1, 10]`` at weights ``[1, 0.1]`` ties at a mass of exactly 1, so + ``top_1_weight`` is the larger weight, 1. Three times each weight is + ``[3, 0.30000000000000004]``, and the masses come to + ``[3, 3.0000000000000004]``: the second record leads by one rounding + step. ``top_1_weight`` is then its weight, not three times the first + record's, and ``top_1_share`` moves one step off 0.5. Twice each + weight doubles ``top_1_weight`` and changes nothing else. + + A factor on the values moves it too. ``[1, 3]`` at weights ``[9, 3]`` + ties at a mass of 9 and reports weight 9. A tenth of each value is + ``[0.1, 0.30000000000000004]``, the masses come to + ``[0.9, 0.9000000000000001]``, and the report is the second record's + weight, 3. Half of each value changes nothing. + """ + values, weights = [1.0, 10.0], [1.0, 0.1] + tied = { + "carriers": 2, + "top_1_share": 0.5, + "top_1_weight": 1.0, + "top_k_share": 1.0, + } + + assert single_record_concentration(values, weights) == tied + assert single_record_concentration( + values, [2.0 * weight for weight in weights] + ) == {**tied, "top_1_weight": 2.0} + assert single_record_concentration( + values, [3.0 * weight for weight in weights] + ) == { + "carriers": 2, + "top_1_share": 0.5000000000000001, + "top_1_weight": 0.30000000000000004, + "top_k_share": 1.0, + } + + values, weights = [1.0, 3.0], [9.0, 3.0] + tied = {**tied, "top_1_weight": 9.0} + + assert single_record_concentration(values, weights) == tied + assert ( + single_record_concentration([0.5 * value for value in values], weights) + == tied + ) + assert single_record_concentration( + [0.1 * value for value in values], weights + ) == {**tied, "top_1_weight": 3.0} + + def test_a_larger_top_record_can_lower_its_share_by_one_float_step( + self, + ) -> None: + """Intended: the share divides by a float total summed in record order. + + Float64's spacing is 2 from ``2**53`` to ``2**54``. The masses + ``[2**53, 2**51 + 1]`` add up to ``5 * 2**51 + 1``, halfway between + two floats, and the sum rounds to the even one, ``5 * 2**51``: a + share of 0.8. One float step up, ``[2**53 + 2, 2**51 + 1]`` adds up + to ``5 * 2**51 + 3`` and the sum rounds to ``5 * 2**51 + 4``: a share + of 0.7999999999999999, the float just below 0.8. The total rose by + two steps where the largest mass rose by one. The exact share rises, + and both exact shares round to 0.7999999999999999, so each reported + share is within one float step of its exact one. + """ + lift = 1.0 + 2.0**-52 + assert 2.0**53 * lift == 2.0**53 + 2 + base_records = [(2.0**53, 1.0), (2.0**51 + 1, 1.0)] + lifted_records = [(2.0**53 * lift, 1.0), (2.0**51 + 1, 1.0)] + assert float(_masses(base_records).sum()) == 5 * 2.0**51 + assert float(_masses(lifted_records).sum()) == 5 * 2.0**51 + 4 + + base = _measure(base_records)["top_1_share"] + lifted = _measure(lifted_records)["top_1_share"] + + assert (base, lifted) == (0.8, 0.7999999999999999) + assert lifted == math.nextafter(base, 0.0) + assert lifted >= base * (1.0 - _ROUNDING) + assert Fraction(2**53, 5 * 2**51 + 1) < Fraction(2**53 + 2, 5 * 2**51 + 3) + for records in (base_records, lifted_records): + assert _exact_top_k_share(records, 1) == 0.7999999999999999 + + def test_top_k_share_is_exactly_1_when_every_carrier_is_in_the_top_k( + self, + ) -> None: + # Summed in the order introselect leaves them (macOS arm64), these + # masses give 0.9999999999999998 of their record-order total. With + # every carrier in the tail, the measurement sums no partition. + values = [2.0, 1e15, 4.5e15, 1e16, 1.0, 1e15, 4.5e15] + introselect = [1.0, 1e15, 4.5e15, 1e16, 2.0, 1e15, 4.5e15] + assert float(np.sum(introselect)) / float(np.sum(values)) == ( + 0.9999999999999998 + ) + + # The six values above the smallest, sorted: 2.0, 1e15, 1e15, 4.5e15, + # 4.5e15 and 1e16. Introselect leaves them as 1e15, 4.5e15, 1e16, + # 2.0, 1e15, 4.5e15. + with _partition_arranged((1, 3, 5, 0, 2, 4)): + result = single_record_concentration(values, [1.0] * 7, top_k=7) + + assert result["top_k_share"] == 1.0 + + def test_invalid_arguments_are_rejected(self) -> None: + with pytest.raises(ValueError, match="top_k"): + single_record_concentration([1.0], [1.0], top_k=0) + with pytest.raises(ValueError, match="align"): + single_record_concentration([1.0, 2.0], [1.0]) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py index cefaff3415..fdcac214fe 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py @@ -11,10 +11,13 @@ from types import SimpleNamespace import h5py +import hypothesis import numpy as np import pandas as pd import pytest +from hypothesis import strategies as st +from microcosm.build.gates import single_record_concentration, tail_concentration_gate from microcosm.build.us_runtime import h5_io as builder_h5_io from microcosm.calibrate import ( CalibrationHierarchy, @@ -16287,6 +16290,747 @@ def test_qrf_tail_concentration_gate_passes_dispersed_sparse_mass() -> None: assert gate.passed +# --- Single-record concentration: reported beside the gate, never graded --- + +#: The gate's details keys before the single-record diagnostic. The +#: diagnostic lives in the surface, so the details keep exactly these. +_TAIL_GATE_DETAIL_KEYS = { + "columns_checked", + "top_k", + "max_top_share", + "min_nonzero_records", + "top_share", + "carrier_counts", + "thin_columns", + "reviewed_exclusions", + "stale_exclusions", + "dormant_exclusions", +} + + +def _qrf_person_frame( + builder, + columns: dict[str, np.ndarray], + household_weights: np.ndarray, + *, + household_columns: dict[str, np.ndarray] | None = None, + tax_unit_weights: np.ndarray | None = None, +) -> Frame: + n = int(household_weights.size) + ids = np.arange(1, n + 1, dtype="int64") + person = pd.DataFrame( + { + "person_id": ids, + "person_household_id": ids, + "person_tax_unit_id": ids, + "person_spm_unit_id": ids, + "person_family_id": ids, + "person_marital_unit_id": ids, + **columns, + } + ) + weights = { + "household": builder.Weights( + values=np.asarray(household_weights, dtype=np.float64), + kind=WeightKind.DESIGN, + ) + } + if tax_unit_weights is not None: + weights["tax_unit"] = builder.Weights( + values=np.asarray(tax_unit_weights, dtype=np.float64), + kind=WeightKind.DESIGN, + ) + return Frame( + { + "person": person, + "household": pd.DataFrame( + {"household_id": ids, **(household_columns or {})} + ), + "tax_unit": pd.DataFrame({"tax_unit_id": ids}), + "spm_unit": pd.DataFrame({"spm_unit_id": ids}), + "family": pd.DataFrame({"family_id": ids}), + "marital_unit": pd.DataFrame({"marital_unit_id": ids}), + }, + builder.US_SCHEMA, + weights, + ) + + +def _single_record_fixture(builder) -> tuple[Frame, np.ndarray]: + """One record carries 57% of a checked column whose gate passes. + + ``non_sch_d_capital_gains``: 500 carriers of 12,000 records. Record 0 has + weight 2 and value $1M, so mass $2M of $3,486,521 (57.4%); the top 100 + carry 65.8%, under the 0.75 threshold. ``taxable_interest_income`` is + dense, ``casualty_loss`` thin (10 carriers), ``estate_income`` all zero, + ``business_is_sstb`` boolean, and ``short_term_capital_gains`` absent. + """ + n = 12_000 + weights = np.ones(n) + weights[0] = 2.0 + non_sch_d = np.zeros(n) + non_sch_d[:500] = 2_979.0 + non_sch_d[0] = 1_000_000.0 + interest = np.zeros(n) + interest[: n // 2] = 1_000.0 + interest[1] = 50_000.0 + casualty = np.zeros(n) + casualty[100:110] = 500.0 + frame = _qrf_person_frame( + builder, + { + "non_sch_d_capital_gains": non_sch_d, + "taxable_interest_income": interest, + "casualty_loss": casualty, + "estate_income": np.zeros(n), + "business_is_sstb": np.zeros(n, dtype=bool), + }, + weights, + ) + return frame, weights + + +def test_qrf_tail_surface_reports_the_largest_single_record() -> None: + builder = _load_builder_module() + frame, weights = _single_record_fixture(builder) + + gate, surface = builder._qrf_tail_concentration_gate(frame) + + # The measurement leaves the gate as it was: it passes and carries only + # its own detail keys. + assert gate.passed + assert set(gate.details) == _TAIL_GATE_DETAIL_KEYS + sparse = ["casualty_loss", "estate_income", "non_sch_d_capital_gains"] + direct = tail_concentration_gate( + {column: frame.table("person")[column].to_numpy() for column in sparse}, + {column: weights for column in sparse}, + top_k=builder.US_QRF_TAIL_CONCENTRATION_TOP_K, + max_top_share=builder.US_QRF_TAIL_CONCENTRATION_MAX_TOP_SHARE, + min_nonzero_records=builder.US_QRF_TAIL_CONCENTRATION_MIN_NONZERO_RECORDS, + ) + assert gate.details == direct.details + assert surface["checked_sparse_columns"] == sparse + + block = surface["single_record_concentration"] + assert block["top_k"] == 100 + assert block["unmeasured"] == {} + # The surface measures every numeric output, dense and thin ones included. + assert ( + set(block["columns"]) + == set(surface["nonzero_shares"]) + == { + *sparse, + "taxable_interest_income", + } + ) + columns = block["columns"] + assert columns["non_sch_d_capital_gains"] == { + "carriers": 500, + "top_1_share": pytest.approx(2_000_000.0 / 3_486_521.0), + "top_1_weight": 2.0, + "top_k_share": gate.details["top_share"]["non_sch_d_capital_gains"], + } + assert gate.details["top_share"]["non_sch_d_capital_gains"] == pytest.approx( + 2_294_921.0 / 3_486_521.0 + ) + assert columns["taxable_interest_income"] == { + "carriers": 6_000, + # Record 0 (weight 2) carries $2,000 here: 5,998 x $1,000 + $2,000 + # + $50,000, and the top 100 are $50,000 + $2,000 + 98 x $1,000. + "top_1_share": pytest.approx(50_000.0 / 6_050_000.0), + "top_1_weight": 1.0, + "top_k_share": pytest.approx(150_000.0 / 6_050_000.0), + } + assert columns["casualty_loss"] == { + "carriers": 10, + "top_1_share": pytest.approx(0.1), + "top_1_weight": 1.0, + "top_k_share": 1.0, + } + # The surface reports a zero-mass column and never divides by its mass. + assert columns["estate_income"] == { + "carriers": 0, + "top_1_share": None, + "top_1_weight": None, + "top_k_share": None, + } + + +def test_qrf_tail_evidence_file_carries_the_single_record_block(tmp_path) -> None: + builder = _load_builder_module() + frame, _ = _single_record_fixture(builder) + _, surface = builder._qrf_tail_concentration_gate(frame) + failures: list[str] = [] + + _record_qrf_tail( + builder, tmp_path, frame, register=None, allow=False, failures=failures + ) + + assert failures == [] + + def refuse(constant: str) -> None: + raise AssertionError(f"non-finite {constant} in the evidence file") + + payload = json.loads( + (tmp_path / "qrf_tail_concentration.json").read_text(), + parse_constant=refuse, + ) + assert payload["surface"]["single_record_concentration"] == json.loads( + json.dumps(surface["single_record_concentration"]) + ) + assert set(payload["tail_concentration"]["details"]) == _TAIL_GATE_DETAIL_KEYS + + +def test_a_dense_output_with_unresolvable_weights_is_unmeasured_not_fatal() -> None: + """Weighted on two group entities, person weights do not resolve. The gate + never resolves weights for a dense output, so neither may its measurement + fail the run; a sparse person output still raises, as it always did.""" + builder = _load_builder_module() + n = 12_000 + interest = np.zeros(n) + interest[: n // 2] = 1_000.0 + auto_loans = np.zeros(n) + auto_loans[:500] = 4_000.0 + frame = _qrf_person_frame( + builder, + {"taxable_interest_income": interest}, + np.ones(n), + household_columns={"auto_loan_balance": auto_loans}, + tax_unit_weights=np.ones(n), + ) + + gate, surface = builder._qrf_tail_concentration_gate(frame) + + assert gate.passed + assert surface["dense_columns"] == ["taxable_interest_income"] + assert surface["checked_sparse_columns"] == ["auto_loan_balance"] + block = surface["single_record_concentration"] + assert set(block["columns"]) == {"auto_loan_balance"} + assert block["columns"]["auto_loan_balance"]["top_1_share"] == pytest.approx( + 1 / 500 + ) + assert set(block["unmeasured"]) == {"taxable_interest_income"} + assert block["unmeasured"]["taxable_interest_income"].startswith( + "ValueError: Cannot resolve person-level weights" + ) + + sparse_person = np.zeros(n) + sparse_person[:500] = 2_979.0 + broken = _qrf_person_frame( + builder, + {"taxable_interest_income": interest, "casualty_loss": sparse_person}, + np.ones(n), + tax_unit_weights=np.ones(n), + ) + with pytest.raises(ValueError, match="Cannot resolve person-level weights"): + builder._qrf_tail_concentration_gate(broken) + + +class _WeightResolutionSpy: + """An export frame that records each entity whose weights it resolves. + + For ``entity`` it raises ``error``, or returns ``values`` as the weights, + in place of the frame's own; every other attribute is the frame's. + """ + + def __init__( + self, + frame: Frame, + entity: str | None = None, + *, + error: Exception | None = None, + values: np.ndarray | None = None, + ) -> None: + self._frame = frame + self._entity = entity + self._error = error + self._values = values + self.resolved: list[str] = [] + + def __getattr__(self, name: str): + return getattr(self._frame, name) + + def resolve_weights(self, entity: str): + self.resolved.append(entity) + if entity == self._entity and self._error is not None: + raise self._error + if entity == self._entity and self._values is not None: + return SimpleNamespace(values=self._values) + return self._frame.resolve_weights(entity) + + +@pytest.mark.parametrize( + ("failure", "reason"), + [ + ( + {"error": RuntimeError("weight store offline")}, + "RuntimeError: weight store offline", + ), + ( + {"values": np.array([object()] * 12_000, dtype=object)}, + "TypeError: ", + ), + ( + {"values": np.ones(11_999)}, + "ValueError: values and weights must align, got 12000 values vs " + "11999 weights.", + ), + ], + ids=["resolution-raises", "weights-not-numbers", "weights-misaligned"], +) +def test_any_error_measuring_a_dense_output_lands_under_unmeasured( + failure, reason +) -> None: + """Review N1: the gate never weighs a dense output, so no error from + measuring one may fail the run, whatever its type or its source.""" + builder = _load_builder_module() + n = 12_000 + interest = np.zeros(n) + interest[: n // 2] = 1_000.0 + auto_loans = np.zeros(n) + auto_loans[:500] = 4_000.0 + frame = _WeightResolutionSpy( + _qrf_person_frame( + builder, + {"taxable_interest_income": interest}, + np.ones(n), + household_columns={"auto_loan_balance": auto_loans}, + ), + "person", + **failure, + ) + + gate, surface = builder._qrf_tail_concentration_gate(frame) + + assert gate.passed + assert surface["dense_columns"] == ["taxable_interest_income"] + assert surface["checked_sparse_columns"] == ["auto_loan_balance"] + block = surface["single_record_concentration"] + assert set(block["columns"]) == {"auto_loan_balance"} + assert set(block["unmeasured"]) == {"taxable_interest_income"} + assert block["unmeasured"]["taxable_interest_income"].startswith(reason) + # The sparse output's measurement reuses the weights the gate loop + # resolved, so the frame resolves the household's weights once; the dense + # output's measurement then asks for the person's. + assert frame.resolved == ["household", "person"] + + +class _StrRaisesError(Exception): + def __str__(self) -> str: + raise RuntimeError("str failed") + + +class _FormatRaisesError(Exception): + def __format__(self, spec: str) -> str: + raise LookupError("format failed") + + +class _NameRaisesMeta(type): + @property + def __name__(cls) -> str: + raise OSError("name failed") + + +class _NameRaisesError(Exception, metaclass=_NameRaisesMeta): + pass + + +def test_a_dense_output_whose_error_cannot_print_itself_is_unmeasured() -> None: + """Review G-1: resolving a dense output's weights raises an error whose + ``__str__`` raises. Formatting the reason must not raise in its turn: the + gate passes, and the output goes under ``unmeasured`` with the type's + name.""" + builder = _load_builder_module() + n = 12_000 + interest = np.zeros(n) + interest[: n // 2] = 1_000.0 + auto_loans = np.zeros(n) + auto_loans[:500] = 4_000.0 + frame = _WeightResolutionSpy( + _qrf_person_frame( + builder, + {"taxable_interest_income": interest}, + np.ones(n), + household_columns={"auto_loan_balance": auto_loans}, + ), + "person", + error=_StrRaisesError(), + ) + + gate, surface = builder._qrf_tail_concentration_gate(frame) + + assert gate.passed + block = surface["single_record_concentration"] + assert set(block["columns"]) == {"auto_loan_balance"} + assert block["unmeasured"] == { + "taxable_interest_income": "_StrRaisesError: unprintable error" + } + + +@pytest.mark.parametrize( + ("error_type", "reason"), + [ + (ValueError, "ValueError: weights do not align"), + (_StrRaisesError, "_StrRaisesError: unprintable error"), + (_FormatRaisesError, "_FormatRaisesError: unprintable error"), + (_NameRaisesError, "unprintable error"), + ], + ids=["prints", "str-raises", "format-raises", "type-name-raises"], +) +def test_a_single_record_unmeasured_reason_never_raises(error_type, reason) -> None: + """Review G-1: the reason is the error's type and text; an error whose + text cannot format keeps its type's name, and one whose type cannot name + itself keeps the fixed text. + + The test takes the error's class and builds the instance inside the call: + pytest prints a failing test's arguments with ``reprlib``, which reads + ``type(argument).__name__`` and so cannot print a ``_NameRaisesError``. + """ + builder = _load_builder_module() + + assert builder._unmeasured_reason(error_type("weights do not align")) == reason + + +def test_a_single_record_unmeasured_reason_is_total() -> None: + """For every error the strategies build, the reason is the text the error + can still give, and no ``Exception`` leaves the helper. Each of + ``__str__``, ``__format__`` and the type's ``__name__`` either works or + raises a drawn ``Exception``, and ``__str__`` may return a number. The + reason is the type's name and the text, then the type's name with + ``unprintable error``, then ``unprintable error`` alone.""" + builder = _load_builder_module() + raised = st.sampled_from( + [ + ArithmeticError, + AttributeError, + KeyError, + MemoryError, + OSError, + RecursionError, + RuntimeError, + StopIteration, + TypeError, + ValueError, + ] + ) + works_or_raises = st.one_of(st.none(), raised) + + @hypothesis.settings(max_examples=200, deadline=None, database=None) + @hypothesis.given( + text=st.text(max_size=20), + str_raises=works_or_raises, + str_returns_a_number=st.booleans(), + format_raises=works_or_raises, + name_raises=works_or_raises, + ) + def check( + text, str_raises, str_returns_a_number, format_raises, name_raises + ) -> None: + def broken_str(self): + if str_raises is not None: + raise str_raises("str failed") + return 7 + + def broken_format(self, spec): + raise format_raises("format failed") + + def broken_name(cls): + raise name_raises("name failed") + + methods: dict[str, object] = {} + if str_raises is not None or str_returns_a_number: + methods["__str__"] = broken_str + if format_raises is not None: + methods["__format__"] = broken_format + meta_methods: dict[str, object] = {} + if name_raises is not None: + meta_methods["__name__"] = property(broken_name) + meta = type("DrawnMeta", (type,), meta_methods) + error_type = meta("DrawnError", (Exception,), methods) + + reason = builder._unmeasured_reason(error_type(text)) + + if name_raises is not None: + assert reason == "unprintable error" + elif methods: + assert reason == "DrawnError: unprintable error" + else: + assert reason == f"DrawnError: {text}" + + check() + + +class _TableSpy: + """An export frame that records each table it hands out. + + Once ``offline`` is set, asking for a table raises; every other attribute + is the frame's. + """ + + def __init__(self, frame: Frame) -> None: + self._frame = frame + self.offline = False + self.tables_read: list[str] = [] + + def __getattr__(self, name: str): + return getattr(self._frame, name) + + def table(self, entity: str): + self.tables_read.append(entity) + if self.offline: + raise RuntimeError("frame offline") + return self._frame.table(entity) + + +def test_a_dense_output_the_frame_cannot_give_again_is_unmeasured_not_fatal() -> None: + """Review G-2: the gate loop stores no dense output's values, so the + measurement reads a dense column from the frame again, after the gate. A + frame that fails then leaves the gate's verdict alone: the dense output + goes under ``unmeasured`` and the sparse one keeps its measurement.""" + builder = _load_builder_module() + n = 12_000 + interest = np.zeros(n) + interest[: n // 2] = 1_000.0 + auto_loans = np.zeros(n) + auto_loans[:500] = 4_000.0 + frame = _TableSpy( + _qrf_person_frame( + builder, + {"taxable_interest_income": interest}, + np.ones(n), + household_columns={"auto_loan_balance": auto_loans}, + ) + ) + shared_gate = builder.tail_concentration_gate + + def gate_then_offline(*args, **kwargs): + result = shared_gate(*args, **kwargs) + frame.offline = True + return result + + builder.tail_concentration_gate = gate_then_offline + + gate, surface = builder._qrf_tail_concentration_gate(frame) + + assert gate.passed + assert surface["dense_columns"] == ["taxable_interest_income"] + # The loop reads each output's table once; the measurement asks for the + # dense output's table again. + assert frame.tables_read == ["household", "person", "person"] + block = surface["single_record_concentration"] + assert set(block["columns"]) == {"auto_loan_balance"} + assert block["unmeasured"] == { + "taxable_interest_income": "RuntimeError: frame offline" + } + + +def test_a_dense_output_stored_as_text_is_measured_as_the_gate_loop_read_it() -> None: + """Review G-2: the measurement converts a dense column as the gate loop + does, so an entry that is no number counts as zero in both. The column + holds text and one missing entry: 6,000 entries read ``"0"``, and of the + other 6,000 one is not a number and one is missing. The loop counts 5,998 + nonzero records, and the measurement finds the same 5,998 carriers.""" + builder = _load_builder_module() + n = 12_000 + interest = np.array(["0"] * n, dtype=object) + interest[: n // 2] = "1000" + interest[1] = "50000" + interest[2] = "not a number" + interest[3] = None + frame = _TableSpy( + _qrf_person_frame(builder, {"taxable_interest_income": interest}, np.ones(n)) + ) + + gate, surface = builder._qrf_tail_concentration_gate(frame) + + assert gate.passed + assert surface["dense_columns"] == ["taxable_interest_income"] + assert surface["nonzero_records"] == {"taxable_interest_income": 5_998} + assert frame.tables_read == ["person", "person"] + block = surface["single_record_concentration"] + assert block["unmeasured"] == {} + # 5,997 records of $1,000 and one of $50,000, at weight 1. + assert block["columns"] == { + "taxable_interest_income": { + "carriers": 5_998, + "top_1_share": pytest.approx(50_000.0 / 6_047_000.0), + "top_1_weight": 1.0, + "top_k_share": pytest.approx(149_000.0 / 6_047_000.0), + } + } + + +def test_a_dense_output_is_measured_at_float64_as_the_gate_loop_read_it() -> None: + """Review G-2: the measurement rereads a dense column as float64, the + type the gate loop read it at. The block equals the shared measurement on + the column's float64 values, with no tolerance. 0.1 is not a float32 + number, so a float32 reread would move both shares.""" + builder = _load_builder_module() + n = 12_000 + interest = np.zeros(n) + interest[: n // 2] = 0.1 + interest[1] = 50_000.0 + frame = _qrf_person_frame( + builder, {"taxable_interest_income": interest}, np.ones(n) + ) + + gate, surface = builder._qrf_tail_concentration_gate(frame) + + assert gate.passed + assert surface["dense_columns"] == ["taxable_interest_income"] + block = surface["single_record_concentration"] + assert block["unmeasured"] == {} + assert block["columns"] == { + "taxable_interest_income": single_record_concentration( + interest, np.ones(n), top_k=builder.US_QRF_TAIL_CONCENTRATION_TOP_K + ) + } + + +def test_a_misaligned_sparse_output_fails_with_the_gates_own_message() -> None: + """Review N2: misaligned weights on a sparse output raise the gate's error, + which names the column, because no measurement runs before the gate.""" + builder = _load_builder_module() + n = 12_000 + casualty = np.zeros(n) + casualty[:500] = 2_979.0 + frame = _WeightResolutionSpy( + _qrf_person_frame(builder, {"casualty_loss": casualty}, np.ones(n)), + "person", + values=np.ones(n - 1), + ) + + with pytest.raises(ValueError) as raised: + builder._qrf_tail_concentration_gate(frame) + + assert str(raised.value) == ( + "casualty_loss: values and weights must align, got 12000 values vs " + "11999 weights." + ) + + +def test_no_measurement_runs_before_the_gate_raises() -> None: + """A sparse household output's weights do not align with its values, and + a dense person output waits for its measurement. The gate raises its own + message, and the frame has resolved the household's weights only: the + measurement, which would resolve the person's, has not run.""" + builder = _load_builder_module() + n = 12_000 + interest = np.zeros(n) + interest[: n // 2] = 1_000.0 + auto_loans = np.zeros(n) + auto_loans[:500] = 4_000.0 + frame = _WeightResolutionSpy( + _qrf_person_frame( + builder, + {"taxable_interest_income": interest}, + np.ones(n), + household_columns={"auto_loan_balance": auto_loans}, + ), + "household", + values=np.ones(n - 1), + ) + + with pytest.raises(ValueError) as raised: + builder._qrf_tail_concentration_gate(frame) + + assert str(raised.value) == ( + "auto_loan_balance: values and weights must align, got 12000 values vs " + "11999 weights." + ) + assert frame.resolved == ["household"] + + +def test_a_dense_output_before_a_sparse_one_leaves_the_gate_to_raise() -> None: + """Review N4: a dense output sorts before a sparse output of the same + entity, and that entity's weights do not resolve. The sparse output's + error still fails the run, and the frame resolves the entity's weights + once, for the sparse output: the dense output's measurement waits until + after the gate, so it never runs.""" + builder = _load_builder_module() + n = 12_000 + dense = np.zeros(n) + dense[: n // 2] = 500.0 + sparse = np.zeros(n) + sparse[:500] = 2_979.0 + frame = _WeightResolutionSpy( + _qrf_person_frame( + builder, + {"casualty_loss": dense, "taxable_interest_income": sparse}, + np.ones(n), + tax_unit_weights=np.ones(n), + ) + ) + + with pytest.raises(ValueError, match="Cannot resolve person-level weights"): + builder._qrf_tail_concentration_gate(frame) + + assert frame.resolved == ["person"] + + +def test_qrf_tail_single_record_measurement_never_moves_the_gate() -> None: + """For any column geometry the strategies reach: the gate's details equal + the shared gate run on the sparse columns alone; the surface measures + every numeric output exactly once, with the shared measurement at the + frame's weights; and a checked column's top-k share is the gate's own, + capped at 1.""" + builder = _load_builder_module() + n = 12_000 + max_share = builder.US_QRF_SPARSE_NONZERO_SHARE_MAX + columns = ("non_sch_d_capital_gains", "casualty_loss", "estate_income") + + @hypothesis.settings(max_examples=40, deadline=None, database=None) + @hypothesis.given( + carriers=st.tuples(*(st.integers(0, 1_200) for _ in columns)), + sigma=st.floats(min_value=0.1, max_value=4.0), + seed=st.integers(0, 2**32 - 1), + ) + def check(carriers, sigma, seed) -> None: + rng = np.random.default_rng(seed) + weights = rng.uniform(0.5, 900.0, size=n) + values: dict[str, np.ndarray] = {} + for column, count in zip(columns, carriers, strict=True): + array = np.zeros(n) + chosen = rng.choice(n, size=count, replace=False) + array[chosen] = rng.lognormal(8.0, sigma, size=count) * rng.choice( + [-1.0, 1.0], size=count + ) + values[column] = array + frame = _qrf_person_frame(builder, values, weights) + + gate, surface = builder._qrf_tail_concentration_gate(frame) + + sparse = { + column: array + for column, array in values.items() + if (array != 0.0).mean() <= max_share + } + direct = tail_concentration_gate( + sparse, + {column: weights for column in sparse}, + top_k=builder.US_QRF_TAIL_CONCENTRATION_TOP_K, + max_top_share=builder.US_QRF_TAIL_CONCENTRATION_MAX_TOP_SHARE, + min_nonzero_records=(builder.US_QRF_TAIL_CONCENTRATION_MIN_NONZERO_RECORDS), + ) + assert gate.passed == direct.passed + assert gate.failures == direct.failures + assert gate.details == direct.details + block = surface["single_record_concentration"] + assert block["unmeasured"] == {} + assert set(block["columns"]) == set(columns) + for column, array in values.items(): + measured = block["columns"][column] + assert measured == single_record_concentration(array, weights) + if column in gate.details["top_share"]: + assert measured["top_k_share"] == min( + gate.details["top_share"][column], 1.0 + ) + if measured["carriers"]: + assert 0.0 < measured["top_1_share"] <= measured["top_k_share"] <= 1.0 + + check() + + def test_allow_qrf_tail_concentration_flag_parses(monkeypatch) -> None: builder = _load_builder_module() diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py index 51678d1bb9..c24d8d8234 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py @@ -868,6 +868,208 @@ def sha256(path) -> str: } +def _tail_result(single_record=None, *, passed=True, share=0.4, unmeasured=None): + surface = {"checked_sparse_columns": ["partnership_income"]} + if single_record is not None: + surface["single_record_concentration"] = { + "top_k": 100, + "columns": single_record, + "unmeasured": unmeasured or {}, + } + return { + "passed": passed, + "surface": surface, + "details": {"top_share": {"partnership_income": share}}, + } + + +def _tail_reference(single_record=None, **options): + result = _tail_result(single_record, **options) + return { + "surface": result["surface"], + "tail_concentration": { + "passed": result["passed"], + "details": result["details"], + }, + } + + +# Line 32 in #1259's seed-0 rerun of the #1251 chain, at initial weights: one +# measurement, rounded. +_LINE_32 = { + "carriers": 16_001, + "top_1_share": 0.217, + "top_1_weight": 644.7, + "top_k_share": 0.451, +} +_ZERO_MASS = { + "carriers": 0, + "top_1_share": None, + "top_1_weight": None, + "top_k_share": None, +} + + +def test_the_probe_compares_single_record_measurements(probe_tool) -> None: + measured = {"partnership_income": _LINE_32, "estate_income": _ZERO_MASS} + + same = probe_tool.compare_qrf_tail( + _tail_result(measured), _tail_reference(measured) + ) + + assert same == { + "differences": [], + "columns_compared": 1, + "single_record_columns_compared": 2, + } + + moved = probe_tool.compare_qrf_tail( + _tail_result( + {**measured, "partnership_income": {**_LINE_32, "top_1_weight": 1.08}} + ), + _tail_reference(measured), + ) + + assert moved["differences"] == ["partnership_income: top_1_weight 1.08 vs 644.7"] + + lost = probe_tool.compare_qrf_tail( + _tail_result({**measured, "estate_income": {**_ZERO_MASS, "top_1_share": 0.5}}), + _tail_reference(measured), + ) + + assert lost["differences"] == ["estate_income: top_1_share 0.5 vs None"] + + # The other direction, a probe column with the release's carriers and no + # share: what the measurement reports when a column's mass sums past the + # float range. + no_share = { + **_LINE_32, + "top_1_share": None, + "top_1_weight": None, + "top_k_share": None, + } + unshared = probe_tool.compare_qrf_tail( + _tail_result({**measured, "partnership_income": no_share}), + _tail_reference(measured), + ) + + assert unshared["differences"] == [ + "partnership_income: top_1_share None vs 0.217", + "partnership_income: top_1_weight None vs 644.7", + "partnership_income: top_k_share None vs 0.451", + ] + + narrower = probe_tool.compare_qrf_tail( + _tail_result({"partnership_income": _LINE_32}), _tail_reference(measured) + ) + + assert narrower["differences"] == [ + "single-record columns differ: only probe [], only release ['estate_income']" + ] + assert narrower["single_record_columns_compared"] == 1 + + wider = probe_tool.compare_qrf_tail( + _tail_result(measured), _tail_reference({"partnership_income": _LINE_32}) + ) + + assert wider["differences"] == [ + "single-record columns differ: only probe ['estate_income'], only release []" + ] + assert wider["single_record_columns_compared"] == 1 + + for field, value in (("carriers", 16_002), ("top_k_share", 0.452)): + one_field = probe_tool.compare_qrf_tail( + _tail_result( + {**measured, "partnership_income": {**_LINE_32, field: value}} + ), + _tail_reference(measured), + ) + + assert one_field["differences"] == [ + f"partnership_income: {field} {value!r} vs {_LINE_32[field]!r}" + ] + + +def test_the_probe_compares_unmeasured_reasons(probe_tool) -> None: + """Review N8: an output unmeasured in both runs for different reasons is a + difference, and so is an output unmeasured in one run only.""" + measured = {"partnership_income": _LINE_32} + unmeasured = { + "taxable_interest_income": "ValueError: Cannot resolve person-level weights" + } + + same = probe_tool.compare_qrf_tail( + _tail_result(measured, unmeasured=unmeasured), + _tail_reference(measured, unmeasured=unmeasured), + ) + + assert same["differences"] == [] + + another_reason = probe_tool.compare_qrf_tail( + _tail_result( + measured, + unmeasured={ + "taxable_interest_income": "RuntimeError: weight store offline" + }, + ), + _tail_reference(measured, unmeasured=unmeasured), + ) + + assert another_reason["differences"] == [ + "taxable_interest_income: unmeasured as 'RuntimeError: weight store " + "offline' vs 'ValueError: Cannot resolve person-level weights'" + ] + + only_release = probe_tool.compare_qrf_tail( + _tail_result(measured), _tail_reference(measured, unmeasured=unmeasured) + ) + + assert only_release["differences"] == [ + "unmeasured columns differ: only probe [], only release " + "['taxable_interest_income']" + ] + + only_probe = probe_tool.compare_qrf_tail( + _tail_result(measured, unmeasured=unmeasured), _tail_reference(measured) + ) + + assert only_probe["differences"] == [ + "unmeasured columns differ: only probe ['taxable_interest_income'], " + "only release []" + ] + + +def test_a_release_without_single_record_measurements_compares_none( + probe_tool, +) -> None: + """A release built before its tail surface carried the block (Route A).""" + comparison = probe_tool.compare_qrf_tail( + _tail_result({"partnership_income": _LINE_32}), _tail_reference() + ) + + assert comparison == { + "differences": [], + "columns_compared": 1, + "single_record_columns_compared": 0, + } + + +def test_a_probe_surface_without_the_block_compares_none(probe_tool) -> None: + """The comparison skips the block when either side lacks it. A probe run's + side is the surface its builder's ``_qrf_tail_concentration_gate`` + returns, and the release tool's always carries the block, so this pins + the skip on a hand-built result.""" + comparison = probe_tool.compare_qrf_tail( + _tail_result(), _tail_reference({"partnership_income": _LINE_32}) + ) + + assert comparison == { + "differences": [], + "columns_compared": 1, + "single_record_columns_compared": 0, + } + + def test_the_timed_scorer_passes_every_scoring_argument_on( probe_tool, builder, tmp_path, monkeypatch ) -> None: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_release_gate_dry_run.py b/packages/microcosm-build/tests/engine_free/us/test_us_release_gate_dry_run.py index c0c8a2c27c..87c28c5cd5 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_release_gate_dry_run.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_release_gate_dry_run.py @@ -807,6 +807,145 @@ def check(removed, stale, unused, allow): check() +_SINGLE_RECORD_ROW_KEYS = ( + "top_1_share_at_base_weights", + "top_1_weight_at_base_weights", +) + + +def _register_check(builder, surface, gate, register, *, allow, margins): + mismatch = builder._qrf_tail_register_mismatch(register, gate) + gate_lines, register_lines = builder._qrf_tail_gate_lines( + gate, mismatch, allow_concentration=allow + ) + return dry.qrf_tail_register_check( + qrf_outputs=sorted(builder._qrf_imputed_source_outputs()), + register=register, + surface=surface, + gate_details=gate.details, + release_lines_at_base_weights=[*gate_lines, *register_lines], + support_fixed=True, + margins=margins, + allow_concentration=allow, + register_source={}, + ) + + +def test_rows_carry_the_single_record_measurements(builder, tail_frame) -> None: + register = {column: "reviewed" for column in _OVER} + gate, surface = builder._qrf_tail_concentration_gate( + tail_frame, reviewed_exclusions=register + ) + + check = _register_check( + builder, surface, gate, register, allow=False, margins=dry.DryRunMargins() + ) + + measured = surface["single_record_concentration"]["columns"] + rows = {row["column"]: row for row in check.rows} + for column, row in rows.items(): + if column in measured: + assert ( + row["top_1_share_at_base_weights"] == (measured[column]["top_1_share"]) + ) + assert ( + row["top_1_weight_at_base_weights"] + == (measured[column]["top_1_weight"]) + ) + else: + assert row["top_1_share_at_base_weights"] is None + assert row["top_1_weight_at_base_weights"] is None + # 100 records of $594,484 and 450 of $2,979, all of weight 1. + assert rows["estate_income"]["top_1_share_at_base_weights"] == pytest.approx( + 594_484.0 / (100 * 594_484.0 + 450 * 2_979.0) + ) + assert set(_BOOLEAN) | set(_ABSENT) <= { + column for column in rows if column not in measured + } + + +def test_single_record_measurements_never_move_a_dry_run_verdict( + builder, tail_frame +) -> None: + """Reported only: any values in the block, or no block at all (a release + built before it existed), give the same verdicts, lines and details; the + rows differ only in the two reported fields.""" + + hypothesis, st = _hypothesis() + gate_base, surface = builder._qrf_tail_concentration_gate(tail_frame) + columns = sorted(surface["single_record_concentration"]["columns"]) + share = st.one_of(st.none(), st.floats(min_value=0.0, max_value=1.0)) + weight = st.one_of(st.none(), st.floats(min_value=0.0, max_value=1e6)) + + @hypothesis.settings(max_examples=60, deadline=None) + @hypothesis.given( + replacement=st.one_of( + st.none(), + st.fixed_dictionaries( + { + column: st.fixed_dictionaries( + { + "carriers": st.integers(0, 10_000), + "top_1_share": share, + "top_1_weight": weight, + "top_k_share": share, + } + ) + for column in columns + } + ), + ), + register=st.sets(st.sampled_from((*_OVER, *_UNDER, *_THIN))), + allow=st.booleans(), + exact=st.booleans(), + ) + def check(replacement, register, allow, exact): + entries = {column: "reviewed" for column in register} + gate, original = builder._qrf_tail_concentration_gate( + tail_frame, reviewed_exclusions=entries + ) + changed = dict(original) + if replacement is None: + del changed["single_record_concentration"] + else: + changed["single_record_concentration"] = { + "top_k": 100, + "columns": replacement, + "unmeasured": {}, + } + margins = dry.DryRunMargins.exact() if exact else dry.DryRunMargins() + + before = _register_check( + builder, original, gate, entries, allow=allow, margins=margins + ) + after = _register_check( + builder, changed, gate, entries, allow=allow, margins=margins + ) + + assert after.status == before.status + assert after.summary == before.summary + assert after.failures == before.failures + assert after.at_risks == before.at_risks + assert after.details == before.details + + def without(rows): + return [ + {k: v for k, v in row.items() if k not in _SINGLE_RECORD_ROW_KEYS} + for row in rows + ] + + assert without(after.rows) == without(before.rows) + if replacement is None: + assert all( + row[key] is None + for row in after.rows + for key in _SINGLE_RECORD_ROW_KEYS + ) + + assert gate_base.details["top_share"] + check() + + def test_a_surface_that_misplaces_an_output_is_refused() -> None: with pytest.raises(ValueError, match="exactly once"): dry.base_tail_classes( diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 243b4d688b..1f7602005e 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -77,6 +77,7 @@ nonconstant_columns_gate, observed_value_counts, parity_gate, + single_record_concentration, tail_concentration_gate, target_fit_gate, target_profile_coverage_gate, @@ -8362,6 +8363,20 @@ def _qrf_tail_concentration_gate( absent, or non-numeric, and each numeric output's record nonzero share and finite nonzero record count, the numbers behind the dense/sparse split) for the release artifact and the ``--dry-run-gates-report`` certainty model. + + The surface also measures every numeric output, dense and thin ones + included, with :func:`microcosm.build.gates.single_record_concentration`: + the largest single record's share of the column's weighted absolute mass + and that record's weight, next to the top-k share. The measurements cannot + change the gate's inputs, its verdict or the errors it raises: the loop + resolves weights only for sparse outputs, and the gate runs before any + measurement. A misaligned sparse output therefore still fails with the + gate's own message, which names the column. The loop stores a dense + output's entity and not its values, and the measurement reads the column + from the frame again. + :func:`_qrf_single_record_measurements` runs after the gate and turns + every ``Exception`` into an ``unmeasured`` entry, so no ``Exception`` + from a measurement fails a run the gate would pass. """ qrf_outputs = sorted(_qrf_imputed_source_outputs()) values: dict[str, np.ndarray] = {} @@ -8372,6 +8387,7 @@ def _qrf_tail_concentration_gate( nonzero_shares: dict[str, float] = {} nonzero_records: dict[str, int] = {} entity_weights: dict[str, np.ndarray] = {} + dense_entities: dict[str, str] = {} for column in qrf_outputs: try: entity = export_frame.column_entity(column) @@ -8389,6 +8405,7 @@ def _qrf_tail_concentration_gate( nonzero_records[column] = int((np.isfinite(array) & (array != 0.0)).sum()) if nonzero_share > US_QRF_SPARSE_NONZERO_SHARE_MAX: dense.append(column) + dense_entities[column] = entity continue if entity not in entity_weights: entity_weights[entity] = np.asarray( @@ -8404,6 +8421,14 @@ def _qrf_tail_concentration_gate( min_nonzero_records=US_QRF_TAIL_CONCENTRATION_MIN_NONZERO_RECORDS, reviewed_exclusions=reviewed_exclusions, ) + single_record, unmeasured = _qrf_single_record_measurements( + export_frame, + qrf_outputs, + sparse_values=values, + sparse_weights=weights, + dense_entities=dense_entities, + entity_weights=entity_weights, + ) surface: dict[str, object] = { "qrf_imputed_outputs": len(qrf_outputs), "checked_sparse_columns": sorted(values), @@ -8413,10 +8438,88 @@ def _qrf_tail_concentration_gate( "sparse_nonzero_share_max": US_QRF_SPARSE_NONZERO_SHARE_MAX, "nonzero_shares": nonzero_shares, "nonzero_records": nonzero_records, + "single_record_concentration": { + "top_k": US_QRF_TAIL_CONCENTRATION_TOP_K, + "columns": single_record, + "unmeasured": unmeasured, + }, } return gate, surface +def _qrf_single_record_measurements( + export_frame: Frame, + qrf_outputs: Sequence[str], + *, + sparse_values: Mapping[str, np.ndarray], + sparse_weights: Mapping[str, np.ndarray], + dense_entities: Mapping[str, str], + entity_weights: Mapping[str, np.ndarray], +) -> tuple[dict[str, dict[str, float | int | None]], dict[str, str]]: + """Each numeric QRF output's single-record measurements, after the gate. + + A sparse output reuses the values and weights the gate checked. For a + dense output the gate loop stored only the entity, so this reads the + column from the frame again, with the loop's two conversion statements. + A dense column's converted values stay in local names: this stores them + in no mapping and returns none of them. A dense output resolves its + entity's weights here, since the gate never weighs one, and reuses + weights that a sparse output of the same entity already resolved. Any + ``Exception``, from reading a dense column, from resolving weights or + from measuring, lists the output under ``unmeasured`` with the reason + :func:`_unmeasured_reason` builds, so no ``Exception`` from an output + fails the run. Both mappings keep the order of ``qrf_outputs``. + """ + resolved = dict(entity_weights) + columns: dict[str, dict[str, float | int | None]] = {} + unmeasured: dict[str, str] = {} + for column in qrf_outputs: + if column not in sparse_values and column not in dense_entities: + continue + try: + if column in sparse_values: + column_values = sparse_values[column] + column_weights = sparse_weights[column] + else: + entity = dense_entities[column] + series = export_frame.table(entity)[column] + numeric = pd.to_numeric(series, errors="coerce").fillna(0.0) + column_values = numeric.to_numpy(dtype=np.float64) + if entity not in resolved: + resolved[entity] = np.asarray( + export_frame.resolve_weights(entity).values, + dtype=np.float64, + ) + column_weights = resolved[entity] + columns[column] = single_record_concentration( + column_values, + column_weights, + top_k=US_QRF_TAIL_CONCENTRATION_TOP_K, + ) + except Exception as error: + unmeasured[column] = _unmeasured_reason(error) + return columns, unmeasured + + +def _unmeasured_reason(error: Exception) -> str: + """Why an output went unmeasured: the error's type and text. + + Formatting an error runs the error's own ``__str__`` or ``__format__``, + and reading its type's name can run a metaclass property; any of them + can raise. When one raises an ``Exception``, the reason falls back to + the type's name with ``unprintable error``, then to ``unprintable + error`` alone, so no ``Exception`` raised while formatting leaves this + function. + """ + try: + return f"{type(error).__name__}: {error}" + except Exception: + try: + return f"{type(error).__name__}: unprintable error" + except Exception: + return "unprintable error" + + #: Failure-line prefix for a per-run QRF tail-concentration register that does #: not match the checked surface. Deliberately distinct from the standing #: evidence owner "QRF tail concentration failed:" (US_EVIDENCE_FAILURE_OWNERS): @@ -8514,9 +8617,9 @@ def _record_qrf_tail_concentration_gate( flag says) to ``terminal_gate_failures``, so the batched pre-export raise refuses the run with the #568 weight sidecar on disk. Whenever the gate evaluated, ``qrf_tail_concentration.json`` is written with the per-column - shares, carrier counts, and the mismatch. Only a genuine evaluation crash - escapes: it propagates on an otherwise-clean run and becomes one unowned - failure line under earlier failures. + shares, carrier counts, single-record shares, and the mismatch. Only a + genuine evaluation crash escapes: it propagates on an otherwise-clean run + and becomes one unowned failure line under earlier failures. Returns the register-mismatch failure lines (empty when the register matches) so --evidence-release can refuse them. diff --git a/tools/probe_us_post_export.py b/tools/probe_us_post_export.py index 85f19ec8ce..d9ea886b6a 100644 --- a/tools/probe_us_post_export.py +++ b/tools/probe_us_post_export.py @@ -1365,7 +1365,11 @@ def compare_qrf_tail( ) -> dict[str, Any]: """The probe's source-export QRF tail result against a release's ``qrf_tail_concentration.json`` (same frame columns and weights, so the - shares must agree to rounding).""" + shares must agree to rounding). + + It compares the single-record measurements, and the reason behind each + unmeasured output, when the release recorded them, and none against a + release built before its surface carried them.""" differences: list[str] = [] tail = reference["tail_concentration"] if bool(tail["passed"]) != bool(result["passed"]): @@ -1389,7 +1393,51 @@ def compare_qrf_tail( continue if not math.isclose(float(left), float(right), rel_tol=1e-9, abs_tol=1e-12): differences.append(f"{column}: top share {left!r} vs {right!r}") - return {"differences": differences, "columns_compared": len(shares)} + block = _single_record_block(result["surface"]) + reference_block = _single_record_block(reference["surface"]) + if block is None or reference_block is None: + block = reference_block = {"columns": {}, "unmeasured": {}} + measured, recorded = block["columns"], reference_block["columns"] + if sorted(measured) != sorted(recorded): + differences.append( + "single-record columns differ: only probe " + f"{sorted(set(measured) - set(recorded))}, only release " + f"{sorted(set(recorded) - set(measured))}" + ) + compared = sorted(set(measured) & set(recorded)) + for column in compared: + for field in ("carriers", "top_1_share", "top_1_weight", "top_k_share"): + left, right = measured[column].get(field), recorded[column].get(field) + if left is None or right is None: + if left != right: + differences.append(f"{column}: {field} {left} vs {right}") + continue + if not math.isclose(float(left), float(right), rel_tol=1e-9, abs_tol=1e-12): + differences.append(f"{column}: {field} {left!r} vs {right!r}") + skipped, recorded_skipped = block["unmeasured"], reference_block["unmeasured"] + if sorted(skipped) != sorted(recorded_skipped): + differences.append( + "unmeasured columns differ: only probe " + f"{sorted(set(skipped) - set(recorded_skipped))}, only release " + f"{sorted(set(recorded_skipped) - set(skipped))}" + ) + for column in sorted(set(skipped) & set(recorded_skipped)): + if skipped[column] != recorded_skipped[column]: + differences.append( + f"{column}: unmeasured as {skipped[column]!r} vs " + f"{recorded_skipped[column]!r}" + ) + return { + "differences": differences, + "columns_compared": len(shares), + "single_record_columns_compared": len(compared), + } + + +def _single_record_block(surface: Mapping[str, Any]) -> Mapping[str, Any] | None: + """A tail surface's single-record block (``columns`` and ``unmeasured``), + if it has one.""" + return surface.get("single_record_concentration") def compare_post_export_plans( @@ -2268,7 +2316,12 @@ def evaluate(frame) -> dict[str, Any]: "pass" if not comparison["differences"] else "fail", AUTHORITATIVE, "; ".join(comparison["differences"]) - or "same verdict, columns and top-k shares", + or ( + "same verdict, columns, top-k shares and single-record " + "measurements" + if comparison["single_record_columns_compared"] + else "same verdict, columns and top-k shares" + ), "fidelity of this probe to the release", ) _write_json(self.out_dir / "qrf_tail_concentration.json", record)