Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/v5-power-plan-input-contract.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ jobs:
timeout-minutes: 10
steps:
- name: Checkout exact PR head with no persistent credential
uses: actions/checkout@v4
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2, immutable checkout revision
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 1
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# V5 mechanical power-planner input ambiguity guard — 2026-10-10

Status: `DEVELOPMENT_ONLY_INPUT_INTEGRITY; UNREVIEWED_HYPOTHESES; NOT_FINAL_POWER`.

## Reproduced flaw

The unqualified development-only `scripts/v5_power_margin_plan.py` previously used the default Python `json.loads` behavior on caller-supplied power-planning specifications. When an object supplied the same key multiple times, **the last occurrence silently won**. A synthetic JSON specification based on the existing regression fixture was augmented with contradictory `primary_non_target_family_size` entries (`1`, then `4`). The command succeeded with `PASS_DEVELOPMENT_ONLY_INPUT_CONTRACT` using `4`, despite the conflicting source text. Nested hypothesis identity or per-hypothesis nuisance keys had the same ambiguity. At no point did this bug prove that final power, hypothesis-family completeness, or clinical utility were qualified; all scientific/confirmatory authority flags were already `false`.

Standard Python's non-strict JSON decoder also accepts `NaN`, `Infinity`, and `-Infinity`, which are **not** JSON numbers under RFC 8259. The downstream numeric contract rejected these if routed through its numeric fields, but rejecting them at source is a clearer, uniform trust boundary.

## Narrow source-bound correction

The CLI now loads all caller-supplied planning specifications with a strict JSON object-pairs hook that **rejects duplicate keys at every object depth**, after JSON unescaping (including `\\u` escapes). There is no silent last-wins canonicalization; a failed input produces no new plan output. It also rejects nonstandard `NaN`/`Infinity` literals, invalid UTF-8, malformed JSON and non-object JSON roots with controlled input-contract errors. A valid unambiguous input still emits `PASS_DEVELOPMENT_ONLY_INPUT_CONTRACT` and `final_90_percent_power_qualified=false`, without a review or confirmatory grant.

Real CLI subprocess negative tests (from an unrelated working directory with no `PYTHONPATH`) cover conflicting top-level Holm-family sizes, nested descriptive paired SD, nested hypothesis ID, Unicode-escaped equivalent duplicate names, `NaN`, `Infinity`, non-object roots and malformed JSON. The existing exact-head GitHub Actions V5 input-contract workflow includes the expanded focused test suite.

## Non-overwrite protection for existing scientific evidence

A separate Mac-only synthetic regression demonstrated that the original direct CLI allowed `--spec` and `--output` to reference the **same existing path**: it exited with `PASS_DEVELOPMENT_ONLY_INPUT_CONTRACT` while destroying its own input bytes. Any previously written development planning receipt or original evidence file could have been similarly overwritten by an unintended output path.

A subsequent bounded output-integrity correction writes new plan bytes to a same-directory temporary file with restrictive creation permissions, flushes and `fsync`s the full content, then publishes its *completed* bytes by atomic no-clobber hard link before removing the temporary name. A partial write, disk-full exception, sync failure, destination collision or publication failure cannot leave a newly visible partially written output filename. Regression tests inject failures **after a partial write**, during `fsync`, and while publishing the hard link, proving no destination and no leftover temporary file; positive tests prove exact bytes and immutable existing outputs. This is atomic filename visibility after complete file sync on supported filesystems, **not** a guarantee of parent-directory fsync or crash/power-loss persistence on every filesystem. Unsupported hard links fail closed rather than falling back to unsafe output truncation.

The CLI now serializes its *unqualified* development-only result first, then publishes complete bytes by same-filesystem atomic no-clobber hard link after writing and syncing a temporary file, rather than truncating an existing path. An existing output file, the input source itself, a symlink to evidence, or a second attempt to use the same output name is rejected with `OUTPUT_ALREADY_EXISTS` and no success receipt. A failed temporary write/flush/sync or link leaves no partial new evidence filename. This is not an absolute power-loss durability guarantee on every filesystem. Direct-subprocess regressions use temp files to verify preserved bytes, symlink preservation and repeat invocation, without touching any actual frozen evidence.

## Explicit boundaries

- Strict JSON syntax **cannot** establish that a user-supplied hypothesis list is prospectively complete, that declared coupling tags are valid, or that an SHA-shaped evidence identifier identifies genuine qualified research evidence.
- The descriptive paired SD values still do **not** qualify the crossed source-case and stochastic training-seed nuisance model or 90% power.
- Scientific `main`, the frozen case generator/evidence/307 bound files, benchmark margins, study endpoints, actual observations and prior negative results are unchanged.
- No inference, model weights, GPU, paid cloud, PHI, confirmatory/reserve case identity access, independent review or founder authority is implied.
- The fix is isolated in a stacked draft successor to PR #327 because the existing local PR #327 worktree has separately owned uncommitted edits and must not be overwritten or committed by another session. No history rewrite or merge is performed.

Reference: statistical and founder authorization gate [#326](https://github.com/TheHalfMoon/commandMed/issues/326), original defect report [PR #327 issuecomment-6094934938](https://github.com/TheHalfMoon/commandMed/pull/327#issuecomment-6094934938).
122 changes: 111 additions & 11 deletions scripts/v5_power_margin_plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import hashlib
import json
import math
import os
import tempfile
import re
from pathlib import Path
import sys
Expand Down Expand Up @@ -127,6 +129,20 @@ def conservative_holm_planning_alpha(family_alpha: float, family_size: int) -> f
return alpha / family_size



def _finite_meaningful_margin(domain_floor: float, repeatability95: float) -> float:
"""Keep the fixed 2x-repeatability margin finite at every planning scope."""
repeat_component = 2.0 * repeatability95
if not math.isfinite(repeat_component):
raise PowerPlanContractError(
"repeatability95: two-times repeatability margin overflows finite precision"
)
margin = max(domain_floor, repeat_component)
if not math.isfinite(margin) or margin <= 0.0:
raise PowerPlanContractError("meaningful_margin: positive finite margin required")
return margin


def _plan_metric(
*,
domain_floor: float,
Expand All @@ -139,7 +155,7 @@ def _plan_metric(
floor = _finite_positive(domain_floor, "domain_floor")
repeat = _finite_nonnegative(repeatability95, "repeatability95")
sd = _finite_nonnegative(paired_sd, "paired_sd")
margin = max(floor, 2.0 * repeat)
margin = _finite_meaningful_margin(floor, repeat)
if type(planned_clusters) is not int or planned_clusters < 2:
raise PowerPlanContractError("planned_clusters: expected an integer >= 2")
power = _finite_positive(desired_power, "desired_power")
Expand Down Expand Up @@ -168,6 +184,13 @@ def _plan_metric(
"paired_sd/meaningful_margin: finite input produced "
"an unrepresentable normal-approximation planning result"
) from exc
# A strictly positive source-case SD must never become an *exact zero*
# detectable effect because float arithmetic underflows. Zero has a
# distinct, explicitly handled branch above; reject lost precision.
if mde == 0.0:
raise PowerPlanContractError(
"paired_sd: positive planning noise underflowed to a zero MDE"
)
if not math.isfinite(mde):
raise PowerPlanContractError(
"paired_sd: normal-approximation minimum effect must be finite"
Expand Down Expand Up @@ -204,8 +227,11 @@ def build_plan(spec: dict[str, Any]) -> dict[str, Any]:
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")
if any(
not isinstance(name, str) or not name.strip() or name != name.strip()
for name in metrics
):
raise PowerPlanContractError("metrics: nonempty unpadded metric name required")
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")
Expand Down Expand Up @@ -240,7 +266,7 @@ def build_plan(spec: dict[str, Any]) -> dict[str, Any]:
result_metrics[name] = {
"domain_floor": floor,
"repeatability95": repeat,
"meaningful_margin": max(floor, 2.0 * repeat),
"meaningful_margin": _finite_meaningful_margin(floor, repeat),
"domain_floor_justification_sha256": row["domain_floor_justification_sha256"],
"repeatability_evidence_sha256": row["repeatability_evidence_sha256"],
}
Expand Down Expand Up @@ -327,19 +353,93 @@ def build_plan(spec: dict[str, Any]) -> dict[str, Any]:
}


def _strict_json_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
"""Reject duplicate keys after JSON unicode-escape decoding at every depth."""
result: dict[str, Any] = {}
for key, value in pairs:
if key in result:
raise PowerPlanContractError(
f"AMBIGUOUS_JSON_DUPLICATE_KEY: {key!r}"
)
result[key] = value
return result


def _reject_json_constant(value: str) -> None:
# Python's default JSON parser accepts NaN/Infinity despite JSON RFC 8259.
raise PowerPlanContractError(f"NONSTANDARD_JSON_CONSTANT: {value}")


def _load_strict_plan(path: Path) -> dict[str, Any]:
"""Load only unambiguous JSON; preserve every downstream provenance check."""
try:
payload = json.loads(
path.read_text(encoding="utf-8"),
object_pairs_hook=_strict_json_object,
parse_constant=_reject_json_constant,
)
except PowerPlanContractError:
# Preserve precise ambiguity and nonstandard-constant rejections.
raise
except (UnicodeError, OSError, ValueError, RecursionError) as exc:
# json.loads can raise ValueError for Python's oversized integer guard
# and RecursionError for adversarial nesting, not just JSONDecodeError.
raise PowerPlanContractError("INVALID_POWER_PLAN_JSON") from exc
if not isinstance(payload, dict):
raise PowerPlanContractError("POWER_PLAN_ROOT_MUST_BE_OBJECT")
return payload



def _publish_complete_output_no_clobber(output: Path, serialized: str) -> None:
"""Expose a new evidence filename only after all bytes are written and synced.

Hard-link publication is atomic and fails if the destination already exists,
including a symlink. Temp and destination are on the same filesystem.
This does not claim directory fsync or power-loss durability.
"""
destination_bytes = serialized.encode("utf-8")
fd, temporary = tempfile.mkstemp(
dir=output.parent, prefix=f".{output.name}.", suffix=".tmp"
)
try:
try:
pending = memoryview(destination_bytes)
while pending:
written = os.write(fd, pending)
if written <= 0:
raise OSError("incomplete output write")
pending = pending[written:]
os.fsync(fd)
finally:
os.close(fd)
# Unlike replace/rename, this cannot overwrite even if a competing
# writer creates the destination while our temporary file is written.
os.link(temporary, output)
finally:
Path(temporary).unlink(missing_ok=True)


def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--spec", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
spec = json.loads(args.spec.read_text(encoding="utf-8"))
spec = _load_strict_plan(args.spec)
payload = build_plan(spec)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(
json.dumps(payload, indent=2, sort_keys=True) + "\n",
encoding="utf-8",
newline="\n",
)
# Evidence is append-only: an accidental --output pointing at the input,
# an existing scientific artifact, or a symlink must not overwrite bytes.
# Exclusive creation is atomic at the destination on macOS/Linux/Windows.
serialized = json.dumps(payload, indent=2, sort_keys=True, allow_nan=False) + "\n"
try:
args.output.parent.mkdir(parents=True, exist_ok=True)
_publish_complete_output_no_clobber(args.output, serialized)
except FileExistsError as exc:
raise PowerPlanContractError(
"OUTPUT_ALREADY_EXISTS: refusing to overwrite prior research evidence"
) from exc
except OSError as exc:
raise PowerPlanContractError("OUTPUT_NOT_WRITABLE") from exc
print(json.dumps({
"status": "PASS_DEVELOPMENT_ONLY_INPUT_CONTRACT",
"final_90_percent_power_qualified": False,
Expand Down
Loading
Loading