From e38569ff80d80c72c6e70581547abfb3b0cf5bea Mon Sep 17 00:00:00 2001 From: Gocceri Date: Sat, 10 Oct 2026 08:52:34 +0300 Subject: [PATCH 1/4] fix(v5): fail closed on weakened power planning inputs Signed-off-by: Gocceri --- .../v5-power-plan-input-contract.yml | 65 +++++++++++++++++++ ...R_INPUT_VALIDATION_HARDENING_2026-10-10.md | 30 +++++++++ scripts/v5_power_margin_plan.py | 48 +++++++++----- .../reliability_v5/test_power_margin_plan.py | 31 +++++++++ 4 files changed, 158 insertions(+), 16 deletions(-) create mode 100644 .github/workflows/v5-power-plan-input-contract.yml create mode 100644 docs/research/paper-rebuild-v2-2026-10-02/V5_POWER_PLANNER_INPUT_VALIDATION_HARDENING_2026-10-10.md diff --git a/.github/workflows/v5-power-plan-input-contract.yml b/.github/workflows/v5-power-plan-input-contract.yml new file mode 100644 index 00000000..0635d526 --- /dev/null +++ b/.github/workflows/v5-power-plan-input-contract.yml @@ -0,0 +1,65 @@ +# Model-free protection of frozen V5 development power-planning constants. +# This CI is a source-input contract check, not a statistical power certificate. +name: V5 power planner input contract + +on: + pull_request: + paths: + - ".github/workflows/v5-power-plan-input-contract.yml" + - "scripts/v5_power_margin_plan.py" + - "tests/reliability_v5/test_power_margin_plan.py" + - "docs/research/paper-rebuild-v2-2026-10-02/V5_POWER_PLANNER_INPUT_VALIDATION_HARDENING_2026-10-10.md" + +permissions: + contents: read + +concurrency: + group: v5-power-plan-contract-${{ github.event.pull_request.number }} + cancel-in-progress: false + +jobs: + validate: + name: Frozen-statistic input contract (mechanics only) + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: Checkout exact PR head with no persistent credential + uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 1 + persist-credentials: false + + - name: Assert exact event head + shell: bash + env: + EXPECTED_HEAD: ${{ github.event.pull_request.head.sha }} + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" + echo "DEVELOPMENT_ONLY_PLANNING=YES" + echo "SCIENTIFIC_FAMILY_FREEZE=NO" + echo "QUALIFIED_POWER=NO" + echo "MODEL_LOAD_AND_GPU=NO" + + - name: Compile local statistical source and synthetic tests + shell: bash + run: | + set -euo pipefail + python3 -m compileall -q \ + scripts/v5_power_margin_plan.py \ + tests/reliability_v5/test_power_margin_plan.py + + - name: Install pinned test runner + shell: bash + run: | + set -euo pipefail + python3 -m pip install --disable-pip-version-check --no-cache-dir pytest==8.4.2 + + - name: Reject weakened frozen design, fake source hashes and Boolean variance + shell: bash + env: + PYTHONPATH: src + run: | + set -euo pipefail + python3 -m pytest -q tests/reliability_v5/test_power_margin_plan.py diff --git a/docs/research/paper-rebuild-v2-2026-10-02/V5_POWER_PLANNER_INPUT_VALIDATION_HARDENING_2026-10-10.md b/docs/research/paper-rebuild-v2-2026-10-02/V5_POWER_PLANNER_INPUT_VALIDATION_HARDENING_2026-10-10.md new file mode 100644 index 00000000..3693559a --- /dev/null +++ b/docs/research/paper-rebuild-v2-2026-10-02/V5_POWER_PLANNER_INPUT_VALIDATION_HARDENING_2026-10-10.md @@ -0,0 +1,30 @@ +# V5 development-only power planner input-contract hardening — 2026-10-10 + +Status: `MECHANICS_ONLY_VALIDATION; NOT_PROSPECTIVE_FAMILY_FREEZE; NO_QUALIFIED_POWER`. + +## Verified defect + +The unfrozen mechanical planning helper `scripts/v5_power_margin_plan.py` previously accepted caller-supplied `desired_power=0.51`, `family_alpha=0.20`, `planned_clusters=2`, fabricated one-character 'hashes', and Boolean `paired_sd=false` (implicitly converted to zero). This allowed a caller to generate apparently valid development power-plan output by **weakening prespecified constants or fabricating evidence identifiers**. Each failure mode was reproduced against the pre-fix helper on the Mac on 2026-10-10. No confirmatory data or model call was involved. + +## Narrow correction + +The corrected helper rejects those unreviewed substitutions. It requires the **exact current frozen V5 planning constants** family-wise `alpha=0.05`, desired power `0.90` and planned primary source cases `4096`; the project may authorize a *versioned, reviewed redesign* for a different sample count later, not silently mutate these inputs. It rejects booleans and numeric strings for the numeric nuisance, floor and repeatability fields, and requires three complete lowercase 64-character SHA-256 strings for each reported development metric (domain-floor justification, repeatability evidence, paired SD evidence). Negative synthetic tests cover relaxed parameters, corrupted hash lengths/characters/case, and Boolean/typed SD for reproducibility. + +The output includes explicit `false` flags for independently frozen/qualified Holm family membership, the source-case × training-seed nuisance model, final 90% power and confirmatory execution authorization. The arithmetic helper remains a **normal-approximation planning mechanic** and does not enumerate the actual non-target hypothesis family. + +## What a passing input contract does **not** establish + +- A syntactically correct 64-character hash does **not** prove the file exists, that the file is a reviewed justification, or that the value actually came from that file. A later separate source-bound, reviewer-approved family/evidence reader must independently verify membership and provenance. +- A caller-supplied `primary_non_target_family_size` is not a prospectively reviewed manifest; the planner cannot certify Holm multiplicity just from a valid integer. +- Within-seed task/source-case SDs are **not** a conservative crossed multi-training-seed nuisance estimate. The 64-generator's unique original source-case/task mapping does not close between-seed inferential uncertainty. +- Neither syntax checks nor passing pytest, GitHub CI, Alibaba OCR eligibility or a signed-off commit prove clinical utility, qualified 90% power or publication authority. + +This narrow successor does not edit the original 307 frozen entries, the scientific protocol, available development evidence, frozen benchmark margins or claim ledger. It creates no research/GPU/Kaggle/PHI/confirmatory/reserve action. The exact family, proper training-seed uncertainty/missingness conventions and independent methodological approval remain documented in [issue #326](https://github.com/TheHalfMoon/commandMed/issues/326). + +## Reproduction + +```sh +PYTHONPATH=src python3 -m pytest -q tests/reliability_v5/test_power_margin_plan.py +``` + +Do not interpret `PASS_POWER_MARGIN_PLAN` or `all_metrics_meet_normal_approx_target` as a final inferential certificate; these remain **development mechanics only**. diff --git a/scripts/v5_power_margin_plan.py b/scripts/v5_power_margin_plan.py index 5aaa2b81..4214563c 100644 --- a/scripts/v5_power_margin_plan.py +++ b/scripts/v5_power_margin_plan.py @@ -10,6 +10,7 @@ import argparse import json import math +import re from pathlib import Path from typing import Any @@ -24,11 +25,24 @@ class PowerPlanContractError(ValueError): """Raised when a prospective power-plan input is incomplete or malformed.""" +SHA256_PATTERN = re.compile(r"[0-9a-f]{64}\Z") + + +def _require_sha256(value: Any, field: str) -> str: + """Require actual SHA-256 syntax, not a placeholder or arbitrary nonempty text.""" + if not isinstance(value, str) or SHA256_PATTERN.fullmatch(value) is None: + raise PowerPlanContractError(f"{field}: frozen 64-character lowercase SHA-256 required") + return value + + def _finite_nonnegative(value: Any, field: str) -> float: + # JSON booleans and numeric strings must not silently become real variance. + if type(value) not in (int, float): + raise PowerPlanContractError(f"{field}: expected a finite nonnegative JSON number") try: number = float(value) - except (TypeError, ValueError) as exc: - raise PowerPlanContractError(f"{field}: expected a finite nonnegative number") from exc + except OverflowError as exc: + raise PowerPlanContractError(f"{field}: expected a finite nonnegative JSON number") from exc if not math.isfinite(number) or number < 0.0: raise PowerPlanContractError(f"{field}: expected a finite nonnegative number") return number @@ -116,12 +130,16 @@ def build_plan(spec: dict[str, Any]) -> dict[str, Any]: raise PowerPlanContractError("multiplicity: HOLM required") family_alpha = _finite_positive(spec.get("family_alpha"), "family_alpha") + if family_alpha != 0.05: + raise PowerPlanContractError("family_alpha: frozen V5 family-wise alpha 0.05 required") family_size = spec.get("primary_non_target_family_size") planning_alpha = conservative_holm_planning_alpha(family_alpha, family_size) desired_power = _finite_positive(spec.get("desired_power"), "desired_power") + if desired_power != 0.90: + raise PowerPlanContractError("desired_power: frozen V5 target 0.90 required") planned_clusters = spec.get("planned_clusters") - if type(planned_clusters) is not int or planned_clusters < 2: - raise PowerPlanContractError("planned_clusters: expected an integer >= 2") + if type(planned_clusters) is not int or planned_clusters != 4096: + raise PowerPlanContractError("planned_clusters: current frozen V5 plan is exactly 4096") metrics = spec.get("metrics") if not isinstance(metrics, dict) or not metrics: @@ -131,18 +149,12 @@ def build_plan(spec: dict[str, Any]) -> dict[str, Any]: row = metrics[name] if not isinstance(name, str) or not name.strip() or not isinstance(row, dict): raise PowerPlanContractError("metrics: invalid metric entry") - if row.get("domain_floor_justification_sha256") in (None, "", "TBD"): - raise PowerPlanContractError( - f"metrics.{name}.domain_floor_justification_sha256: frozen justification required" - ) - if row.get("repeatability_evidence_sha256") in (None, "", "TBD"): - raise PowerPlanContractError( - f"metrics.{name}.repeatability_evidence_sha256: frozen repeatability evidence required" - ) - if row.get("paired_sd_evidence_sha256") in (None, "", "TBD"): - raise PowerPlanContractError( - f"metrics.{name}.paired_sd_evidence_sha256: frozen nuisance evidence required" - ) + _require_sha256(row.get("domain_floor_justification_sha256"), + f"metrics.{name}.domain_floor_justification_sha256: frozen justification") + _require_sha256(row.get("repeatability_evidence_sha256"), + f"metrics.{name}.repeatability_evidence_sha256: repeatability evidence") + _require_sha256(row.get("paired_sd_evidence_sha256"), + f"metrics.{name}.paired_sd_evidence_sha256: nuisance evidence") result_metrics[name] = { **_plan_metric( domain_floor=row.get("domain_floor"), @@ -174,6 +186,10 @@ def build_plan(spec: dict[str, Any]) -> dict[str, Any]: row["planned_clusters_meet_normal_approx_target"] for row in result_metrics.values() ), + "family_membership_frozen_and_independently_reviewed": False, + "source_case_seed_nuisance_qualified": False, + "final_90_percent_power_qualified": False, + "confirmatory_execution_authorized": False, "interpretation_boundary": ( "Normal-approximation development planning only. Holm is handled " "conservatively using the first-step alpha/family_size threshold. " diff --git a/tests/reliability_v5/test_power_margin_plan.py b/tests/reliability_v5/test_power_margin_plan.py index 568cacf8..8ba118fc 100644 --- a/tests/reliability_v5/test_power_margin_plan.py +++ b/tests/reliability_v5/test_power_margin_plan.py @@ -55,6 +55,10 @@ def test_build_plan_applies_frozen_margin_rule_and_power() -> None: assert isinstance(result["all_metrics_meet_normal_approx_target"], bool) assert result["confirmatory"] is False assert result["reserve"] is False + assert result["family_membership_frozen_and_independently_reviewed"] is False + assert result["source_case_seed_nuisance_qualified"] is False + assert result["final_90_percent_power_qualified"] is False + assert result["confirmatory_execution_authorized"] is False def test_zero_paired_sd_is_handled_without_fake_positive_noise() -> None: @@ -101,3 +105,30 @@ def test_plan_fails_closed_on_unfrozen_or_invalid_inputs(mutator, match) -> None mutator(spec) with pytest.raises(plan.PowerPlanContractError, match=match): plan.build_plan(spec) + +@pytest.mark.parametrize( + "mutator,match", + [ + (lambda s: s.update(family_alpha=0.20), "frozen V5 family-wise alpha"), + (lambda s: s.update(family_alpha=0.01), "frozen V5 family-wise alpha"), + (lambda s: s.update(desired_power=0.51), "frozen V5 target"), + (lambda s: s.update(desired_power=0.95), "frozen V5 target"), + (lambda s: s.update(planned_clusters=2), "frozen V5 plan"), + (lambda s: s.update(planned_clusters=8192), "frozen V5 plan"), + (lambda s: s["metrics"]["canonical_nll"].update(paired_sd=False), "JSON number"), + (lambda s: s["metrics"]["canonical_nll"].update(paired_sd=True), "JSON number"), + (lambda s: s["metrics"]["canonical_nll"].update(paired_sd="0.001"), "JSON number"), + (lambda s: s["metrics"]["canonical_nll"].update(paired_sd=10 ** 1000), "JSON number"), + (lambda s: s["metrics"]["canonical_nll"].update(domain_floor=True), "JSON number"), + (lambda s: s["metrics"]["canonical_nll"].update(repeatability95="0"), "JSON number"), + (lambda s: s["metrics"]["canonical_nll"].update(domain_floor_justification_sha256="x"), "SHA-256"), + (lambda s: s["metrics"]["canonical_nll"].update(repeatability_evidence_sha256="g" * 64), "SHA-256"), + (lambda s: s["metrics"]["canonical_nll"].update(paired_sd_evidence_sha256="0" * 63), "SHA-256"), + (lambda s: s["metrics"]["canonical_nll"].update(paired_sd_evidence_sha256="A" * 64), "SHA-256"), + ], +) +def test_reject_unreviewed_power_relaxation_or_forged_hash(mutator, match) -> None: + spec = copy.deepcopy(_spec()) + mutator(spec) + with pytest.raises(plan.PowerPlanContractError, match=match): + plan.build_plan(spec) From 93687dd133582252fa88db058ce1b7c35dc1bf3d Mon Sep 17 00:00:00 2001 From: Gocceri Date: Sat, 10 Oct 2026 09:02:47 +0300 Subject: [PATCH 2/4] fix(v5): bind illustrative Holm family size to explicit hypotheses Signed-off-by: Gocceri --- ...R_INPUT_VALIDATION_HARDENING_2026-10-10.md | 2 +- scripts/v5_power_margin_plan.py | 77 +++++++++++++++++-- .../reliability_v5/test_power_margin_plan.py | 57 ++++++++++++++ 3 files changed, 128 insertions(+), 8 deletions(-) diff --git a/docs/research/paper-rebuild-v2-2026-10-02/V5_POWER_PLANNER_INPUT_VALIDATION_HARDENING_2026-10-10.md b/docs/research/paper-rebuild-v2-2026-10-02/V5_POWER_PLANNER_INPUT_VALIDATION_HARDENING_2026-10-10.md index 3693559a..dc6e5c5d 100644 --- a/docs/research/paper-rebuild-v2-2026-10-02/V5_POWER_PLANNER_INPUT_VALIDATION_HARDENING_2026-10-10.md +++ b/docs/research/paper-rebuild-v2-2026-10-02/V5_POWER_PLANNER_INPUT_VALIDATION_HARDENING_2026-10-10.md @@ -15,7 +15,7 @@ The output includes explicit `false` flags for independently frozen/qualified Ho ## What a passing input contract does **not** establish - A syntactically correct 64-character hash does **not** prove the file exists, that the file is a reviewed justification, or that the value actually came from that file. A later separate source-bound, reviewer-approved family/evidence reader must independently verify membership and provenance. -- A caller-supplied `primary_non_target_family_size` is not a prospectively reviewed manifest; the planner cannot certify Holm multiplicity just from a valid integer. +- The latest validation now requires an **explicit caller-supplied `primary_non_target_hypotheses` list** and derives/cross-checks `primary_non_target_family_size` against its item count. Each candidate must carry a unique stable ID, intervention, target property, non-target metric present in the plan, scientific coupling classification, `SOURCE_CASE` inferential unit and explicit primary flag. Duplicate IDs/cells, metricless claims, prompt-level units, missing required item fields and family-size mismatches fail closed. The helper binds the **ordered, unreviewed list** to a deterministic SHA-256 for reproducible tracing. **This is not** a reviewed, prospectively frozen family manifest: the caller could still deliberately omit entire hypotheses or misclassify their primary/coupling status. The planner explicitly emits `family_membership_frozen_and_independently_reviewed=false` even when the count matches a caller-declared list. Independent methodological review and prospective cell enumeration remain prerequisites to any final power claim. - Within-seed task/source-case SDs are **not** a conservative crossed multi-training-seed nuisance estimate. The 64-generator's unique original source-case/task mapping does not close between-seed inferential uncertainty. - Neither syntax checks nor passing pytest, GitHub CI, Alibaba OCR eligibility or a signed-off commit prove clinical utility, qualified 90% power or publication authority. diff --git a/scripts/v5_power_margin_plan.py b/scripts/v5_power_margin_plan.py index 4214563c..98431ad8 100644 --- a/scripts/v5_power_margin_plan.py +++ b/scripts/v5_power_margin_plan.py @@ -8,6 +8,7 @@ from __future__ import annotations import argparse +import hashlib import json import math import re @@ -55,6 +56,62 @@ def _finite_positive(value: Any, field: str) -> float: return number +FAMILY_TAGS = frozenset(("STRUCTURALLY_DISTINCT", "SHARED_INPUT", "MATHEMATICALLY_COUPLED")) +HYPOTHESIS_ID_PATTERN = re.compile(r"[A-Z][A-Z0-9_-]{3,63}\Z") + + +def _unreviewed_family_bindings(spec: dict[str, Any], metric_names: set[str]) -> tuple[int, str]: + """Check manifest completeness, not the scientific validity of its members. + + This manifest is entirely caller-provided and remains *unreviewed*. + No input field can change the hard-coded review/confirmatory=false outputs. + """ + hypotheses = spec.get("primary_non_target_hypotheses") + if not isinstance(hypotheses, list) or not hypotheses: + raise PowerPlanContractError("primary_non_target_hypotheses: nonempty explicit list required") + declared_size = spec.get("primary_non_target_family_size") + if type(declared_size) is not int or declared_size != len(hypotheses): + raise PowerPlanContractError("primary_non_target_family_size: must equal declared hypothesis list length") + ids: set[str] = set() + cells: set[tuple[str, str, str]] = set() + required_fields = frozenset(( + "hypothesis_id", "intervention", "target_property", + "non_target_metric", "coupling_tag", "inferential_unit", "primary", + )) + for idx, row in enumerate(hypotheses): + prefix = f"primary_non_target_hypotheses[{idx}]" + if not isinstance(row, dict) or set(row) != required_fields: + raise PowerPlanContractError(prefix + ": exact hypothesis fields required") + identifier = row["hypothesis_id"] + if not isinstance(identifier, str) or HYPOTHESIS_ID_PATTERN.fullmatch(identifier) is None: + raise PowerPlanContractError(prefix + ": stable uppercase hypothesis ID required") + if identifier in ids: + raise PowerPlanContractError(prefix + ": duplicate hypothesis_id") + ids.add(identifier) + for key in ("intervention", "target_property", "non_target_metric"): + val = row[key] + if not isinstance(val, str) or not val.strip() or val != val.strip(): + raise PowerPlanContractError(prefix + ": invalid " + key) + if row["non_target_metric"] not in metric_names: + raise PowerPlanContractError(prefix + ": non_target_metric lacks planning metric") + if row["target_property"] == row["non_target_metric"]: + raise PowerPlanContractError(prefix + ": non-target cannot equal target") + if not isinstance(row["coupling_tag"], str) or row["coupling_tag"] not in FAMILY_TAGS: + raise PowerPlanContractError(prefix + ": coupling_tag must be declared") + if row["inferential_unit"] != "SOURCE_CASE": + raise PowerPlanContractError(prefix + ": source medical case is required inferential unit") + if row["primary"] is not True: + raise PowerPlanContractError(prefix + ": primary hard-gate membership required") + cell = (row["intervention"], row["target_property"], row["non_target_metric"]) + if cell in cells: + raise PowerPlanContractError(prefix + ": duplicate primary intervention-target-non-target cell") + cells.add(cell) + digest = hashlib.sha256( + json.dumps(hypotheses, sort_keys=True, separators=(",", ":"), allow_nan=False).encode("utf-8") + ).hexdigest() + return len(hypotheses), digest + + def conservative_holm_planning_alpha(family_alpha: float, family_size: int) -> float: """Return the Holm first-step alpha used for conservative per-cell planning.""" alpha = _finite_positive(family_alpha, "family_alpha") @@ -132,7 +189,12 @@ def build_plan(spec: dict[str, Any]) -> dict[str, Any]: family_alpha = _finite_positive(spec.get("family_alpha"), "family_alpha") if family_alpha != 0.05: raise PowerPlanContractError("family_alpha: frozen V5 family-wise alpha 0.05 required") - family_size = spec.get("primary_non_target_family_size") + metrics = spec.get("metrics") + if not isinstance(metrics, dict) or not metrics: + raise PowerPlanContractError("metrics: expected a non-empty object") + if any(not isinstance(name, str) or not name.strip() for name in metrics): + raise PowerPlanContractError("metrics: invalid metric name") + family_size, unreviewed_family_sha = _unreviewed_family_bindings(spec, set(metrics)) planning_alpha = conservative_holm_planning_alpha(family_alpha, family_size) desired_power = _finite_positive(spec.get("desired_power"), "desired_power") if desired_power != 0.90: @@ -141,9 +203,6 @@ def build_plan(spec: dict[str, Any]) -> dict[str, Any]: if type(planned_clusters) is not int or planned_clusters != 4096: raise PowerPlanContractError("planned_clusters: current frozen V5 plan is exactly 4096") - metrics = spec.get("metrics") - if not isinstance(metrics, dict) or not metrics: - raise PowerPlanContractError("metrics: expected a non-empty object") result_metrics: dict[str, Any] = {} for name in sorted(metrics): row = metrics[name] @@ -177,6 +236,8 @@ def build_plan(spec: dict[str, Any]) -> dict[str, Any]: "family_alpha": family_alpha, "multiplicity": "HOLM", "primary_non_target_family_size": family_size, + "unreviewed_family_declaration_sha256": unreviewed_family_sha, + "family_size_matches_unreviewed_declared_hypotheses": True, "conservative_holm_planning_alpha": planning_alpha, "desired_power": desired_power, "planned_clusters": planned_clusters, @@ -191,9 +252,11 @@ def build_plan(spec: dict[str, Any]) -> dict[str, Any]: "final_90_percent_power_qualified": False, "confirmatory_execution_authorized": False, "interpretation_boundary": ( - "Normal-approximation development planning only. Holm is handled " - "conservatively using the first-step alpha/family_size threshold. " - "This output is not final inference and cannot authorize confirmatory access." + "Normal-approximation development planning only. Family membership " + "and multiplicity count derive from a caller-supplied, unreviewed " + "hypothesis list, not independently qualified prospective science. " + "Holm uses first-step alpha/family_size. This is not final power " + "or authorization for confirmatory access." ), } diff --git a/tests/reliability_v5/test_power_margin_plan.py b/tests/reliability_v5/test_power_margin_plan.py index 8ba118fc..532496ff 100644 --- a/tests/reliability_v5/test_power_margin_plan.py +++ b/tests/reliability_v5/test_power_margin_plan.py @@ -18,6 +18,23 @@ def _spec() -> dict: "family_alpha": 0.05, "multiplicity": "HOLM", "primary_non_target_family_size": 4, + "primary_non_target_hypotheses": [ + { + "hypothesis_id": f"SYNTH-HYP-{i:02d}", + "intervention": intervention, + "target_property": "canonical_accuracy", + "non_target_metric": metric, + "coupling_tag": "SHARED_INPUT", + "inferential_unit": "SOURCE_CASE", + "primary": True, + } + for i, (intervention, metric) in enumerate(( + ("B1", "canonical_nll"), + ("B1", "semantic_js"), + ("C1", "canonical_nll"), + ("C1", "semantic_js"), + )) + ], "desired_power": 0.90, "planned_clusters": 4096, "margin_rule": "MAX_DOMAIN_FLOOR_2X_REPEATABILITY95", @@ -49,6 +66,8 @@ def test_holm_planning_alpha_is_conservative_first_step() -> None: def test_build_plan_applies_frozen_margin_rule_and_power() -> None: result = plan.build_plan(_spec()) assert result["conservative_holm_planning_alpha"] == pytest.approx(0.0125) + assert result["family_size_matches_unreviewed_declared_hypotheses"] is True + assert len(result["unreviewed_family_declaration_sha256"]) == 64 assert result["metrics"]["canonical_nll"]["meaningful_margin"] == pytest.approx(0.01) assert result["metrics"]["semantic_js"]["meaningful_margin"] == pytest.approx(0.002) assert result["metrics"]["canonical_nll"]["normal_approx_required_clusters_at_margin"] >= 2 @@ -132,3 +151,41 @@ def test_reject_unreviewed_power_relaxation_or_forged_hash(mutator, match) -> No mutator(spec) with pytest.raises(plan.PowerPlanContractError, match=match): plan.build_plan(spec) + + +@pytest.mark.parametrize("mutator,match", [ + (lambda s: s.pop("primary_non_target_hypotheses"), "explicit list"), + (lambda s: s.update(primary_non_target_hypotheses=[]), "explicit list"), + (lambda s: s.update(primary_non_target_family_size=1), "must equal declared"), + (lambda s: s.update(primary_non_target_family_size=True), "must equal declared"), + (lambda s: s["primary_non_target_hypotheses"][1].update(hypothesis_id="SYNTH-HYP-00"), "duplicate hypothesis_id"), + (lambda s: s["primary_non_target_hypotheses"][1].update(intervention="B1", non_target_metric="canonical_nll"), "duplicate primary"), + (lambda s: s["primary_non_target_hypotheses"][0].update(non_target_metric="unknown"), "lacks planning metric"), + (lambda s: s["primary_non_target_hypotheses"][0].update(target_property="canonical_nll"), "non-target cannot equal target"), + (lambda s: s["primary_non_target_hypotheses"][0].update(inferential_unit="PROMPT_VARIANT"), "source medical case"), + (lambda s: s["primary_non_target_hypotheses"][0].update(primary=False), "primary hard-gate"), + (lambda s: s["primary_non_target_hypotheses"][0].update(coupling_tag="NOT_REVIEWED"), "coupling_tag"), + (lambda s: s["primary_non_target_hypotheses"][0].update(coupling_tag=[]), "coupling_tag"), + (lambda s: s["primary_non_target_hypotheses"][0].update(hypothesis_id="x"), "stable uppercase"), + (lambda s: s["primary_non_target_hypotheses"][0].update(extra_field="hidden"), "exact hypothesis fields"), +]) +def test_unreviewed_family_declaration_rejects_count_or_membership_drift(mutator, match) -> None: + spec = copy.deepcopy(_spec()) + mutator(spec) + with pytest.raises(plan.PowerPlanContractError, match=match): + plan.build_plan(spec) + + +def test_unreviewed_family_digest_binds_order_and_member_content() -> None: + original = plan.build_plan(_spec()) + spec = _spec() + spec["primary_non_target_hypotheses"].reverse() + reordered = plan.build_plan(spec) + assert reordered["primary_non_target_family_size"] == original["primary_non_target_family_size"] + assert reordered["unreviewed_family_declaration_sha256"] != original["unreviewed_family_declaration_sha256"] + assert reordered["family_membership_frozen_and_independently_reviewed"] is False + spec = _spec() + spec["primary_non_target_hypotheses"][0]["coupling_tag"] = "STRUCTURALLY_DISTINCT" + changed = plan.build_plan(spec) + assert changed["unreviewed_family_declaration_sha256"] != original["unreviewed_family_declaration_sha256"] + assert changed["final_90_percent_power_qualified"] is False From 5cd1de66c9158f8f3bf6a649d7089bb8cedae0da Mon Sep 17 00:00:00 2001 From: Gocceri Date: Sat, 10 Oct 2026 09:17:38 +0300 Subject: [PATCH 3/4] fix(v5): require per-hypothesis nuisance before illustrative power Signed-off-by: Gocceri --- ...R_INPUT_VALIDATION_HARDENING_2026-10-10.md | 11 +- scripts/v5_power_margin_plan.py | 91 ++++++++++++--- .../reliability_v5/test_power_margin_plan.py | 107 +++++++++++++++--- 3 files changed, 176 insertions(+), 33 deletions(-) diff --git a/docs/research/paper-rebuild-v2-2026-10-02/V5_POWER_PLANNER_INPUT_VALIDATION_HARDENING_2026-10-10.md b/docs/research/paper-rebuild-v2-2026-10-02/V5_POWER_PLANNER_INPUT_VALIDATION_HARDENING_2026-10-10.md index dc6e5c5d..2966048e 100644 --- a/docs/research/paper-rebuild-v2-2026-10-02/V5_POWER_PLANNER_INPUT_VALIDATION_HARDENING_2026-10-10.md +++ b/docs/research/paper-rebuild-v2-2026-10-02/V5_POWER_PLANNER_INPUT_VALIDATION_HARDENING_2026-10-10.md @@ -8,17 +8,20 @@ The unfrozen mechanical planning helper `scripts/v5_power_margin_plan.py` previo ## Narrow correction -The corrected helper rejects those unreviewed substitutions. It requires the **exact current frozen V5 planning constants** family-wise `alpha=0.05`, desired power `0.90` and planned primary source cases `4096`; the project may authorize a *versioned, reviewed redesign* for a different sample count later, not silently mutate these inputs. It rejects booleans and numeric strings for the numeric nuisance, floor and repeatability fields, and requires three complete lowercase 64-character SHA-256 strings for each reported development metric (domain-floor justification, repeatability evidence, paired SD evidence). Negative synthetic tests cover relaxed parameters, corrupted hash lengths/characters/case, and Boolean/typed SD for reproducibility. +The corrected helper rejects those unreviewed substitutions. It requires the **exact current frozen V5 planning constants** family-wise `alpha=0.05`, desired power `0.90` and planned primary source cases `4096`; the project may authorize a *versioned, reviewed redesign* for a different sample count later, not silently mutate these inputs. It rejects booleans and numeric strings for the numeric nuisance, floor and repeatability fields, and requires lowercase 64-character SHA-256 syntax for metric-level floor and repeatability evidence, plus separate per-hypothesis descriptive paired-SD evidence identifiers. Negative synthetic tests cover relaxed parameters, corrupted hash lengths/characters/case, and Boolean/typed SD for reproducibility. -The output includes explicit `false` flags for independently frozen/qualified Holm family membership, the source-case × training-seed nuisance model, final 90% power and confirmatory execution authorization. The arithmetic helper remains a **normal-approximation planning mechanic** and does not enumerate the actual non-target hypothesis family. +The output includes explicit `false` flags for independently frozen/qualified Holm family membership, the source-case × training-seed nuisance model, final 90% power and confirmatory execution authorization. The arithmetic helper remains a **normal-approximation planning mechanic** and cannot attest that the caller's purported complete non-target hypothesis family is substantively or prospectively valid. ## What a passing input contract does **not** establish - A syntactically correct 64-character hash does **not** prove the file exists, that the file is a reviewed justification, or that the value actually came from that file. A later separate source-bound, reviewer-approved family/evidence reader must independently verify membership and provenance. - The latest validation now requires an **explicit caller-supplied `primary_non_target_hypotheses` list** and derives/cross-checks `primary_non_target_family_size` against its item count. Each candidate must carry a unique stable ID, intervention, target property, non-target metric present in the plan, scientific coupling classification, `SOURCE_CASE` inferential unit and explicit primary flag. Duplicate IDs/cells, metricless claims, prompt-level units, missing required item fields and family-size mismatches fail closed. The helper binds the **ordered, unreviewed list** to a deterministic SHA-256 for reproducible tracing. **This is not** a reviewed, prospectively frozen family manifest: the caller could still deliberately omit entire hypotheses or misclassify their primary/coupling status. The planner explicitly emits `family_membership_frozen_and_independently_reviewed=false` even when the count matches a caller-declared list. Independent methodological review and prospective cell enumeration remain prerequisites to any final power claim. -- Within-seed task/source-case SDs are **not** a conservative crossed multi-training-seed nuisance estimate. The 64-generator's unique original source-case/task mapping does not close between-seed inferential uncertainty. +- **Fixed an additional per-cell mismatch**: a shared `metrics[name].paired_sd` wrongly allowed an apparently passing NLL variance from one intervention to represent a second, much more variable intervention with the **same** metric. The v2 input contract now forbids metric-wide paired SD: `metrics` specifies research-only domain floors and repeatability margins, while `paired_nuisance_by_hypothesis` must contain exactly one `paired_sd`, SHA-256-shaped source identifier and `nuisance_scope=UNQUALIFIED_DEVELOPMENT_DESCRIPTIVE` per declared primary hypothesis ID. `hypothesis_plans` reports each cell's own illustrative MDE/required-cluster count and `all_declared_hypotheses_meet_illustrative_normal_approx_target` is their **intersection**. An unfavorable cell cannot be masked by another intervention sharing its metric. Synthetic regression explicitly proves a small-SD B1 NLL cell passes while a large-SD C1 NLL cell fails, making the intersection false. This is a **breaking, deliberately fail-closed input/output contract revision**, with output schema `commandmed.v5.power-margin-plan.v2` and CLI status `PASS_DEVELOPMENT_ONLY_INPUT_CONTRACT`. +- Within-seed task/source-case SDs are **not** a conservative crossed multi-training-seed nuisance estimate; each cell's added source-hash field checks syntax only and cannot prove the actual SD provenance or full multi-seed qualification. The 64-generator's unique original source-case/task mapping does not close between-seed inferential uncertainty. - Neither syntax checks nor passing pytest, GitHub CI, Alibaba OCR eligibility or a signed-off commit prove clinical utility, qualified 90% power or publication authority. +A separate direct-entrypoint check uncovered a broken script import: `python3 scripts/v5_power_margin_plan.py` failed with `ModuleNotFoundError: src` even though in-process tests passed. The CLI now resolves the repository root explicitly, and regression tests launch it from an independent temporary working directory without `PYTHONPATH`, verifying both the truthful development-only success status and fail-closed invalid-input rejection without writing an output file. + This narrow successor does not edit the original 307 frozen entries, the scientific protocol, available development evidence, frozen benchmark margins or claim ledger. It creates no research/GPU/Kaggle/PHI/confirmatory/reserve action. The exact family, proper training-seed uncertainty/missingness conventions and independent methodological approval remain documented in [issue #326](https://github.com/TheHalfMoon/commandMed/issues/326). ## Reproduction @@ -27,4 +30,4 @@ This narrow successor does not edit the original 307 frozen entries, the scienti PYTHONPATH=src python3 -m pytest -q tests/reliability_v5/test_power_margin_plan.py ``` -Do not interpret `PASS_POWER_MARGIN_PLAN` or `all_metrics_meet_normal_approx_target` as a final inferential certificate; these remain **development mechanics only**. +Do not interpret `PASS_DEVELOPMENT_ONLY_INPUT_CONTRACT` or `all_declared_hypotheses_meet_illustrative_normal_approx_target` as a final inferential certificate: these remain **unreviewed development mechanics only**. No output field can assert 90% power qualification or permission to generate confirmatory/reserve identities. diff --git a/scripts/v5_power_margin_plan.py b/scripts/v5_power_margin_plan.py index 98431ad8..ae0708ee 100644 --- a/scripts/v5_power_margin_plan.py +++ b/scripts/v5_power_margin_plan.py @@ -13,8 +13,13 @@ import math import re from pathlib import Path +import sys from typing import Any +# Direct CLI execution must find the repository module from outside scripts/. +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + from src.commandmed.reliability_v5.statistics import ( StatisticsContractError, normal_approx_paired_mde, @@ -203,33 +208,84 @@ def build_plan(spec: dict[str, Any]) -> dict[str, Any]: if type(planned_clusters) is not int or planned_clusters != 4096: raise PowerPlanContractError("planned_clusters: current frozen V5 plan is exactly 4096") + # Metric-level margins are shared, but training-run/source-case variance + # is intervention/hypothesis-specific. Never infer cell power from an + # arbitrary pooled or favorable metric-level paired_sd. result_metrics: dict[str, Any] = {} + expected_metric_fields = { + "domain_floor", "repeatability95", + "domain_floor_justification_sha256", "repeatability_evidence_sha256", + } for name in sorted(metrics): row = metrics[name] if not isinstance(name, str) or not name.strip() or not isinstance(row, dict): raise PowerPlanContractError("metrics: invalid metric entry") - _require_sha256(row.get("domain_floor_justification_sha256"), + if set(row) != expected_metric_fields: + raise PowerPlanContractError( + f"metrics.{name}: margins must not supply metric-level paired_sd" + ) + floor = _finite_positive(row["domain_floor"], f"metrics.{name}.domain_floor") + repeat = _finite_nonnegative(row["repeatability95"], f"metrics.{name}.repeatability95") + _require_sha256(row["domain_floor_justification_sha256"], f"metrics.{name}.domain_floor_justification_sha256: frozen justification") - _require_sha256(row.get("repeatability_evidence_sha256"), + _require_sha256(row["repeatability_evidence_sha256"], f"metrics.{name}.repeatability_evidence_sha256: repeatability evidence") - _require_sha256(row.get("paired_sd_evidence_sha256"), - f"metrics.{name}.paired_sd_evidence_sha256: nuisance evidence") result_metrics[name] = { + "domain_floor": floor, + "repeatability95": repeat, + "meaningful_margin": max(floor, 2.0 * repeat), + "domain_floor_justification_sha256": row["domain_floor_justification_sha256"], + "repeatability_evidence_sha256": row["repeatability_evidence_sha256"], + } + + nuisance = spec.get("paired_nuisance_by_hypothesis") + ids = {row["hypothesis_id"] for row in spec["primary_non_target_hypotheses"]} + if not isinstance(nuisance, dict) or set(nuisance) != ids: + raise PowerPlanContractError( + "paired_nuisance_by_hypothesis: one hypothesis-specific " + "descriptive nuisance record required for every declared " + "hypothesis, with no extras" + ) + result_hypotheses: dict[str, Any] = {} + for row in spec["primary_non_target_hypotheses"]: + hypothesis_id = row["hypothesis_id"] + metric_name = row["non_target_metric"] + metric = metrics[metric_name] + record = nuisance[hypothesis_id] + if not isinstance(record, dict) or set(record) != { + "paired_sd", "paired_sd_evidence_sha256", "nuisance_scope" + }: + raise PowerPlanContractError( + f"paired_nuisance_by_hypothesis.{hypothesis_id}: exact nuisance fields required" + ) + if record["nuisance_scope"] != "UNQUALIFIED_DEVELOPMENT_DESCRIPTIVE": + raise PowerPlanContractError( + f"paired_nuisance_by_hypothesis.{hypothesis_id}: unqualified development scope required" + ) + _require_sha256( + record["paired_sd_evidence_sha256"], + f"paired_nuisance_by_hypothesis.{hypothesis_id}.paired_sd_evidence_sha256: nuisance evidence", + ) + result_hypotheses[hypothesis_id] = { + "intervention": row["intervention"], + "target_property": row["target_property"], + "non_target_metric": metric_name, + "coupling_tag": row["coupling_tag"], + "inferential_unit": row["inferential_unit"], + "nuisance_scope": "UNQUALIFIED_DEVELOPMENT_DESCRIPTIVE", **_plan_metric( - domain_floor=row.get("domain_floor"), - repeatability95=row.get("repeatability95"), - paired_sd=row.get("paired_sd"), + domain_floor=metric["domain_floor"], + repeatability95=metric["repeatability95"], + paired_sd=record["paired_sd"], planned_clusters=planned_clusters, planning_alpha=planning_alpha, desired_power=desired_power, ), - "domain_floor_justification_sha256": row["domain_floor_justification_sha256"], - "repeatability_evidence_sha256": row["repeatability_evidence_sha256"], - "paired_sd_evidence_sha256": row["paired_sd_evidence_sha256"], + "paired_sd_evidence_sha256": record["paired_sd_evidence_sha256"], } return { - "schema": "commandmed.v5.power-margin-plan.v1", + "schema": "commandmed.v5.power-margin-plan.v2", "scope": "DEVELOPMENT_ONLY_POWER_PLANNING", "confirmatory": False, "reserve": False, @@ -243,9 +299,10 @@ def build_plan(spec: dict[str, Any]) -> dict[str, Any]: "planned_clusters": planned_clusters, "margin_rule": "MAX_DOMAIN_FLOOR_2X_REPEATABILITY95", "metrics": result_metrics, - "all_metrics_meet_normal_approx_target": all( + "hypothesis_plans": result_hypotheses, + "all_declared_hypotheses_meet_illustrative_normal_approx_target": all( row["planned_clusters_meet_normal_approx_target"] - for row in result_metrics.values() + for row in result_hypotheses.values() ), "family_membership_frozen_and_independently_reviewed": False, "source_case_seed_nuisance_qualified": False, @@ -255,6 +312,8 @@ def build_plan(spec: dict[str, Any]) -> dict[str, Any]: "Normal-approximation development planning only. Family membership " "and multiplicity count derive from a caller-supplied, unreviewed " "hypothesis list, not independently qualified prospective science. " + "Each declared hypothesis has its own unqualified descriptive paired " + "SD; a shared metric SD cannot stand in for an intervention cell. " "Holm uses first-step alpha/family_size. This is not final power " "or authorization for confirmatory access." ), @@ -274,7 +333,11 @@ def main() -> int: encoding="utf-8", newline="\n", ) - print(json.dumps({"status": "PASS_POWER_MARGIN_PLAN", "output": str(args.output)}, sort_keys=True)) + print(json.dumps({ + "status": "PASS_DEVELOPMENT_ONLY_INPUT_CONTRACT", + "final_90_percent_power_qualified": False, + "output": str(args.output), + }, sort_keys=True)) return 0 diff --git a/tests/reliability_v5/test_power_margin_plan.py b/tests/reliability_v5/test_power_margin_plan.py index 532496ff..1a7b9019 100644 --- a/tests/reliability_v5/test_power_margin_plan.py +++ b/tests/reliability_v5/test_power_margin_plan.py @@ -1,6 +1,8 @@ from __future__ import annotations import copy +import json +import subprocess import sys from pathlib import Path @@ -42,20 +44,24 @@ def _spec() -> dict: "canonical_nll": { "domain_floor": 0.01, "repeatability95": 0.002, - "paired_sd": 0.20, "domain_floor_justification_sha256": "a" * 64, "repeatability_evidence_sha256": "b" * 64, - "paired_sd_evidence_sha256": "c" * 64, }, "semantic_js": { "domain_floor": 0.001, "repeatability95": 0.001, - "paired_sd": 0.02, "domain_floor_justification_sha256": "d" * 64, "repeatability_evidence_sha256": "e" * 64, - "paired_sd_evidence_sha256": "f" * 64, }, }, + "paired_nuisance_by_hypothesis": { + f"SYNTH-HYP-{i:02d}": { + "paired_sd": 0.20 if i % 2 == 0 else 0.02, + "paired_sd_evidence_sha256": "c" * 64 if i % 2 == 0 else "f" * 64, + "nuisance_scope": "UNQUALIFIED_DEVELOPMENT_DESCRIPTIVE", + } + for i in range(4) + }, } @@ -65,13 +71,15 @@ def test_holm_planning_alpha_is_conservative_first_step() -> None: def test_build_plan_applies_frozen_margin_rule_and_power() -> None: result = plan.build_plan(_spec()) + assert result["schema"] == "commandmed.v5.power-margin-plan.v2" assert result["conservative_holm_planning_alpha"] == pytest.approx(0.0125) assert result["family_size_matches_unreviewed_declared_hypotheses"] is True assert len(result["unreviewed_family_declaration_sha256"]) == 64 assert result["metrics"]["canonical_nll"]["meaningful_margin"] == pytest.approx(0.01) assert result["metrics"]["semantic_js"]["meaningful_margin"] == pytest.approx(0.002) - assert result["metrics"]["canonical_nll"]["normal_approx_required_clusters_at_margin"] >= 2 - assert isinstance(result["all_metrics_meet_normal_approx_target"], bool) + assert result["hypothesis_plans"]["SYNTH-HYP-00"]["normal_approx_required_clusters_at_margin"] >= 2 + assert isinstance(result["all_declared_hypotheses_meet_illustrative_normal_approx_target"], bool) + assert "paired_sd" not in result["metrics"]["canonical_nll"] assert result["confirmatory"] is False assert result["reserve"] is False assert result["family_membership_frozen_and_independently_reviewed"] is False @@ -82,9 +90,9 @@ def test_build_plan_applies_frozen_margin_rule_and_power() -> None: def test_zero_paired_sd_is_handled_without_fake_positive_noise() -> None: spec = _spec() - spec["metrics"]["canonical_nll"]["paired_sd"] = 0.0 + spec["paired_nuisance_by_hypothesis"]["SYNTH-HYP-00"]["paired_sd"] = 0.0 result = plan.build_plan(spec) - row = result["metrics"]["canonical_nll"] + row = result["hypothesis_plans"]["SYNTH-HYP-00"] assert row["normal_approx_mde_at_planned_clusters"] == 0.0 assert row["normal_approx_required_clusters_at_margin"] == 2 assert row["planned_clusters_meet_normal_approx_target"] is True @@ -112,7 +120,7 @@ def test_zero_paired_sd_is_handled_without_fake_positive_noise() -> None: "repeatability evidence", ), ( - lambda s: s["metrics"]["canonical_nll"].update( + lambda s: s["paired_nuisance_by_hypothesis"]["SYNTH-HYP-00"].update( paired_sd_evidence_sha256=None ), "nuisance evidence", @@ -134,16 +142,16 @@ def test_plan_fails_closed_on_unfrozen_or_invalid_inputs(mutator, match) -> None (lambda s: s.update(desired_power=0.95), "frozen V5 target"), (lambda s: s.update(planned_clusters=2), "frozen V5 plan"), (lambda s: s.update(planned_clusters=8192), "frozen V5 plan"), - (lambda s: s["metrics"]["canonical_nll"].update(paired_sd=False), "JSON number"), - (lambda s: s["metrics"]["canonical_nll"].update(paired_sd=True), "JSON number"), - (lambda s: s["metrics"]["canonical_nll"].update(paired_sd="0.001"), "JSON number"), - (lambda s: s["metrics"]["canonical_nll"].update(paired_sd=10 ** 1000), "JSON number"), + (lambda s: s["paired_nuisance_by_hypothesis"]["SYNTH-HYP-00"].update(paired_sd=False), "JSON number"), + (lambda s: s["paired_nuisance_by_hypothesis"]["SYNTH-HYP-00"].update(paired_sd=True), "JSON number"), + (lambda s: s["paired_nuisance_by_hypothesis"]["SYNTH-HYP-00"].update(paired_sd="0.001"), "JSON number"), + (lambda s: s["paired_nuisance_by_hypothesis"]["SYNTH-HYP-00"].update(paired_sd=10 ** 1000), "JSON number"), (lambda s: s["metrics"]["canonical_nll"].update(domain_floor=True), "JSON number"), (lambda s: s["metrics"]["canonical_nll"].update(repeatability95="0"), "JSON number"), (lambda s: s["metrics"]["canonical_nll"].update(domain_floor_justification_sha256="x"), "SHA-256"), (lambda s: s["metrics"]["canonical_nll"].update(repeatability_evidence_sha256="g" * 64), "SHA-256"), - (lambda s: s["metrics"]["canonical_nll"].update(paired_sd_evidence_sha256="0" * 63), "SHA-256"), - (lambda s: s["metrics"]["canonical_nll"].update(paired_sd_evidence_sha256="A" * 64), "SHA-256"), + (lambda s: s["paired_nuisance_by_hypothesis"]["SYNTH-HYP-00"].update(paired_sd_evidence_sha256="0" * 63), "SHA-256"), + (lambda s: s["paired_nuisance_by_hypothesis"]["SYNTH-HYP-00"].update(paired_sd_evidence_sha256="A" * 64), "SHA-256"), ], ) def test_reject_unreviewed_power_relaxation_or_forged_hash(mutator, match) -> None: @@ -189,3 +197,72 @@ def test_unreviewed_family_digest_binds_order_and_member_content() -> None: changed = plan.build_plan(spec) assert changed["unreviewed_family_declaration_sha256"] != original["unreviewed_family_declaration_sha256"] assert changed["final_90_percent_power_qualified"] is False + + +@pytest.mark.parametrize("mutator,reason", [ + (lambda s: s.pop("paired_nuisance_by_hypothesis"), "one hypothesis-specific"), + (lambda s: s["paired_nuisance_by_hypothesis"].pop("SYNTH-HYP-00"), "one hypothesis-specific"), + (lambda s: s["paired_nuisance_by_hypothesis"].update(GHOST={}), "one hypothesis-specific"), + (lambda s: s["metrics"]["canonical_nll"].update(paired_sd=0.001), "must not supply metric-level paired_sd"), + (lambda s: s["paired_nuisance_by_hypothesis"]["SYNTH-HYP-00"].update(nuisance_scope="QUALIFIED"), "unqualified development scope"), + (lambda s: s["paired_nuisance_by_hypothesis"]["SYNTH-HYP-00"].update(nuisance_scope=[]), "unqualified development scope"), + (lambda s: s["paired_nuisance_by_hypothesis"]["SYNTH-HYP-00"].update(hidden=True), "exact nuisance fields"), + (lambda s: s["paired_nuisance_by_hypothesis"]["SYNTH-HYP-00"].pop("paired_sd"), "exact nuisance fields"), + (lambda s: s["paired_nuisance_by_hypothesis"]["SYNTH-HYP-00"].update(paired_sd=False), "JSON number"), + (lambda s: s["paired_nuisance_by_hypothesis"]["SYNTH-HYP-00"].update(paired_sd_evidence_sha256="G" * 64), "SHA-256"), +]) +def test_hypothesis_specific_nuisance_fails_closed_on_missing_or_invalid_cell(mutator, reason): + spec = copy.deepcopy(_spec()) + mutator(spec) + with pytest.raises(plan.PowerPlanContractError, match=reason): + plan.build_plan(spec) + + +def test_intervention_specific_nuisance_cannot_be_masked_by_same_metric_good_cell(): + spec = _spec() + # Two declared interventions on canonical NLL, wildly different source-case SDs. + spec["paired_nuisance_by_hypothesis"]["SYNTH-HYP-00"]["paired_sd"] = 0.001 + spec["paired_nuisance_by_hypothesis"]["SYNTH-HYP-02"]["paired_sd"] = 5.0 + result = plan.build_plan(spec) + assert result["hypothesis_plans"]["SYNTH-HYP-00"]["non_target_metric"] == "canonical_nll" + assert result["hypothesis_plans"]["SYNTH-HYP-02"]["non_target_metric"] == "canonical_nll" + assert result["hypothesis_plans"]["SYNTH-HYP-00"]["planned_clusters_meet_normal_approx_target"] is True + assert result["hypothesis_plans"]["SYNTH-HYP-02"]["planned_clusters_meet_normal_approx_target"] is False + assert result["hypothesis_plans"]["SYNTH-HYP-02"]["normal_approx_required_clusters_at_margin"] > 4096 + assert result["all_declared_hypotheses_meet_illustrative_normal_approx_target"] is False + assert "all_metrics_meet_normal_approx_target" not in result + assert result["final_90_percent_power_qualified"] is False + assert result["confirmatory_execution_authorized"] is False + +def test_direct_cli_reports_only_dev_contract_status_without_pythonpath(tmp_path: Path) -> None: + spec = tmp_path / "input.json" + target = tmp_path / "output.json" + spec.write_text(json.dumps(_spec()), encoding="utf-8") + script = Path(__file__).resolve().parents[2] / "scripts" / "v5_power_margin_plan.py" + completed = subprocess.run( + [sys.executable, str(script), "--spec", str(spec), "--output", str(target)], + cwd=tmp_path, capture_output=True, text=True, check=True, + env={"PATH": "/usr/bin:/bin"}, + ) + receipt = json.loads(completed.stdout) + result = json.loads(target.read_text(encoding="utf-8")) + assert receipt["status"] == "PASS_DEVELOPMENT_ONLY_INPUT_CONTRACT" + assert receipt["final_90_percent_power_qualified"] is False + assert result["schema"] == "commandmed.v5.power-margin-plan.v2" + assert result["confirmatory_execution_authorized"] is False + + +def test_direct_cli_rejects_fake_family_nuisance_without_output(tmp_path: Path) -> None: + data = _spec() + data["paired_nuisance_by_hypothesis"].pop("SYNTH-HYP-02") + src = tmp_path / "invalid.json" + out = tmp_path / "should-not-exist.json" + src.write_text(json.dumps(data), encoding="utf-8") + script = Path(__file__).resolve().parents[2] / "scripts" / "v5_power_margin_plan.py" + completed = subprocess.run( + [sys.executable, str(script), "--spec", str(src), "--output", str(out)], + cwd=tmp_path, capture_output=True, text=True, env={"PATH": "/usr/bin:/bin"}, + ) + assert completed.returncode != 0 + assert "one hypothesis-specific" in completed.stderr + assert not out.exists() From 9c55c233be9e932557e2de109b852a0265f51772 Mon Sep 17 00:00:00 2001 From: Gocceri Date: Sat, 10 Oct 2026 09:31:01 +0300 Subject: [PATCH 4/4] fix(v5): fail closed on numeric power-planning overflow Signed-off-by: Gocceri --- ...R_PLANNER_INPUT_VALIDATION_HARDENING_2026-10-10.md | 2 ++ scripts/v5_power_margin_plan.py | 11 +++++++++-- tests/reliability_v5/test_power_margin_plan.py | 7 +++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/docs/research/paper-rebuild-v2-2026-10-02/V5_POWER_PLANNER_INPUT_VALIDATION_HARDENING_2026-10-10.md b/docs/research/paper-rebuild-v2-2026-10-02/V5_POWER_PLANNER_INPUT_VALIDATION_HARDENING_2026-10-10.md index 2966048e..63616dc9 100644 --- a/docs/research/paper-rebuild-v2-2026-10-02/V5_POWER_PLANNER_INPUT_VALIDATION_HARDENING_2026-10-10.md +++ b/docs/research/paper-rebuild-v2-2026-10-02/V5_POWER_PLANNER_INPUT_VALIDATION_HARDENING_2026-10-10.md @@ -20,6 +20,8 @@ The output includes explicit `false` flags for independently frozen/qualified Ho - Within-seed task/source-case SDs are **not** a conservative crossed multi-training-seed nuisance estimate; each cell's added source-hash field checks syntax only and cannot prove the actual SD provenance or full multi-seed qualification. The 64-generator's unique original source-case/task mapping does not close between-seed inferential uncertainty. - Neither syntax checks nor passing pytest, GitHub CI, Alibaba OCR eligibility or a signed-off commit prove clinical utility, qualified 90% power or publication authority. +Additional numeric stress testing also reproduced `OverflowError: cannot convert float infinity to integer` from a **finite but extremely large** `paired_sd=1e308`: the normal-approximation helper overflowed an intermediate quantity while deriving required source clusters. The caller now receives a fail-closed `PowerPlanContractError` for an unrepresentable plan instead of an uncontrolled numeric exception or a fabricated successful count. The original frozen statistical mechanics are **not** altered. + A separate direct-entrypoint check uncovered a broken script import: `python3 scripts/v5_power_margin_plan.py` failed with `ModuleNotFoundError: src` even though in-process tests passed. The CLI now resolves the repository root explicitly, and regression tests launch it from an independent temporary working directory without `PYTHONPATH`, verifying both the truthful development-only success status and fail-closed invalid-input rejection without writing an output file. This narrow successor does not edit the original 307 frozen entries, the scientific protocol, available development evidence, frozen benchmark margins or claim ledger. It creates no research/GPU/Kaggle/PHI/confirmatory/reserve action. The exact family, proper training-seed uncertainty/missingness conventions and independent methodological approval remain documented in [issue #326](https://github.com/TheHalfMoon/commandMed/issues/326). diff --git a/scripts/v5_power_margin_plan.py b/scripts/v5_power_margin_plan.py index ae0708ee..39886c4b 100644 --- a/scripts/v5_power_margin_plan.py +++ b/scripts/v5_power_margin_plan.py @@ -163,8 +163,15 @@ def _plan_metric( alpha=planning_alpha, power=power, ) - except StatisticsContractError as exc: - raise PowerPlanContractError(str(exc)) from exc + except (StatisticsContractError, OverflowError) as exc: + raise PowerPlanContractError( + "paired_sd/meaningful_margin: finite input produced " + "an unrepresentable normal-approximation planning result" + ) from exc + if not math.isfinite(mde): + raise PowerPlanContractError( + "paired_sd: normal-approximation minimum effect must be finite" + ) return { "domain_floor": floor, diff --git a/tests/reliability_v5/test_power_margin_plan.py b/tests/reliability_v5/test_power_margin_plan.py index 1a7b9019..4e0344b4 100644 --- a/tests/reliability_v5/test_power_margin_plan.py +++ b/tests/reliability_v5/test_power_margin_plan.py @@ -146,6 +146,7 @@ def test_plan_fails_closed_on_unfrozen_or_invalid_inputs(mutator, match) -> None (lambda s: s["paired_nuisance_by_hypothesis"]["SYNTH-HYP-00"].update(paired_sd=True), "JSON number"), (lambda s: s["paired_nuisance_by_hypothesis"]["SYNTH-HYP-00"].update(paired_sd="0.001"), "JSON number"), (lambda s: s["paired_nuisance_by_hypothesis"]["SYNTH-HYP-00"].update(paired_sd=10 ** 1000), "JSON number"), + (lambda s: s["paired_nuisance_by_hypothesis"]["SYNTH-HYP-00"].update(paired_sd=1e308), "unrepresentable"), (lambda s: s["metrics"]["canonical_nll"].update(domain_floor=True), "JSON number"), (lambda s: s["metrics"]["canonical_nll"].update(repeatability95="0"), "JSON number"), (lambda s: s["metrics"]["canonical_nll"].update(domain_floor_justification_sha256="x"), "SHA-256"), @@ -266,3 +267,9 @@ def test_direct_cli_rejects_fake_family_nuisance_without_output(tmp_path: Path) assert completed.returncode != 0 assert "one hypothesis-specific" in completed.stderr assert not out.exists() + +def test_large_finite_nuisance_exposes_contract_error_not_overflow() -> None: + spec = _spec() + spec["paired_nuisance_by_hypothesis"]["SYNTH-HYP-00"]["paired_sd"] = 1e308 + with pytest.raises(plan.PowerPlanContractError, match="unrepresentable"): + plan.build_plan(spec)