Skip to main content

polydat_core/iteration/comprehension/strategies/
mod.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Strategy implementations — spec §3.6 + §10.2 R2 + §10.7.8.
5//!
6//! ## Single invocation surface
7//!
8//! Every named strategy exposes one public entry point —
9//! [`Strategy::apply`]. The caller passes an [`EvaluatedInput`]
10//! carrying the materialized tuples, their cardinality, and the
11//! `IndexFn` they actually satisfy. The strategy decides
12//! internally whether to dispatch its closed-form indexed
13//! algorithm (when `has_closed_form_for(&input.index_fn)`) or
14//! its fallback reorder over the materialized tuples.
15//!
16//! Per spec §10.7.8 this is the **strategy invocation
17//! contract**: V4 fires at `apply` time against the
18//! `EvaluatedInput`'s `index_fn` — definitively, regardless of
19//! how the input source was authored (literal, range,
20//! registry-recognized generator, or workload-param).
21//!
22//! ## Internal split
23//!
24//! Per-strategy modules organise the implementation into two
25//! private helpers (`apply_indexed` for the R2 closed-form path
26//! when applicable, `apply_naive` for the generic fallback);
27//! [`Strategy::apply`] is the dispatcher. The trait surface
28//! exposes only the dispatcher plus the V4/R2 introspection
29//! predicates ([`Strategy::accepts_input`],
30//! [`Strategy::has_closed_form_for`]).
31//!
32//! Strategies are selected by [`StrategyName`]; [`for_name`]
33//! dispatches a strategy name to its boxed [`Strategy`] impl.
34
35use super::metadata::IndexFn;
36use super::strategy::StrategyName;
37
38pub mod antidiagonal;
39pub mod diagonal;
40pub mod extrema;
41pub mod halton;
42pub mod lex;
43pub mod lhs;
44pub mod prng;
45pub mod reverse_lex;
46pub mod shells;
47pub mod shuffle;
48pub mod sobol;
49
50/// A multi-coordinate index. Each component is the per-axis
51/// position in the input's index space. Length equals the
52/// input's dimensionality (1 for `Lockstep` / `Modular` /
53/// `Concatenation`; N for `Lattice` / `Continuous` /
54/// `Hybrid`).
55///
56/// `MultiIndex` is the indexed-form output type. The R2 IR
57/// opcode emitted by the optimizer consumes these and resolves
58/// each through the input's `IndexFn` to dispense the actual
59/// tuple.
60pub type MultiIndex = Vec<u64>;
61
62/// A named-tuple value. Subset of the polydat `Value` set
63/// sufficient for naïve-form strategy testing; the production
64/// strategy layer will operate on the full polydat `Value` type
65/// via the IR interpreter (Phase 7). For the strategy module
66/// in isolation, this lightweight type lets tests run without
67/// pulling in the broader runtime.
68#[derive(Debug, Clone, PartialEq)]
69pub struct Tuple {
70    /// The tuple's `(name, value)` pairs, in shape order.
71    pub bindings: Vec<(String, TupleValue)>,
72}
73
74/// Subset of polydat's `Value` enum used by strategy tests.
75/// Production-side `naive_apply` will wrap polydat's full
76/// `Value`; this type is the algebraic-layer testing currency.
77#[derive(Debug, Clone, PartialEq)]
78pub enum TupleValue {
79    /// An unsigned integer.
80    U64(u64),
81    /// A signed integer.
82    I64(i64),
83    /// A float.
84    F64(f64),
85    /// A string.
86    Str(String),
87    /// A boolean.
88    Bool(bool),
89}
90
91impl Tuple {
92    /// An empty tuple.
93    pub fn new() -> Self {
94        Self {
95            bindings: Vec::new(),
96        }
97    }
98
99    /// The tuple with one more binding.
100    pub fn with<K: Into<String>>(mut self, key: K, value: TupleValue) -> Self {
101        self.bindings.push((key.into(), value));
102        self
103    }
104}
105
106impl Default for Tuple {
107    fn default() -> Self {
108        Self::new()
109    }
110}
111
112/// The materialized input to a strategy at invocation time
113/// (spec §10.7.8).
114///
115/// `tuples` are the input stream's tuples in source order (the
116/// natural enumeration of the upstream comprehension subtree).
117/// `cardinality` matches `tuples.len() as u64`. `index_fn` is
118/// the addressing scheme the input actually satisfies —
119/// derived from observed shape for Generator /
120/// WorkloadParamList leaves via the [`crate::iteration::comprehension::eval_source`]
121/// layer, combined upward by the runtime walker per spec
122/// §10.7.2 propagation rules.
123pub struct EvaluatedInput {
124    /// The input's tuples, in source order.
125    pub tuples: Vec<Tuple>,
126    /// How many tuples: `tuples.len()`.
127    pub cardinality: u64,
128    /// The addressing scheme the input satisfies.
129    pub index_fn: IndexFn,
130}
131
132/// The strategy invocation surface per spec §10.7.8.
133///
134/// Implementations are stateless — every call to [`apply`](Strategy::apply)
135/// produces the same output given the same inputs
136/// (deterministic). PRNG-based strategies (`Shuffle`) take
137/// their seed from the truncation companion — the seed is
138/// captured at the `Comprehension::Order { strategy, truncation }`
139/// level by the runtime, not by the strategy itself.
140pub trait Strategy {
141    /// The strategy's name. Mirrors [`StrategyName`].
142    fn name(&self) -> StrategyName;
143
144    /// V4 input-shape check (spec §3.6). `None` represents an
145    /// input with no closed-form index function; only `Lex`
146    /// accepts that. Concrete `IndexFn` variants are accepted
147    /// per the per-strategy rules in spec §3.6's table.
148    fn accepts_input(&self, idx: Option<&IndexFn>) -> bool;
149
150    /// R2 push-down eligibility (spec §10.2 R2). `true` if
151    /// this strategy has a closed-form indexed lookup over the
152    /// given input. If `false`, [`apply`](Strategy::apply) uses the strategy's
153    /// fallback reorder over the materialized tuples.
154    fn has_closed_form_for(&self, idx: &IndexFn) -> bool;
155
156    /// Apply this strategy to the given input.
157    ///
158    /// Internally dispatches: when the strategy has a
159    /// closed-form rule for `input.index_fn`, it uses the
160    /// indexed-form algorithm (compute multi-indices over the
161    /// index space, look up against `input.tuples` via
162    /// [`multi_index_to_flat`]). Otherwise it falls back to a
163    /// per-strategy reorder over `input.tuples` directly.
164    ///
165    /// V4 is the caller's responsibility — call
166    /// `accepts_input(Some(&input.index_fn))` before `apply`
167    /// to fire V4 at strategy-invocation time per spec §10.7.8.
168    fn apply(&self, input: &EvaluatedInput, truncation: Option<u64>) -> Vec<Tuple>;
169}
170
171/// Dispatch a [`StrategyName`] to its concrete [`Strategy`]
172/// implementation. The returned trait object is stateless;
173/// callers can hold a single instance per strategy name for
174/// the life of the process if desired.
175pub fn for_name(name: StrategyName) -> Box<dyn Strategy + Send + Sync> {
176    match name {
177        StrategyName::Lex => Box::new(lex::Lex),
178        StrategyName::ReverseLex => Box::new(reverse_lex::ReverseLex),
179        StrategyName::Shuffle => Box::new(shuffle::Shuffle),
180        StrategyName::Halton => Box::new(halton::Halton),
181        StrategyName::Sobol => Box::new(sobol::Sobol),
182        StrategyName::Lhs => Box::new(lhs::Lhs),
183        StrategyName::Extrema => Box::new(extrema::Extrema),
184        StrategyName::Shells => Box::new(shells::Shells),
185        StrategyName::Diagonal => Box::new(diagonal::Diagonal),
186        StrategyName::Antidiagonal => Box::new(antidiagonal::Antidiagonal),
187    }
188}
189
190/// Resolve a [`MultiIndex`] to a flat position in the
191/// input's tuple list, given the input's [`IndexFn`].
192///
193/// The flat position matches the natural enumeration order
194/// the runtime walker produces:
195///
196/// - `Lattice { axis_sizes: [s0, s1, …, sN-1] }` — row-major
197///   over the axes: `flat = i0 * s1 * s2 * … + i1 * s2 * … + … + iN-1`.
198///   This matches the runtime walker's cartesian enumeration
199///   (head axis varies slowest, tail nested).
200/// - `Lockstep { length }` — one-axis identity:
201///   `flat = mi[0]`.
202/// - `Modular { axis_sizes }` — one-axis identity over `max(axis_sizes)`:
203///   `flat = mi[0]`.
204/// - `Concatenation { segment_sizes }` — one-axis identity
205///   over `Σ segment_sizes`: `flat = mi[0]`.
206/// - `Continuous` / `Hybrid` — `None`; these inputs have no
207///   pre-materialized tuple list (the strategy's multi-indices
208///   are quantiles, not lookups).
209///
210/// Returns `None` for out-of-range positions or dimension
211/// mismatches.
212pub fn multi_index_to_flat(idx: &IndexFn, mi: &MultiIndex) -> Option<usize> {
213    match idx {
214        IndexFn::Lattice { axis_sizes } => {
215            if mi.len() != axis_sizes.len() {
216                return None;
217            }
218            let mut flat: u64 = 0;
219            let mut stride: u64 = 1;
220            for i in (0..axis_sizes.len()).rev() {
221                let pos = mi[i];
222                let size = axis_sizes[i];
223                if pos >= size {
224                    return None;
225                }
226                flat = flat.checked_add(pos.checked_mul(stride)?)?;
227                stride = stride.checked_mul(size)?;
228            }
229            Some(flat as usize)
230        }
231        IndexFn::Lockstep { length } => {
232            if mi.len() != 1 || mi[0] >= *length {
233                return None;
234            }
235            Some(mi[0] as usize)
236        }
237        IndexFn::Modular { axis_sizes } => {
238            let max = axis_sizes.iter().copied().max().unwrap_or(0);
239            if mi.len() != 1 || mi[0] >= max {
240                return None;
241            }
242            Some(mi[0] as usize)
243        }
244        IndexFn::Concatenation { segment_sizes } => {
245            let total: u64 = segment_sizes.iter().copied().sum();
246            if mi.len() != 1 || mi[0] >= total {
247                return None;
248            }
249            Some(mi[0] as usize)
250        }
251        IndexFn::Continuous { .. } | IndexFn::Hybrid { .. } => None,
252    }
253}
254
255/// `true` when [`multi_index_to_flat`] returns a usable
256/// position for in-range multi-indices over this `IndexFn`.
257/// `false` for `Continuous` / `Hybrid` where the indexed
258/// strategy emits quantiles, not lookups.
259pub fn index_fn_supports_lookup(idx: &IndexFn) -> bool {
260    !matches!(idx, IndexFn::Continuous { .. } | IndexFn::Hybrid { .. })
261}
262
263/// Cardinality of an `IndexFn`. Used by strategies to size
264/// their output when no truncation is specified. Mirrors the
265/// helper in `metadata.rs` but lives here to avoid a circular
266/// dependency.
267pub(crate) fn index_fn_size(idx: &IndexFn) -> u64 {
268    match idx {
269        IndexFn::Lattice { axis_sizes } => axis_sizes
270            .iter()
271            .copied()
272            .fold(1u64, |a, b| a.saturating_mul(b)),
273        IndexFn::Lockstep { length } => *length,
274        IndexFn::Modular { axis_sizes } => axis_sizes.iter().copied().max().unwrap_or(0),
275        IndexFn::Concatenation { segment_sizes } => segment_sizes
276            .iter()
277            .copied()
278            .fold(0u64, |a, b| a.saturating_add(b)),
279        IndexFn::Continuous { .. } | IndexFn::Hybrid { .. } => 0,
280    }
281}
282
283/// Lattice dimensionality of an `IndexFn`. Used by strategies
284/// that branch on dimensionality (Extrema's corner count,
285/// Lhs's per-axis stratification).
286pub(crate) fn index_fn_dim(idx: &IndexFn) -> usize {
287    match idx {
288        IndexFn::Lattice { axis_sizes } => axis_sizes.len(),
289        IndexFn::Continuous { intervals, .. } => intervals.len(),
290        IndexFn::Hybrid {
291            discrete_axes,
292            continuous_axes,
293            ..
294        } => discrete_axes.len() + continuous_axes.len(),
295        IndexFn::Lockstep { .. } | IndexFn::Modular { .. } => 1,
296        IndexFn::Concatenation { segment_sizes } => segment_sizes.len(),
297    }
298}
299
300#[cfg(test)]
301mod tests {
302    use super::*;
303
304    #[test]
305    fn for_name_dispatches_to_correct_strategy() {
306        assert_eq!(for_name(StrategyName::Lex).name(), StrategyName::Lex);
307        assert_eq!(for_name(StrategyName::Halton).name(), StrategyName::Halton);
308        assert_eq!(
309            for_name(StrategyName::Extrema).name(),
310            StrategyName::Extrema
311        );
312    }
313
314    #[test]
315    fn index_fn_size_lattice() {
316        let idx = IndexFn::Lattice {
317            axis_sizes: vec![3, 4, 5],
318        };
319        assert_eq!(index_fn_size(&idx), 60);
320    }
321
322    #[test]
323    fn index_fn_size_concatenation() {
324        let idx = IndexFn::Concatenation {
325            segment_sizes: vec![10, 20, 30],
326        };
327        assert_eq!(index_fn_size(&idx), 60);
328    }
329
330    #[test]
331    fn index_fn_dim_classifies_correctly() {
332        assert_eq!(
333            index_fn_dim(&IndexFn::Lattice {
334                axis_sizes: vec![3, 4]
335            }),
336            2
337        );
338        assert_eq!(index_fn_dim(&IndexFn::Lockstep { length: 10 }), 1);
339        assert_eq!(
340            index_fn_dim(&IndexFn::Concatenation {
341                segment_sizes: vec![1, 2, 3]
342            }),
343            3
344        );
345    }
346}