diff --git a/Clean.lean b/Clean.lean index ae6092d69..fbe674b9f 100644 --- a/Clean.lean +++ b/Clean.lean @@ -28,6 +28,7 @@ public import Clean.Examples.FemtoCairo.FlatAir public import Clean.Air.WitnessGeneration public import Clean.Air.Lookup public import Clean.Air.CountedChannel +public import Clean.Air.StagedChannels public import Clean.Backends.Plonky3.Print public import Clean.Tables.Fibonacci8 public import Clean.Tables.Fibonacci32 @@ -48,6 +49,8 @@ public import Clean.Gadgets.BLAKE3.Round public import Clean.Gadgets.BLAKE3.FinalizeChunk public import Clean.Examples.FibonacciVm.Ensemble public import Clean.Examples.CountedSquares.Ensemble +public import Clean.Examples.StagedSquares.Ensemble +public import Clean.Examples.SameBus.Ensemble public import Clean.Examples.OpcodeVm.Ensemble public import Clean.Examples.BinaryFibonacci.Ensemble public import Clean.Gadgets.SHA256.SHA256Compress diff --git a/Clean/Air/Balance.lean b/Clean/Air/Balance.lean index 5f9c06e5e..a672f9cb5 100644 --- a/Clean/Air/Balance.lean +++ b/Clean/Air/Balance.lean @@ -48,8 +48,9 @@ This is how a circuit discharges the requirement of a counted pull. The pull owe `mult ≠ 0` and `mult.val ≤ N`. Stating it over `ZMod p` rather than a general field is what makes `mult.val` available. -No example in this repo range-checks a multiplicity, because the bound there is `2` and a -constraint is cheaper. The chips that do are in lambda_vm, where the bound is a byte. -/ +`Clean/Examples/StagedSquares` range-checks a multiplicity by pulling a channel that guarantees +`CountUpTo`. No example range-checks one by its `.val` against a table, because the bound there is +`2` and a constraint is cheaper; the chips that do are in lambda_vm, where the bound is a byte. -/ lemma countUpTo_of_ne_zero_of_val_le {p : ℕ} [Fact p.Prime] {N : ℕ} {mult : ZMod p} (h0 : mult ≠ 0) (hN : mult.val ≤ N) : CountUpTo N mult := ⟨ mult.val, Nat.one_le_iff_ne_zero.mpr ((ZMod.val_ne_zero mult).mpr h0), hN, @@ -195,6 +196,47 @@ lemma balancedUpTo_one_iff {interactions : List (Interaction F)} : ⟨ fun balanced => balanced.toBalancedInteractions, fun balanced => ⟨ balanced, balanced.matchedUpTo_one ⟩ ⟩ +/-- Filtering by a class of messages keeps the active count of a message in the class and zeroes +it outside. -/ +lemma activeCount_filter_msg (interactions : List (Interaction F)) (cls : Array F → Bool) + (direction : Channel.Direction) (msg : Array F) : + activeCount (interactions.filter fun i => cls i.msg) direction msg = + if cls msg then activeCount interactions direction msg else 0 := by + simp only [activeCount, List.countP_filter] + split_ifs with h_cls + · apply List.countP_congr + intro i _ + simp only [Bool.and_eq_true, decide_eq_true_eq] + constructor + · exact fun h => h.1 + · exact fun h => ⟨ h, h.2.1 ▸ h_cls ⟩ + · rw [List.countP_eq_zero] + intro i _ + simp only [Bool.and_eq_true, decide_eq_true_eq, not_and] + rintro ⟨ -, rfl, - ⟩ h + exact h_cls h + +/-- Restricting a balanced list to a class of messages keeps it balanced: every interaction +carrying a message is kept or dropped together. -/ +lemma BalancedUpTo.filter_msg {N : ℕ} {interactions : List (Interaction F)} + (cls : Array F → Bool) (balanced : BalancedUpTo N interactions) : + BalancedUpTo N (interactions.filter fun i => cls i.msg) := by + refine ⟨ ⟨ ?_, ?_ ⟩, ?_ ⟩ + · intro a a_mem a_pull + obtain ⟨ a_mem, a_cls ⟩ := List.mem_filter.mp a_mem + obtain ⟨ b, b_mem, b_msg, b_push ⟩ := balanced.exists_push_of_pull a a_mem a_pull + exact ⟨ b, List.mem_filter.mpr ⟨ b_mem, b_msg ▸ a_cls ⟩, b_msg, b_push ⟩ + · intro msg is_bool + rw [activeCount_filter_msg, activeCount_filter_msg] + split_ifs with h_cls + · exact balanced.activeCount_push_eq_activeCount_pull_of_isBool msg fun i i_mem i_msg => + is_bool i (List.mem_filter.mpr ⟨ i_mem, i_msg ▸ h_cls ⟩) i_msg + · rfl + · intro a a_mem a_pull + obtain ⟨ a_mem, a_cls ⟩ := List.mem_filter.mp a_mem + obtain ⟨ b, b_mem, b_msg, b_push ⟩ := balanced.matchedUpTo a a_mem a_pull + exact ⟨ b, List.mem_filter.mpr ⟨ b_mem, b_msg ▸ a_cls ⟩, b_msg, b_push ⟩ + /-- A balance check: the condition that a verifier checks on the interactions with each channel, the numbers of interactions with a channel that the check is sound for, and its proof that the condition diff --git a/Clean/Air/README.md b/Clean/Air/README.md index 9a85c8242..af551417a 100644 --- a/Clean/Air/README.md +++ b/Clean/Air/README.md @@ -35,12 +35,14 @@ It also proves the basic row-level transport lemmas: instantiated component oper **Ensemble-level soundness** is more than a simple lifting of per-circuit soundness: it requires that channel guarantees, which were _assumed_ as part of local circuit proofs, are shown to hold unconditionally from global channel balance and constraints. -The library currently provides two distinct arguments to establish soundness, covering two prominent ways of using channels: +The library currently provides three distinct arguments to establish soundness, covering prominent ways of using channels: -`OrderedChannel.lean` contains a staged channel construction for ordinary lookup-like channels. The defining property is a strict hierarchy on the list of component tables: any table that pushes to a channel must come before every table that pulls from it. From little more than this property, we prove ensemble-level soundness, as encapsulated in the `SoundEnsemble` structure. On the way, we introduce a relaxed notion of channel balance called `PartialBalancedChannel` that allows the balanced interaction list to contain additional interactions from tables added later. This makes it suitable for an inductive argument or gradual addition of tables to an existing sound ensemble. +`OrderedChannel.lean` contains a construction for ordinary lookup-like channels. The defining property is a strict hierarchy on the list of component tables: any table that pushes to a channel must come before every table that pulls from it. From little more than this property, we prove ensemble-level soundness, as encapsulated in the `SoundEnsemble` structure. On the way, we introduce a relaxed notion of channel balance called `PartialBalancedChannel` that allows the balanced interaction list to contain additional interactions from tables added later. This makes it suitable for an inductive argument or gradual addition of tables to an existing sound ensemble. `Vm.lean` contains a construction aimed at "VM-like" components that perform one transition per row. Since VM components both pull from and push to one distinguished state channel, they cannot follow the theory of ordered lookup-channel soundness. Instead, we prove a dedicated soundness theorem that applies to a set of VM components added to an existing hierarchical ensemble; a typical modern zkVMs layout. `Clean/Examples/BinaryFibonacci` is a VM over the binary field GF(2^64), sound under multiset balance. +`StagedChannels.lean` orders the channels instead of the tables. A table's requirements on a channel may follow from its guarantees on channels finished earlier, which the hierarchy of `OrderedChannel.lean` cannot express: a counted pull whose multiplicity is range-checked on a second channel is the case. `finished` lists the channels newest first, `Component.StagedRequirements` says that each component's requirements on one of them follow from its guarantees on those finished before it, and `Ensemble.tableSoundness_of_stagedRequirements` proves soundness by induction from the oldest. A `Stage` refines this to a channel together with a class of its messages, so a bus shared by several operations can be finished in several steps and a table that pulls some of its messages and pushes others is not a cycle; balance is message by message (`BalancedUpTo.filter_msg`), so each stage balances by itself. `Clean/Examples/StagedSquares` is the first case and `Clean/Examples/SameBus` the second. Two limits distinguish it from `OrderedChannel.lean`: the argument is made for a whole ensemble at once rather than built up table by table as `SoundEnsemble` does, and it applies only to ensembles whose verifier is empty. That hypothesis stands for two obligations at once: that every interaction on a stage comes from a table, so that the requirements the induction establishes cover the whole list consistency is applied to, and that the verifier's own spec follows from its guarantees. `OrderedChannel.lean` discharges the first through `PartialBalancedChannel`, which tolerates interactions from outside the list it is stated for, and the second through `verifierChannelGuarantees_of_tableRequirements`. The staged argument has neither, so lifting the hypothesis means saying what a verifier owes on a stage and adding it to the induction. + `WitnessGeneration.lean` constructs ensemble witnesses from the public input and the prover's private input, see the next section. ## Witness generation diff --git a/Clean/Air/StagedChannels.lean b/Clean/Air/StagedChannels.lean new file mode 100644 index 000000000..759d86424 --- /dev/null +++ b/Clean/Air/StagedChannels.lean @@ -0,0 +1,376 @@ +module + +public import Clean.Air.FlatEnsemble + +@[expose] public section + +/-! +# Soundness by channel finishing order + +`OrderedChannel` orders tables: on each channel, every table that pushes comes before every table +that pulls, and no table does both. That rules out a table whose requirements on one channel follow +from its guarantees on *another*. A counted pull is the case that needs this: its multiplicity owes +`CountUpTo N`, and for a bound too large to constrain arithmetically that comes from range-checking +the multiplicity on a second channel. `Clean/Examples/CountedSquares` counts to `2` and constrains +its count in the circuit, which is why one finished channel is enough there. + +Here channels are ordered instead. `finished` lists the channels newest first, and a component's +requirements on a channel may use its guarantees on the channels finished before it +(`Component.StagedRequirements`). Then, by induction from the oldest channel, every channel's +requirements hold, so by consistency every channel's guarantees hold, and every table's spec follows. + +Not covered: both soundness theorems assume `ens.verifier = .empty F PublicIO`, unlike +`Ensemble.tableSoundness_of_soundChannels`, and there is no staged counterpart of +`Ensemble.addVm_soundVmChannel_of_soundChannels` for adding a VM. `Clean/Air/README.md` says what +that hypothesis stands for and what `OrderedChannel.lean` uses in its place. + +This was written for lambda_vm, a RISC-V zkVM built on Clean, whose lookup channels admit a +finishing order with one cycle, an arithmetic bus that one table both reads and writes. The cycle +is what the message classes break. `Clean/Examples/StagedSquares` and `Clean/Examples/SameBus` are +the two shapes in miniature. +-/ + +variable {F : Type} [FiniteField F] + +namespace Air.Flat + +/-- The requirements of `table` on `channel` follow from its assumptions, its constraints and its +guarantees on `earlier` channels. -/ +def Table.RequirementsAfter (table : Table F) (channel : RawChannel F) + (earlier : List (RawChannel F)) : Prop := + table.Assumptions → table.Constraints → (∀ c ∈ earlier, table.ChannelGuarantees c) → + table.ChannelRequirements channel + +/-- `Table.RequirementsAfter` for every table of the component. -/ +def Component.RequirementsAfter (component : Component F) (channel : RawChannel F) + (earlier : List (RawChannel F)) : Prop := + ∀ table : Table F, table.component = component → table.RequirementsAfter channel earlier + +/-- The requirements of a component on each channel of `finished`, newest first, follow from its +guarantees on the channels finished before it. -/ +def Component.StagedRequirements (component : Component F) : List (RawChannel F) → Prop + | [] => True + | channel :: earlier => + component.RequirementsAfter channel earlier ∧ component.StagedRequirements earlier + +@[circuit_norm] lemma Component.stagedRequirements_nil (component : Component F) : + component.StagedRequirements [] := trivial + +@[circuit_norm] lemma Component.stagedRequirements_cons (component : Component F) + (channel : RawChannel F) (earlier : List (RawChannel F)) : + component.StagedRequirements (channel :: earlier) ↔ + component.RequirementsAfter channel earlier ∧ component.StagedRequirements earlier := + .rfl + +/-- A component owes nothing on a channel outside its `channelsWithRequirements`. -/ +lemma Component.requirementsAfter_of_not_mem {component : Component F} {channel : RawChannel F} + (earlier : List (RawChannel F)) + (h : channel ∉ component.circuit.channelsWithRequirements) : + component.RequirementsAfter channel earlier := by + rintro table rfl - constraints - + exact table.requirements_of_not_mem_of_constraints constraints h + +/-- A component whose guarantees all come from earlier channels gets its requirements from +soundness. -/ +lemma Component.requirementsAfter_of_guarantees_subset {component : Component F} + {channel : RawChannel F} {earlier : List (RawChannel F)} + (h : component.circuit.channelsWithGuarantees ⊆ earlier) : + component.RequirementsAfter channel earlier := by + rintro table rfl assumptions constraints guarantees + have all_guarantees : table.Guarantees := by + rw [Table.guarantees_iff_channelGuarantees] + exact fun c hc => guarantees c (h hc) + exact table.channelRequirements_of_requirements + (Table.weakSoundness assumptions constraints all_guarantees).2 + +/-- `StagedRequirements` from `RequirementsAfter` at every position of the list. -/ +lemma Component.stagedRequirements_of_forall {component : Component F} : + ∀ {finished : List (RawChannel F)}, + (∀ (channel : RawChannel F) (earlier : List (RawChannel F)), + (∃ later, later ++ channel :: earlier = finished) → + component.RequirementsAfter channel earlier) → + component.StagedRequirements finished + | [], _ => trivial + | channel :: earlier, h => + ⟨h channel earlier ⟨[], rfl⟩, + stagedRequirements_of_forall fun c e ⟨later, hl⟩ => + h c e ⟨channel :: later, by simp [hl]⟩⟩ + +/-! +## Stages: a channel and a class of its messages + +A channel that one table both pulls from and pushes to, on different messages, is not a cycle: what +it reads and what it writes are disjoint. A bus shared by several operations is where this happens. +A table that answers one operation by using the answers to others pulls those answers and pushes +its own, all under one channel name, and ordering whole channels cannot express that. Ordering by +stage, a channel together with a class of its messages, lets the class it pushes be finished after +the classes it pulls. Balance is message by message (`BalancedUpTo.filter_msg`), so each stage +balances by itself, and a whole channel is the stage whose class is every message. Genuine cycles +still have no valid order. +-/ + +/-- The messages of one class on one channel. -/ +structure Stage (F : Type) where + channel : RawChannel F + cls : Array F → Bool := fun _ => true + +/-- The guarantees of `table` on the interactions of a stage. -/ +def Table.GuaranteesOn (table : Table F) (stage : Stage F) : Prop := + ∀ i ∈ table.interactionsWith stage.channel, stage.cls i.msg → i.Guarantees table.data + +/-- The requirements of `table` on the interactions of a stage. -/ +def Table.RequirementsOn (table : Table F) (stage : Stage F) : Prop := + ∀ i ∈ table.interactionsWith stage.channel, stage.cls i.msg → i.Requirements table.data + +/-- The requirements of `table` on a stage follow from its guarantees on `earlier` stages. -/ +def Table.RequirementsAfterOn (table : Table F) (stage : Stage F) (earlier : List (Stage F)) : + Prop := + table.Assumptions → table.Constraints → (∀ s ∈ earlier, table.GuaranteesOn s) → + table.RequirementsOn stage + +/-- `Table.RequirementsAfterOn` for every table of the component. -/ +def Component.RequirementsAfterOn (component : Component F) (stage : Stage F) + (earlier : List (Stage F)) : Prop := + ∀ table : Table F, table.component = component → table.RequirementsAfterOn stage earlier + +/-- `Component.StagedRequirements` over stages, newest first. -/ +def Component.StagedRequirementsOn (component : Component F) : List (Stage F) → Prop + | [] => True + | stage :: earlier => + component.RequirementsAfterOn stage earlier ∧ component.StagedRequirementsOn earlier + +@[circuit_norm] lemma Component.stagedRequirementsOn_nil (component : Component F) : + component.StagedRequirementsOn [] := trivial + +@[circuit_norm] lemma Component.stagedRequirementsOn_cons (component : Component F) + (stage : Stage F) (earlier : List (Stage F)) : + component.StagedRequirementsOn (stage :: earlier) ↔ + component.RequirementsAfterOn stage earlier ∧ component.StagedRequirementsOn earlier := + .rfl + +/-- Guarantees on stages that cover every pull of a table give all its guarantees. -/ +lemma Table.guarantees_of_guaranteesOn {table : Table F} {stages : List (Stage F)} + (covered : ∀ c ∈ table.component.circuit.channelsWithGuarantees, + ∀ i ∈ table.interactionsWith c, i.direction = .pull → + ∃ s ∈ stages, s.channel = c ∧ s.cls i.msg) + (guarantees : ∀ s ∈ stages, table.GuaranteesOn s) : table.Guarantees := by + rw [guarantees_iff_channelGuarantees] + intro c h_c + rw [channelGuarantees_iff_forall] + intro i h_i + by_cases h_pull : i.direction = .pull + · obtain ⟨ s, h_s, rfl, h_cls ⟩ := covered c h_c i h_i h_pull + exact guarantees s h_s i h_i h_cls + · exact fun h => absurd h h_pull + +/-- A component owes nothing on a stage whose channel is outside its `channelsWithRequirements`. -/ +lemma Component.requirementsAfterOn_of_not_mem {component : Component F} {stage : Stage F} + (earlier : List (Stage F)) + (h : stage.channel ∉ component.circuit.channelsWithRequirements) : + component.RequirementsAfterOn stage earlier := by + rintro table rfl - constraints - i h_i - + have := table.requirements_of_not_mem_of_constraints constraints h + rw [Table.channelRequirements_iff_forall] at this + exact this i h_i + +/-- A component whose pulls all lie in earlier stages gets its requirements from soundness. -/ +lemma Component.requirementsAfterOn_of_covered {component : Component F} {stage : Stage F} + {earlier : List (Stage F)} + (covered : ∀ table : Table F, table.component = component → + ∀ c ∈ component.circuit.channelsWithGuarantees, + ∀ i ∈ table.interactionsWith c, i.direction = .pull → + ∃ s ∈ earlier, s.channel = c ∧ s.cls i.msg) : + component.RequirementsAfterOn stage earlier := by + rintro table rfl assumptions constraints guarantees i h_i - + have all_guarantees := Table.guarantees_of_guaranteesOn (covered table rfl) guarantees + have := table.channelRequirements_of_requirements (channel := stage.channel) + (Table.weakSoundness assumptions constraints all_guarantees).2 + rw [Table.channelRequirements_iff_forall] at this + exact this i h_i + +/-- The same, when every message of each guarantee channel lies in an earlier stage. -/ +lemma Component.requirementsAfterOn_of_guarantees_subset {component : Component F} + {stage : Stage F} {earlier : List (Stage F)} + (h : ∀ c ∈ component.circuit.channelsWithGuarantees, ∀ msg, + ∃ s ∈ earlier, s.channel = c ∧ s.cls msg) : + component.RequirementsAfterOn stage earlier := + requirementsAfterOn_of_covered fun _ _ c h_c i _ _ => h c h_c i.msg + +/-- A stage's obligation read one row and one interaction at a time, which is the form a +component's own `circuit_norm` lemmas normalize to. `Table.RequirementsOn` quantifies over the +interactions of the whole table; `Table.forall_interactionsWith_iff` turns that into rows times the +component's row operations, and `AbstractInteraction.eval_requirements` carries the requirement +back. -/ +lemma Component.requirementsAfterOn_of_rowOperations {component : Component F} {stage : Stage F} + {earlier : List (Stage F)} + (h : ∀ table : Table F, table.component = component → table.Assumptions → table.Constraints → + (∀ s ∈ earlier, table.GuaranteesOn s) → + ∀ row ∈ table.table, ∀ i ∈ component.rowOperations.interactions, + i.channel = stage.channel → + stage.cls ((i.eval (table.environment row)).msg) = true → + i.Requirements (table.environment row)) : + component.RequirementsAfterOn stage earlier := by + rintro table rfl assumptions constraints guarantees + show ∀ i ∈ table.interactionsWith stage.channel, _ + rw [Table.forall_interactionsWith_iff] + intro row h_row i h_i h_channel h_cls + rw [interactions_eq] at h_i + exact AbstractInteraction.eval_requirements.mpr + (h table rfl assumptions constraints guarantees row h_row i h_i h_channel h_cls) + +/-- A component that receives no guarantee owes nothing on any stage: its requirements are already +unconditional. A provider, which pushes its table and pulls nothing, is the case. -/ +lemma Component.stagedRequirementsOn_of_no_guarantees {component : Component F} + (h : component.circuit.channelsWithGuarantees = []) : + ∀ stages : List (Stage F), component.StagedRequirementsOn stages + | [] => trivial + | _ :: rest => + ⟨requirementsAfterOn_of_guarantees_subset (by simp [h]), + stagedRequirementsOn_of_no_guarantees h rest⟩ + +/-- A channel-level `RequirementsAfter` gives the stage-level one for the whole channel, when every +earlier channel is a whole-channel stage. -/ +lemma Component.requirementsAfterOn_of_requirementsAfter {component : Component F} + {channel : RawChannel F} {earlierChannels : List (RawChannel F)} {earlier : List (Stage F)} + (h : component.RequirementsAfter channel earlierChannels) + (h_earlier : ∀ c ∈ earlierChannels, ∃ s ∈ earlier, s.channel = c ∧ ∀ msg, s.cls msg) : + component.RequirementsAfterOn { channel } earlier := by + rintro table h_comp assumptions constraints guarantees i h_i - + have := h table h_comp assumptions constraints (fun c hc => by + obtain ⟨s, hs, rfl, hall⟩ := h_earlier c hc + rw [Table.channelGuarantees_iff_forall] + exact fun i hi => guarantees s hs i hi (hall _)) + rw [Table.channelRequirements_iff_forall] at this + exact this i h_i + +/-- The stage that is a whole channel. -/ +def Stage.ofChannel (channel : RawChannel F) : Stage F := { channel } + +omit [FiniteField F] in +@[circuit_norm] lemma Stage.channel_ofChannel (channel : RawChannel F) : + (ofChannel channel).channel = channel := rfl + +lemma Component.stagedRequirementsOn_of_stagedRequirements + {component : Component F} : + ∀ {finished : List (RawChannel F)}, component.StagedRequirements finished → + component.StagedRequirementsOn (finished.map Stage.ofChannel) + | [], _ => trivial + | _ :: _, ⟨after, rest⟩ => + ⟨ requirementsAfterOn_of_requirementsAfter after + fun c hc => ⟨Stage.ofChannel c, List.mem_map_of_mem hc, rfl, fun _ => rfl⟩, + stagedRequirementsOn_of_stagedRequirements rest ⟩ + +namespace Ensemble +variable {PublicIO : TypeMap} [ProvableType PublicIO] + +/-- Every table's guarantees on every stage hold, by induction from the oldest stage. -/ +theorem guaranteesOn_of_stagedRequirementsOn {ens : Ensemble F PublicIO} {N : ℕ} + (verifier_empty : ens.verifier = .empty F PublicIO) + (witness : EnsembleWitness ens) (assumptions : witness.Assumptions) + (constraints : witness.Constraints) + (balanced : witness.BalancedChannels N) : + ∀ {finished : List (Stage F)}, (∀ s ∈ finished, s.channel ∈ ens.channels) → + (∀ s ∈ finished, s.channel.ConsistentUpTo N) → + (∀ component ∈ ens.tables, component.StagedRequirementsOn finished) → + ∀ table ∈ witness.tables, ∀ s ∈ finished, table.GuaranteesOn s + | [], _, _, _ => by simp + | stage :: earlier, finished_channels, consistent, staged => by + have ih := guaranteesOn_of_stagedRequirementsOn verifier_empty witness assumptions + constraints balanced + (fun s hs => finished_channels s (List.mem_cons_of_mem _ hs)) + (fun s hs => consistent s (List.mem_cons_of_mem _ hs)) + (fun component h => (staged component h).2) + have requirements : ∀ table ∈ witness.tables, table.RequirementsOn stage := + fun table h_table => + (staged table.component (witness.component_mem_tables_of_mem h_table)).1 table rfl + (assumptions table h_table) (constraints table h_table) (ih table h_table) + -- the stage's interactions balance by themselves, satisfy their requirements, and so by + -- consistency their guarantees + have : stage.channel.ConsistentUpTo N := consistent stage List.mem_cons_self + have mem_stage : ∀ i, i ∈ (witness.interactionsWith stage.channel).filter + (fun i => stage.cls i.msg) ↔ (∃ table ∈ witness.tables, + i ∈ table.interactionsWith stage.channel) ∧ stage.cls i.msg = true := by + intro i + rw [List.mem_filter, EnsembleWitness.interactionsWith_of_verifier_empty verifier_empty, + List.mem_flatMap] + have all_guarantees := RawChannel.ConsistentUpTo.consistent + ((witness.interactionsWith stage.channel).filter fun i => stage.cls i.msg) witness.data + ((balanced stage.channel (finished_channels stage List.mem_cons_self)).filter_msg _) + (by + intro i h_i + refine ⟨witness.channel_eq_of_mem_interactionsWith (List.mem_filter.mp h_i).1, ?_⟩ + obtain ⟨⟨table, h_table, h_i⟩, h_cls⟩ := (mem_stage i).mp h_i + have := requirements table h_table i h_i h_cls + rwa [witness.same_data table h_table] at this) + intro table h_table s h_s + rcases List.mem_cons.mp h_s with rfl | h_s + · intro i h_i h_cls + rw [witness.same_data table h_table] + exact all_guarantees i ((mem_stage i).mpr ⟨⟨table, h_table, h_i⟩, h_cls⟩) + · exact ih table h_table s h_s + +/-- +Soundness from the finishing order of stages. Every pull of every table lies in a finished stage; +every finished stage's channel is consistent under the balance check; every component's +requirements on a stage follow from its guarantees on the stages finished before it. +-/ +theorem tableSoundness_of_stagedRequirementsOn {ens : Ensemble F PublicIO} {balance : Balance F} + (finished : List (Stage F)) + (verifier_empty : ens.verifier = .empty F PublicIO) + (finished_channels : ∀ s ∈ finished, s.channel ∈ ens.channels) + (covered : ∀ table : Table F, table.component ∈ ens.tables → + ∀ c ∈ table.component.circuit.channelsWithGuarantees, + ∀ i ∈ table.interactionsWith c, i.direction = .pull → + ∃ s ∈ finished, s.channel = c ∧ s.cls i.msg) + (consistent : ∀ s ∈ finished, s.channel.ConsistentUpTo balance.pullBound) + (staged : ∀ component ∈ ens.tables, component.StagedRequirementsOn finished) : + ens.TableSoundness balance := by + intro witness assumptions constraints fit balanced + have guarantees := guaranteesOn_of_stagedRequirementsOn verifier_empty witness assumptions + constraints + (witness.balancedChannels_of_balanced fit balanced) + finished_channels consistent staged + refine ⟨?_, fun table h_table => ?_⟩ + · apply ens.verifierSpec_of_verifierGuarantees + rw [verifierGuarantees_iff] + intro channel h_channel + simp [verifier_empty, Verifier.Program.empty, circuit_norm] at h_channel + · have h_comp := witness.component_mem_tables_of_mem h_table + have all_guarantees : table.Guarantees := + Table.guarantees_of_guaranteesOn (covered table h_comp) (guarantees table h_table) + exact (Table.weakSoundness (assumptions table h_table) (constraints table h_table) + all_guarantees).1 + +/-! +### The channel form + +A whole channel is the stage whose class is every message, so a finishing order of channels is the +finishing order of those stages, and the theorem below is the stage one read through that +correspondence. The statement is kept because an ensemble whose channels finish whole is the +simpler thing to say, and to use. +-/ + +/-- +Soundness from channel finishing order: if every table's guarantees come from finished channels, +every finished channel is consistent under the balance check, and every component's requirements +on a finished channel follow from its guarantees on the channels finished before it, then the +tables are sound. +-/ +theorem tableSoundness_of_stagedRequirements {ens : Ensemble F PublicIO} {balance : Balance F} + (finished : List (RawChannel F)) + (verifier_empty : ens.verifier = .empty F PublicIO) + (finished_subset : finished ⊆ ens.channels) + (subset_finished : ∀ component ∈ ens.tables, + component.circuit.channelsWithGuarantees ⊆ finished) + (consistent : ∀ channel ∈ finished, channel.ConsistentUpTo balance.pullBound) + (staged : ∀ component ∈ ens.tables, component.StagedRequirements finished) : + ens.TableSoundness balance := + tableSoundness_of_stagedRequirementsOn (finished.map Stage.ofChannel) verifier_empty + (by simpa [circuit_norm] using fun _ h => finished_subset h) + (fun table h c h_c _ _ _ => ⟨Stage.ofChannel c, + List.mem_map_of_mem (subset_finished table.component h h_c), rfl, rfl⟩) + (by simpa [circuit_norm] using consistent) + (fun component h => Component.stagedRequirementsOn_of_stagedRequirements (staged component h)) + +end Ensemble +end Air.Flat diff --git a/Clean/Examples/CountedSquares/Ensemble.lean b/Clean/Examples/CountedSquares/Ensemble.lean index 44ee08a7d..669e87782 100644 --- a/Clean/Examples/CountedSquares/Ensemble.lean +++ b/Clean/Examples/CountedSquares/Ensemble.lean @@ -35,7 +35,8 @@ here pulls a fixed count per row instead. Constraining the count arithmetically only scales for a small bound. A circuit counting to `510` would range-check its multiplicity on another channel instead, which needs a finishing order over -several channels rather than the single finished channel here. +several channels rather than the single finished channel here, as in +`Clean/Examples/StagedSquares`. -/ namespace CountedSquares diff --git a/Clean/Examples/SameBus/Ensemble.lean b/Clean/Examples/SameBus/Ensemble.lean new file mode 100644 index 000000000..b019b6ab6 --- /dev/null +++ b/Clean/Examples/SameBus/Ensemble.lean @@ -0,0 +1,260 @@ +module + +public import Clean.Air.StagedChannels +public import Clean.Air.WitnessGeneration + +@[expose] public section + +/-! +# One bus, pulled and pushed by the same table + +A table that both pulls from a channel and pushes to it is not a cycle when what it reads and +what it writes are disjoint classes of messages. A bus shared by several operations is where this +happens: the table that answers one operation does so by using the answers to others, and all of +it travels under one channel name. + +The bus here carries `(tag, a, b)`. At `tag = 0` the channel guarantees `b = a * a`, at `tag = 1` +it guarantees `b = a⁴`. Every interaction is a plain push or pull: multiplicity is what +`Clean/Examples/CountedSquares` is about, and it is orthogonal to the ordering question here. A squaring chip provides the squares. A fourth-power chip pulls a square +and pushes a fourth power, on the same bus: its push owes `b = a⁴`, and it pays for it with the +guarantee it got from its pull, plus one constraint of its own. + +Ordering whole channels cannot express that — `powers` would have to come before itself. Ordering +*stages*, a channel together with a class of its messages, can: the squares are finished before +the fourth powers, and `Ensemble.tableSoundness_of_stagedRequirementsOn` runs the induction over +those two classes. +-/ + +namespace SameBus + +open Air.Flat + +variable {p : ℕ} [Fact p.Prime] + +/-- A message of the bus: an operation tag, an argument and a result. -/ +structure PowerMsg (F : Type) where + /-- `0` for a square, `1` for a fourth power -/ + tag : F + a : F + b : F +deriving ProvableStruct + +/-- The bus. What it guarantees depends on the tag, which is what makes the two classes of +messages different obligations rather than the same one twice. -/ +def powers : Channel (F p) PowerMsg where + name := "powers" + Guarantees m _ := + (m.tag = 0 → m.b = m.a * m.a) ∧ (m.tag = 1 → m.b = (m.a * m.a) * (m.a * m.a)) + +/-- The fourth-power messages of the bus, read off the raw message. -/ +def isFourth (msg : Array (F p)) : Bool := + if h : msg.size = size PowerMsg then + decide ((fromElements (⟨msg, h⟩ : Vector (F p) (size PowerMsg)) : PowerMsg (F p)).tag = 1) + else false + +lemma isFourth_toElements (m : PowerMsg (F p)) : + isFourth (toElements m).toArray = decide (m.tag = 1) := by + simp [isFourth, ProvableType.fromElements_toElements] + +/-! ## The three chips -/ + +structure SquareInput (F : Type) where + a : F + b : F +deriving ProvableStruct + +/-- Provides the squares: constrains `b = a * a` and pushes it at `tag = 0`. Its own constraint +pays for the guarantee, so it pulls nothing and receives nothing. -/ +def squareProvider : GeneralFormalCircuit (F p) SquareInput unit where + name := "square-provider" + main input := do + input.b === input.a * input.a + powers.push { tag := 0, a := input.a, b := input.b } + + channelsWithRequirements := [powers.toRaw] + Spec _ _ _ := True + ProverAssumptions input _ _ := input.b = input.a * input.a + + soundness := by + circuit_proof_start [powers] + simp_all + completeness := by + circuit_proof_start [powers] + simp_all + +structure FourthInput (F : Type) where + x : F + /-- the square of `x`, read off the bus -/ + y : F + z : F +deriving ProvableStruct + +/-- Pulls a square and pushes a fourth power, on the same bus. Its push owes `b = a⁴`, and one +constraint is not enough to pay for it: `z = y * y` says nothing about `x` until the bus says +`y = x * x`. That is the obligation the finishing order discharges. -/ +def fourthChip : GeneralFormalCircuit (F p) FourthInput unit where + name := "fourth-chip" + main input := do + powers.pull { tag := 0, a := input.x, b := input.y } + input.z === input.y * input.y + powers.push { tag := 1, a := input.x, b := input.z } + + channelsWithRequirements := [powers.toRaw] + Spec _ _ _ := True + ProverAssumptions input _ _ := input.y = input.x * input.x ∧ input.z = input.y * input.y + + soundness := by + circuit_proof_start [powers] + simp_all + completeness := by + circuit_proof_start [powers] + simp_all + +structure ConsumerInput (F : Type) where + x : F + z : F +deriving ProvableStruct + +/-- Reads a fourth power off the bus. -/ +def fourthConsumer : GeneralFormalCircuit (F p) ConsumerInput unit where + name := "fourth-consumer" + main input := do + powers.pull { tag := 1, a := input.x, b := input.z } + + Spec input _ _ := input.z = (input.x * input.x) * (input.x * input.x) + ProverAssumptions input _ _ := input.z = (input.x * input.x) * (input.x * input.x) + + soundness := by + circuit_proof_start [powers] + simp_all + completeness := by + circuit_proof_start [powers] + simp_all + +/-! ## The ensemble and its two stages -/ + +abbrev squareProviderComponent : Component (F p) where + circuit := squareProvider + generation := .demand { + channel := powers + trigger := .pull + input m := pure { a := .witness m.a, b := .witness m.b } + } + +abbrev fourthChipComponent : Component (F p) where + circuit := fourthChip + generation := .demand { + channel := powers + trigger := .pull + input m := pure { x := .witness m.a, y := .witness 0, z := .witness m.b } + } + +abbrev fourthConsumerComponent : Component (F p) where + circuit := fourthConsumer + generation := .demand { + channel := powers + trigger := .push + input m := pure { x := .witness m.a, z := .witness m.b } + } + +/-- The three chips and the one bus they share. -/ +def ensemble : Ensemble (F p) unit where + tables := [squareProviderComponent, fourthChipComponent, fourthConsumerComponent] + unique_names := by + simp [squareProviderComponent, fourthChipComponent, fourthConsumerComponent, + squareProvider, fourthChip, fourthConsumer] + channels := [powers.toRaw] + unique_channel_names := by simp [circuit_norm, powers] + tables_channels := by + intro table h + simp only [List.mem_cons, List.not_mem_nil, or_false] at h + rcases h with rfl | rfl | rfl <;> simp [circuit_norm, squareProvider, fourthChip, fourthConsumer] + verifier_channels := by simp [circuit_norm] + +/-- The two classes of the bus, newest first: the fourth powers, then the squares. One channel, +finished in two steps. -/ +def stages : List (Stage (F p)) := + [{ channel := powers.toRaw, cls := isFourth }, + { channel := powers.toRaw, cls := fun m => !isFourth m }] + +/-- Every interaction the chip makes on the bus is either its pull, at `tag = 0`, or its push, at +`tag = 1`. Nothing else travels, which is what lets the two classes split its obligations. -/ +lemma chip_shape {table : Table (F p)} (h_comp : table.component = fourthChipComponent) + {i : Interaction (F p)} (h_i : i ∈ table.interactionsWith powers.toRaw) : + (i.direction = .pull ∧ isFourth i.msg = false) ∨ + (i.direction = .push ∧ isFourth i.msg = true) := by + cases table + simp only at h_comp + subst h_comp + simp [Table.interactionsWith, List.mem_flatMap, Operations.interactionValuesWith_eq_map, + Component.interactionsWith_eq, Component.rowOperations, fourthChipComponent, fourthChip, + powers, circuit_norm] at h_i + obtain ⟨a, -, h⟩ := h_i + rcases h with rfl | rfl + · left; simp [AbstractInteraction.eval, isFourth_toElements, circuit_norm] + · right; simp [AbstractInteraction.eval, isFourth_toElements, circuit_norm] + +/-- On the squares the chip owes only what any plain pull owes, a multiplicity of `0` or `1`, and +it pulls exactly once. Its push is a fourth power, so this class excludes it. -/ +theorem chip_requirementsAfterOn_square {earlier : List (Stage (F p))} : + (fourthChipComponent (p := p)).RequirementsAfterOn + { channel := powers.toRaw, cls := fun m => !isFourth m } earlier := by + apply Component.requirementsAfterOn_of_rowOperations + rintro table - - - - row hrow i h_i h_chan h_cls + simp [circuit_norm, fourthChipComponent, fourthChip, powers] at h_i ⊢ + rcases h_i with rfl | h_i | rfl + · simp [circuit_norm] + · simp [circuit_norm, Gadgets.Equality.circuit, + Gadgets.Equality.main, FormalAssertion.toSubcircuit_interactions] at h_i + · simp [AbstractInteraction.eval, isFourth_toElements, circuit_norm] at h_cls + +/-- The chip's push at `tag = 1` owes `b = a⁴`, and the guarantee it was handed at `tag = 0` is +what pays for it: the bus said `y = x * x`, the chip's own constraint says `z = y * y`. Its only +pull lies in the earlier class, so its soundness closes the rest. -/ +theorem chip_requirementsAfterOn_fourth : + (fourthChipComponent (p := p)).RequirementsAfterOn + { channel := powers.toRaw, cls := isFourth } + [{ channel := powers.toRaw, cls := fun m => !isFourth m }] := by + apply Component.requirementsAfterOn_of_covered + intro table h_comp c h_c i h_i h_pull + have hc : c = powers.toRaw := by + simpa [circuit_norm, fourthChipComponent, fourthChip] using h_c + subst hc + rcases chip_shape h_comp h_i with ⟨-, h_cls⟩ | ⟨h_push, -⟩ + · exact ⟨{ channel := powers.toRaw, cls := fun m => !isFourth m }, by simp, rfl, by simp [h_cls]⟩ + · rw [h_push] at h_pull; exact absurd h_pull (by decide) + +theorem tableSoundness : + (ensemble (p := p)).TableSoundness Balance.logUp := by + apply Ensemble.tableSoundness_of_stagedRequirementsOn stages rfl + · intro s hs + simp only [stages, List.mem_cons, List.not_mem_nil, or_false] at hs + rcases hs with rfl | rfl <;> simp [ensemble] + · -- the bus is the only channel with guarantees, and the two classes cover every message + intro table h_comp c h_c i h_i h_pull + have hc : c = powers.toRaw := by + simp only [ensemble, List.mem_cons, List.not_mem_nil, or_false] at h_comp + rcases h_comp with h | h | h <;> rw [h] at h_c <;> + simp_all [circuit_norm, squareProvider, fourthChip, fourthConsumer] + subst hc + by_cases h : isFourth i.msg + · exact ⟨{ channel := powers.toRaw, cls := isFourth }, by simp [stages], rfl, h⟩ + · exact ⟨{ channel := powers.toRaw, cls := fun m => !isFourth m }, by simp [stages], rfl, + by simp [h]⟩ + · intro s hs + show s.channel.ConsistentUpTo (Balance.logUp (F := F p)).pullBound + simp only [stages, List.mem_cons, List.not_mem_nil, or_false] at hs + rcases hs with rfl | rfl <;> infer_instance + · intro component h + simp only [ensemble, List.mem_cons, List.not_mem_nil, or_false] at h + rcases h with rfl | rfl | rfl + -- the square provider receives no guarantee, so it owes nothing anywhere + · exact Component.stagedRequirementsOn_of_no_guarantees + (by simp [circuit_norm, squareProvider]) _ + -- the chip: the fourth powers after the squares, and a plain pull on the squares + · exact ⟨chip_requirementsAfterOn_fourth, chip_requirementsAfterOn_square, trivial⟩ + -- the consumer declares no requirements at all + · refine ⟨?_, ?_, trivial⟩ <;> + exact Component.requirementsAfterOn_of_not_mem _ (by simp [circuit_norm, fourthConsumer]) + +end SameBus diff --git a/Clean/Examples/StagedSquares/Ensemble.lean b/Clean/Examples/StagedSquares/Ensemble.lean new file mode 100644 index 000000000..9ff3cdd66 --- /dev/null +++ b/Clean/Examples/StagedSquares/Ensemble.lean @@ -0,0 +1,187 @@ +module + +public import Clean.Examples.CountedSquares.Ensemble +public import Clean.Air.OrderedChannel +public import Clean.Air.StagedChannels + +@[expose] public section + +/-! +# A count bounded on another channel + +`Clean/Examples/CountedSquares` pulls a square with multiplicity `1` or `2`, and the consumer +discharges the pull's requirement `count = 0 ∨ CountUpTo 2 count` with a constraint of its own, +`(count - 1) * (count - 2) = 0`. That only scales while the bound is small enough to write as a +polynomial: a chip counting to `255` range-checks its multiplicity instead, on a second channel. + +Here the range check is that second channel. `counts` carries a multiplicity that counts up to +`countBound`, a chip provides it, and the consumer pulls from it rather than constraining its +count. The consumer's requirement on `squares` then follows from its *guarantee* on `counts`, +which `OrderedChannel` cannot express: it orders tables, and nothing about the order of these +three tables says where the bound comes from. `Ensemble.tableSoundness_of_stagedRequirements` +orders the channels instead, `counts` finished before `squares`. + +The ensemble is assembled directly rather than through `SoundEnsemble`, which the staged argument +does not compose with. It generates, and `WitnessGenerationTest.lean` pins what it generates. +-/ + +namespace StagedSquares + +open Air.Flat CountedSquares + +variable {p : ℕ} [Fact p.Prime] + +/-- A multiplicity that counts up to `countBound`. Pulling it is the range check. -/ +def counts : Channel (F p) field where + name := "counts" + Guarantees c _ := CountUpTo countBound c + +structure RangeInput (F : Type) where + /-- the multiplicity being range-checked -/ + c : F + /-- how many pulls this row answers -/ + mult : F +deriving ProvableStruct + +/-- The range chip: constrains its value to `1` or `2` and pushes it as often as it is pulled. Its +constraint is what pays for the guarantee, exactly as the squaring chip's constraint pays for +`y = x * x`. + +The multiplicity is pushed as it stands. The squaring chip of `CountedSquares` emits `mult + 1` +because it is `preallocated`: its rows exist before any demand and their multiplicity cells start +at `0`, so the `+ 1` is what seeds a run. This chip is `demand`, so a row is created only by a pull +it has to answer and is born with that pull counted; a `+ 1` here would push once more than anyone +pulls, and the channel would not balance. -/ +def rangeProvider : GeneralFormalCircuit (F p) RangeInput unit where + name := "counts-provider" + main input := do + assertZero ((input.c - 1) * (input.c - 2)) + counts.emit input.mult input.c + + channelsWithRequirements := [counts.toRaw] + Spec _ _ _ := True + ProverAssumptions input _ _ := input.c = 1 ∨ input.c = 2 + + soundness := by + circuit_proof_start [counts] + simp_all [countUpTo_of_sub_one_mul_sub_two_eq_zero] + completeness := by + circuit_proof_start [counts] + rcases h_assumptions with h | h <;> simp [h] + +/-- A row that needs `y = x * x` `count` times, and says nothing about `count` itself: the bound +comes from the pull on `counts`. The pull on `squares` therefore owes a requirement this circuit +cannot pay on its own, which is the point of the example. -/ +def stagedConsumer : GeneralFormalCircuit (F p) ConsumerInput unit where + name := "staged-squares-consumer" + main input := do + counts.pull input.count + squares.pullUpTo countBound input.count (input.x, input.y) + + channelsWithRequirements := [squares.counted countBound] + Spec input _ _ := input.y = input.x * input.x + ProverAssumptions input _ _ := + (input.count = 1 ∨ input.count = 2) ∧ input.y = input.x * input.x + + soundness := by + circuit_proof_start [squares, counts] + simp_all + completeness := by + circuit_proof_start [squares, counts] + obtain ⟨h_count, h_square⟩ := h_assumptions + refine ⟨?_, fun _ => h_square⟩ + rcases h_count with h | h <;> simp [h] <;> + exact countUpTo_of_sub_one_mul_sub_two_eq_zero (by ring) + +/-- One row per pulled count that nothing has pushed. The padding row answers nothing — multiplicity +`0`, no push — and `c := 1` is there to satisfy the chip's own constraint, which `0` would not. -/ +abbrev rangeProviderComponent : Component (F p) where + circuit := rangeProvider + generation := .demand { + channel := counts + trigger := .pull + input c := pure { c, mult := .multiplicity } + padding := { c := 1, mult := 0 } + } + +/-- One row per pushed square that nothing has pulled, as in `CountedSquares`, but pulling its +count from `counts` instead of constraining it. -/ +abbrev stagedConsumerComponent : Component (F p) where + circuit := stagedConsumer + generation := .demand { + channel := squares + trigger := .push + input | (x, y) => pure { x, y, count := .witness 2 } + } + +/-- The claim the module docstring makes, machine-checked: the hierarchy of `OrderedChannel.lean` +cannot take this consumer, which both pulls from `squares` and owes requirements on it. -/ +example : ¬ OrderedChannelRefl (squares.counted countBound : RawChannel (F p)) + (stagedConsumerComponent (p := p)) := by + simp [circuit_norm, stagedConsumer] + +/-- The three chips and the two channels they share. Assembled directly: the staged argument is +stated for a whole ensemble, so there is no `SoundEnsemble` to build up. -/ +def ensemble : Ensemble (F p) unit where + tables := [rangeProviderComponent, providerComponent, stagedConsumerComponent] + unique_names := by + simp [rangeProviderComponent, providerComponent, stagedConsumerComponent, rangeProvider, + provider, stagedConsumer] + channels := [squares.counted countBound, counts.toRaw] + unique_channel_names := by simp [circuit_norm, squares, counts] + tables_channels := by + intro table h + simp only [List.mem_cons, List.not_mem_nil, or_false] at h + rcases h with rfl | rfl | rfl <;> simp [circuit_norm, rangeProvider, provider, stagedConsumer] + verifier_channels := by simp [circuit_norm] + +/-- `counts` finished before `squares`: the consumer's requirement on the second uses its +guarantee on the first. -/ +def finished : List (RawChannel (F p)) := [squares.counted countBound, counts.toRaw] + +/-- The heart of the example: the consumer owes `count = 0 ∨ CountUpTo countBound count` on its +counted pull, and pays for it with the guarantee it got from `counts`, not with a constraint. -/ +theorem consumer_requirementsAfter {earlier : List (RawChannel (F p))} + (h_earlier : counts.toRaw ∈ earlier) : + (stagedConsumerComponent (p := p)).RequirementsAfter (squares.counted countBound) earlier := by + rintro table h_comp - constraints guarantees row hrow + have g := guarantees _ h_earlier row hrow + cases table + simp only at h_comp + subst h_comp + simp only [Component.channelGuarantees_iff, Component.channelRequirements_iff] at g ⊢ + simp [circuit_norm, Component.rowOperations, stagedConsumerComponent, stagedConsumer, + counts, squares] at g ⊢ + exact .inr g.1 + +/-- Every table of the ensemble is sound, from the finishing order `counts`, then `squares`. The +consumer constrains nothing about its count; what makes its pull legal is a guarantee it was +handed on another channel, and the order is what says that guarantee was already earned. -/ +theorem tableSoundness : + (ensemble (p := p)).TableSoundness (Balance.logUpUpTo countBound) := by + apply Ensemble.tableSoundness_of_stagedRequirements finished rfl (List.Subset.refl _) + · intro component h + simp only [ensemble, List.mem_cons, List.not_mem_nil, or_false] at h + rcases h with rfl | rfl | rfl <;> + simp [circuit_norm, finished, rangeProvider, provider, stagedConsumer, counts, squares] + · intro c hc + show c.ConsistentUpTo (Balance.logUpUpTo countBound).pullBound + simp only [finished, List.mem_cons, List.not_mem_nil, or_false] at hc + rcases hc with rfl | rfl <;> infer_instance + · intro component h + simp only [ensemble, List.mem_cons, List.not_mem_nil, or_false] at h + rcases h with rfl | rfl | rfl + -- the two providers pull nothing, so they receive no guarantee and owe unconditionally + · exact Component.stagedRequirements_of_forall fun _ _ _ => + Component.requirementsAfter_of_guarantees_subset (by simp [circuit_norm, rangeProvider]) + · exact Component.stagedRequirements_of_forall fun _ _ _ => + Component.requirementsAfter_of_guarantees_subset (by simp [circuit_norm, provider]) + -- the consumer: `squares` after `counts`, and nothing owed on `counts` itself + · refine ⟨consumer_requirementsAfter (by simp), ?_, trivial⟩ + apply Component.requirementsAfter_of_not_mem + simp only [circuit_norm, stagedConsumer, List.mem_cons, List.not_mem_nil, or_false] + intro h + have := congrArg RawChannel.name h + simp [counts, squares, Channel.toRaw, Channel.counted] at this + +end StagedSquares diff --git a/Clean/Examples/StagedSquares/WitnessGenerationTest.lean b/Clean/Examples/StagedSquares/WitnessGenerationTest.lean new file mode 100644 index 000000000..57a5e77f1 --- /dev/null +++ b/Clean/Examples/StagedSquares/WitnessGenerationTest.lean @@ -0,0 +1,39 @@ +module + +public import Clean.Examples.StagedSquares.Ensemble +public import Clean.Utils.Primes + +-- `native_decide` runs compiled code from these modules. +public meta import Clean.Examples.StagedSquares.Ensemble +public meta import Clean.Utils.Primes + +@[expose] public section + +namespace StagedSquares.WitnessGenerationTest + +open Air.Flat Air.Flat.WitnessGeneration CountedSquares + +/-- Small enough to run in, and large enough for the bound: the run below makes `8` interactions on +`squares`, and `Balance.logUpUpTo 2` asks for `8 * 2 < p1009`. -/ +abbrev p : ℕ := p1009 + +/-- The heights of the generated tables, and whether the witness satisfies the constraints, the +balance check and its interaction bound. -/ +def result : Except String (List ℕ × Bool × Bool × Bool) := + match generate (ensemble (p := p)) 100 () () with + | .error error => .error (toString error) + | .ok witness => + .ok (witness.heights, constraintsHold witness, channelsBalanced witness, + (ensemble (p := p)).interactionsFit (Balance.logUpUpTo countBound) witness.heights) + +/-- Four provider rows seed `squares` with one push each, two consumer rows answer them at +multiplicity `2`, and each consumer row pulls its count once, so one range row answers both at +multiplicity `2`. `heights` lists the tables in the ensemble's order. + +This is what the example claims and could not claim before: the count a consumer pulls is a +message on a channel like any other, so a run has to balance it like any other. An earlier version +of the range chip emitted `mult + 1`, as the preallocated squaring chip does, and generation +stopped with `unhandled channel imbalance on: counts`. -/ +example : result = .ok ([1, 4, 2], true, true, true) := by native_decide + +end StagedSquares.WitnessGenerationTest diff --git a/Clean/Test.lean b/Clean/Test.lean index 1e59a56ee..a587fa2c8 100644 --- a/Clean/Test.lean +++ b/Clean/Test.lean @@ -17,3 +17,4 @@ public import Clean.Examples.FemtoCairo.FlatAirTest public import Clean.Examples.OpcodeVm.WitnessGenerationTest public import Clean.Examples.BinaryFibonacci.WitnessGenerationTest public import Clean.Examples.CountedSquares.WitnessGenerationTest +public import Clean.Examples.StagedSquares.WitnessGenerationTest