Skip to main content

hydro_lang/properties/
mod.rs

1//! Types for reasoning about algebraic properties for Rust closures.
2
3use std::marker::PhantomData;
4
5use stageleft::properties::Property;
6
7use crate::live_collections::boundedness::Boundedness;
8use crate::live_collections::keyed_singleton::KeyedSingletonBound;
9use crate::live_collections::singleton::SingletonBound;
10use crate::live_collections::stream::{ExactlyOnce, Ordering, Retries, TotalOrder};
11
12/// A trait for proof mechanisms that can validate commutativity.
13#[sealed::sealed]
14pub trait CommutativeProof {
15    /// Registers the expression with the proof mechanism.
16    ///
17    /// This should not perform any blocking analysis; it is only intended to record the expression for later processing.
18    fn register_proof(&self, expr: &syn::Expr);
19}
20
21/// A trait for proof mechanisms that can validate idempotence.
22#[sealed::sealed]
23pub trait IdempotentProof {
24    /// Registers the expression with the proof mechanism.
25    ///
26    /// This should not perform any blocking analysis; it is only intended to record the expression for later processing.
27    fn register_proof(&self, expr: &syn::Expr);
28}
29
30/// A trait for proof mechanisms that can validate monotonicity.
31#[sealed::sealed]
32pub trait MonotoneProof {
33    /// Registers the expression with the proof mechanism.
34    ///
35    /// This should not perform any blocking analysis; it is only intended to record the expression for later processing.
36    fn register_proof(&self, expr: &syn::Expr);
37}
38
39/// A trait for proof mechanisms that can validate order-preservation (monotonicity of a map function).
40#[sealed::sealed]
41pub trait OrderPreservingProof {
42    /// Registers the expression with the proof mechanism.
43    ///
44    /// This should not perform any blocking analysis; it is only intended to record the expression for later processing.
45    fn register_proof(&self, expr: &syn::Expr);
46}
47
48/// A trait for proof mechanisms that can validate consistency of a collection.
49#[sealed::sealed]
50pub trait ConsistencyProof {}
51
52/// A hand-written human proof of the correctness property.
53///
54/// To create a manual proof, use the [`manual_proof!`] macro, which takes in a doc comment
55/// explaining why the property holds.
56pub struct ManualProof();
57#[sealed::sealed]
58impl CommutativeProof for ManualProof {
59    fn register_proof(&self, _expr: &syn::Expr) {}
60}
61#[sealed::sealed]
62impl IdempotentProof for ManualProof {
63    fn register_proof(&self, _expr: &syn::Expr) {}
64}
65#[sealed::sealed]
66impl MonotoneProof for ManualProof {
67    fn register_proof(&self, _expr: &syn::Expr) {}
68}
69#[sealed::sealed]
70impl OrderPreservingProof for ManualProof {
71    fn register_proof(&self, _expr: &syn::Expr) {}
72}
73#[sealed::sealed]
74impl ConsistencyProof for ManualProof {}
75
76#[doc(inline)]
77pub use crate::__manual_proof__ as manual_proof;
78
79#[macro_export]
80/// Fulfills a proof parameter by declaring a human-written justification for why
81/// the algebraic property (e.g. commutativity, idempotence) holds.
82///
83/// The argument must be a doc comment explaining why the property is satisfied.
84///
85/// # Examples
86/// ```rust,ignore
87/// use hydro_lang::prelude::*;
88///
89/// stream.fold(
90///     q!(|| 0),
91///     q!(
92///         |acc, x| *acc += x,
93///         commutative = manual_proof!(/** integer addition is commutative */)
94///     )
95/// )
96/// ```
97macro_rules! __manual_proof__ {
98    ($(#[doc = $doc:expr])+) => {
99        $crate::properties::ManualProof()
100    };
101}
102
103/// Marks that the property is not proved.
104pub enum NotProved {}
105
106/// Marks that the property is proven.
107pub enum Proved {}
108
109/// Algebraic properties for an aggregation function of type (T, &mut A) -> ().
110///
111/// Commutativity:
112/// ```rust,ignore
113/// let mut state = ???;
114/// f(a, &mut state); f(b, &mut state) // produces same final state as
115/// f(b, &mut state); f(a, &mut state)
116/// ```
117///
118/// Idempotence:
119/// ```rust,ignore
120/// let mut state = ???;
121/// f(a, &mut state);
122/// let state1 = *state;
123/// f(a, &mut state);
124/// // state1 must be equal to state
125/// ```
126pub struct AggFuncAlgebra<Commutative = NotProved, Idempotent = NotProved, Monotone = NotProved>(
127    Option<Box<dyn CommutativeProof>>,
128    Option<Box<dyn IdempotentProof>>,
129    Option<Box<dyn MonotoneProof>>,
130    PhantomData<(Commutative, Idempotent, Monotone)>,
131);
132
133impl<C, I, M> AggFuncAlgebra<C, I, M> {
134    /// Marks the function as being commutative, with the given proof mechanism.
135    pub fn commutative(
136        self,
137        proof: impl CommutativeProof + 'static,
138    ) -> AggFuncAlgebra<Proved, I, M> {
139        AggFuncAlgebra(Some(Box::new(proof)), self.1, self.2, PhantomData)
140    }
141
142    /// Marks the function as being idempotent, with the given proof mechanism.
143    pub fn idempotent(self, proof: impl IdempotentProof + 'static) -> AggFuncAlgebra<C, Proved, M> {
144        AggFuncAlgebra(self.0, Some(Box::new(proof)), self.2, PhantomData)
145    }
146
147    /// Marks the function as being monotone, with the given proof mechanism.
148    pub fn monotone(self, proof: impl MonotoneProof + 'static) -> AggFuncAlgebra<C, I, Proved> {
149        AggFuncAlgebra(self.0, self.1, Some(Box::new(proof)), PhantomData)
150    }
151
152    /// Registers the expression with the underlying proof mechanisms.
153    pub(crate) fn register_proof(self, expr: &syn::Expr) {
154        if let Some(comm_proof) = self.0 {
155            comm_proof.register_proof(expr);
156        }
157
158        if let Some(idem_proof) = self.1 {
159            idem_proof.register_proof(expr);
160        }
161
162        if let Some(monotone_proof) = self.2 {
163            monotone_proof.register_proof(expr);
164        }
165    }
166}
167
168impl<C, I, M> Property for AggFuncAlgebra<C, I, M> {
169    type Root = AggFuncAlgebra;
170
171    fn make_root(_target: &mut Option<Self>) -> Self::Root {
172        AggFuncAlgebra(None, None, None, PhantomData)
173    }
174}
175
176/// Algebraic properties for a map function of type T -> U.
177///
178/// Order-preserving means that if the input grows monotonically, the output also grows monotonically.
179pub struct MapFuncAlgebra<OrderPreserving = NotProved>(
180    Option<Box<dyn OrderPreservingProof>>,
181    PhantomData<OrderPreserving>,
182);
183
184impl<O> MapFuncAlgebra<O> {
185    /// Marks the function as being order-preserving, with the given proof mechanism.
186    pub fn order_preserving(
187        self,
188        proof: impl OrderPreservingProof + 'static,
189    ) -> MapFuncAlgebra<Proved> {
190        MapFuncAlgebra(Some(Box::new(proof)), PhantomData)
191    }
192
193    /// Registers the expression with the underlying proof mechanisms.
194    pub(crate) fn register_proof(self, expr: &syn::Expr) {
195        if let Some(proof) = self.0 {
196            proof.register_proof(expr);
197        }
198    }
199}
200
201impl<O> Property for MapFuncAlgebra<O> {
202    type Root = MapFuncAlgebra;
203
204    fn make_root(_target: &mut Option<Self>) -> Self::Root {
205        MapFuncAlgebra(None, PhantomData)
206    }
207}
208
209/// Marker trait identifying that the commutativity property is valid for the given stream ordering.
210#[diagnostic::on_unimplemented(
211    message = "Because the input stream has ordering `{O}`, the closure must demonstrate commutativity with a `commutative = ...` annotation.",
212    label = "required for this call",
213    note = "To intentionally process the stream by observing a non-deterministic (shuffled) order of elements, use `.assume_ordering`. This introduces non-determinism so avoid unless necessary."
214)]
215#[sealed::sealed]
216pub trait ValidCommutativityFor<O: Ordering> {}
217#[sealed::sealed]
218impl ValidCommutativityFor<TotalOrder> for NotProved {}
219#[sealed::sealed]
220impl<O: Ordering> ValidCommutativityFor<O> for Proved {}
221
222/// Marker trait identifying that the idempotence property is valid for the given stream ordering.
223#[diagnostic::on_unimplemented(
224    message = "Because the input stream has retries `{R}`, the closure must demonstrate idempotence with an `idempotent = ...` annotation.",
225    label = "required for this call",
226    note = "To intentionally process the stream by observing non-deterministic (randomly duplicated) retries, use `.assume_retries`. This introduces non-determinism so avoid unless necessary."
227)]
228#[sealed::sealed]
229pub trait ValidIdempotenceFor<R: Retries> {}
230#[sealed::sealed]
231impl ValidIdempotenceFor<ExactlyOnce> for NotProved {}
232#[sealed::sealed]
233impl<R: Retries> ValidIdempotenceFor<R> for Proved {}
234
235/// Marker trait identifying the boundedness of a singleton given a monotonicity property of
236/// an aggregation on a stream.
237#[sealed::sealed]
238pub trait ApplyMonotoneStream<P, B2: SingletonBound> {}
239
240#[sealed::sealed]
241impl<B: Boundedness> ApplyMonotoneStream<NotProved, B> for B {}
242
243#[sealed::sealed]
244impl<B: Boundedness> ApplyMonotoneStream<Proved, B::StreamToMonotone> for B {}
245
246/// Marker trait identifying the boundedness of a singleton given a monotonicity property of
247/// an aggregation on a keyed stream.
248#[sealed::sealed]
249pub trait ApplyMonotoneKeyedStream<P, B2: KeyedSingletonBound> {}
250
251#[sealed::sealed]
252impl<B: Boundedness> ApplyMonotoneKeyedStream<NotProved, B> for B {}
253
254#[sealed::sealed]
255impl<B: Boundedness> ApplyMonotoneKeyedStream<Proved, B::KeyedStreamToMonotone> for B {}
256
257/// Marker trait identifying the boundedness of a singleton after a map operation,
258/// given an order-preserving property.
259#[sealed::sealed]
260pub trait ApplyOrderPreservingSingleton<P, B2: SingletonBound> {}
261
262#[sealed::sealed]
263impl<B: SingletonBound> ApplyOrderPreservingSingleton<NotProved, B::UnderlyingBound> for B {}
264
265#[sealed::sealed]
266impl<B: SingletonBound> ApplyOrderPreservingSingleton<Proved, B> for B {}