From cc0935141300c08d1cdd013c116a8e98f2087898 Mon Sep 17 00:00:00 2001 From: Devon Tuma Date: Tue, 17 Nov 2026 20:12:22 -0600 Subject: [PATCH 1/5] feat(pfunctor): extend expected charge to unbounded resumptions Take the supremum over finite query prefixes with zero credit at cutoffs. Use the continuous query algebra to prove sequencing, agreement with finite programs, and transfer of potential bounds. Co-Authored-By: Codex --- PolyFun.lean | 1 + .../Resumption/Measure/ExpectedCharge.lean | 193 ++++++++++++++++++ PolyFunTest/Probability/ResumptionCharge.lean | 105 ++++++++++ docs/guides/cost.md | 14 ++ docs/reference/repo-map.md | 2 +- .../PolyFunDocumentationConsumer.lean | 26 +++ 6 files changed, 340 insertions(+), 1 deletion(-) create mode 100644 PolyFun/PFunctor/Resumption/Measure/ExpectedCharge.lean create mode 100644 PolyFunTest/Probability/ResumptionCharge.lean diff --git a/PolyFun.lean b/PolyFun.lean index df64b33b..5040e806 100644 --- a/PolyFun.lean +++ b/PolyFun.lean @@ -484,6 +484,7 @@ public import PolyFun.PFunctor.Resumption.Domain public import PolyFun.PFunctor.Resumption.DomainLaws public import PolyFun.PFunctor.Resumption.DomainTruncate public import PolyFun.PFunctor.Resumption.Empty +public import PolyFun.PFunctor.Resumption.Measure.ExpectedCharge public import PolyFun.PFunctor.Resumption.Truncate public import PolyFun.PFunctor.Resumption.WellFounded public import PolyFun.PFunctor.Slice diff --git a/PolyFun/PFunctor/Resumption/Measure/ExpectedCharge.lean b/PolyFun/PFunctor/Resumption/Measure/ExpectedCharge.lean new file mode 100644 index 00000000..c2c2142a --- /dev/null +++ b/PolyFun/PFunctor/Resumption/Measure/ExpectedCharge.lean @@ -0,0 +1,193 @@ +/- +Copyright (c) 2026 PolyFun Contributors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Devon Tuma +-/ + +module + +public import PolyFun.PFunctor.Free.Measure.StatefulExpectedCharge +public import PolyFun.PFunctor.Resumption.DomainTruncate +public import PolyFun.PFunctor.Resumption.DomainLaws + +/-! +# Expected charges of resumptions + +A resumption can accumulate charges without returning. Folding its finite query prefixes and +then taking their supremum retains each incurred charge. A cutoff receives zero terminal credit. +The step equation follows by monotone convergence on the joint answer-and-state kernel. +-/ + +public section + +open MeasureTheory ProbabilityTheory OmegaCompletePartialOrder +open scoped ENNReal + +namespace PFunctor.Resumption + +universe uA uB uS uR + +variable {P : PFunctor.{uA, uB}} {S : Type uS} {α : Type uR} + [∀ a, MeasurableSpace (P.B a)] [MeasurableSpace S] + (K : KernelHandler P S) (c : P.A → S → ℝ≥0∞) + +/-- Expected incurred charge plus terminal credit on returned results. -/ +@[expose] noncomputable def expectedCharge (tree : Resumption P α) (post : α → S → ℝ≥0∞) + (s : S) : ℝ≥0∞ := + ⨆ n, FreeM.wpFold (OpSpec.statefulExpectedCharge K c) (truncate n tree) + (fun result => result.elim (fun _ => 0) post) s + +theorem expectedCharge_eq_iSup (tree : Resumption P α) (post : α → S → ℝ≥0∞) (s : S) : + expectedCharge K c tree post s = ⨆ n, + FreeM.wpFold (OpSpec.statefulExpectedCharge K c) (truncate n tree) + (fun result => result.elim (fun _ => 0) post) s := rfl + +@[simp] theorem expectedCharge_pure (x : α) (post : α → S → ℝ≥0∞) : + expectedCharge K c (pure x) post = post x := by + funext s + simp [expectedCharge_eq_iSup] + +/-- Increasing prefix depth increases the expected cost and nonnegative terminal credit. -/ +theorem monotone_wpFold_expectedCharge_truncate (tree : Resumption P α) (post : α → S → ℝ≥0∞) : + Monotone fun n => FreeM.wpFold (OpSpec.statefulExpectedCharge K c) (truncate n tree) + (fun result => result.elim (fun _ => 0) post) := by + apply monotone_nat_of_le_succ + intro n + induction n generalizing tree with + | zero => + rw [truncate_zero, truncate_succ] + rcases dest tree with x | ⟨a, next⟩ + · rfl + · exact fun _ => bot_le + | succ n ih => + rw [truncate_succ, truncate_succ (n + 1)] + rcases dest tree with x | ⟨a, next⟩ + · rfl + · simp only [FreeM.wpFold_liftBind] + intro s + simp only [OpSpec.statefulExpectedCharge_apply] + exact add_le_add_right (lintegral_mono fun z : P.B a × S => ih (next z.1) z.2) _ + +/-- A per-operation potential bounds incurred costs through the limit. Unfinished prefixes +carry zero terminal credit, so their nonnegative residual potential may be discarded. -/ +theorem expectedCharge_le_of_potential (d : P.A → S → ℝ≥0∞) (I : S → Prop) + (V : S → ℝ≥0∞) (hV : Measurable V) (hI : ∀ a s, I s → ∀ᵐ z ∂K a s, I z.2) + (hstep : ∀ a s, I s → d a s + ∫⁻ z, V z.2 ∂K a s ≤ c a s + V s) + (tree : Resumption P α) (post : α → S → ℝ≥0∞) {s : S} (hs : I s) : + expectedCharge K d tree (fun r t => post r t + V t) s ≤ + expectedCharge K c tree post s + V s := by + rw [expectedCharge_eq_iSup] + apply iSup_le + intro n + let f (r : Option α) := r.elim (fun _ : S => (0 : ℝ≥0∞)) post + refine le_trans ?_ ((FreeM.wpFold_statefulExpectedCharge_le_of_potential K c d I V hV hI + hstep (truncate n tree) f hs).trans (add_le_add_left ?_ _)) + · apply FreeM.wpFold_mono (OpSpec.statefulExpectedCharge_mono K d) _ _ s + rintro (_ | r) t + · exact bot_le + · rfl + · exact le_iSup + (fun m => FreeM.wpFold (OpSpec.statefulExpectedCharge K c) (truncate m tree) f s) n + +variable [∀ a, Countable (P.B a)] [∀ a, MeasurableSingletonClass (P.B a)] + +/-- Nonnegative measurable functions of the private state, ordered pointwise. -/ +abbrev MeasurableExpectation (S : Type*) [MeasurableSpace S] := {f : S → ℝ≥0∞ // Measurable f} + +noncomputable instance MeasurableExpectation.instOmegaCompletePartialOrder : + OmegaCompletePartialOrder (MeasurableExpectation S) := + OmegaCompletePartialOrder.subtype _ fun f hf => + Measurable.iSup fun n => hf (f n) ⟨n, rfl⟩ + +instance MeasurableExpectation.instOrderBot : OrderBot (MeasurableExpectation S) where + bot := ⟨fun _ => 0, measurable_const⟩ + bot_le _ _ := bot_le + +/-- The continuous query algebra for incurred costs and joint state transitions. -/ +@[expose] noncomputable def statefulExpectedChargeAlgebra (hc : ∀ a, Measurable (c a)) : + ContinuousAlgebra P (MeasurableExpectation S) := + fun a => .ofFun (fun k => ⟨OpSpec.statefulExpectedCharge K c a (fun b => (k b).1), + (hc a).add (measurable_from_prod_countable_right fun b => (k b).2).lintegral_kernel⟩) (by + refine ωScottContinuous.of_monotone_map_ωSup ⟨?_, ?_⟩ + · intro f g h s + exact add_le_add_right (lintegral_mono fun z : P.B a × S => h z.1 z.2) _ + · intro ch + apply Subtype.ext + funext s + change (c a s + ∫⁻ z, ⨆ n, ((ch n) z.1).1 z.2 ∂K a s) = + ⨆ n, c a s + ∫⁻ z, ((ch n) z.1).1 z.2 ∂K a s + rw [lintegral_iSup, ENNReal.add_iSup] + · exact fun n => measurable_from_prod_countable_right fun b => ((ch n) b).2 + · exact fun i j h z => ch.monotone h z.1 z.2) + +@[simp] theorem statefulExpectedChargeAlgebra_apply (hc : ∀ a, Measurable (c a)) (a : P.A) + (k : P.B a → MeasurableExpectation S) (s : S) : + (statefulExpectedChargeAlgebra K c hc a k).1 s = + c a s + ∫⁻ z, (k z.1).1 z.2 ∂K a s := by + exact OpSpec.statefulExpectedCharge_apply K c a (fun b => (k b).1) s + +private theorem foldAlg_eq (hc : ∀ a, Measurable (c a)) {β : Type*} + (ret : β → MeasurableExpectation S) (x : FreeM P β) : + (FreeM.foldFreeM ret (fun a => statefulExpectedChargeAlgebra K c hc a) x).1 = + FreeM.wpFold (OpSpec.statefulExpectedCharge K c) x (fun b => (ret b).1) := by + induction x with + | pure x => simp + | lift_bind a next ih => + change (FreeM.foldFreeM ret (fun a => statefulExpectedChargeAlgebra K c hc a) + (FreeM.liftBind a next)).1 = + FreeM.wpFold _ (FreeM.liftBind a next) _ + rw [FreeM.foldFreeM_liftBind, FreeM.wpFold_liftBind] + exact congrArg (OpSpec.statefulExpectedCharge K c a) (funext ih) + +/-- Prefix expectations compute the least continuous-algebra interpretation of the tree. -/ +theorem expectedCharge_eq_denote (hc : ∀ a, Measurable (c a)) (tree : Resumption P α) + (post : α → S → ℝ≥0∞) (hpost : ∀ x, Measurable (post x)) : + expectedCharge K c tree post = + (denote (fun x => ⟨post x, hpost x⟩) (statefulExpectedChargeAlgebra K c hc) tree).1 := by + rw [denote_eq_ωSup] + funext s + unfold expectedCharge + congr 1 + funext n + change _ = (FreeM.foldFreeM (fun r : Option α => r.elim ⊥ (fun x => ⟨post x, hpost x⟩)) + (fun a => statefulExpectedChargeAlgebra K c hc a) (truncate n tree)).1 s + rw [foldAlg_eq] + apply congrArg (fun q => FreeM.wpFold (OpSpec.statefulExpectedCharge K c) (truncate n tree) q s) + funext r + cases r <;> rfl + +/-- The expected cost-to-go from a state is measurable. -/ +theorem measurable_expectedCharge (hc : ∀ a, Measurable (c a)) (tree : Resumption P α) + (post : α → S → ℝ≥0∞) (hpost : ∀ x, Measurable (post x)) : + Measurable (expectedCharge K c tree post) := by + rw [expectedCharge_eq_denote K c hc tree post hpost] + exact Subtype.property _ + +/-- A request contributes its charge immediately, including when its kernel has zero mass. -/ +theorem expectedCharge_query (hc : ∀ a, Measurable (c a)) (a : P.A) + (next : P.B a → Resumption P α) (post : α → S → ℝ≥0∞) (hpost : ∀ x, Measurable (post x)) + (s : S) : expectedCharge K c (query a next) post s = + c a s + ∫⁻ z, expectedCharge K c (next z.1) post z.2 ∂K a s := by + simp only [expectedCharge_eq_denote K c hc _ post hpost, denote_query] + rfl + +/-- On a well-founded tree, the finite program's fold gives its entire expected charge. -/ +theorem expectedCharge_toResumption (hc : ∀ a, Measurable (c a)) (x : FreeM P α) + (post : α → S → ℝ≥0∞) (hpost : ∀ y, Measurable (post y)) : + expectedCharge K c (FreeM.toResumption x) post = + FreeM.wpFold (OpSpec.statefulExpectedCharge K c) x post := by + rw [expectedCharge_eq_denote K c hc _ post hpost, denote_toResumption, foldAlg_eq] + +/-- Sequencing a resumption substitutes the exact expected cost of its continuation. -/ +theorem expectedCharge_bind (hc : ∀ a, Measurable (c a)) {β : Type*} (tree : Resumption P α) + (next : α → Resumption P β) (post : β → S → ℝ≥0∞) (hpost : ∀ y, Measurable (post y)) : + expectedCharge K c (bind tree next) post = + expectedCharge K c tree (fun x => expectedCharge K c (next x) post) := by + rw [expectedCharge_eq_denote K c hc _ post hpost, denote_bind, + expectedCharge_eq_denote K c hc _ _ + (fun x => measurable_expectedCharge K c hc (next x) post hpost)] + congr 2 + funext x + exact Subtype.ext (expectedCharge_eq_denote K c hc (next x) post hpost).symm + +end PFunctor.Resumption diff --git a/PolyFunTest/Probability/ResumptionCharge.lean b/PolyFunTest/Probability/ResumptionCharge.lean new file mode 100644 index 00000000..1e7c6bc9 --- /dev/null +++ b/PolyFunTest/Probability/ResumptionCharge.lean @@ -0,0 +1,105 @@ +/- +Copyright (c) 2026 PolyFun Contributors. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Devon Tuma +-/ + +module + +public import PolyFun.PFunctor.Resumption.Measure.ExpectedCharge + +/-! +# Incurred charges on an infinite sequence of requests + +The same deterministic client can pay a finite setup cost or an infinite per-request bill. +Even infinite terminal credit has no effect on this client because it never returns. +-/ + +public section + +open PFunctor PFunctor.Resumption MeasureTheory ProbabilityTheory +open scoped ENNReal + +namespace PolyFunTest.Probability.ResumptionCharge + +/-- The interface of the repeated unit request. -/ +abbrev Tick : PFunctor.{0, 0} := ⟨Unit, fun _ => Unit⟩ + +private noncomputable def ticks : Resumption Tick Unit := + Resumption.corec (fun _ : Unit => .inr ⟨(), fun _ => ()⟩) () + +private theorem ticks_unfold : ticks = query () (fun _ => ticks) := by + apply Resumption.eq_of_dest_eq + rw [dest_query] + simp [ticks, PFunctor.map] + rfl + +private noncomputable def service : KernelHandler Tick Bool := + KernelHandler.ofFun (fun _ _ => ((), true)) (fun _ => measurable_const) + +private noncomputable def setup (_ : Tick.A) (ready : Bool) : ℝ≥0∞ := + if ready then 0 else 1 + +private noncomputable def prefixCost (price : Tick.A → Bool → ℝ≥0∞) + (post : Unit → Bool → ℝ≥0∞) (n : ℕ) (s : Bool) : ℝ≥0∞ := + FreeM.wpFold (OpSpec.statefulExpectedCharge service price) (truncate n ticks) + (fun result => result.elim (fun _ => 0) post) s + +private theorem prefix_zero (price : Tick.A → Bool → ℝ≥0∞) (post : Unit → Bool → ℝ≥0∞) + (s : Bool) : prefixCost price post 0 s = 0 := by + rw [prefixCost, ticks_unfold, truncate_query_zero] + rfl + +private theorem prefix_succ (price : Tick.A → Bool → ℝ≥0∞) (post : Unit → Bool → ℝ≥0∞) + (n : ℕ) (s : Bool) : + prefixCost price post (n + 1) s = price () s + prefixCost price post n true := by + unfold prefixCost + conv_lhs => rw [ticks_unfold, truncate_query_succ, FreeM.wpFold_liftBind, + OpSpec.statefulExpectedCharge_apply (P := Tick) service price] + simp [service, KernelHandler.ofFun, Kernel.deterministic_apply] + +private theorem ready_prefix (post : Unit → Bool → ℝ≥0∞) (n : ℕ) : + prefixCost setup post n true = 0 := by + induction n with + | zero => exact prefix_zero .. + | succ n ih => simp [prefix_succ, setup, ih] + +/-- The first request costs one, subsequent requests are free, and no cutoff earns credit. -/ +example (post : Unit → Bool → ℝ≥0∞) : + expectedCharge service setup ticks post false = 1 := by + change (⨆ n, prefixCost setup post n false) = 1 + have h (n : ℕ) : prefixCost setup post (n + 1) false = 1 := by + simp [prefix_succ, ready_prefix, setup] + apply le_antisymm + · apply iSup_le + rintro (_ | n) + · simp [prefix_zero] + · exact (h n).le + · exact le_iSup_of_le 1 (h 0).ge + +/-- At one per request the finite prefixes cost exactly their depth, so the total is infinite. -/ +example (post : Unit → Bool → ℝ≥0∞) (s : Bool) : + expectedCharge service (fun _ _ => 1) ticks post s = ⊤ := by + change (⨆ n, prefixCost (fun _ _ => 1) post n s) = ⊤ + have h (n : ℕ) (t : Bool) : prefixCost (fun _ _ => 1) post n t = n := by + induction n generalizing t with + | zero => simp [prefix_zero] + | succ n ih => simp [prefix_succ, ih, Nat.cast_succ, add_comm] + simp [h, ENNReal.iSup_natCast] + +/-- A zero-mass request incurs its charge even when terminal credit is infinite. -/ +example (next : Unit → Resumption Tick Unit) : + expectedCharge (P := Tick) (fun _ => 0) (fun _ (_ : Unit) => 7) + (query () next) (fun _ _ => ⊤) () = 7 := by + rw [expectedCharge_query (P := Tick) (S := Unit) _ _ (fun _ => measurable_const) _ _ _ + (fun _ => measurable_const)] + simp + +/-- A finite program still receives its terminal credit at the state where it returns. -/ +example (program : FreeM Tick Unit) (post : Unit → Bool → ℝ≥0∞) : + expectedCharge service setup program.toResumption post = + FreeM.wpFold (OpSpec.statefulExpectedCharge service setup) program post := + expectedCharge_toResumption service setup (fun _ => Measurable.of_discrete) program post + (fun _ => Measurable.of_discrete) + +end PolyFunTest.Probability.ResumptionCharge diff --git a/docs/guides/cost.md b/docs/guides/cost.md index 9c7fa909..17acbcaf 100644 --- a/docs/guides/cost.md +++ b/docs/guides/cost.md @@ -328,6 +328,20 @@ call from earlier answers. For a setup cost shared across calls, use `FreeM.wpFold_statefulExpectedCharge_le_of_potential` with an invariant preserved almost surely and a measurable potential. See also the [measure fold](probability.md). +### Expected cost of an unbounded client + +`Resumption.expectedCharge K c tree post` takes the supremum of the expected charges of finite +truncations. A prefix earns `post` if it returns and zero terminal credit if it stops at a pending +request. This distinguishes two prices for the same infinite sequence of requests. If only the +first request costs one, the total is one. If every request costs one, the total is infinite. + +With countable answer spaces having measurable singletons, measurable prices, and measurable +terminal observations in the private state, `Resumption.expectedCharge_bind` prices a prefix +using the expected charge of its continuation as the terminal payoff. For a prefix embedded from +a finite program, `Resumption.expectedCharge_toResumption` then reduces the calculation to +`FreeM.wpFold`. The almost-sure invariant and local potential inequality used for a finite client +also bound a resumption through `Resumption.expectedCharge_le_of_potential`. + ## Layers and certified implementations A cost argument usually spans layers. A specification is priced by its calls, an algorithm diff --git a/docs/reference/repo-map.md b/docs/reference/repo-map.md index 3a94e7c4..84efeacf 100644 --- a/docs/reference/repo-map.md +++ b/docs/reference/repo-map.md @@ -64,7 +64,7 @@ Example and test imports never flow back into production. | Kernel handlers | [Kernel semantics of free programs](../../PolyFun/PFunctor/Free/Measure/Kernel.lean), [state invariants and projections](../../PolyFun/PFunctor/Free/Measure/Kernel/Transport.lean), [handler constructions](../../PolyFun/PFunctor/Free/Measure/Kernel/Handler.lean), [polynomial wiring](../../PolyFun/PFunctor/Wiring/Measure.lean) | [Probability](../guides/probability.md) | | Measure semantics of monads | [Output measures (`evalDist`)](../../PolyFun/Control/Monad/Measure.lean), [events](../../PolyFun/Control/Monad/Measure/Event.lean), [failure](../../PolyFun/Control/Monad/Measure/Failure.lean), [equality in distribution](../../PolyFun/Control/Monad/Measure/EvalDistEq.lean), [deterministic monads](../../PolyFun/Control/Monad/Measure/Deterministic.lean), [partial results](../../PolyFun/Control/Domain/Measure/EvalDist.lean), [free programs](../../PolyFun/PFunctor/Free/Measure/EvalDist.lean), [`OptionT`](../../PolyFun/Control/Monad/Measure/OptionT.lean), [`ExceptT`](../../PolyFun/Control/Monad/Measure/ExceptT.lean), [bundled semantics](../../PolyFun/Control/Monad/Measure/SemanticsVia.lean) | [Probability](../guides/probability.md) | | Couplings and relational program logic | [Couplings](../../ToCslib/MeasureTheory/Measure/Coupling.lean), [their composition](../../ToCslib/MeasureTheory/Measure/Coupling/Bind.lean), [relational judgments](../../PolyFun/Control/Monad/Measure/Relational.lean), [bind rules](../../PolyFun/Control/Monad/Measure/Relational/Bind.lean), [the coupling algebra](../../PolyFun/Control/Monad/Measure/Relational/Algebra.lean), [countable support](../../PolyFun/Control/Monad/Measure/Countable.lean) | [Probability](../guides/probability.md), [program logic](../guides/program-logic.md) | -| Expectations and expected charges | [Expectation algebras of free programs](../../PolyFun/PFunctor/Free/Measure/Expectation.lean), [their weakest-precondition readings](../../PolyFun/PFunctor/Free/Measure/WP.lean), [integration through the fold](../../PolyFun/PFunctor/Free/Measure/Lintegral.lean), [expectation algebras of monads](../../PolyFun/Control/Monad/Measure/Expectation.lean), [expected charges](../../PolyFun/PFunctor/Free/Measure/ExpectedCharge.lean), [stateful expected charges](../../PolyFun/PFunctor/Free/Measure/StatefulExpectedCharge.lean) | [Probability](../guides/probability.md), [program logic](../guides/program-logic.md#expectation-readings-of-free-programs), [interaction cost](../guides/cost.md) | +| Expectations and expected charges | [Expectation algebras of free programs](../../PolyFun/PFunctor/Free/Measure/Expectation.lean), [their weakest-precondition readings](../../PolyFun/PFunctor/Free/Measure/WP.lean), [integration through the fold](../../PolyFun/PFunctor/Free/Measure/Lintegral.lean), [expectation algebras of monads](../../PolyFun/Control/Monad/Measure/Expectation.lean), [expected charges](../../PolyFun/PFunctor/Free/Measure/ExpectedCharge.lean), [stateful expected charges](../../PolyFun/PFunctor/Free/Measure/StatefulExpectedCharge.lean), [expected charges of resumptions](../../PolyFun/PFunctor/Resumption/Measure/ExpectedCharge.lean) | [Probability](../guides/probability.md), [program logic](../guides/program-logic.md#expectation-readings-of-free-programs), [interaction cost](../guides/cost.md) | | Uniform measures and uniform draws | [Uniform measures](../../ToCslib/Probability/UniformOn.lean), [uniform draws](../../PolyFun/Control/Monad/Measure/Uniform.lean), [uniform answers](../../PolyFun/PFunctor/Free/Measure/Uniform.lean), [mass functions](../../ToCslib/Probability/UniformOn/PMF.lean) | [Probability](../guides/probability.md) | | Admissible implementations and resources | [Realizability](../../PolyFun/Realizability/Basic.lean), [quantitative certificates](../../PolyFun/Realizability/Quantitative.lean), [description measures](../../PolyFun/Realizability/Quantitative/Description.lean) | [Realizability](../guides/realizability.md) | | Strength, the strong bind, and structural cost laws | [Strength](../../PolyFun/Realizability/Quantitative/Strength.lean), [cost laws](../../PolyFun/Realizability/Quantitative/CostLaws.lean), [carries](../../PolyFun/Realizability/Quantitative/Carry.lean) | [Realizability](../guides/realizability.md#strength-and-the-strong-bind) | diff --git a/test/DocumentationConsumer/PolyFunDocumentationConsumer.lean b/test/DocumentationConsumer/PolyFunDocumentationConsumer.lean index 361b2d24..ac9254d5 100644 --- a/test/DocumentationConsumer/PolyFunDocumentationConsumer.lean +++ b/test/DocumentationConsumer/PolyFunDocumentationConsumer.lean @@ -16,6 +16,7 @@ import Examples.Tutorials.VersionedRequests import Examples.Tutorials.UpdatePolicies import PolyFun.PFunctor.Free.Measure.StatefulExpectedCharge import PolyFun.PFunctor.Handler.Sum +import PolyFun.PFunctor.Resumption.Measure.ExpectedCharge import Examples.Tutorials.ScopedPrograms import Examples.Tutorials.ScopedExecution import Examples.Tutorials.ScopedFamily @@ -237,3 +238,28 @@ example {α : Type} (client : FreeM Tick α) (reward : α → Bool → ℝ≥0 cases warm <;> simp [price] end StatefulCostConsumer + +namespace ResumptionChargeConsumer + +open PFunctor Resumption +open scoped ENNReal + +-- A finite setup can use the budget of each possible service as its terminal payoff, +-- even when the service itself runs forever. +example {P : PFunctor} {S α β : Type*} [MeasurableSpace S] + [∀ a, MeasurableSpace (P.B a)] [∀ a, Countable (P.B a)] + [∀ a, MeasurableSingletonClass (P.B a)] + (replies : KernelHandler P S) (price : P.A → S → ℝ≥0∞) + (hprice : ∀ a, Measurable (price a)) + (setup : FreeM P α) (serve : α → Resumption P β) + (reward : β → S → ℝ≥0∞) (hreward : ∀ y, Measurable (reward y)) + (budget : α → S → ℝ≥0∞) + (hbudget : ∀ x, expectedCharge replies price (serve x) reward ≤ budget x) : + expectedCharge replies price (bind (FreeM.toResumption setup) serve) reward ≤ + FreeM.wpFold (OpSpec.statefulExpectedCharge replies price) setup budget := by + rw [expectedCharge_bind replies price hprice _ _ reward hreward, + expectedCharge_toResumption replies price hprice setup _ + (fun x => measurable_expectedCharge replies price hprice (serve x) reward hreward)] + exact FreeM.wpFold_mono (OpSpec.statefulExpectedCharge_mono replies price) setup hbudget + +end ResumptionChargeConsumer From a5e3509c335e3740e2afd758b81110cda33e4268 Mon Sep 17 00:00:00 2001 From: Devon Tuma Date: Wed, 25 Nov 2026 16:38:02 -0600 Subject: [PATCH 2/5] chore(pfunctor): import resumption domain laws as proof dependencies The statements about expected charges of resumptions use continuous algebras and truncations. The fusion and approximation theorems occur only in proofs. Co-Authored-By: Claude Opus 5.5 --- PolyFun/PFunctor/Resumption/Measure/ExpectedCharge.lean | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/PolyFun/PFunctor/Resumption/Measure/ExpectedCharge.lean b/PolyFun/PFunctor/Resumption/Measure/ExpectedCharge.lean index c2c2142a..a5a9ebe7 100644 --- a/PolyFun/PFunctor/Resumption/Measure/ExpectedCharge.lean +++ b/PolyFun/PFunctor/Resumption/Measure/ExpectedCharge.lean @@ -7,8 +7,10 @@ Authors: Devon Tuma module public import PolyFun.PFunctor.Free.Measure.StatefulExpectedCharge -public import PolyFun.PFunctor.Resumption.DomainTruncate -public import PolyFun.PFunctor.Resumption.DomainLaws +public import PolyFun.PFunctor.Resumption.Domain +public import PolyFun.PFunctor.Resumption.Truncate +import PolyFun.PFunctor.Resumption.DomainLaws +import PolyFun.PFunctor.Resumption.DomainTruncate /-! # Expected charges of resumptions From 927c15a9d97e1ca4eab47ce6accbae7006ab8c5b Mon Sep 17 00:00:00 2001 From: Devon Tuma Date: Wed, 25 Nov 2026 16:38:02 -0600 Subject: [PATCH 3/5] test(pfunctor): bound, sequence and delimit expected charges of resumptions Attain the potential bound on a client that never returns, price an adaptive client's second request in the state left by its first, and refute agreement with the finite fold over answers without measurable singletons. Co-Authored-By: Claude Opus 5.5 --- PolyFunTest/Probability/ResumptionCharge.lean | 157 +++++++++++++++++- 1 file changed, 155 insertions(+), 2 deletions(-) diff --git a/PolyFunTest/Probability/ResumptionCharge.lean b/PolyFunTest/Probability/ResumptionCharge.lean index 1e7c6bc9..e8d2a0dd 100644 --- a/PolyFunTest/Probability/ResumptionCharge.lean +++ b/PolyFunTest/Probability/ResumptionCharge.lean @@ -12,7 +12,12 @@ public import PolyFun.PFunctor.Resumption.Measure.ExpectedCharge # Incurred charges on an infinite sequence of requests The same deterministic client can pay a finite setup cost or an infinite per-request bill. -Even infinite terminal credit has no effect on this client because it never returns. +Even infinite terminal credit has no effect on this client because it never returns. A potential +bounds the setup cost of every client. An adaptive client pays for its second request in the state +left by its first. + +Agreement with the fold of a finite program needs answers with measurable singletons. Over a +coarser answer space, a client that always returns can lose its whole terminal payoff. -/ public section @@ -65,7 +70,7 @@ private theorem ready_prefix (post : Unit → Bool → ℝ≥0∞) (n : ℕ) : | succ n ih => simp [prefix_succ, setup, ih] /-- The first request costs one, subsequent requests are free, and no cutoff earns credit. -/ -example (post : Unit → Bool → ℝ≥0∞) : +private theorem expectedCharge_setup_ticks (post : Unit → Bool → ℝ≥0∞) : expectedCharge service setup ticks post false = 1 := by change (⨆ n, prefixCost setup post n false) = 1 have h (n : ℕ) : prefixCost setup post (n + 1) false = 1 := by @@ -102,4 +107,152 @@ example (program : FreeM Tick Unit) (post : Unit → Bool → ℝ≥0∞) : expectedCharge_toResumption service setup (fun _ => Measurable.of_discrete) program post (fun _ => Measurable.of_discrete) +/-! ## Potential bounds -/ + +/-- The setup charge that remains to be paid. -/ +private noncomputable def credit (ready : Bool) : ℝ≥0∞ := if ready then 0 else 1 + +/-- The potential pays for the setup of any client. A return before setup keeps the credit. -/ +example (tree : Resumption Tick Unit) (post : Unit → Bool → ℝ≥0∞) (s : Bool) : + expectedCharge service setup tree (fun r t => post r t + credit t) s ≤ + expectedCharge service (fun _ _ => 0) tree post s + credit s := by + refine expectedCharge_le_of_potential service (fun _ _ => 0) setup (fun _ => True) credit + Measurable.of_discrete (fun _ _ _ => .of_forall fun _ => trivial) ?_ tree post trivial + rintro ⟨⟩ (_ | _) _ <;> + simp [service, setup, credit, KernelHandler.ofFun, Kernel.deterministic_apply] + +/-- The client that never returns attains this bound from the state before setup. -/ +example (post : Unit → Bool → ℝ≥0∞) : + expectedCharge service setup ticks (fun r t => post r t + credit t) false = + expectedCharge service (fun _ _ => 0) ticks post false + credit false := by + have h (n : ℕ) (t : Bool) : prefixCost (fun _ _ => 0) post n t = 0 := by + induction n generalizing t with + | zero => exact prefix_zero .. + | succ n ih => simp [prefix_succ, ih] + rw [expectedCharge_setup_ticks] + change 1 = (⨆ n, prefixCost (fun _ _ => 0) post n false) + credit false + simp [h, credit] + +/-- Without credit, the price premise fails in the state before setup. -/ +example : ¬ setup () false ≤ 0 := by simp [setup] + +/-- Setup is free in the ready state, which the service never leaves. -/ +example (tree : Resumption Tick Unit) : + expectedCharge service setup tree (fun _ _ => 0) true ≤ + expectedCharge service (fun _ _ => 0) tree (fun _ _ => 0) true := by + have h := expectedCharge_le_of_potential service (fun _ _ => 0) setup (fun ready => ready = true) + (fun _ => 0) measurable_const ?_ ?_ tree (fun _ _ => 0) (s := true) rfl + · simpa using h + · rintro ⟨⟩ s _ + simp [service, KernelHandler.ofFun, Kernel.deterministic_apply] + · rintro ⟨⟩ s rfl + simp [setup] + +/-! ## Sequencing -/ + +/-- A request answered by a Boolean. -/ +abbrev Ask : PFunctor.{0, 0} := ⟨Unit, fun _ => Bool⟩ + +private noncomputable def toggle : KernelHandler Ask Bool := + KernelHandler.ofFun (fun _ s => (s, !s)) (fun _ => Measurable.of_discrete) + +private noncomputable def price (_ : Ask.A) (s : Bool) : ℝ≥0∞ := if s then 3 else 2 + +private noncomputable def ask : Resumption Ask Bool := Resumption.lift (p := Ask) () + +private noncomputable def askTwice : Resumption Ask Bool := + Resumption.bind ask fun b => if b then .pure b else ask + +private theorem expectedCharge_ask (post : Bool → Bool → ℝ≥0∞) (s : Bool) : + expectedCharge toggle price ask post s = price () s + post s (!s) := by + rw [ask, Resumption.lift, expectedCharge_query (P := Ask) _ _ (fun _ => Measurable.of_discrete) + _ _ _ (fun _ => Measurable.of_discrete)] + simp [toggle, KernelHandler.ofFun, Kernel.deterministic_apply] + +/-- The second request is priced in the state that the first one leaves. -/ +example (post : Bool → Bool → ℝ≥0∞) : + expectedCharge toggle price askTwice post false = 2 + (3 + post true false) := by + rw [askTwice, expectedCharge_bind (P := Ask) toggle price (fun _ => Measurable.of_discrete) + _ _ _ (fun _ => Measurable.of_discrete), expectedCharge_ask] + simp [expectedCharge_ask, price] + +/-- A `true` answer returns without a second request. -/ +example (post : Bool → Bool → ℝ≥0∞) : + expectedCharge toggle price askTwice post true = 3 + post true false := by + rw [askTwice, expectedCharge_bind (P := Ask) toggle price (fun _ => Measurable.of_discrete) + _ _ _ (fun _ => Measurable.of_discrete), expectedCharge_ask] + simp [price] + +/-! ## Answers without measurable singletons -/ + +/-- A natural number whose measurable structure does not distinguish its values. -/ +structure CoarseNat where + /-- The underlying value, which the measurable structure does not expose. -/ + down : ℕ + +instance : MeasurableSpace CoarseNat := ⊥ + +/-- Measurable functions of a coarse number are constant, so one zero of `f` makes its integral +vanish. -/ +private theorem lintegral_coarse_eq_zero (μ : Measure (CoarseNat × Unit)) + {f : CoarseNat × Unit → ℝ≥0∞} {z : CoarseNat × Unit} (hz : f z = 0) : ∫⁻ w, f w ∂μ = 0 := by + obtain ⟨g, hg, hgf, heq⟩ := exists_measurable_le_lintegral_eq μ f + have hgz : g z = 0 := le_antisymm ((hgf z).trans hz.le) bot_le + have hconst (w : CoarseNat × Unit) : g w = 0 := by + have hm : Measurable fun n => g (n, ()) := hg.comp measurable_prodMk_right + rcases MeasurableSpace.measurableSet_bot_iff.mp (hm (measurableSet_singleton 0)) with h | h + · exact absurd hgz (Set.eq_empty_iff_forall_notMem.mp h z.1) + · exact Set.eq_univ_iff_forall.mp h w.1 + simp [heq, hconst] + +/-- One operation with coarse natural-number answers. -/ +abbrev Pick : PFunctor.{0, 0} := ⟨Unit, fun _ => CoarseNat⟩ + +private noncomputable def zeroes : KernelHandler Pick Unit := + KernelHandler.ofFun (fun _ _ => (⟨0⟩, ())) (fun _ => measurable_const) + +private noncomputable abbrev free : OpSpec Pick (Unit → ℝ≥0∞) := + OpSpec.statefulExpectedCharge (P := Pick) zeroes (fun _ _ => 0) + +private theorem free_const (x : ℝ≥0∞) (s : Unit) : free () (fun _ _ => x) s = x := by + simp [free, zeroes, KernelHandler.ofFun, Kernel.deterministic_apply] + +/-- Make `n` requests and return. -/ +private def wait : ℕ → FreeM Pick Unit + | 0 => .pure () + | n + 1 => .liftBind () fun _ => wait n + +/-- The first answer chooses the number of further requests. -/ +private def pickThenWait : FreeM Pick Unit := .liftBind () fun n => wait n.down + +private theorem wpFold_wait (n : ℕ) (s : Unit) : + FreeM.wpFold free (wait n) (fun _ _ => 1) s = 1 := by + induction n generalizing s with + | zero => rfl + | succ n ih => simp only [wait, FreeM.wpFold_liftBind, funext ih, free_const] + +private theorem wpFold_truncate_wait (n : ℕ) (s : Unit) : + FreeM.wpFold free (truncate n (wait (n + 1)).toResumption) + (fun result => result.elim (fun _ => 0) fun _ _ => 1) s = 0 := by + induction n generalizing s with + | zero => rw [wait, FreeM.toResumption_liftBind, truncate_query_zero]; rfl + | succ n ih => + rw [wait, FreeM.toResumption_liftBind, truncate_query_succ, FreeM.wpFold_liftBind, funext ih] + exact free_const 0 s + +/-- Every branch of the finite program returns, so its fold gives the whole terminal payoff. -/ +example : FreeM.wpFold free pickThenWait (fun _ _ => 1) () = 1 := by + simp only [pickThenWait, FreeM.wpFold_liftBind, funext (wpFold_wait _), free_const] + +/-- No truncation depth bounds every branch, and each truncation integrates to zero. The measure +puts all its mass at the immediate return, but the coarse answers do not distinguish that branch +from the ones that are cut off. -/ +example : expectedCharge zeroes (fun _ _ => 0) pickThenWait.toResumption (fun _ _ => 1) () = 0 := by + rw [expectedCharge_eq_iSup (P := Pick), ENNReal.iSup_eq_zero] + rintro (_ | n) + · rw [pickThenWait, FreeM.toResumption_liftBind, truncate_query_zero]; rfl + · rw [pickThenWait, FreeM.toResumption_liftBind, truncate_query_succ, FreeM.wpFold_liftBind, + OpSpec.statefulExpectedCharge_apply (P := Pick) zeroes, zero_add] + exact lintegral_coarse_eq_zero _ (z := (⟨n + 1⟩, ())) (wpFold_truncate_wait n ()) + end PolyFunTest.Probability.ResumptionCharge From ff5d1304547a6302d1639821a14ab6d96dec8dab Mon Sep 17 00:00:00 2001 From: Devon Tuma Date: Wed, 25 Nov 2026 16:45:45 -0600 Subject: [PATCH 4/5] docs(pfunctor): state when expected charges of resumptions are infinite or exact An infinite total needs a handler that keeps answering, since the zero kernel stops the same client after one charge. The step equation and agreement with finite folds need measurability conditions. Co-Authored-By: Claude Opus 5.5 --- PolyFun/PFunctor/Resumption/Measure/ExpectedCharge.lean | 8 +++++--- docs/guides/cost.md | 3 ++- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/PolyFun/PFunctor/Resumption/Measure/ExpectedCharge.lean b/PolyFun/PFunctor/Resumption/Measure/ExpectedCharge.lean index a5a9ebe7..1e762372 100644 --- a/PolyFun/PFunctor/Resumption/Measure/ExpectedCharge.lean +++ b/PolyFun/PFunctor/Resumption/Measure/ExpectedCharge.lean @@ -15,9 +15,11 @@ import PolyFun.PFunctor.Resumption.DomainTruncate /-! # Expected charges of resumptions -A resumption can accumulate charges without returning. Folding its finite query prefixes and -then taking their supremum retains each incurred charge. A cutoff receives zero terminal credit. -The step equation follows by monotone convergence on the joint answer-and-state kernel. +A resumption can accumulate charges without returning. Its expected charge is the supremum of the +folds of its finite query prefixes. A cutoff receives zero terminal credit. The step equation +follows by monotone convergence on the joint answer-and-state kernel. It assumes countable answers +with measurable singletons and state-measurable prices and terminal credit. Over other answer spaces +the supremum can lie below the fold of a finite program. -/ public section diff --git a/docs/guides/cost.md b/docs/guides/cost.md index 1855cb33..586de822 100644 --- a/docs/guides/cost.md +++ b/docs/guides/cost.md @@ -352,7 +352,8 @@ actual mass, so the calculation also applies when the total mass is less than on `Resumption.expectedCharge K c tree post` takes the supremum of the expected charges of finite truncations. A prefix earns `post` if it returns and zero terminal credit if it stops at a pending request. This distinguishes two prices for the same infinite sequence of requests. If only the -first request costs one, the total is one. If every request costs one, the total is infinite. +first request costs one, the total is one. If every request costs one, the total is infinite under +a handler that always answers. With countable answer spaces having measurable singletons, measurable prices, and measurable terminal observations in the private state, `Resumption.expectedCharge_bind` prices a prefix From b46e02cf4a4544cb32c30831ecbc8718432d3735 Mon Sep 17 00:00:00 2001 From: Devon Tuma Date: Wed, 25 Nov 2026 16:45:45 -0600 Subject: [PATCH 5/5] test(pfunctor): evaluate terminal credit, a half-mass answer and an invariant boundary Co-Authored-By: Claude Opus 5.5 --- PolyFunTest/Probability/ResumptionCharge.lean | 49 +++++++++++++------ 1 file changed, 33 insertions(+), 16 deletions(-) diff --git a/PolyFunTest/Probability/ResumptionCharge.lean b/PolyFunTest/Probability/ResumptionCharge.lean index e8d2a0dd..bc3c0582 100644 --- a/PolyFunTest/Probability/ResumptionCharge.lean +++ b/PolyFunTest/Probability/ResumptionCharge.lean @@ -16,8 +16,9 @@ Even infinite terminal credit has no effect on this client because it never retu bounds the setup cost of every client. An adaptive client pays for its second request in the state left by its first. -Agreement with the fold of a finite program needs answers with measurable singletons. Over a -coarser answer space, a client that always returns can lose its whole terminal payoff. +Agreement with the fold of a finite program can fail for answers without measurable singletons. +Over a coarser answer space, a client that always returns, after a number of requests that has no +bound, can lose its whole terminal payoff. -/ public section @@ -101,11 +102,22 @@ example (next : Unit → Resumption Tick Unit) : simp /-- A finite program still receives its terminal credit at the state where it returns. -/ -example (program : FreeM Tick Unit) (post : Unit → Bool → ℝ≥0∞) : - expectedCharge service setup program.toResumption post = - FreeM.wpFold (OpSpec.statefulExpectedCharge service setup) program post := - expectedCharge_toResumption service setup (fun _ => Measurable.of_discrete) program post - (fun _ => Measurable.of_discrete) +example (post : Unit → Bool → ℝ≥0∞) : + expectedCharge service setup (FreeM.lift (P := Tick) ()).toResumption post false = + 1 + post () true := by + rw [expectedCharge_toResumption service setup (fun _ => Measurable.of_discrete) _ post + (fun _ => Measurable.of_discrete)] + simp [setup, service, KernelHandler.ofFun, Kernel.deterministic_apply] + +private noncomputable def half : KernelHandler Tick Unit := + fun _ => Kernel.const _ ((2⁻¹ : ℝ≥0∞) • Measure.dirac ((), ())) + +/-- A request answered with mass one half pays its price in full and half of its terminal credit. -/ +example : expectedCharge half (fun _ _ => 1) (Resumption.lift (p := Tick) ()) (fun _ _ => 1) () = + 1 + 2⁻¹ := by + rw [Resumption.lift, expectedCharge_query (P := Tick) _ _ (fun _ => measurable_const) _ _ _ + (fun _ => measurable_const)] + simp [half] /-! ## Potential bounds -/ @@ -121,20 +133,20 @@ example (tree : Resumption Tick Unit) (post : Unit → Bool → ℝ≥0∞) (s : rintro ⟨⟩ (_ | _) _ <;> simp [service, setup, credit, KernelHandler.ofFun, Kernel.deterministic_apply] -/-- The client that never returns attains this bound from the state before setup. -/ -example (post : Unit → Bool → ℝ≥0∞) : - expectedCharge service setup ticks (fun r t => post r t + credit t) false = - expectedCharge service (fun _ _ => 0) ticks post false + credit false := by +private theorem expectedCharge_free_ticks (post : Unit → Bool → ℝ≥0∞) (s : Bool) : + expectedCharge service (fun _ _ => 0) ticks post s = 0 := by + change (⨆ n, prefixCost (fun _ _ => 0) post n s) = 0 have h (n : ℕ) (t : Bool) : prefixCost (fun _ _ => 0) post n t = 0 := by induction n generalizing t with | zero => exact prefix_zero .. | succ n ih => simp [prefix_succ, ih] - rw [expectedCharge_setup_ticks] - change 1 = (⨆ n, prefixCost (fun _ _ => 0) post n false) + credit false - simp [h, credit] + simp [h] -/-- Without credit, the price premise fails in the state before setup. -/ -example : ¬ setup () false ≤ 0 := by simp [setup] +/-- The client that never returns attains this bound from the state before setup. -/ +example (post : Unit → Bool → ℝ≥0∞) : + expectedCharge service setup ticks (fun r t => post r t + credit t) false = + expectedCharge service (fun _ _ => 0) ticks post false + credit false := by + simp [expectedCharge_setup_ticks, expectedCharge_free_ticks, credit] /-- Setup is free in the ready state, which the service never leaves. -/ example (tree : Resumption Tick Unit) : @@ -148,6 +160,11 @@ example (tree : Resumption Tick Unit) : · rintro ⟨⟩ s rfl simp [setup] +/-- That bound fails in the other state, which its invariant excludes. -/ +example : ¬ expectedCharge service setup ticks (fun _ _ => 0) false ≤ + expectedCharge service (fun _ _ => 0) ticks (fun _ _ => 0) false := by + simp [expectedCharge_setup_ticks, expectedCharge_free_ticks] + /-! ## Sequencing -/ /-- A request answered by a Boolean. -/