Repository navigation
Refuse invalid fit input that the microimpute bug-parity audit reproduced - #1543
Merged
Merged
Conversation
…uced microcosm-fit accepted, or crashed on, nine kinds of invalid input that the microimpute bug-parity audit reproduced. It now refuses each with a named error: - seeds and n_estimators: refuse bools and non-integers (D010) - zero_atol: require a finite value >= 0 in the constructor, detect_regime and chain checkpoints (D034) - DataFrame fits: refuse a predictor, target, weight or groups label that names more than one column (D031) - categorical_scores: validate probabilities, classes, weights and strata, and map labels by the supplied class order (D022) - a weighted target whose positive or negative rows all carry zero weight - an empty training table - donor_distance_features: refuse missing or non-finite values, and add an explicit unseen_categories policy, "refuse" by default (D067) A gated model now answers an empty recipient batch with an empty result instead of the sign gate's zero-row error. Valid input fits, draws and scores exactly as before: a differential run of one fixed workload through main and this branch matched in all 239 arrays. The fit kernels' attested source moves, so this repins seed_map and seed_protocol, the golden spec hashes, the coverage evidence and the fit.qrf graph parity pins. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The empty-batch fix reads classes_ from either gate type, so the empty predict, conditional_uniforms, chain-step and no-draw tests now run under both sign-gate calibrations. The fixture asserts that every gated target really gets a cross-fitted gate, so the new cases cannot pass vacuously. On main all ten empty-batch cases fail with sklearn's zero-row refusal. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Resolves the RegimeGatedQRF constructor conflict by keeping main's gate_level_columns checks and this branch's seed, n_estimators and zero_atol checks. The attested-hash files take main's versions here; the next commit repins them for the merged source. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…checks - categorical_scores finds labels by main's sorted search and NumPy equality again, so boolean labels still match 0/1 classes. It reads the classes in sorted order whatever order they come in, so the calibration no longer depends on the column order, and sorted input keeps main's exact array (np.take keeps a permuted copy C-ordered). - It refuses complex probabilities and weights before the float cast, which dropped NaN or infinite imaginary parts. - detect_regime checks zero_atol without converting it, so an integer tolerance compares exactly with integer targets above 2**53. - Corrects the wording the review flagged in docstrings, the donor distance error message and the changelog. - Repins the attested kernel hashes for the merged source. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
main's microcosm#1585 moved the same attested hashes this branch moves. The merge keeps main's comments, adds this PR's, and repins the hashes for the combined source: repin_us_spec_engine_contracts.py, then spec_engine_coverage.py (42,395 of 42,395 fields, 41 of 41 checks), the repin again, --check clean, and the fit.qrf graph parity repin (pins unchanged). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MaxGhenis
added a commit
that referenced
this pull request
Nov 14, 2026
#1543 merged main again (085672f), which moved the attested spec-engine hashes. The four hash-only conflicts took #1543's side, then tools/repin_us_spec_engine_contracts.py, tools/spec_engine_coverage.py and the repin again (--check clean) repinned them for this branch's qrf.py, and ruff format restored the double quotes the repin tool drops. No microcosm-fit source or fit.qrf parity pin changes in the merge. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Main's microcosm#1096 (exact softmax cap projection in solve) moved the same attested hashes this branch moves. The conflicts were hash-only: keep both sides' comments and re-pin seed_map, seed_protocol, the coverage evidence and the golden spec_sha256 values for the combined source. The fit.qrf graph parity pins do not move. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… claims (review round 2) - The empty-batch fixture asserted every cross-fitted gate calibrated out of fold, so seeds whose gate falls back to the class rates (5, 14) failed it before the empty batch ran. Accept both cross-fitted outcomes, and pin both cross-fitted calibrations at seeds 7 and 14 as explicit examples (finding 1). - The changelog said main refused every unsorted class order. Main scored the orders its sorted search happened to locate, in the order given, and those now score as the sorted columns do. Say so, with what moves: log loss never, share gaps in the last bits, and the calibration slope and outcome materially only where the fit is ill-posed (finding 2). - Name the argument types now refused that main converted (seed 1.0 or "3", n_estimators 4.0, a Decimal or 0-d zero_atol), and correct the empty-table, duplicate-label, strata, permutation-layout and test docstring wording (findings 3 and 4). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…bound Round 2 (finding 2) asked for a test that pins one unsorted-class input main scored. Main scores classes [0, 2, 1] with one observed class at a slope of about 0.849, in the order given; the sorted order gives about 0.875, and the test pins that the input now scores exactly as its sorted columns do. The brief owner accepted this change, and the stricter seed and tolerance types, as documented exceptions. The changelog's 1e-12 slope bound held only with at least two observed classes: with one, slopes between 0.1 and 5 move too. Say so. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…-order wording An in-session check of the changes since review round 2 found: - The new pin asserted a slope of about 0.8754, the stop point of an ill-posed one-class calibration that a different row-sum association moves to 0.849. Pin only that the input scores exactly as its sorted columns do, which holds on any platform and fails on main. - Both orders in that pin fix class 0's offset; the gap comes from the order of the other columns in an ill-posed fit. Say so in the test and changelog. - The changelog's slope bullets: with two or more observed classes the outcome never changed and only slopes far above 1 moved by more than rounding; drop "near 0" from the material cases. - Both models refuse a negative seed; only RegimeGatedQRF turned 1.0 and "3" into integers; its constructor also turned a string or bool zero_atol into a float. - The zero-weight-sign crash belongs with the defects, not with the less-specific errors, in the module docstring. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MaxGhenis
marked this pull request as ready for review
November 16, 2026 04:25
Contributor
Author
|
The Microcosm hub now owns this PR and lands it.
|
Main brought nine first-parent merges since c4ad232: #1626 (Belgium gate rows), #1628 (NZ B8 reference teen heads), #1621 (County Files household measures sidecar and schema manifest tools), #1540 (L0 release practice docs), #1609 (gate battery shared scopes), #1619 (ACS partnership_income kept at zero where SEMP holds it, #1387), #1629 (untimed composed stage-scan test), #1594 (withdraw a release build) and #1541 (Microcosm name sweep). Main changed nothing under packages/microcosm-fit or packages/microcosm-graph. Four pin files conflicted; each block took main's text plus this branch's own comment lines, placed after main's #1387 sentence: - docs/evidence/spec-engine/us-f0-coverage.json: five digest blocks, main's side (the branch has no comment there). - packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py: main's #1387 comment, then the branch's #1543 sentence, then the digests. - packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py: main's #1387 comment, then the branch's fit-input-checks sentence, then the golden. - packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py: main's #1387 comment, then the branch's #1543 line, then spec_sha256. No code or test file conflicted, and no other file was changed by both sides. The tools then wrote every value on the merged tree: - tools/repin_us_spec_engine_contracts.py: EXPECTED_HASHES seed_map d5898b93 and seed_protocol 206be396, the loader golden b7c843a1 and the multispine pool spec_sha256 4062e22e (its first pass moved the coverage tool test's covered_item_count to 40; its second pass restored 41, so that file equals main's). - tools/spec_engine_coverage.py: us-f0-coverage.json's eight digest lines (42395/42395 configuration fields; 41/41 inventory checks). - fit.qrf/pins.json keeps the branch's values: the merged fit sources equal the branch's and the kernel's implementation hash reproduces, so tools/graph_parity_repin.py was not run. The repinner's quote style was then reformatted with ruff format. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Main brought five first-parent merges since 14797c6: #1640 (UK dense bus floor for 21 families), #1642 (Belgium's ten gate entries in the gate contract), #1643 (Belgium's Axiom engine pinned at 753ce7d9), #1608 (promotions notify collector; emitter-interface floor 0.16.0) and #1614 (LWI's US county facts pin). Main changed nothing under packages/microcosm-fit or packages/microcosm-graph. Two pin files conflicted, both through #1614; each block took main's text plus this branch's own comment lines, placed after main's sentence: - docs/evidence/spec-engine/us-f0-coverage.json: two spec_sha256 blocks, main's side (the branch has no comment there). - packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py: main's #922 county-facts comment, then the branch's #1543 line, then spec_sha256. No code or test file other than these two pins conflicted, and no other file was changed by both sides. The tools then wrote every value on the merged tree: - tools/repin_us_spec_engine_contracts.py: the multispine pool spec_sha256 9ad067de (tools/generate_us_bundle_from_constants.py --check computes the same digest). It left the branch's EXPECTED_HASHES seed_map d5898b93 and seed_protocol 206be396 and the loader golden b7c843a1 as they were, and main's field-usage and coverage-tool pins as main has them. - tools/spec_engine_coverage.py: us-f0-coverage.json's two spec_sha256 lines (42401/42401 configuration fields; 41/41 inventory checks). - fit.qrf/pins.json keeps the branch's values: the merged fit sources equal the branch's and the kernel's implementation hash reproduces, so tools/graph_parity_repin.py was not run. The repinner's quote style was then reformatted with ruff format. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MaxGhenis
added a commit
that referenced
this pull request
Nov 17, 2026
…-degenerate-classes #1543 landed on main as a merge commit, so this branch's copies of its commits are already in main's history. The only conflicts were the attested spec-engine hashes in four pin files. They took main's side, and #1617's line in inventory_coverage.py's repin comment was restored. Then tools/repin_us_spec_engine_contracts.py, tools/spec_engine_coverage.py (42,401/42,401 fields, 41/41 inventory checks), the repin again and --check (all exit 0), and python -m tools.graph_parity_repin fit.qrf. The fit.qrf node keys are unchanged from 708d67e, because qrf.py is unchanged. ruff format restores the double quotes. Main's other change to microcosm-fit since #1617's base is #1543's docstring edit to categorical_scores, which merged cleanly. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MaxGhenis
added a commit
that referenced
this pull request
Nov 17, 2026
microcosm#1614 and #1543 moved the same pins as this PR, so the seed, loader, multispine, pointer-inventory and coverage-report pins conflicted. Main's side was taken in each pin file and both PRs' comments kept; the repinner, bundle generator, coverage tool and graph-parity repin then rewrote every value. The three --check runs exit 0 and tools/ci_test_plan.py verify reports ok. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
juaristi22
added a commit
that referenced
this pull request
Nov 17, 2026
main's 124 commits since 9504278 conflicted only in the six F0 pin files. They were resolved to main's side and re-pinned: repin --legacy-only (no change), the generator with the US engine (no bundle file changed), the full repin, spec_engine_coverage.py, then ruff format on the five Python files it rewrites. Coverage reads 42404/42404 configuration fields and 41/41 inventory checks, and every --check passes. spec_sha256 is now 0088d3f6; the pool test's comment keeps main's three lines (#922, #1543, #1641) and this branch's us/gates.json line. main's microcosm#922 county work merged cleanly into the ACS local tool: county support, its re-applied moves, the resume shortcut's evidence check and do_package's county CSV all sit outside this branch's shadow sites, which keep their call shapes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Both review rounds have run, and round 2 raised no P0 or P1. The brief owner accepted the two valid-input exceptions below as documented changes.
The microimpute bug-parity audit reproduced nine defects in microcosm-fit. This PR fixes each one, with tests that fail on main for the defect under test. The checks are meant to leave the output for valid input unchanged, and a differential run against main matched bit for bit. There are two exceptions, both outside every production caller: unsorted classes in
categorical_scores, and argument types outside the annotations that main converted. Only the attested kernel hashes move.The PR has merged main five times, last at
c7a5f9679. The first merge (52aea1477) brought balanced and level-offset gate calibration. The second (085672fa9), third (c4ad23289) and fourth (14797c665) changed nomicrocosm-fitfile but moved the same attested hashes (microcosm#1585, microcosm#1096, microcosm#1387), so the branch repins them for the combined source. The fifth changed nomicrocosm-fitfile either, but microcosm#1614 moved one of those hashes, thespec_sha256thatus-f0-coverage.jsonandtest_us_multispine_pool_tool.pypin, so the branch repins it too. "Main" below means52aea1477'smicrocosm-fit, identical to085672fa9's, unless it saysdc00d158.What changes
RegimeGatedQRFturnsseed=Trueandseed=1.9into seed 1, andCategoricalClassifierturnsseed=Trueinto 1. A negative QRF seed constructs and then fails at fit with numpy's "expected non-negative integer".TypeError) and a negative seed (ValueError) at construction. The QRF also refuses a bool or non-integern_estimatorsthere. Only Python and NumPy integers pass, soseed=1.0,seed="3"andn_estimators=4.0, which main's QRF turned into equal integers, are refused too.zero_atol=nanor+infmakes a positive target fit as degenerate zero and draw only zeros, and a chain checkpoint restoresnan.detect_regimeandQRFChainStaterequire a finitezero_atol >= 0that is anumbers.Realand not a bool. The check converts nothing, sodetect_regimestill compares an integer tolerance exactly with integer targets. A string, a bool, aDecimalor a 0-d array, which main's constructor turned into a float, is refused.IndexError. A duplicated weight or groups label crashes with an unrelated error ('DataFrame' object has no attribute 'dtype',The truth value of a Series is ambiguous).categorical_scoresscores[[2, 0], [0, 2]]at a log loss of -0.69, accepts NaN, negative and all-zero weights, and drops the imaginary part of complex probabilities and weights (NaN ones included) with only a NumPy warning. Unsorted classes fail with "Every label must be one of classes", unless the sorted search happens to find every label; then they score in the order given, and the calibration fit reads that order: it fixes the first class's offset, and an ill-posed fit also depends on the order of the other columns.classesin every row, distinct classes, real finite non-negative weights with a positive total, and each stratum as a 1-D array with one label per row (a shape check). It reads the classes in sorted order whatever order they come in: labels are found by main's sorted search and NumPy equality (Truestill matches1), and sorted classes keep main's exact arrays. A permutation of the classes with the probability columns leaves every score, the calibration included, unchanged, bit for bit for a C-orderedproba.start_chain.predict,conditional_uniformsand the chain step.predictconsumes no draws for it, andpredict_from_uniformsalready returned early.donor_distance_featuresrefuses missing or non-finite rank and presence-rank values and missing categories, and names the column and the side.unseen_categoriesargument followsCategoricalClassifier's convention:"refuse", the default, raises, and"ignore"keeps the old all-zero indicators.Valid input is unchanged, with two exceptions
categorical_scores(accepted by the brief owner). Unsorted classes that main's sorted search happened to locate scored in the order given; they now score as the same columns sorted would. This is the cost of round 1's finding 3, a canonical class order. No production caller passes unsorted classes: each passesnp.uniqueorclasses_order. I measured it on 4,107 random unsorted inputs that main scored, drawn three ways (labels unrelated to the probabilities, labels drawn from them, and inputs where only one class may be observed):test_an_unsorted_order_main_scored_now_scores_as_sortedpins one such input, with classes[0, 2, 1]. Both orders fix class 0's offset, but the order of the other two columns tips where the ill-posed fit stops: on arm64 main reports a slope of about 0.849 and the sorted order about 0.875. That stop point is not portable, so the test pins only that the input scores exactly as its sorted columns do.seed=1.0,seed="3"andn_estimators=4.0for the QRF, and a string, bool,Decimalor 0-d arrayzero_atolfor its constructor, used to be converted and are now refused. The round-2 reviewer's walk over the build configs found 282 seed andn_estimatorsvalues, all integers, and everyzero_atolis1e-6.For everything else:
microcosm.fit(52aea1477) and this branch's. It covers fourRegimeGatedQRFconfigurations spanning every regime, weighted and unweighted, in-sample and cross-fitted gates, with groups. Each one runspredict,predict_from_uniforms,conditional_uniforms,release_modelsand a full checkpointed chain with positional and keyed steps. The workload also coversdetect_regimeat four float tolerances and at integer tolerances and targets around 2^53,CategoricalClassifierprobabilities and draws,out_of_fold_probaandcategorical_scoreswith strata, the scorer on sorted integer, string, float and boolean classes and boolean labels against integer classes, each in C and Fortran layout (calibration fallback cases included), anddonor_distance_featuresfeedingkeyed_nearest_donors. All 335 arrays, 33,492 values in total, match bit for bit, and so does the serialized chain state. The first version of the sorted-order fix failed this run:proba[:, order]returns a Fortran-ordered copy, and the share-gap sums rounded differently in the last bit. The branch now leaves sorted input untouched and permutes withnp.take.python -m tools.graph_parity_repin fit.qrfrefuses to write when the local direct call's bytes move from the pinneddirect.csv. It wrote, so thefit.qrfparity case's outputs stayed byte-identical.test_valid_input_gets_the_coordinates_it_got_beforeembeds an adaptation of main'sdonor_distance_features(arguments renamed, rank helper copied in, guards left out) and checks that every valid Hypothesis input gets exactly main's coordinates.can_deal_foldsandstratified_folds. The stricter scorer refuses an all-zero row, whichout_of_fold_probaleaves for each learner in a fold whose training rows hold a single class. APS deals rows, so every class (each with at least as many rows as folds) reaches every fold, and every training fold holds every class. SPI deals whole households, so another class can sit in one fold only (the first review built such a case). A training fold then holds a single class only if every class but one sits in the held-out fold. The round-2 reviewer's caller trace argues that this cannot happen with at least 3 folds, and SPI pins 5. Its random search found single-class training folds only at 2 folds (9 of 689 cases), and none at 3 or 5. If it did happen, the scorer would now raise where main scored those rows at the 1e-4 floor. The follow-up below covers it.donor_distance_features, and it reaches the function on two paths. Its held-out copy runs after_held_out_evidence, whose fold classifiers train on exactly the copy's donor rows and predict every row it uses as a recipient. Its draw path runs after_draw_held_groupspredicts the same recipients with the classifier fitted on the same donors. Those classifiers listregionamong their categorical predictors and refuse unseen categories by default. An unseen region therefore raises there first, on main as on this branch, so the new"refuse"default adds no failure.n_estimatorsis a Python int.Invariants
The new file
packages/microcosm-fit/tests/engine_free/shared/test_input_validation.pyholds these as Hypothesis properties (derandomized):validated_integerkeeps each integer at or above the minimum, as an equal Python int, and refuses everything else by type or range. A NumPy integer seed draws exactly as the equal Python int.zero_atolexactly when it is finite and>= 0. Example tests cover a bool, a string andNone. A checkpoint round-trips every valid tolerance exactly.[0, -log(1e-4)]and every share gap in[0, 1]. Permuting the classes together with the probability columns leaves every score bit for bit unchanged, calibration slope and outcome and strata included, for C-ordered probabilities. (A Fortran-orderedprobawith sorted classes keeps main's untouched path, whose weighted sums round in another order.) The scorer refuses any probability outside[0, 1].detect_regimeon integer targets and an integer tolerance (up to 2^62) gives the regime that exact integer arithmetic gives."ignore"matches main everywhere, and"refuse"raises exactly when a row holds an unseen category. Rank coordinates lie in[0, 1]and never fall as the value grows.Tests
packages/microcosm-fit/tests/engine_free/shared/test_input_validation.py. Against main at52aea1477, 98 fail and 15 pass.IndexError,'<' not supported, "Probabilities contain NaN"), or refuses unsorted classes.unseen_categorieskeyword orvalidated_integerhelper, or raised a less specific error:float()'s ownTypeErrorforzero_atol=None, a matmul shape error for too few weights, and an unknown label it did not name.predict_from_uniformson an empty batch, score and rank bounds, and the new exact-integer-tolerance and NumPy-label-equality tests.3254ba08, apart from the one guard case (2**53read as zero).cross_fitted_balanced. The fixture asserts that the cross-fitted cases get cross-fitted gates, calibrated out of fold or fallen back to the class rates. The empty-batch property pins both cross-fitted calibrations as explicit examples, at seed 7 (every gate calibrated) and seed 14 (one gate on the class rates). Called directly, it passes at seeds 0 to 40, 224 and 2^32 under each calibration.4052c126c, the head before the fifth merge, every microcosm-fit test (337), the spec-engine loader tests (10) and the graph parity pin tests (11) passed, as did all 12 CI checks. The fifth merge changed nomicrocosm-fitormicrocosm-graphfile. CI runs every suite on this head, including thepolicyengine-usand orrery-contract jobs this venv cannot.tools/ci_test_plan.py verifypasses, and ruff check and format are clean on the changed files.Attested hashes
microcosm.build.spec_engine.seedsattestsmicrocosm.fit.qrf's source bytes, so this PR repins:seed_mapandseed_protocolininventory_coverage.py, plusdocs/evidence/spec-engine/us-f0-coverage.json, throughtools/repin_us_spec_engine_contracts.pyandtools/spec_engine_coverage.py. After the last merge the result shows 41 of 41 inventory checks and 42,401 of 42,401 configuration fields, and--checkis clean. This PR changes no bundle constant, andgenerate_us_bundle_from_constants.py --checkpasses and reports the pinnedspec_sha256.spec_sha256intest_spec_engine_loader.pyandtest_us_multispine_pool_tool.py.fit.qrfgraph parity pins (implementation hash and node keys for arm64/darwin/py3.14 and x86_64/linux/py3.13 and py3.14), written bytools/graph_parity_repin.py.Review
3254ba08: REQUEST_CHANGES, four should-fix findings and three nits, all fixed in18924d618; round 2 confirmed each.881cc983(Subfleet hard tier): REQUEST_CHANGES, with two P2 findings and several P3s and no P0 or P1, so the review has finished.80628146efixes them:001b8daf7adds the pinning test round 2 asked for. An in-session delta check at001b8daf7of everything since round 2 (the third merge and its hashes, the tests, and every claim; each P0–P2 finding went to a refuter) found no P0 or P1. Its one P2, a slope pin on a stop point that isn't portable, and its P3 wording findings are fixed ine93a1c0cb.Out of scope
min_samples_leaf=1, andCategoricalClassifier's sensitivity to the scale of the weights. Both are methodology calls for Max.Follow-up
out_of_fold_probaleaves all-zero rows for a learner in any fold whose training rows hold a single class. The scorer now refuses such rows, where main scored them at the 1e-4 floor. APS never reaches it, and SPI does not at its 5 folds (see Production callers), but a direct caller with unstratified folds can. Score single-class folds and refuse weightless balanced classes in microcosm-fit #1617, which waits on this PR, scores those folds and also refuses a balanced class with no weight in a fold.🤖 Generated with Claude Code