diff --git a/.github/workflows/fold-affine-bridge.yml b/.github/workflows/fold-affine-bridge.yml new file mode 100644 index 000000000..01cced2fb --- /dev/null +++ b/.github/workflows/fold-affine-bridge.yml @@ -0,0 +1,50 @@ +name: Exact fold affine bridge companion +'on': + pull_request: + paths: + - 'companions/fold_affine_bridge_20261006/**' + - '.github/workflows/fold-affine-bridge.yml' + - 'formal/**' + push: + branches: [main] + paths: + - 'companions/fold_affine_bridge_20261006/**' + - '.github/workflows/fold-affine-bridge.yml' + - 'formal/**' + workflow_dispatch: +permissions: + contents: read +jobs: + fold-affine-bridge: + runs-on: ubuntu-latest + timeout-minutes: 35 + env: + LEAN_NUM_THREADS: 2 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + persist-credentials: false + fetch-depth: 0 + - name: Install existing pinned Lean and retrieve dependency cache + uses: leanprover/lean-action@f061402b660e0c34644504b324e830f2991d4865 + with: + lake-package-directory: formal + auto-config: 'false' + build: 'false' + test: 'false' + lint: 'false' + use-mathlib-cache: 'true' + use-github-cache: 'false' + - name: Check primary package and separate exact fold contracts + run: python3 -B -S companions/fold_affine_bridge_20261006/replay.py execute + - name: Preserve original success or failure evidence + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a + with: + name: fold-affine-bridge-${{ github.run_id }}-${{ github.run_attempt }} + path: | + .lake/fold-affine-bridge-evidence/ + formal/.lake/formal-evidence/ + include-hidden-files: true + if-no-files-found: error + retention-days: 30 diff --git a/companions/fold_affine_bridge_20261006/Contract.lean b/companions/fold_affine_bridge_20261006/Contract.lean new file mode 100644 index 000000000..199339e01 --- /dev/null +++ b/companions/fold_affine_bridge_20261006/Contract.lean @@ -0,0 +1,99 @@ +import FoldAffineBridge + +open ResearchFormalCoreR1 FoldAffineBridge +set_option autoImplicit false + +example (s x : ℝ) : HasDerivAt (foldPotential s) (s^2-x^2) x := fold_hasDerivAt s x +example (s x : ℝ) : deriv (foldPotential s) x = s^2-x^2 := fold_deriv s x +example (s x : ℝ) : deriv (deriv (foldPotential s)) x = -2*x := fold_second s x +example (s x : ℝ) : deriv (foldPotential s) x = 0 ↔ x=s ∨ x= -s := fold_critical s x +example (s : ℝ) : + (deriv (deriv (foldPotential s)) s ≠ 0 ∧ + deriv (deriv (foldPotential s)) (-s) ≠ 0) ↔ s ≠ 0 := fold_nondegenerate s +example (s : ℝ) : + (deriv (deriv (foldPotential s)) s < 0 ↔ 0 < s) ∧ + (0 < deriv (deriv (foldPotential s)) (-s) ↔ 0 < s) := fold_curvature s + +example (s a b c y : ℝ) : HasDerivAt (affinePotential s a b c) + (c*a*(s^2-(a*y+b)^2)) y := affine_hasDerivAt s a b c y +example (s a b c y : ℝ) : deriv (affinePotential s a b c) y = + c*a*(s^2-(a*y+b)^2) := affine_deriv s a b c y +example (s a b c y : ℝ) : HasDerivAt (deriv (affinePotential s a b c)) + (-2*c*a^2*(a*y+b)) y := affine_hasDerivAt_deriv s a b c y +example (s a b c y : ℝ) : deriv (deriv (affinePotential s a b c)) y = + -2*c*a^2*(a*y+b) := affine_second s a b c y +example (s a b : ℝ) (ha : a ≠ 0) : + a*plusPoint s a b+b=s ∧ a*minusPoint s a b+b= -s := affine_coordinates s a b ha +example (s a b c y : ℝ) (ha : a ≠ 0) (hc : c ≠ 0) : + deriv (affinePotential s a b c) y=0 ↔ y=plusPoint s a b ∨ y=minusPoint s a b := + affine_critical s a b c y ha hc +example (s a b : ℝ) : plusPoint s a b-minusPoint s a b=2*s/a := affine_orientation s a b +example (s a b : ℝ) (ha : a ≠ 0) : plusPoint s a b ≠ minusPoint s a b ↔ s ≠ 0 := + affine_distinct s a b ha +example (s a b c : ℝ) (ha : a ≠ 0) : + deriv (deriv (affinePotential s a b c)) (plusPoint s a b)= -2*c*a^2*s ∧ + deriv (deriv (affinePotential s a b c)) (minusPoint s a b)=2*c*a^2*s := + affine_curvature s a b c ha +example (s a b c : ℝ) (ha : a ≠ 0) (hc : c ≠ 0) : + (deriv (deriv (affinePotential s a b c)) (plusPoint s a b) ≠ 0 ∧ + deriv (deriv (affinePotential s a b c)) (minusPoint s a b) ≠ 0) ↔ s ≠ 0 := + affine_nondegenerate s a b c ha hc +example (s a b c : ℝ) (ha : a ≠ 0) : + (deriv (deriv (affinePotential s a b c)) (plusPoint s a b) < 0 ↔ 0 first | rfl | ring + +theorem fold_deriv (s x : ℝ) : deriv (foldPotential s) x = s^2-x^2 := + (fold_hasDerivAt s x).deriv + +theorem fold_second (s x : ℝ) : deriv (deriv (foldPotential s)) x = -2*x := by + have hf : deriv (foldPotential s) = fun z => s^2-z^2 := funext (fold_deriv s) + rw [hf] + have hd : HasDerivAt (fun z : ℝ => s^2-z^2) (-2*x) x := by + convert (hasDerivAt_const x (s^2)).sub (hasDerivAt_pow 2 x) using 1; first | rfl | ring + exact hd.deriv + +theorem fold_critical (s x : ℝ) : deriv (foldPotential s) x = 0 ↔ x=s ∨ x= -s := by + rw [fold_deriv] + constructor + · intro h + have hp : (x-s)*(x+s)=0 := by nlinarith + rcases mul_eq_zero.mp hp with h1 | h2 + · left; linarith + · right; linarith + · rintro (rfl | rfl) <;> ring + +theorem fold_nondegenerate (s : ℝ) : + (deriv (deriv (foldPotential s)) s ≠ 0 ∧ + deriv (deriv (foldPotential s)) (-s) ≠ 0) ↔ s ≠ 0 := by + simp only [fold_second] + constructor + · rintro ⟨h, _⟩ hs + apply h + rw [hs, mul_zero] + · intro hs + exact ⟨mul_ne_zero (by norm_num) hs, mul_ne_zero (by norm_num) (neg_ne_zero.mpr hs)⟩ + +theorem fold_curvature (s : ℝ) : + (deriv (deriv (foldPotential s)) s < 0 ↔ 0 < s) ∧ + (0 < deriv (deriv (foldPotential s)) (-s) ↔ 0 < s) := by + simp only [fold_second] + constructor <;> constructor <;> intro h <;> nlinarith + +theorem affine_hasDerivAt (s a b c y : ℝ) : HasDerivAt (affinePotential s a b c) + (c*a*(s^2-(a*y+b)^2)) y := by + have hl : HasDerivAt (fun z : ℝ => a*z+b) a y := by + simpa using ((hasDerivAt_id y).const_mul a).add_const b + unfold affinePotential + convert ((fold_hasDerivAt s (a*y+b)).comp y hl).const_mul c using 1 <;> first | rfl | ring + +theorem affine_deriv (s a b c y : ℝ) : deriv (affinePotential s a b c) y = + c*a*(s^2-(a*y+b)^2) := (affine_hasDerivAt s a b c y).deriv + +theorem affine_hasDerivAt_deriv (s a b c y : ℝ) : + HasDerivAt (deriv (affinePotential s a b c)) (-2*c*a^2*(a*y+b)) y := by + have hf : deriv (affinePotential s a b c) = fun z => c*a*(s^2-(a*z+b)^2) := + funext (affine_deriv s a b c) + rw [hf] + have hl : HasDerivAt (fun z : ℝ => a*z+b) a y := by + simpa using ((hasDerivAt_id y).const_mul a).add_const b + convert ((hasDerivAt_const y (s^2)).sub (hl.pow 2)).const_mul (c*a) using 1; first | rfl | ring + +theorem affine_second (s a b c y : ℝ) : deriv (deriv (affinePotential s a b c)) y = + -2*c*a^2*(a*y+b) := (affine_hasDerivAt_deriv s a b c y).deriv + +theorem affine_coordinates (s a b : ℝ) (ha : a ≠ 0) : + a*plusPoint s a b+b=s ∧ a*minusPoint s a b+b= -s := by + unfold plusPoint minusPoint + constructor <;> field_simp [ha] <;> ring + +theorem affine_critical (s a b c y : ℝ) (ha : a ≠ 0) (hc : c ≠ 0) : + deriv (affinePotential s a b c) y=0 ↔ y=plusPoint s a b ∨ y=minusPoint s a b := by + rw [affine_deriv] + constructor + · intro h + have hz : s^2-(a*y+b)^2=0 := (mul_eq_zero.mp h).resolve_left (mul_ne_zero hc ha) + have hp : (a*y+b-s)*(a*y+b+s)=0 := by nlinarith + rcases mul_eq_zero.mp hp with h1 | h2 + · left + unfold plusPoint + field_simp [ha] + nlinarith + · right + unfold minusPoint + field_simp [ha] + nlinarith + · rintro (rfl | rfl) + · rw [(affine_coordinates s a b ha).1]; ring + · rw [(affine_coordinates s a b ha).2]; ring + +theorem affine_orientation (s a b : ℝ) : plusPoint s a b-minusPoint s a b=2*s/a := by + unfold plusPoint minusPoint + ring + +theorem affine_distinct (s a b : ℝ) (ha : a ≠ 0) : + plusPoint s a b ≠ minusPoint s a b ↔ s ≠ 0 := by + constructor + · intro h hs + apply h + simp [hs, plusPoint, minusPoint] + · intro hs heq + apply hs + unfold plusPoint minusPoint at heq + field_simp [ha] at heq + linarith + +theorem affine_curvature (s a b c : ℝ) (ha : a ≠ 0) : + deriv (deriv (affinePotential s a b c)) (plusPoint s a b)= -2*c*a^2*s ∧ + deriv (deriv (affinePotential s a b c)) (minusPoint s a b)=2*c*a^2*s := by + rw [affine_second, affine_second, (affine_coordinates s a b ha).1, + (affine_coordinates s a b ha).2] + constructor <;> ring + +theorem affine_nondegenerate (s a b c : ℝ) (ha : a ≠ 0) (hc : c ≠ 0) : + (deriv (deriv (affinePotential s a b c)) (plusPoint s a b) ≠ 0 ∧ + deriv (deriv (affinePotential s a b c)) (minusPoint s a b) ≠ 0) ↔ s ≠ 0 := by + rw [(affine_curvature s a b c ha).1, (affine_curvature s a b c ha).2] + constructor + · rintro ⟨h, _⟩ hs + apply h + rw [hs, mul_zero] + · intro hs + exact ⟨mul_ne_zero (mul_ne_zero (mul_ne_zero (by norm_num) hc) (pow_ne_zero 2 ha)) hs, + mul_ne_zero (mul_ne_zero (mul_ne_zero (by norm_num) hc) (pow_ne_zero 2 ha)) hs⟩ + +theorem affine_curvature_sign (s a b c : ℝ) (ha : a ≠ 0) : + (deriv (deriv (affinePotential s a b c)) (plusPoint s a b) < 0 ↔ 0 ring + +theorem affine_local_signs (s a b c h : ℝ) (ha : a ≠ 0) (hc : c ≠ 0) (hs : s ≠ 0) + (hh0 : 0 < |h|) (hh1 : |h| < |s|/|a|) : + c*s*(affinePotential s a b c (plusPoint s a b+h)-affinePotential s a b c (plusPoint s a b)) < 0 ∧ + 0 < c*s*(affinePotential s a b c (minusPoint s a b+h)-affinePotential s a b c (minusPoint s a b)) := by + rw [(affine_increments s a b c h ha).1, (affine_increments s a b c h ha).2] + have haabs : 0 < |a| := abs_pos.mpr ha + have hhbound : |h| * |a| < |s| := (lt_div_iff₀ haabs).mp hh1 + have hah : |a*h| < |s| := by rw [abs_mul]; nlinarith + have hsprod : 0 < s*(s+a*h/3) ∧ 0 < s*(s-a*h/3) := by + rcases lt_or_gt_of_ne hs with hn | hp + · rw [abs_of_neg hn] at hah + have hb := abs_lt.mp hah + constructor + · exact mul_pos_of_neg_of_neg hn (by linarith [hb.2]) + · exact mul_pos_of_neg_of_neg hn (by linarith [hb.1]) + · rw [abs_of_pos hp] at hah + have hb := abs_lt.mp hah + constructor + · exact mul_pos hp (by linarith [hb.1]) + · exact mul_pos hp (by linarith [hb.2]) + have hch : 0 < c^2*(a*h)^2 := + mul_pos (sq_pos_of_ne_zero hc) (sq_pos_of_ne_zero (mul_ne_zero ha (abs_pos.mp hh0))) + have hp := mul_pos hch hsprod.1 + have hm := mul_pos hch hsprod.2 + constructor <;> nlinarith + +theorem affine_zero_degenerate (a b c : ℝ) (ha : a ≠ 0) : + plusPoint 0 a b=minusPoint 0 a b ∧ plusPoint 0 a b= -b/a ∧ + deriv (affinePotential 0 a b c) (-b/a)=0 ∧ + deriv (deriv (affinePotential 0 a b c)) (-b/a)=0 := by + have hx : a*(-b/a)+b=0 := by field_simp [ha]; ring + refine ⟨by simp [plusPoint, minusPoint], by simp [plusPoint], ?_, ?_⟩ + · rw [affine_deriv, hx]; ring + · rw [affine_second, hx]; ring + +theorem affine_zero_increment (a b c h : ℝ) (ha : a ≠ 0) : + affinePotential 0 a b c (-b/a+h)-affinePotential 0 a b c (-b/a)= -c*a^3*h^3/3 := by + have hp := (affine_increments 0 a b c h ha).1 + simp only [plusPoint, zero_sub] at hp + rw [hp] + ring + +/-- Nonzero a and c are essential: without them the function is constant. -/ +theorem affine_zero_crossing (a b c h : ℝ) (ha : a ≠ 0) (hc : c ≠ 0) (hh : h ≠ 0) : + (affinePotential 0 a b c (-b/a+h)-affinePotential 0 a b c (-b/a))* + (affinePotential 0 a b c (-b/a-h)-affinePotential 0 a b c (-b/a)) < 0 := by + rw [show -b/a-h = -b/a+(-h) by ring, + affine_zero_increment a b c h ha, affine_zero_increment a b c (-h) ha] + have hz : c*a^3*h^3/3 ≠ 0 := + div_ne_zero (mul_ne_zero (mul_ne_zero hc (pow_ne_zero 3 ha)) (pow_ne_zero 3 hh)) (by norm_num) + calc + (-c*a^3*h^3/3)*(-c*a^3*(-h)^3/3) = -(c*a^3*h^3/3)^2 := by ring + _ < 0 := neg_lt_zero.mpr (sq_pos_of_ne_zero hz) + +theorem affine_constant_a (s b c y : ℝ) : affinePotential s 0 b c y=c*foldPotential s b ∧ + deriv (affinePotential s 0 b c) y=0 := by + simp [affinePotential, affine_deriv] + +theorem affine_constant_c (s a b y : ℝ) : affinePotential s a b 0 y=0 ∧ + deriv (affinePotential s a b 0) y=0 := by + simp [affinePotential, affine_deriv] + +end FoldAffineBridge diff --git a/companions/fold_affine_bridge_20261006/README.md b/companions/fold_affine_bridge_20261006/README.md new file mode 100644 index 000000000..b34100a77 --- /dev/null +++ b/companions/fold_affine_bridge_20261006/README.md @@ -0,0 +1,154 @@ +# Exact fold derivatives and affine coordinates + +Scientific effect: NONE. Author: OpenAI, `fold-affine-bridge-author-20261006`, +exact model/session UNKNOWN, organizational-independence credit 0. This is +Dylan Roy's delegated AI work, not his personal reading. The author is +source-exposed and will not supply independent alignment or integrate this work. + +Reservation and source-bound statement contract: +- https://github.com/d6g8k5htny-coder/main/issues/275#issuecomment-6027534463 +- https://github.com/d6g8k5htny-coder/main/issues/275#issuecomment-6027637137 +- https://github.com/d6g8k5htny-coder/main/issues/275#issuecomment-6027667849 +- Own continuation: https://github.com/d6g8k5htny-coder/main/issues/275#issuecomment-6027692808 + +## Publication phase + +The initial commit f83bb592 was an intentionally empty test-first stub. +Dedicated run37549682550/1 at merge checkout +fcf5c6ba05d15323f10d8e555c9a3e125a079d8b passed both full Python modes, the +unchanged primary kernel gate and the stub module build, then Contract.lean +failed on absent new declarations (exit1). Its original artifact11451893422 +is retained,48344bytes/SHA2566060fc6658508d97b544290742c759512513f9216f27ae04bce8619ba7da41bf. +Proof bodies are supplied only after that observed failure. Their compilation, +current-source kernel evidence and independently authenticated statement/source +alignment are separate evidence stages. The PR records their actual completion +at exact source identities; this static scope note does not award acceptance. Failed attempts stay in the PR record. The first proof-source head48544ac5 +failed candidate compilation in37551282778/1 after the full suites and unchanged +core passed: pointwise function equalities needed explicit extensionality, one +tactic was unreachable under warnings-as-errors, and adjacent absolute-value +bars/multiplication formed the Lean |* token. Original artifact11453177336 +(45870bytes, SHA25686036e287059a5d8540bad534ae1a8348e4cd5bd7075b3a0571e9b6717cfc0c5) +is retained. The successor repairs these source issues without changing target +hypotheses; candidate contract/axiom/recheck/negative stages were unrun there. +The next exact run37552472542/1 at ea86cd53 failed only on unreachable +tactics in unused extensionality branches and a trailing ring after field_simp +had closed the absolute-gap goal. Artifact11453480961 retains that failure +(23452bytes, SHA256a51829d0a2bbb1666bd859abd10f2fe71b7d08e47224fea688f9d1665e2a1b73). +The successor removes those dead tactics without disabling any linter or +changing theorem statements. Run37553111010/1 at cc3681cc then reported only +two unnecessarySeqFocus lint errors for single-goal derivative conversions; +artifact11454255745 (23429bytes, SHA256c6ece3872717be3ffd1a5cae715def936e280749ed6050436bc46150f07e86e8) +preserves that attempt. The next successor uses the requested ordinary tactic +sequencing at those two sites. No linter is disabled, and all later stages +still require actual execution. Run37553676722/1 at60b5ef19 then compiled +all29theorems/4definitions with warnings-as-errors, but the numeric Hessian +consumer failed because simp left2*3*2^2 unevaluated rather than24. Its original +artifact11453487543 is416601bytes with SHA2565766ec45c8184ac73de883e3bea84ccbcf275cb70f2c38b2a27fdf456bc29e49. +The consumer now invokes explicit norm_num without changing its statement. +A module build alone is not the final axiom/recheck/negative-control receipt. + +## Exact mathematical contract + +All parameters are real. Reuse `ResearchFormalCoreR1.foldPotential s x`, +F_s(x)=-x^3/3+s^2*x, and its existing `ec005_fold_gap` subtraction theorem. +New definitions only: G(y)=c*F_s(a*y+b), plusPoint=(s-b)/a, +minusPoint=(-s-b)/a, physicalSeparation=2*abs(s)/abs(a). +Plus/minus labels name the source coordinate, not spatial order or extrema. + +The 29 target declarations are explicitly inventoried in replay.py and +SOURCE_FILES.json; the four definitions are audited too. Contract.lean is an +exact-type consumer of every target. It retains all quantifiers/hypotheses: + +- Canonical HasDerivAt witness and derivative s^2-x^2, second derivative -2*x, + and complete critical set x=s or x=-s. Both Hessians are nonzero iff s is + nonzero; at s the curvature is negative iff s>0 and at -s positive iff s>0. +- Affine first/second derivative witnesses and formulas + c*a*(s^2-(a*y+b)^2) and -2*c*a^2*(a*y+b), including zero parameters. +- With a,c nonzero, full critical set plusPoint/minusPoint; source-coordinate + identities and Hessians -2*c*a^2*s / 2*c*a^2*s. Nondegeneracy iff s is + nonzero; source-labelled maximum/minimum classification depends on c*s. +- Orientation plusPoint-minusPoint=2*s/a. Absolute separation equals r and + is nonnegative; for a nonzero it vanishes exactly when s=0. +- With a nonzero, invoke ec005_fold_gap to transfer the signed gap + c*(2*s)^3/6 and absolute gap abs(c)*abs(a)^3*r^3/6. The algebra allows c=0; + the isolated-pair interpretation requires c nonzero. +- Exact point increments -c*(a*h)^2*(s+a*h/3) and + c*(a*h)^2*(s-a*h/3). For a,c,s nonzero and + 00 +curvature label at s=-1. Missing imports, toolchain failure, other diagnostics, +stderr, wrong exit status or timeouts do not satisfy this negative gate. + +## Sources, execution and limits + +Frozen source base: Math- 34618d0d032f4361c1ec163f3b4cfd6ad01ab814. +Consumed AlgebraV2 blob: a8b42432cc65095b37750b24ea2d617dd437092a. +Unchanged primary formal tree: d7422c6b1acbf3e20c75a1ed7fc13fc30125ec14. +The only source import is ResearchFormalCoreR1.AlgebraV2, including its Mathlib +import. No duplicate canonical fold definition or subtraction proof is added. +Lean remains leanprover/lean4:v4.34.1; mathlib remains + d13f23b723b8a846827a245b89c10fc7d3f11612; lake configuration/manifest untouched. +Driver patterns reuse the inspected d2_square_schur companion, with separate +stdout/stderr, bounded children and an output build directory. The unchanged +primary gate's exact-hash axiom auditor is reused, not replaced by this driver. +The small explicit inventory is not the RF312 general declaration scanner. + +From the repository root: + + python3 -B -S companions/fold_affine_bridge_20261006/test_contract.py + python3 -B -O -S companions/fold_affine_bridge_20261006/test_contract.py + python3 -B -S companions/fold_affine_bridge_20261006/replay.py source + python3 -B -S companions/fold_affine_bridge_20261006/replay.py controls + python3 -B -S companions/fold_affine_bridge_20261006/replay.py execute + +Execute requires the existing pinned toolchain already available. Its fresh +output directory defaults to .lake/fold-affine-bridge-evidence. It runs the unchanged primary kernel gate, then candidate warnings-as-errors +build, exact-type consumers, transitive axiom/type audits, fresh leanchecker +and reason-specific controls. Both full root/formal Python suites and companion +tests in normal and optimized modes remain mandatory before any final receipt. +This early-positive ordering changes failure latency only; unrun stages never +inherit earlier results. The companion .olean +is written only under the separate output/build directory. Every child keeps +raw stdout/stderr/status, including failure and timeout. Receipt creation is +last and cannot turn a partial run into success. The dedicated read-only +workflow preserves original outputs on success or failure. Required aggregate +checks and current tested checkout remain separately binding before integration. + +No local Lean execution was available when this stub was prepared. Local +Python arithmetic is finite diagnostic evidence only. A configured workflow +is not an executed result; the primary package does not check this companion. +No nonlinear/approximate chart, random-field construction, stochastic or Palm +realization, persistence pairing, probability, multiplicity or parent theorem +is claimed. There is no primary target registration, formal-manifest change, +scientific-status promotion or transfer of older review acceptance. + +## Proposed source-specific runtime budget + +The exact runtime profile is retained at PR391 comment6029164512. The required +AlgebraV2 import contributes778683eligible constants; this candidate adds45, +while the narrower D2Schur baseline has433798. Import loading is about3.4seconds; +that is not fresh-kernel runtime or a linear time estimate. + +This successor proposes only the fresh-checker child cap1200seconds and overall +job cap35minutes; all other child limits and all positive/type/axiom/negative/ +full-suite gates remain. No ordinary checker replaces --fresh. No proof or +Contract source changes. Execution requires a distinct nonauthor engineering +read of this exact delta and a finite confirmed continuation. + +The fresh-checker process group receives0.5second Linux/proc observations, +flushed as raw JSONL, plus a summary and separate RUSAGE_CHILDREN CPU deltas. +Observed peak process VmHWM and summed group RSS are diagnostic observations, +not guaranteed whole-run maxima: fast/exited children and final spikes can be +missed; RSS sums may double-count shared pages. Cumulative child maxrss is +labelled cumulative, not checker-only. Forced kill can exclude unreaped +descendants from child-CPU deltas. Raw streams/status and partial observations +survive timeout; capture failures cannot mint a passing receipt. diff --git a/companions/fold_affine_bridge_20261006/SOURCE_FILES.json b/companions/fold_affine_bridge_20261006/SOURCE_FILES.json new file mode 100644 index 000000000..242b1bbf9 --- /dev/null +++ b/companions/fold_affine_bridge_20261006/SOURCE_FILES.json @@ -0,0 +1,74 @@ +{ + "core_tree": "d7422c6b1acbf3e20c75a1ed7fc13fc30125ec14", + "definitions": [ + "FoldAffineBridge.affinePotential", + "FoldAffineBridge.plusPoint", + "FoldAffineBridge.minusPoint", + "FoldAffineBridge.physicalSeparation" + ], + "files": { + ".github/workflows/fold-affine-bridge.yml": { + "bytes": 1684, + "git_blob": "01cced2fb8c65ec62041e4bfbe3e6859f782f790", + "sha256": "20d9011e9ddd1d03a09101dbab8d5d730349028b4a7b1e4c7716cefe3eccd67b" + }, + "companions/fold_affine_bridge_20261006/Contract.lean": { + "bytes": 5724, + "git_blob": "199339e0151af44c3087ae47598e5c854a64bdfc", + "sha256": "58bfef2ba4b4782f933ea54c54234db06b0b36e43015a9c671132fd744044e3a" + }, + "companions/fold_affine_bridge_20261006/FoldAffineBridge.lean": { + "bytes": 11435, + "git_blob": "e41b9c0d5ff59b1b84909d81baf05eb6ffb6f483", + "sha256": "e43c0d2084590b564618d9774feae9a40a24a31deb5227b66b6e54901ada56ea" + }, + "companions/fold_affine_bridge_20261006/README.md": { + "bytes": 10000, + "git_blob": "b34100a77e0ce28dcbe8a8f8b43c74f307a48e18", + "sha256": "c04d3fe52a3a19667c81180bf5aa4b26bb100b4ada495d1462af11660e72ddaf" + }, + "companions/fold_affine_bridge_20261006/replay.py": { + "bytes": 17089, + "git_blob": "d18d61abd2b04d86537dc868cf89978663855dbe", + "sha256": "ecbb4b8e2b5890078e612e3152615e53678e016d050363a1127d2ffe3d6e14c4" + }, + "companions/fold_affine_bridge_20261006/test_contract.py": { + "bytes": 8027, + "git_blob": "b9bab675d91a220042b53a4fd50dc0ea2ccb0baa", + "sha256": "436c74b106e22d9235bfd5621775e57dd1dc7d49bd4e22eb1a25f8f98df617ca" + } + }, + "scientific_effect": "NONE", + "targets": [ + "FoldAffineBridge.fold_hasDerivAt", + "FoldAffineBridge.fold_deriv", + "FoldAffineBridge.fold_second", + "FoldAffineBridge.fold_critical", + "FoldAffineBridge.fold_nondegenerate", + "FoldAffineBridge.fold_curvature", + "FoldAffineBridge.affine_hasDerivAt", + "FoldAffineBridge.affine_deriv", + "FoldAffineBridge.affine_hasDerivAt_deriv", + "FoldAffineBridge.affine_second", + "FoldAffineBridge.affine_coordinates", + "FoldAffineBridge.affine_critical", + "FoldAffineBridge.affine_orientation", + "FoldAffineBridge.affine_distinct", + "FoldAffineBridge.affine_curvature", + "FoldAffineBridge.affine_nondegenerate", + "FoldAffineBridge.affine_curvature_sign", + "FoldAffineBridge.separation_eq", + "FoldAffineBridge.separation_nonneg", + "FoldAffineBridge.separation_zero", + "FoldAffineBridge.affine_signed_gap", + "FoldAffineBridge.affine_absolute_gap", + "FoldAffineBridge.affine_increments", + "FoldAffineBridge.affine_local_signs", + "FoldAffineBridge.affine_zero_degenerate", + "FoldAffineBridge.affine_zero_increment", + "FoldAffineBridge.affine_zero_crossing", + "FoldAffineBridge.affine_constant_a", + "FoldAffineBridge.affine_constant_c" + ], + "version": 1 +} diff --git a/companions/fold_affine_bridge_20261006/replay.py b/companions/fold_affine_bridge_20261006/replay.py new file mode 100644 index 000000000..d18d61abd --- /dev/null +++ b/companions/fold_affine_bridge_20261006/replay.py @@ -0,0 +1,260 @@ +#!/usr/bin/env python3 +"""Source-bound bounded fold companion replay. Source, kernel and alignment stay separate.""" +import argparse +from fractions import Fraction as Q +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import re +import resource +import threading +import signal +import subprocess +import sys +import time + +SIDE=Path(__file__).resolve().parent +ROOT=SIDE.parents[1] +PACKAGE='companions/fold_affine_bridge_20261006' +WORKFLOW='.github/workflows/fold-affine-bridge.yml' +REPO='d6g8k5htny-coder/Math-' +BASE='34618d0d032f4361c1ec163f3b4cfd6ad01ab814' +CORE_TREE='d7422c6b1acbf3e20c75a1ed7fc13fc30125ec14' +CORE_GATE='958b149ea3a4ce735644a2079f817b5deddf5dc0d5ca347904ad09db6ad47d68' +CORE_MANIFEST='5d7ccdb0885af7bf4a2aa6ec4dce5f5c41435bb10a0a7a426a8af286d4f035e4' +DEFINITIONS=tuple('FoldAffineBridge.'+n for n in ('affinePotential','plusPoint','minusPoint','physicalSeparation')) +TARGETS=tuple('FoldAffineBridge.'+n for n in ( + 'fold_hasDerivAt','fold_deriv','fold_second','fold_critical','fold_nondegenerate','fold_curvature', + 'affine_hasDerivAt','affine_deriv','affine_hasDerivAt_deriv','affine_second','affine_coordinates', + 'affine_critical','affine_orientation','affine_distinct','affine_curvature','affine_nondegenerate', + 'affine_curvature_sign','separation_eq','separation_nonneg','separation_zero','affine_signed_gap', + 'affine_absolute_gap','affine_increments','affine_local_signs','affine_zero_degenerate', + 'affine_zero_increment','affine_zero_crossing','affine_constant_a','affine_constant_c')) +CONTROLS=('RejectMissingScale','RejectZeroNondegenerate','RejectSignedCurvature') +PAYLOADS={PACKAGE+'/'+n for n in ('FoldAffineBridge.lean','Contract.lean','README.md','replay.py','test_contract.py')}|{WORKFLOW} + +def require(ok,message): + if not ok:raise ValueError(message) + +def strict_json(raw): + def pairs(items): + result={} + for k,v in items: + require(k not in result,'duplicate JSON key');result[k]=v + return result + def reject(value):raise ValueError('nonfinite JSON number: '+value) + return json.loads(raw,object_pairs_hook=pairs,parse_constant=reject) + +def identity(raw): + return {'bytes':len(raw),'sha256':hashlib.sha256(raw).hexdigest(), + 'git_blob':hashlib.sha1(b'blob %d\0'%len(raw)+raw).hexdigest()} + +def validate_metadata(meta): + require(type(meta) is dict and set(meta)=={'version','scientific_effect','core_tree','targets','definitions','files'},'metadata schema') + require(type(meta['version']) is int and meta['version']==1,'metadata version') + require(meta['scientific_effect']=='NONE' and meta['core_tree']==CORE_TREE,'metadata scope') + require(meta['targets']==list(TARGETS) and meta['definitions']==list(DEFINITIONS),'declaration inventory') + require(type(meta['files']) is dict and set(meta['files'])==PAYLOADS,'file inventory') + for name,item in meta['files'].items(): + require(type(item) is dict and set(item)=={'bytes','sha256','git_blob'},'file identity schema: '+name) + require(type(item['bytes']) is int and item['bytes']>=0,'byte count') + require(type(item['sha256']) is str and re.fullmatch('[0-9a-f]{64}',item['sha256']) is not None,'sha256') + require(type(item['git_blob']) is str and re.fullmatch('[0-9a-f]{40}',item['git_blob']) is not None,'git blob') + +def git(*args): + return subprocess.run(['git',*args],cwd=ROOT,check=True,capture_output=True,text=True,timeout=30).stdout.strip() + +def source(): + meta=strict_json((SIDE/'SOURCE_FILES.json').read_bytes());validate_metadata(meta) + head=git('rev-parse','HEAD') + require(git('rev-parse',head+':formal')==CORE_TREE,'primary formal tree changed') + require(identity((ROOT/'formal/gate.py').read_bytes())['sha256']==CORE_GATE,'core gate changed') + require(identity((ROOT/'formal/manifest.json').read_bytes())['sha256']==CORE_MANIFEST,'core manifest changed') + expected=PAYLOADS|{PACKAGE+'/SOURCE_FILES.json'} + require(set(git('ls-tree','-r','--name-only',head,'--',PACKAGE).splitlines())|{WORKFLOW}==expected,'tracked membership') + ids={} + for name in sorted(expected): + path=ROOT/name + require(not any(p.is_symlink() for p in (path,*path.parents)),'symlink source: '+name) + ids[name]=identity(path.read_bytes()) + require(ids[name]['git_blob']==git('rev-parse',head+':'+name),'dirty source: '+name) + if name in PAYLOADS:require(ids[name]==meta['files'][name],'source identity: '+name) + git('diff','--exit-code','HEAD','--','formal',PACKAGE,WORKFLOW) + if os.environ.get('GITHUB_ACTIONS')=='true': + require(os.environ.get('GITHUB_SHA')==head and os.environ.get('GITHUB_REPOSITORY')==REPO,'host/source mismatch') + require(os.environ.get('GITHUB_RUN_ID') and os.environ.get('GITHUB_RUN_ATTEMPT'),'missing run identity') + return {'repository':REPO,'checked_commit':head,'core_tree':CORE_TREE,'sources':ids, + 'targets':list(TARGETS),'definitions':list(DEFINITIONS),'scientific_effect':'NONE', + 'run_id':os.environ.get('GITHUB_RUN_ID','local'),'run_attempt':os.environ.get('GITHUB_RUN_ATTEMPT','local')} + +def validate_negative(label,status,stdout,stderr): + require(label in CONTROLS,'unknown control') + require(type(status) is int and status==1,'negative exit must be exactly one') + require(stderr==b'','negative stderr') + pattern=rb'(?:[^\r\n]*[/\\])?'+label.encode()+rb'\.lean:[0-9]+:[0-9]+: error: unsolved goals\s*\n\xe2\x8a\xa2 False\s*' + require(re.fullmatch(pattern,stdout) is not None,'not the intended named False-goal diagnostic') + return label + +def parse_proc_stat(text,ticks,page_size): + prefix,separator,tail=text.rpartition(')') + require(bool(separator),'malformed proc stat') + pid,comm=prefix.split(' (',1);fields=tail.split() + require(len(fields)>=22,'short proc stat') + return {'pid':int(pid),'name':comm,'process_group':int(fields[2]),'start_ticks':int(fields[19]), + 'user_cpu_seconds':int(fields[11])/ticks,'system_cpu_seconds':int(fields[12])/ticks, + 'rss_kib':max(0,int(fields[21]))*page_size//1024} + +def read_process_group(group): + items=[];unreadable=0 + ticks=os.sysconf('SC_CLK_TCK');page_size=os.sysconf('SC_PAGE_SIZE') + for path in Path('/proc').iterdir(): + if not path.name.isdecimal():continue + try:item=parse_proc_stat((path/'stat').read_text(),ticks,page_size) + except (FileNotFoundError,ProcessLookupError):continue + except PermissionError:unreadable+=1;continue + if item['process_group']!=group:continue + try: + match=re.search(r'^VmHWM:\s+([0-9]+)\s+kB$',(path/'status').read_text(),re.M) + item['hwm_kib']=int(match.group(1)) if match else None + except (FileNotFoundError,ProcessLookupError):item['hwm_kib']=None + items.append(item) + return {'processes':items,'unreadable_stat_entries':unreadable} + +def run_process(out,label,argv,timeout=600,require_success=True,cwd=ROOT,env=None, + capture_resources=False,resource_interval=.5): + require(resource_interval>0,'resource interval must be positive') + started=time.monotonic();timed_out=False + usage_before=resource.getrusage(resource.RUSAGE_CHILDREN) if capture_resources else None + process=subprocess.Popen(argv,cwd=cwd,env=env,stdout=subprocess.PIPE,stderr=subprocess.PIPE,start_new_session=True) + stop=threading.Event();samples=[];capture_errors=[] + def monitor(): + try: + with (out/(label+'.resources.jsonl')).open('w') as stream: + while True: + sample={'elapsed_seconds':round(time.monotonic()-started,6),**read_process_group(process.pid)} + stream.write(json.dumps(sample,sort_keys=True)+'\n');stream.flush();samples.append(sample) + if stop.wait(resource_interval):break + except Exception as error:capture_errors.append(repr(error)) + worker=threading.Thread(target=monitor,name='bounded-resource-sampler',daemon=True) if capture_resources else None + if worker:worker.start() + try: + try:stdout,stderr=process.communicate(timeout=timeout) + except subprocess.TimeoutExpired: + timed_out=True;os.killpg(process.pid,signal.SIGKILL);stdout,stderr=process.communicate() + finally: + if worker:stop.set();worker.join() + (out/(label+'.stdout')).write_bytes(stdout);(out/(label+'.stderr')).write_bytes(stderr) + record={'argv':argv,'exit_code':process.returncode,'timed_out':timed_out,'seconds':round(time.monotonic()-started,6)} + if capture_resources: + after=resource.getrusage(resource.RUSAGE_CHILDREN);seen={} + for sample in samples: + for item in sample['processes']: + key=(item['pid'],item['start_ticks']);old=seen.get(key,{'user_cpu_seconds':0,'system_cpu_seconds':0}) + seen[key]={'user_cpu_seconds':max(old['user_cpu_seconds'],item['user_cpu_seconds']), + 'system_cpu_seconds':max(old['system_cpu_seconds'],item['system_cpu_seconds'])} + summary={'observations_only':True,'sample_interval_seconds':resource_interval,'sample_count':len(samples), + 'capture_error':'; '.join(capture_errors) if capture_errors else None, + 'observed_peak_group_rss_sum_kib':max((sum(p['rss_kib'] for p in v['processes']) for v in samples),default=0), + 'observed_peak_process_hwm_kib':max((p['hwm_kib'] or 0 for v in samples for p in v['processes']),default=0), + 'observed_process_cpu_user_seconds':sum(v['user_cpu_seconds'] for v in seen.values()), + 'observed_process_cpu_system_seconds':sum(v['system_cpu_seconds'] for v in seen.values()), + 'children_user_cpu_delta_seconds':after.ru_utime-usage_before.ru_utime, + 'children_system_cpu_delta_seconds':after.ru_stime-usage_before.ru_stime, + 'children_cumulative_maxrss_before_kib':usage_before.ru_maxrss, + 'children_cumulative_maxrss_after_kib':after.ru_maxrss, + 'limits':'Samples can miss fast/exited processes or final peaks; group RSS sums may double-count shared pages. Child CPU deltas may exclude unreaped descendants on forced kill. Cumulative maxrss is not the checker-only peak.'} + (out/(label+'.resources.json')).write_text(json.dumps(summary,sort_keys=True,indent=2)+'\n') + record['resource_capture_error']=summary['capture_error'] + (out/(label+'.status.json')).write_text(json.dumps(record,sort_keys=True,indent=2)+'\n') + sys.stdout.buffer.write(stdout);sys.stderr.buffer.write(stderr) + if timed_out:raise RuntimeError(label+' timed out') + if require_success and process.returncode!=0:raise RuntimeError(label+' exit '+str(process.returncode)) + if capture_errors:raise RuntimeError(label+' resource capture failed: '+str(capture_errors)) + return process.returncode + +def rational_controls(): + def f(s,x):return -x**3/3+s*s*x + cases=0 + for s in map(Q,[-2,-1,0,1,2]): + for a in map(Q,[-3,-2,-1,1,2,3]): + for b in map(Q,[-2,0,3]): + for c in map(Q,[-3,-1,0,1,3]): + p=(s-b)/a;m=(-s-b)/a;r=2*abs(s)/abs(a) + gap=c*f(s,a*p+b)-c*f(s,a*m+b) + require(abs(p-m)==r and abs(gap)==abs(c)*abs(a)**3*r**3/6,'rational affine gap') + require(gap==c*(2*s)**3/6,'signed gap') + require((p==m)==(s==0),'degenerate points') + for h in (Q(-1,5),Q(1,7)): + gp=c*(f(s,a*(p+h)+b)-f(s,a*p+b)) + gm=c*(f(s,a*(m+h)+b)-f(s,a*m+b)) + require(gp==-c*(a*h)**2*(s+a*h/3) and gm==c*(a*h)**2*(s-a*h/3),'increments') + if s and c and abs(h)0,'local signs') + if s==0 and c: + require(gp*c*(f(s,a*(p-h)+b)-f(s,a*p+b))<0,'zero crossing') + cases+=1 + return {'cases':cases,'failed':0,'reference':{'separation':'1','absolute_gap':'4'},'kernel_evidence':False} + +def emit(out): + names=DEFINITIONS+TARGETS + (out/'Audit.lean').write_text('import FoldAffineBridge\n'+'\n'.join('#print axioms '+n for n in names)+'\n') + (out/'Types.lean').write_text('import FoldAffineBridge\nset_option pp.explicit true\n'+'\n'.join('#check '+n for n in names)+'\n') + expressions={ + 'RejectMissingScale':('abs (affinePotential 1 2 0 3 (plusPoint 1 2 0)-affinePotential 1 2 0 3 (minusPoint 1 2 0)) = (1/6 : ℝ)', + 'norm_num [affinePotential, foldPotential, plusPoint, minusPoint]'), + 'RejectZeroNondegenerate':('deriv (deriv (foldPotential 0)) 0 ≠ 0','norm_num [fold_second]'), + 'RejectSignedCurvature':('deriv (deriv (foldPotential (-1))) (-1) < 0','norm_num [fold_second]')} + for label,(statement,tactic) in expressions.items(): + (out/(label+'.lean')).write_text('import FoldAffineBridge\nopen ResearchFormalCoreR1 FoldAffineBridge\nexample : '+statement+' := by\n '+tactic+'\n') + +def execute(out): + require(not out.exists(),'output already exists');out.mkdir(parents=True) + before=source();(out/'source.json').write_text(json.dumps(before,sort_keys=True,indent=2)+'\n') + emit(out) + run_process(out,'core-execute',[sys.executable,'-B','-S','formal/gate.py','--execute'],timeout=1200) + build=out/'build';build.mkdir() + env={**os.environ,'BQ_BUILD':str(build),'BQ_SIDE':str(SIDE)} + prefix=['lake','env','bash','-c','export LEAN_PATH="$BQ_BUILD:$BQ_SIDE:${LEAN_PATH:-}"; export LEAN_SRC_PATH="$BQ_SIDE:${LEAN_SRC_PATH:-}"; exec "$@"','--'] + def lean(label,args,success=True,timeout=600,capture_resources=False): + return run_process(out,label,prefix+args,timeout=timeout,require_success=success,cwd=ROOT/'formal',env=env,capture_resources=capture_resources) + lean('toolchain',['lean','--version']) + require((out/'toolchain.stdout').read_text().startswith('Lean (version 4.34.1,'),'wrong Lean version') + lean('build',['lean','-DwarningAsError=true','--root='+str(SIDE),'-o',str(build/'FoldAffineBridge.olean'),str(SIDE/'FoldAffineBridge.lean')]) + lean('contract',['lean','-DwarningAsError=true','--root='+str(SIDE),str(SIDE/'Contract.lean')]) + lean('axioms',['lean','-DwarningAsError=true','--root='+str(out),str(out/'Audit.lean')]) + lean('types',['lean','-DwarningAsError=true','--root='+str(out),str(out/'Types.lean')]) + lean('leanchecker',['leanchecker','--fresh','FoldAffineBridge'],timeout=1200,capture_resources=True) + for label in CONTROLS: + status=lean(label,['lean','-DwarningAsError=true','--root='+str(out),str(out/(label+'.lean'))],False) + validate_negative(label,status,(out/(label+'.stdout')).read_bytes(),(out/(label+'.stderr')).read_bytes()) + for mode,flags in [('normal',[]),('optimized',['-O'])]: + run_process(out,'companion-tests-'+mode,[sys.executable,'-B',*flags,'-S',str(SIDE/'test_contract.py')]) + for suite in ('tests','formal/tests'): + run_process(out,suite.replace('/','-')+'-'+mode,[sys.executable,'-B',*flags,'-S','-m','unittest','discover','-s',suite,'-v']) + require(source()==before,'source changed during execution') + gate_path=ROOT/'formal/gate.py' + require(identity(gate_path.read_bytes())['sha256']==CORE_GATE,'core audit changed') + spec=importlib.util.spec_from_file_location('unchanged_core_gate',gate_path) + gate=importlib.util.module_from_spec(spec);spec.loader.exec_module(gate) + axioms=gate.audit_axioms((out/'axioms.stdout').read_text(),list(DEFINITIONS+TARGETS)) + require((out/'axioms.stderr').read_bytes()==b'' and (out/'types.stderr').read_bytes()==b'','audit diagnostic stderr') + text=(out/'types.stdout').read_text() + require('error:' not in text and 'warning:' not in text,'type diagnostic') + require(re.findall(r'^FoldAffineBridge\.[A-Za-z][A-Za-z0-9_]*',text,re.M)==list(DEFINITIONS+TARGETS),'type inventory') + raw=(ROOT/'formal/.lake/formal-evidence/receipt.json').read_bytes();core=strict_json(raw) + require(core['checked_commit']==before['checked_commit'] and core['manifest_sha256']==CORE_MANIFEST,'core receipt identity') + require(core['formalization_status']=='kernel-checked','no core kernel receipt') + result={**before,'axioms':axioms,'core_receipt_sha256':identity(raw)['sha256'], + 'formalization_status':'kernel-checked','alignment_status':'PENDING_INDEPENDENT_REVIEW', + 'scientific_acceptance':False,'logs':{p.name:identity(p.read_bytes()) for p in sorted(out.iterdir()) if p.is_file()}} + (out/'receipt.json').write_text(json.dumps(result,sort_keys=True,indent=2)+'\n') + return result + +def main(): + ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('command',choices=('source','controls','execute')) + ap.add_argument('--out',type=Path,default=ROOT/'.lake/fold-affine-bridge-evidence');a=ap.parse_args() + result=source() if a.command=='source' else rational_controls() if a.command=='controls' else execute(a.out.resolve()) + print(json.dumps(result,sort_keys=True,indent=2)) +if __name__=='__main__':main() diff --git a/companions/fold_affine_bridge_20261006/test_contract.py b/companions/fold_affine_bridge_20261006/test_contract.py new file mode 100644 index 000000000..b9bab675d --- /dev/null +++ b/companions/fold_affine_bridge_20261006/test_contract.py @@ -0,0 +1,145 @@ +"""Bounded driver tests and exact rational supplements; not kernel evidence.""" +import importlib.util +import json +import inspect +from pathlib import Path +import sys +import tempfile +import unittest + +SIDE = Path(__file__).resolve().parent +if (SIDE/'replay.py').exists(): + spec=importlib.util.spec_from_file_location('fold_replay', SIDE/'replay.py') + replay=importlib.util.module_from_spec(spec);spec.loader.exec_module(replay) +else: + replay=None + +class DriverTest(unittest.TestCase): + def api(self,name): + self.assertIsNotNone(replay,'bounded replay driver is missing') + self.assertTrue(callable(getattr(replay,name,None)), 'missing driver behavior '+name) + return getattr(replay,name) + + def test_proc_stat_accounting_fields(self): + fn=self.api('parse_proc_stat') + fields=['S','1','77','77','0','0','0','0','0','0','0','10','5','0','0','20','0','1','0','123','4096','7'] + got=fn('88 (name with ) spaces) '+' '.join(fields),100,4096) + self.assertEqual(got['pid'],88);self.assertEqual(got['process_group'],77) + self.assertEqual(got['start_ticks'],123);self.assertEqual(got['rss_kib'],28) + self.assertEqual(got['user_cpu_seconds'],.1);self.assertEqual(got['system_cpu_seconds'],.05) + + def test_resource_capture_normal_and_fast_exit(self): + fn=self.api('run_process') + self.assertIn('capture_resources',inspect.signature(fn).parameters) + for label,body in [('normal','import time; a=bytearray(8*1024*1024); time.sleep(.2)'),('fast','pass')]: + with self.subTest(label=label),tempfile.TemporaryDirectory() as d: + out=Path(d);fn(out,label,[sys.executable,'-c',body],timeout=3,capture_resources=True,resource_interval=.02) + data=json.loads((out/(label+'.resources.json')).read_text()) + self.assertTrue(data['observations_only']);self.assertGreaterEqual(data['sample_count'],1) + self.assertIsNone(data['capture_error']);self.assertGreaterEqual(data['children_user_cpu_delta_seconds'],0) + if label=='normal':self.assertGreater(data['observed_peak_group_rss_sum_kib'],0) + + def test_resource_capture_timeout_retains_partial(self): + fn=self.api('run_process') + self.assertIn('capture_resources',inspect.signature(fn).parameters) + with tempfile.TemporaryDirectory() as d: + out=Path(d) + with self.assertRaisesRegex(RuntimeError,'timed out'): + fn(out,'limit',[sys.executable,'-u','-c','import time; a=bytearray(8*1024*1024); print("ready"); time.sleep(10)'],timeout=.2,capture_resources=True,resource_interval=.02) + data=json.loads((out/'limit.resources.json').read_text()) + self.assertGreater(data['sample_count'],0);self.assertGreater(data['observed_peak_group_rss_sum_kib'],0) + self.assertTrue(json.loads((out/'limit.status.json').read_text())['timed_out']) + self.assertIn(b'ready', (out/'limit.stdout').read_bytes()) + self.assertGreater(len((out/'limit.resources.jsonl').read_bytes()),0) + + def test_absolute_value_token_spacing(self): + for name in ('FoldAffineBridge.lean','Contract.lean'): + with self.subTest(name=name): + self.assertNotIn('|*',(SIDE/name).read_text(), 'absolute-value close must not form the Lean |* token') + + def test_strict_json_accepts_object(self): + self.assertEqual(self.api('strict_json')('{"x":1}'), {'x':1}) + + def test_strict_json_rejects_duplicates(self): + fn=self.api('strict_json') + for raw in ['{"x":1,"x":2}', '{"a":{"x":1,"x":1}}']: + with self.subTest(raw=raw),self.assertRaisesRegex(ValueError,'duplicate'): + fn(raw) + + def test_strict_json_rejects_nonfinite(self): + fn=self.api('strict_json') + for value in ['NaN','Infinity','-Infinity']: + with self.subTest(value=value),self.assertRaises(ValueError):fn(value) + + def test_identity(self): + self.assertEqual(self.api('identity')(b'hello\n'), + {'bytes':6,'sha256':'5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03', + 'git_blob':'ce013625030ba8dba906f756967f9e9ca394464a'}) + + def test_negative_exact_reason(self): + fn=self.api('validate_negative') + for label in ('RejectMissingScale','RejectZeroNondegenerate','RejectSignedCurvature'): + raw=f'/tmp/build/{label}.lean:3:2: error: unsolved goals\n⊢ False\n'.encode() + self.assertEqual(fn(label,1,raw,b''),label) + + def test_negative_refuses_other_failures(self): + fn=self.api('validate_negative');label='RejectMissingScale' + good=f'{label}.lean:3:2: error: unsolved goals\n⊢ False\n'.encode() + for code,out,err in [(0,good,b''),(2,good,b''),(True,good,b''), + (1,b'unknown module prefix FoldAffineBridge\n',b''), + (1,good,b'unrelated error'),(1,b'crash\n'+good,b''), + (1,good.replace(b'RejectMissingScale',b'Other'),b''), + (1,good.replace(b'False',b'True'),b''),(1,b'',b''), + (1,good+good,b'')]: + with self.subTest(code=code,out=out,err=err),self.assertRaises(ValueError): + fn(label,code,out,err) + + def test_negative_refuses_unknown_label(self): + fn=self.api('validate_negative') + with self.assertRaises(ValueError):fn('Other',1,b'',b'') + + def test_metadata_strict_scope(self): + fn=self.api('validate_metadata') + meta={'version':1,'scientific_effect':'NONE','core_tree':replay.CORE_TREE, + 'targets':list(replay.TARGETS),'definitions':list(replay.DEFINITIONS), + 'files':{p:{'bytes':0,'sha256':'0'*64,'git_blob':'0'*40} for p in replay.PAYLOADS}} + fn(meta) + for key,value in [('version',True),('scientific_effect','ACCEPTED'),('core_tree','0'*40), + ('targets',[]),('definitions',[]),('files',{})]: + bad={**meta,key:value} + with self.subTest(key=key),self.assertRaises(ValueError):fn(bad) + with self.assertRaises(ValueError):fn({**meta,'extra':1}) + + def test_process_preserves_both_streams_and_status(self): + fn=self.api('run_process') + with tempfile.TemporaryDirectory() as d: + out=Path(d) + code=fn(out,'child',[sys.executable,'-c','import sys; print("one"); print("two",file=sys.stderr); sys.exit(7)'],timeout=3,require_success=False) + self.assertEqual(code,7) + self.assertEqual((out/'child.stdout').read_bytes(),b'one\n') + self.assertEqual((out/'child.stderr').read_bytes(),b'two\n') + record=json.loads((out/'child.status.json').read_text()) + self.assertEqual(record['exit_code'],7);self.assertFalse(record['timed_out']) + + def test_process_failure_does_not_pass(self): + fn=self.api('run_process') + with tempfile.TemporaryDirectory() as d: + with self.assertRaisesRegex(RuntimeError,'exit 7'): + fn(Path(d),'fail',[sys.executable,'-c','raise SystemExit(7)'],timeout=3) + self.assertEqual(json.loads((Path(d)/'fail.status.json').read_text())['exit_code'],7) + + def test_timeout_is_preserved_and_not_negative_success(self): + fn=self.api('run_process') + with tempfile.TemporaryDirectory() as d: + with self.assertRaisesRegex(RuntimeError,'timed out'): + fn(Path(d),'slow',[sys.executable,'-u','-c','import time; print("started"); time.sleep(10)'],timeout=.1,require_success=False) + self.assertTrue(json.loads((Path(d)/'slow.status.json').read_text())['timed_out']) + self.assertIn(b'started', (Path(d)/'slow.stdout').read_bytes()) + + def test_exact_rational_signed_controls(self): + result=self.api('rational_controls')() + self.assertEqual(result['reference'],{'separation':'1','absolute_gap':'4'}) + self.assertGreater(result['cases'],100) + self.assertEqual(result['failed'],0) + +if __name__=='__main__':unittest.main()