Skip to main content

adam_rs/
sheet.rs

1//! The [`Sheet`] owns and manages a property model constraint graph.
2//!
3//! All cells and relationships are created through the sheet and are
4//! destroyed when the sheet is dropped.
5//!
6//! Queries borrow declarations or describe a completed propagation; they do not
7//! propagate implicitly. This graph combines a conditional relationship, a fixed
8//! writer, a live source filter and a requirement.
9//!
10//! ```
11//! use adam_rs::{CellKind, Filter, MatchExpr, Method, Requirement, Sheet};
12//! use std::any::TypeId;
13//! let mut sheet = Sheet::default();
14//! let mode = sheet.add_source(true);
15//! let limit = sheet.add_source(100_i32);
16//! let a = sheet.add_cell(7_i32);
17//! let b = sheet.add_cell(0_i32);
18//! let out = sheet.add_cell(0_i32);
19//! sheet.add_filter(a, Filter::range(TypeId::of::<i32>(), vec![limit],
20//!     vec![TypeId::of::<i32>()],
21//!     |v, args| Ok(Box::new((*v.downcast_ref::<i32>().unwrap())
22//!         .clamp(0, *args[0].downcast_ref::<i32>().unwrap()))),
23//!     |args| Some((Box::new(0_i32), Box::new(*args[0].downcast_ref::<i32>()?)))))?;
24//! let rel = sheet.add_relationship(vec![Method::from_fn_1_1(a, b, |v: &i32| Ok(*v))])?;
25//! let conditional = sheet.add_conditional(MatchExpr::cell(mode),
26//!     vec![(vec![true], vec![rel])], vec![])?;
27//! sheet.add_out(Method::from_fn_1_1(b, out, |v: &i32| Ok(*v)), vec![])?;
28//! let check = sheet.add_requirement(b, Requirement::from_fn_1(b, |v: &i32| Ok(*v >= 0)))?;
29//! sheet.validate()?;
30//! sheet.write(a, 9_i32)?;
31//! sheet.propagate()?;
32//! assert_eq!(*sheet.read::<i32>(out)?, 9);
33//! assert_eq!(*sheet.source::<i32>(a)?, 9);
34//! assert_eq!(sheet.cell_type_id(a), Some(TypeId::of::<i32>()));
35//! assert_eq!(sheet.cell_kind(out), Some(CellKind::Out));
36//! assert_eq!(sheet.cells().count(), 5);
37//! assert_eq!(sheet.relationships().count(), 2);
38//! assert_eq!(sheet.cell_adj(b).unwrap().len(), 2);
39//! assert_eq!(sheet.relationship_adj(rel), Some([a, b].as_slice()));
40//! assert_eq!(sheet.method_inputs(rel, 0), Some([a].as_slice()));
41//! assert_eq!(sheet.method_outputs(rel, 0), Some([b].as_slice()));
42//! assert_eq!(sheet.selected_method(rel), Some(0));
43//! assert!(sheet.is_source(a));
44//! assert!(sheet.is_forced(b));
45//! assert!(sheet.forced_cells().any(|id| id == b));
46//! assert!(sheet.is_relationship_forced(rel));
47//! assert!(sheet.forced_relationships().any(|id| id == rel));
48//! assert_eq!(sheet.conditionals().collect::<Vec<_>>(), [conditional]);
49//! assert_eq!(sheet.out_cells().collect::<Vec<_>>(), [out]);
50//! assert_eq!(sheet.conditional_match_cells(conditional), Some([mode].as_slice()));
51//! assert_eq!(sheet.conditional_branch_count(conditional), Some(1));
52//! assert_eq!(sheet.conditional_branch_relationships(conditional, 0), Some([rel].as_slice()));
53//! assert_eq!(sheet.conditional_default_relationships(conditional), Some([].as_slice()));
54//! assert_eq!(sheet.conditional_active_branch(conditional)?, Some(0));
55//! assert_eq!(sheet.filter_args(a), Some([limit].as_slice()));
56//! assert_eq!(sheet.filter_dependents(limit), [a]);
57//! assert!(matches!(sheet.filter_kind(a), Some(adam_rs::FilterKind::Range { .. })));
58//! assert_eq!(sheet.filter_range::<i32>(a), Some((0, 100)));
59//! assert!(sheet.filter_violation(a).is_none());
60//! assert_eq!(sheet.filter_violated_cells().count(), 0);
61//! assert!(sheet.filter_violation_cells().is_empty());
62//! assert_eq!(sheet.cell_requirements(b), Some([check].as_slice()));
63//! assert_eq!(sheet.requirement_cell(check), Some(b));
64//! assert_eq!(sheet.requirement_inputs(check), Some([b].as_slice()));
65//! assert!(sheet.cell_requirements_valid(b));
66//! assert_eq!(sheet.violated_requirements(b).count(), 0);
67//! assert!(sheet.contributing_cells(b).contains(&limit));
68//! assert!(sheet.requirement_contributing_cells(check).contains(&a));
69//! assert!(sheet.requirement_relevant_cells().contains(&a));
70//! assert!(sheet.requirement_violation_cells().is_empty());
71//! assert!(sheet.changed().any(|id| id == out));
72//! sheet.clear_changed();
73//! assert_eq!(sheet.changed().count(), 0);
74//! # Ok::<(), adam_rs::Error>(())
75//! ```
76//!
77//! # Forced, self-referencing, and reversible outcomes
78//!
79//! A cell has three distinct outcomes when a relationship determines it:
80//!
81//! - **Conditionally forced.** The forcing relationship supplies the effective
82//!   value, [`Sheet::read`] reports it, and the cell's [`Sheet::source`]
83//!   aspiration is unchanged. The cell keeps the priority it had when forcing
84//!   began, and an explicit write while forced replaces that priority with the
85//!   write's recency. When the last forcing cause ends, the retained aspiration
86//!   and priority compete in the first plan that can use the cell, so no
87//!   additional edit is needed.
88//! - **Self-referencing.** A method that reads and writes the same cell seeds
89//!   from its aspiration and honors that edit's priority. Forcing and release
90//!   do not erase either.
91//! - **Ordinary reversible.** A losing cell receives the winner's value as its
92//!   new aspiration with a derived priority. It does not revive an earlier
93//!   value when the relationship later deactivates, and forcing a cell that
94//!   was already derived retains that derived value and priority.
95//!
96//! ```
97//! use adam_rs::{MatchExpr, Method, Sheet};
98//! let mut sheet = Sheet::default();
99//! let mode = sheet.add_cell(0_i32);
100//! let input = sheet.add_cell(30_i32);
101//! let a = sheet.add_cell(1_i32);
102//! let b = sheet.add_cell(2_i32);
103//! let force = sheet.add_relationship(vec![Method::from_fn_1_1(input, a, |v: &i32| Ok(*v))])?;
104//! let reversible = sheet.add_relationship(vec![
105//!     Method::from_fn_1_1(a, b, |v: &i32| Ok(*v)),
106//!     Method::from_fn_1_1(b, a, |v: &i32| Ok(*v)),
107//! ])?;
108//! sheet.add_conditional(
109//!     MatchExpr::cell(mode),
110//!     vec![(vec![1_i32], vec![force]), (vec![2_i32], vec![reversible])],
111//!     vec![],
112//! )?;
113//! sheet.write(b, 22_i32)?;
114//! sheet.write(a, 11_i32)?;
115//! sheet.write(mode, 1_i32)?;
116//! sheet.propagate()?;
117//! assert!(sheet.is_forced(a));
118//! assert_eq!((*sheet.read::<i32>(a)?, *sheet.source::<i32>(a)?), (30, 11));
119//!
120//! // Releasing `a` keeps its newer edit, so `a` wins the reversible relationship.
121//! sheet.write(mode, 2_i32)?;
122//! sheet.propagate()?;
123//! assert!(sheet.is_source(a));
124//! assert_eq!(*sheet.read::<i32>(b)?, 11);
125//! # Ok::<(), adam_rs::Error>(())
126//! ```
127
128use std::any::{Any, TypeId};
129use std::collections::{HashMap, HashSet};
130use std::rc::Rc;
131
132use slotmap::SlotMap;
133
134use crate::{
135    cell::{CellData, CellId, CellKind},
136    conditional::{Branch, ConditionalData, ConditionalId, MatchExpr, MatchSource},
137    error::{Error, ErrorSite},
138    filter::{Filter, FilterKind, FilterViolation},
139    planner::{Plan, PlanStep, SeedSignatures, SeedSource, Seeds},
140    relationship::{Method, RelationshipData, RelationshipId},
141    requirement::{Requirement, RequirementData, RequirementId},
142};
143
144mod cached;
145mod dependency;
146mod prerequisites;
147
148#[cfg(test)]
149use cached::ReuseStats;
150use cached::{CachedPlan, PreparedPlan};
151
152/// Owns a complete property model constraint graph.
153///
154/// Create cells with [`Sheet::add_cell`], define multi-way constraints with
155/// [`Sheet::add_relationship`], write input values with [`Sheet::write`],
156/// then call [`Sheet::propagate`] to update derived cells. Propagation automatically
157/// reuses eligible prepared plans or plans again when necessary.
158///
159/// After a mutating operation returns an error, the sheet's state is unspecified.
160/// Do not inspect or reuse it; discard it and rebuild from host-owned inputs.
161///
162/// # Example
163///
164/// ```rust
165/// use adam_rs::{Sheet, Method};
166///
167/// let mut sheet = Sheet::new();
168/// let a = sheet.add_cell(0_i32);
169/// let b = sheet.add_cell(0_i32);
170/// sheet.add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x * 2))]).unwrap();
171/// sheet.write(a, 3_i32).unwrap();
172/// assert_eq!(*sheet.read::<i32>(a).unwrap(), 3);
173/// ```
174pub struct Sheet {
175    pub(crate) cells: SlotMap<CellId, CellData>,
176    pub(crate) relationships: SlotMap<RelationshipId, RelationshipData>,
177    pub(crate) changed_cells: Vec<CellId>,
178    /// Monotonic counter incremented by both `add_cell` and `write`; cells added
179    /// later and cells written later have strictly higher strength, making the
180    /// default method-selection direction deterministic.
181    next_strength: u64,
182    /// The prepared snapshot from the last successful `propagate()` call, retained so the
183    /// display-only accessors ([`Sheet::is_source`], [`Sheet::selected_method`],
184    /// [`Sheet::is_forced`]) can report which method the planner picked for each
185    /// relationship without re-planning.
186    last_plan: Option<Rc<PreparedPlan>>,
187    /// Number of cells with a priority retained through conditional forcing.
188    remembered_strength_count: usize,
189    /// Eligible prerequisite plans in validated guard-batch order.
190    pre_plan_caches: Vec<Option<CachedPlan>>,
191    /// Eligible prepared final active plan, independent of the unconditional plan.
192    main_plan_cache: Option<CachedPlan>,
193    /// Ordered method signatures retained until the graph structure changes.
194    seed_signatures: Option<Rc<SeedSignatures>>,
195    /// Counts actual preparation and reuse-validation work for this sheet only.
196    #[cfg(test)]
197    reuse_stats: ReuseStats,
198    /// All conditionals registered on this sheet.
199    pub(crate) conditionals: SlotMap<ConditionalId, ConditionalData>,
200    /// Union of all RelationshipIds assigned to any conditional branch or default.
201    /// Used to exclude them from the unconditional active set.
202    pub(crate) conditional_relationships: HashSet<RelationshipId>,
203    /// All requirements registered on this sheet, across all cells.
204    requirements: SlotMap<RequirementId, RequirementData>,
205    /// Requirements that evaluated `false` as of the last `propagate()` call, grouped
206    /// by cell. Sparse: a cell with no entry had all its requirements hold.
207    last_requirement_violations: HashMap<CellId, Vec<RequirementId>>,
208    /// Filter violations recorded against a derived value as of the last `propagate()`
209    /// call.
210    last_filter_violations: HashMap<CellId, FilterViolation>,
211    /// Reverse index of `filter_args`: for each cell, the live cells whose filter
212    /// references it as one of its dynamic arguments. Built incrementally in
213    /// `add_filter`; cells and filters are never removed once added, so this needs no
214    /// invalidation, matching every other per-cell set/map `Sheet` already maintains
215    /// for its own lifetime.
216    filter_dependents: HashMap<CellId, Vec<CellId>>,
217    /// Validated conditional batches for the current dependency structure.
218    guard_schedule: Option<Rc<dependency::GuardSchedule>>,
219}
220
221/// A conditional's evaluated match value: borrowed (existing cell, no allocation) or owned
222/// (freshly computed by a [`MatchExpr`] function).
223enum MatchValue<'a> {
224    Ref(&'a dyn Any),
225    Owned(Box<dyn Any>),
226}
227
228impl MatchValue<'_> {
229    /// Returns the contained value as a type-erased reference, regardless of variant.
230    fn as_dyn(&self) -> &dyn Any {
231        match self {
232            MatchValue::Ref(r) => *r,
233            MatchValue::Owned(b) => b.as_ref(),
234        }
235    }
236}
237
238/// Provenance needed to decide whether a staged guard-cone step can be reused.
239///
240/// Reuse is intentionally conservative: a step is reusable only when the final plan selects the
241/// same method, producer path, source/derived classification, and seed inputs. A mismatch returns
242/// `Error::Conflict` rather than guessing a compatible assignment or reusing stale values.
243#[derive(Clone, PartialEq, Eq)]
244struct StepProvenance {
245    input_producers: Vec<Option<PlanStep>>,
246    seed_inputs: Vec<CellId>,
247    source_producer: Option<PlanStep>,
248    output_classes: Vec<(CellId, OutputClassification)>,
249}
250
251/// Whether a selected step writes a cell's staged value as source or derived.
252#[derive(Clone, Copy, PartialEq, Eq)]
253enum OutputClassification {
254    /// The write replaces the staged source value.
255    Source,
256    /// The write shadows the staged source value.
257    Derived,
258}
259
260/// Selected producer paths for every step and output in one execution plan.
261#[derive(Default)]
262struct PlanProvenance {
263    steps: HashMap<PlanStep, StepProvenance>,
264    output_producers: HashMap<CellId, PlanStep>,
265}
266
267/// Transactional propagation state whose writes remain private until commit.
268///
269/// Staged derived values override staged sources, which override live sources.
270/// Each replaced source receives a fresh version; absent sources have version zero.
271/// `changed` contains each written cell exactly once and has the same members as
272/// `changed_set`. Dropping an uncommitted stage discards every owned result.
273#[derive(Default)]
274struct PropagationStage {
275    sources: HashMap<CellId, Box<dyn Any>>,
276    /// Version of each staged source value; an absent cell reads its live source (version 0).
277    source_versions: HashMap<CellId, u64>,
278    last_source_version: u64,
279    derived: HashMap<CellId, Box<dyn Any>>,
280    executed_methods: HashSet<(RelationshipId, usize)>,
281    executed_filters: HashSet<CellId>,
282    step_provenance: HashMap<PlanStep, StepProvenance>,
283    changed: Vec<CellId>,
284    changed_set: HashSet<CellId>,
285}
286
287impl PropagationStage {
288    /// Returns the staged effective value for `id`, ignoring any live sheet `derived`.
289    fn effective<'a>(&'a self, cells: &'a SlotMap<CellId, CellData>, id: CellId) -> &'a dyn Any {
290        self.derived
291            .get(&id)
292            .map(|value| value.as_ref())
293            .or_else(|| self.sources.get(&id).map(|value| value.as_ref()))
294            .unwrap_or_else(|| cells[id].source.as_ref())
295    }
296
297    /// Returns the staged source value for `id`, ignoring any live sheet `derived`.
298    fn source<'a>(&'a self, cells: &'a SlotMap<CellId, CellData>, id: CellId) -> &'a dyn Any {
299        self.sources
300            .get(&id)
301            .map(|value| value.as_ref())
302            .unwrap_or_else(|| cells[id].source.as_ref())
303    }
304
305    /// Returns the staged source value for `id` with a version identifying that value.
306    ///
307    /// - Postcondition: two calls return equal versions only if no staged source write or
308    ///   reclassification changed `id`'s source value between them.
309    fn seed_source<'a>(
310        &'a self,
311        cells: &'a SlotMap<CellId, CellData>,
312        id: CellId,
313    ) -> SeedSource<'a> {
314        SeedSource {
315            value: self.source(cells, id),
316            version: self.source_versions.get(&id).copied().unwrap_or(0),
317        }
318    }
319
320    /// Records a new staged source value for `id` under a fresh version.
321    fn insert_source(&mut self, id: CellId, value: Box<dyn Any>) {
322        self.last_source_version += 1;
323        self.source_versions.insert(id, self.last_source_version);
324        self.sources.insert(id, value);
325    }
326
327    /// Shadows the source for derived writes or replaces it for ordinary writes.
328    fn write(&mut self, id: CellId, value: Box<dyn Any>, shadow: bool) {
329        if shadow {
330            self.derived.insert(id, value);
331        } else {
332            self.insert_source(id, value);
333            self.derived.remove(&id);
334        }
335        if self.changed_set.insert(id) {
336            self.changed.push(id);
337        }
338    }
339
340    /// Reclassifies an existing staged output for the general plan's shadowing rule.
341    ///
342    /// - Precondition: `id` has a staged source or derived value.
343    fn reclassify(&mut self, id: CellId, shadow: bool) {
344        if shadow {
345            if let Some(value) = self.sources.remove(&id) {
346                self.source_versions.remove(&id);
347                self.derived.insert(id, value);
348            }
349        } else if let Some(value) = self.derived.remove(&id) {
350            self.insert_source(id, value);
351        }
352    }
353}
354
355impl Sheet {
356    /// Creates an empty sheet with no cells or relationships.
357    ///
358    /// # Examples
359    /// See [`Sheet`]'s example.
360    pub fn new() -> Self {
361        Sheet {
362            cells: SlotMap::with_key(),
363            relationships: SlotMap::with_key(),
364            changed_cells: Vec::new(),
365            next_strength: 0,
366            last_plan: None,
367            remembered_strength_count: 0,
368            pre_plan_caches: Vec::new(),
369            main_plan_cache: None,
370            seed_signatures: None,
371            #[cfg(test)]
372            reuse_stats: ReuseStats::default(),
373            conditionals: SlotMap::with_key(),
374            conditional_relationships: HashSet::new(),
375            requirements: SlotMap::with_key(),
376            last_requirement_violations: HashMap::new(),
377            last_filter_violations: HashMap::new(),
378            filter_dependents: HashMap::new(),
379            guard_schedule: None,
380        }
381    }
382
383    /// Registers a cell with an initial value and returns a stable handle.
384    ///
385    /// The cell's `TypeId` is fixed at creation time; subsequent `write` and
386    /// `read` calls that use a different type will return `Error::TypeMismatch`.
387    ///
388    /// Each call increments the sheet's internal strength counter and sets bit 63
389    /// of the result. This partitions the strength space: written/added cells always
390    /// have higher strength than derived cells, ensuring stability across conditional
391    /// branch switches.
392    ///
393    /// - Complexity: Amortized O(1), plus O(A) when invalidation releases the final
394    ///   owners of prepared artifacts of total size A.
395    ///
396    /// # Examples
397    /// See the [graph example](crate::sheet).
398    pub fn add_cell<T: Any + PartialEq + 'static>(&mut self, value: T) -> CellId {
399        self.guard_schedule = None;
400        self.invalidate_prepared_plans();
401        self.next_strength += 1;
402        let strength = self.next_strength | (1u64 << 63);
403        self.cells.insert(CellData {
404            source: Box::new(value),
405            derived: None,
406            type_id: TypeId::of::<T>(),
407            strength,
408            remembered_strength: None,
409            changed: false,
410            adj: Vec::new(),
411            eq_fn: |a, b| a.downcast_ref::<T>() == b.downcast_ref::<T>(),
412            filter: None,
413            kind: CellKind::Cell,
414            requirements: Vec::new(),
415        })
416    }
417
418    /// Registers a cell that can never be claimed as any method's output — always a
419    /// planner source, forever.
420    ///
421    /// - Complexity: Amortized O(1), plus O(A) when invalidation releases the final
422    ///   owners of prepared artifacts of total size A.
423    ///
424    /// # Examples
425    /// See the [graph example](crate::sheet).
426    pub fn add_source<T: Any + PartialEq + 'static>(&mut self, value: T) -> CellId {
427        let id = self.add_cell(value);
428        self.cells[id].kind = CellKind::Source;
429        id
430    }
431
432    /// Returns the fixed concrete type of a live cell, or `None` for an invalid ID.
433    ///
434    /// # Examples
435    ///
436    /// ```
437    /// use std::any::TypeId;
438    /// use adam_rs::{CellId, Sheet};
439    /// let mut sheet = Sheet::new();
440    /// let cell = sheet.add_cell(7i32);
441    /// assert_eq!(sheet.cell_type_id(cell), Some(TypeId::of::<i32>()));
442    /// assert_eq!(sheet.cell_type_id(CellId::default()), None);
443    /// ```
444    pub fn cell_type_id(&self, id: CellId) -> Option<TypeId> {
445        self.cells.get(id).map(|cell| cell.type_id)
446    }
447
448    /// Returns `id`'s fixed cell kind.
449    ///
450    /// Returns `None` if `id` is not a live cell in this sheet.
451    ///
452    /// # Examples
453    /// See the [graph example](crate::sheet).
454    pub fn cell_kind(&self, id: CellId) -> Option<CellKind> {
455        self.cells.get(id).map(|c| c.kind)
456    }
457
458    /// Registers a relationship defined by a non-empty list of methods.
459    ///
460    /// All methods are validated: their declared `TypeId`s must match the
461    /// registered cells, and each method must have at least one output. A method
462    /// with no inputs is explicitly allowed: it defines a fixed point (a constant,
463    /// independent of every other cell) rather than a derivation.
464    /// On success the `RelationshipId` is added to each adjacent cell's adjacency list.
465    ///
466    /// A cell that appears in both a method's inputs and its outputs is a self-referencing
467    /// cell and is explicitly allowed.
468    ///
469    /// # Errors
470    ///
471    /// - `Error::InvalidMethod` — `methods` is empty, or a method has no outputs.
472    /// - `Error::MismatchedMethodCells` — some method's `inputs ∪ outputs` differs
473    ///   from another method's in the same relationship.
474    /// - `Error::InvalidMethodOutputs` — a method's own `outputs` list names a cell
475    ///   more than once, or two methods in the same relationship have identical or
476    ///   nested `outputs` sets. Overlapping non-nested output sets are allowed.
477    /// - `Error::InvalidId` — a `CellId` in any method is not found in this sheet.
478    /// - `Error::TypeMismatch` — a method's declared `TypeId` does not match the
479    ///   cell's registered `TypeId`.
480    /// - `Error::InvalidCellKind` — a method's output cell is `Source`- or `Out`-kind.
481    ///
482    /// Guard independence is checked by [`Sheet::validate`] and by [`Sheet::propagate`],
483    /// not by this mutator.
484    ///
485    /// - Complexity: O(m² × c) where m is the total number of methods and c is the
486    ///   maximum number of cells per method, due to pairwise output-set comparison,
487    ///   plus O(A) when invalidation releases the final owners of prepared artifacts
488    ///   of total size A.
489    ///
490    /// # Examples
491    /// See the [graph example](crate::sheet).
492    pub fn add_relationship(&mut self, methods: Vec<Method>) -> Result<RelationshipId, Error> {
493        if methods.is_empty() {
494            return Err(Error::InvalidMethod { sites: vec![] });
495        }
496
497        for (idx, method) in methods.iter().enumerate() {
498            if method.outputs.is_empty() {
499                return Err(Error::InvalidMethod {
500                    sites: vec![ErrorSite::MethodIndex(idx)],
501                });
502            }
503
504            // declared type counts must match cell-id counts
505            if method.inputs.len() != method.input_types.len()
506                || method.outputs.len() != method.output_types.len()
507            {
508                return Err(Error::InvalidMethod {
509                    sites: vec![ErrorSite::MethodIndex(idx)],
510                });
511            }
512
513            for (&cell_id, &declared) in method.inputs.iter().zip(method.input_types.iter()) {
514                let cell = self.cells.get(cell_id).ok_or(Error::InvalidId)?;
515                if cell.type_id != declared {
516                    return Err(Error::TypeMismatch {
517                        expected: cell.type_id,
518                        found: declared,
519                        sites: vec![ErrorSite::MethodIndex(idx)],
520                    });
521                }
522            }
523
524            for (&cell_id, &declared) in method.outputs.iter().zip(method.output_types.iter()) {
525                let cell = self.cells.get(cell_id).ok_or(Error::InvalidId)?;
526                if cell.kind != CellKind::Cell {
527                    return Err(Error::InvalidCellKind {
528                        sites: vec![ErrorSite::MethodIndex(idx), ErrorSite::Cell(cell_id)],
529                    });
530                }
531                if cell.type_id != declared {
532                    return Err(Error::TypeMismatch {
533                        expected: cell.type_id,
534                        found: declared,
535                        sites: vec![ErrorSite::MethodIndex(idx)],
536                    });
537                }
538            }
539        }
540
541        // Every method in a relationship must reference the same set of cells: the
542        // union of a method's inputs and outputs (as a set) must be identical across
543        // all methods. A relationship models a fixed set of related cells; methods
544        // differ only in which subset of that set they treat as outputs (using the
545        // "ignore an input" pattern), not in which cells they reference at all.
546        let cell_sets: Vec<HashSet<CellId>> = methods
547            .iter()
548            .map(|m| m.inputs.iter().chain(m.outputs.iter()).copied().collect())
549            .collect();
550        if let Some(rel_idx) = cell_sets[1..].iter().position(|set| set != &cell_sets[0]) {
551            let diverging = rel_idx + 1;
552            let mut sites = vec![ErrorSite::MethodIndex(diverging), ErrorSite::MethodIndex(0)];
553            // Symmetric difference of the two cell sets, in a stable order.
554            for &c in cell_sets[diverging].symmetric_difference(&cell_sets[0]) {
555                sites.push(ErrorSite::Cell(c));
556            }
557            return Err(Error::MismatchedMethodCells { sites });
558        }
559
560        // A method's own outputs must be duplicate-free, and no two methods in a
561        // relationship may claim identical or nested output sets: the planner's
562        // matching stage treats a method's pure-output set as an indivisible claim,
563        // so nested claims would make that claim ambiguous while still allowing
564        // overlapping non-nested sets.
565        let mut seen_output_sets: Vec<(usize, HashSet<CellId>, &[CellId])> =
566            Vec::with_capacity(methods.len());
567        for (idx, method) in methods.iter().enumerate() {
568            let output_set: HashSet<CellId> = method.outputs.iter().copied().collect();
569            if output_set.len() != method.outputs.len() {
570                // A cell repeated within this method's own outputs. Report each
571                // distinct repeated cell once, no matter how many times it repeats.
572                let mut sites = vec![ErrorSite::MethodIndex(idx)];
573                let mut seen = HashSet::new();
574                let mut reported = HashSet::new();
575                for &o in &method.outputs {
576                    if !seen.insert(o) && reported.insert(o) {
577                        sites.push(ErrorSite::Cell(o));
578                    }
579                }
580                return Err(Error::InvalidMethodOutputs { sites });
581            }
582            for (earlier, earlier_set, earlier_outputs) in &seen_output_sets {
583                if output_set == *earlier_set
584                    || (output_set.len() < earlier_set.len() && output_set.is_subset(earlier_set))
585                    || (earlier_set.len() < output_set.len() && earlier_set.is_subset(&output_set))
586                {
587                    let mut sites = vec![
588                        ErrorSite::MethodIndex(idx),
589                        ErrorSite::MethodIndex(*earlier),
590                    ];
591                    let offending_outputs: &[CellId] = if output_set.len() <= earlier_set.len() {
592                        &method.outputs
593                    } else {
594                        earlier_outputs
595                    };
596                    for &o in offending_outputs {
597                        sites.push(ErrorSite::Cell(o));
598                    }
599                    return Err(Error::InvalidMethodOutputs { sites });
600                }
601            }
602            seen_output_sets.push((idx, output_set, &method.outputs));
603        }
604
605        // Collect the union of all adjacent cells in insertion order, deduplicated.
606        let mut adj: Vec<CellId> = Vec::new();
607        let mut seen: std::collections::HashSet<CellId> = std::collections::HashSet::new();
608        for method in &methods {
609            for &cell_id in method.inputs.iter().chain(method.outputs.iter()) {
610                if seen.insert(cell_id) {
611                    adj.push(cell_id);
612                }
613            }
614        }
615
616        self.invalidate_prepared_plans();
617        let rel_id = self.relationships.insert(RelationshipData { methods, adj });
618
619        for &cell_id in &self.relationships[rel_id].adj {
620            if let Some(cell) = self.cells.get_mut(cell_id)
621                && !cell.adj.contains(&rel_id)
622            {
623                cell.adj.push(rel_id);
624            }
625        }
626
627        self.guard_schedule = None;
628        Ok(rel_id)
629    }
630
631    /// Registers a conditional that activates relationships based on the value of a match
632    /// subject: either a single existing cell, or a [`MatchExpr`] computed from multiple
633    /// input cells.
634    ///
635    /// Each element of `branches` is `(keys, relationships)`: when the match subject's
636    /// value equals any key in `keys`, the branch's `relationships` are added to the active
637    /// set for `propagate`. Branches are evaluated in definition order; first match wins.
638    /// `default` holds relationships activated when no branch matches; pass an empty `Vec`
639    /// for no default.
640    /// Multiple conditionals may activate the same relationship; it remains active while
641    /// any owner selects it.
642    ///
643    /// # Errors
644    ///
645    /// - `Error::InvalidId` — the match subject references a cell not in this sheet.
646    /// - `Error::TypeMismatch` — (expression match subject only) an input cell's registered
647    ///   type doesn't match the expression's declared type for that input.
648    /// - `Error::InvalidConditional` — the match subject's output type does not match `T`;
649    ///   a referenced relationship does not exist; a relationship already appears in
650    ///   another branch or default in this call; or a branch has no keys.
651    /// - `Error::InvalidCellKind` — a referenced relationship is a fixed `Out` writer.
652    ///
653    /// Guard independence is checked by [`Sheet::validate`] and by [`Sheet::propagate`],
654    /// not by this mutator.
655    ///
656    /// - Complexity: O(I + K + E) time and O(K + R) space for match inputs I,
657    ///   branch keys K, referenced relationships R and their total method-output
658    ///   edges E, plus O(A) when invalidation releases final prepared artifacts of size A.
659    ///
660    /// # Examples
661    /// See the [graph example](crate::sheet).
662    pub fn add_conditional<T: Any + PartialEq + 'static>(
663        &mut self,
664        source: MatchExpr,
665        branches: Vec<(Vec<T>, Vec<RelationshipId>)>,
666        default: Vec<RelationshipId>,
667    ) -> Result<ConditionalId, Error> {
668        match &source.0 {
669            MatchSource::Cell(cell) => {
670                let cell_data = self.cells.get(*cell).ok_or(Error::InvalidId)?;
671                if cell_data.type_id != TypeId::of::<T>() {
672                    return Err(Error::InvalidConditional {
673                        sites: vec![ErrorSite::Cell(*cell)],
674                    });
675                }
676            }
677            MatchSource::Expr(expr) => {
678                if expr.output_type != TypeId::of::<T>() {
679                    return Err(Error::InvalidConditional { sites: vec![] });
680                }
681                for (&cell_id, &declared) in expr.inputs.iter().zip(expr.input_types.iter()) {
682                    let cell_data = self.cells.get(cell_id).ok_or(Error::InvalidId)?;
683                    if cell_data.type_id != declared {
684                        return Err(Error::TypeMismatch {
685                            expected: cell_data.type_id,
686                            found: declared,
687                            sites: vec![],
688                        });
689                    }
690                }
691            }
692        };
693
694        // Collect and validate all relationship IDs (branches + default).
695        let all_rels: Vec<RelationshipId> = branches
696            .iter()
697            .flat_map(|(_, rels)| rels.iter().copied())
698            .chain(default.iter().copied())
699            .collect();
700
701        for &rel_id in &all_rels {
702            let relationship = self
703                .relationships
704                .get(rel_id)
705                .ok_or(Error::InvalidConditional { sites: vec![] })?;
706            if let Some(output) = relationship
707                .methods
708                .iter()
709                .flat_map(|method| &method.outputs)
710                .find(|&&id| self.cells[id].kind == CellKind::Out)
711            {
712                return Err(Error::InvalidCellKind {
713                    sites: vec![ErrorSite::Relationship(rel_id), ErrorSite::Cell(*output)],
714                });
715            }
716        }
717
718        // Validate branch keys are non-empty.
719        for (keys, _) in &branches {
720            if keys.is_empty() {
721                return Err(Error::InvalidConditional { sites: vec![] });
722            }
723        }
724
725        // Check for duplicate relationship IDs within this call.
726        let mut seen: HashSet<RelationshipId> = HashSet::new();
727        for &rel_id in &all_rels {
728            if !seen.insert(rel_id) {
729                return Err(Error::InvalidConditional {
730                    sites: vec![ErrorSite::Relationship(rel_id)],
731                });
732            }
733        }
734
735        // Type-erase branch keys.
736        let typed_branches: Vec<Branch> = branches
737            .into_iter()
738            .map(|(keys, relationships)| Branch {
739                keys: keys
740                    .into_iter()
741                    .map(|k| Box::new(k) as Box<dyn Any>)
742                    .collect(),
743                relationships,
744            })
745            .collect();
746
747        // Record all relationships as conditional so they are excluded from the
748        // unconditional active set in propagate().
749        self.invalidate_prepared_plans();
750        for &rel_id in &all_rels {
751            self.conditional_relationships.insert(rel_id);
752        }
753
754        let id = self.conditionals.insert(ConditionalData {
755            source: source.0,
756            branches: typed_branches,
757            default,
758        });
759
760        self.guard_schedule = None;
761        Ok(id)
762    }
763
764    /// Returns `true` if `id` is already claimed as some existing method's output —
765    /// i.e. it cannot legally become an `out` cell's writer target, since that would
766    /// leave two producers claiming the same cell.
767    ///
768    /// - Complexity: O(E) for all registered method-output edges E.
769    fn cell_has_prior_use(&self, id: CellId) -> bool {
770        self.relationships
771            .values()
772            .any(|rel| rel.methods.iter().any(|m| m.outputs.contains(&id)))
773    }
774
775    /// Attaches a requirement to `cell` and returns its stable ID.
776    ///
777    /// `requirement.inputs` may be any cells in the sheet, not only `cell` itself.
778    /// The predicate runs during propagation, so callers can report false results
779    /// separately from propagation failures.
780    ///
781    /// # Errors
782    ///
783    /// - `Error::InvalidId` — `cell`, or one of `requirement`'s input cells, is not a
784    ///   live cell in this sheet.
785    /// - `Error::TypeMismatch` — an input's declared type does not match its cell's
786    ///   registered type.
787    /// - `Error::InvalidRequirement` — the input signature is invalid.
788    ///
789    /// - Complexity: O(k) where k is `requirement`'s input count, plus O(A) when
790    ///   invalidation releases the final owners of prepared artifacts of total size A.
791    ///
792    /// # Examples
793    ///
794    /// ```
795    /// use adam_rs::{Requirement, Sheet};
796    /// let mut sheet = Sheet::new();
797    /// let cell = sheet.add_cell(1_i32);
798    /// let id = sheet.add_requirement(cell, Requirement::from_fn_1(cell, |x: &i32| Ok(*x > 0)))?;
799    /// assert_eq!(sheet.cell_requirements(cell), Some([id].as_slice()));
800    /// # Ok::<(), adam_rs::Error>(())
801    /// ```
802    pub fn add_requirement(
803        &mut self,
804        cell: CellId,
805        requirement: Requirement,
806    ) -> Result<RequirementId, Error> {
807        self.cells.get(cell).ok_or(Error::InvalidId)?;
808        if requirement.inputs.len() != requirement.input_types.len() {
809            return Err(Error::InvalidRequirement);
810        }
811        for (&input_id, &declared) in requirement
812            .inputs
813            .iter()
814            .zip(requirement.input_types.iter())
815        {
816            let input_cell = self.cells.get(input_id).ok_or(Error::InvalidId)?;
817            if input_cell.type_id != declared {
818                return Err(Error::TypeMismatch {
819                    expected: input_cell.type_id,
820                    found: declared,
821                    sites: vec![],
822                });
823            }
824        }
825
826        self.invalidate_prepared_plans();
827        let rid = self.requirements.insert(RequirementData {
828            cell,
829            inputs: requirement.inputs,
830            function: requirement.function,
831        });
832        self.cells[cell].requirements.push(rid);
833        Ok(rid)
834    }
835
836    /// Registers `writer` as the sole producer of its one output cell, which becomes
837    /// an `out` cell: always derived by `writer`, never `write()`-able, but otherwise
838    /// an ordinary, freely-referenceable cell. `requirements` are attached to that
839    /// cell one at a time, in order, via [`Sheet::add_requirement`].
840    ///
841    /// # Errors
842    ///
843    /// - `Error::InvalidOutput` — `writer` does not have exactly one output cell.
844    /// - `Error::InvalidCellKind` — the writer's output cell is already `Source` or
845    ///   `Out` kind, or already claimed as some existing method's output.
846    /// - Any error [`Sheet::add_relationship`] or [`Sheet::add_requirement`] can
847    ///   return.
848    ///
849    /// - Postcondition: not atomic — if `add_requirement` fails partway through
850    ///   `requirements`, the output cell is left `Out`-kind, `writer` is already
851    ///   registered as its producer, and every requirement before the failing one is
852    ///   already attached; none of this is rolled back on error.
853    ///
854    /// - Complexity: O(k + i + m²×c) where k is the number of requirements and i is
855    ///   their total input count, plus the
856    ///   cost of `add_relationship` for `writer` alone (m = 1 method, c = cells in
857    ///   that method), plus O(A) when invalidation releases the final owners of
858    ///   prepared artifacts of total size A.
859    ///
860    /// # Examples
861    ///
862    /// ```
863    /// use adam_rs::{Method, Requirement, Sheet};
864    /// let mut sheet = Sheet::new();
865    /// let input = sheet.add_cell(1_i32);
866    /// let output = sheet.add_cell(0_i32);
867    /// let id = sheet.add_out(
868    ///     Method::from_fn_1_1(input, output, |x: &i32| Ok(*x)),
869    ///     vec![Requirement::from_fn_1(output, |x: &i32| Ok(*x > 0))],
870    /// )?;
871    /// assert_eq!(id, output);
872    /// sheet.propagate()?;
873    /// assert!(sheet.cell_requirements_valid(output));
874    /// # Ok::<(), adam_rs::Error>(())
875    /// ```
876    pub fn add_out(
877        &mut self,
878        writer: Method,
879        requirements: Vec<Requirement>,
880    ) -> Result<CellId, Error> {
881        let out_cell = writer
882            .outputs
883            .first()
884            .copied()
885            .ok_or(Error::InvalidOutput)?;
886        self.add_out_writer(writer)?;
887        for requirement in requirements {
888            self.add_requirement(out_cell, requirement)?;
889        }
890        Ok(out_cell)
891    }
892
893    /// Registers the sole output writer and returns its native relationship identity.
894    ///
895    /// Reports the same writer validation errors as [`Self::add_out`].
896    /// - Complexity: O(r × e + i) for prior relationships r, edges e and writer inputs i.
897    pub(crate) fn add_out_writer(&mut self, writer: Method) -> Result<RelationshipId, Error> {
898        if writer.outputs.len() != 1 {
899            return Err(Error::InvalidOutput);
900        }
901        let out_cell = writer.outputs[0];
902
903        let kind = self.cells.get(out_cell).ok_or(Error::InvalidId)?.kind;
904        if kind != CellKind::Cell || self.cell_has_prior_use(out_cell) {
905            return Err(Error::InvalidCellKind { sites: vec![] });
906        }
907
908        let relationship = self.add_relationship(vec![writer])?;
909        self.cells[out_cell].kind = CellKind::Out;
910        Ok(relationship)
911    }
912
913    /// Attaches `filter` to `cell`.
914    ///
915    /// Never evaluates `filter`'s function — attaching a filter is not a fresh
916    /// external input, so it never changes `cell`'s current effective value. The next
917    /// full [`Sheet::propagate`] call conforms `cell` via the planner's
918    /// `PlanStep::FilterReclamp` step; until then, `read()` reflects whatever `cell`
919    /// held before this call.
920    ///
921    /// # Errors
922    ///
923    /// - `Error::InvalidId` — `cell`, or one of `filter`'s argument cells, is not a
924    ///   live cell in this sheet.
925    /// - `Error::InvalidFilter` — `cell` already has a filter, `filter`'s own value
926    ///   type does not match `cell`'s registered type, or `filter`'s argument list
927    ///   names `cell` itself.
928    /// - `Error::TypeMismatch` — an argument cell's registered type does not match the
929    ///   type `filter` declared for it.
930    ///
931    /// Guard independence is checked by [`Sheet::validate`] and by [`Sheet::propagate`],
932    /// not by this mutator.
933    ///
934    /// - Complexity: O(a) where a is the number of filter argument cells, plus O(A)
935    ///   when invalidation releases the final owners of prepared artifacts of total
936    ///   size A.
937    ///
938    /// # Examples
939    /// See the [graph example](crate::sheet).
940    pub fn add_filter(&mut self, cell: CellId, filter: Filter) -> Result<(), Error> {
941        let cell_type = self.cells.get(cell).ok_or(Error::InvalidId)?.type_id;
942        if self.cells[cell].filter.is_some() {
943            return Err(Error::InvalidFilter);
944        }
945        if filter.0.value_type != cell_type {
946            return Err(Error::InvalidFilter);
947        }
948        if filter.0.args.contains(&cell) {
949            return Err(Error::InvalidFilter);
950        }
951        for (&arg_id, &declared) in filter.0.args.iter().zip(filter.0.arg_types.iter()) {
952            let arg_cell = self.cells.get(arg_id).ok_or(Error::InvalidId)?;
953            if arg_cell.type_id != declared {
954                return Err(Error::TypeMismatch {
955                    expected: arg_cell.type_id,
956                    found: declared,
957                    sites: vec![],
958                });
959            }
960        }
961
962        self.invalidate_prepared_plans();
963        for &arg in &filter.0.args {
964            self.filter_dependents.entry(arg).or_default().push(cell);
965        }
966        self.cells[cell].filter = Some(filter.0);
967        self.guard_schedule = None;
968        Ok(())
969    }
970
971    /// Returns the argument cells of `id`'s filter, in declaration order.
972    ///
973    /// Returns `None` if `id` is not a live cell in this sheet, or has no filter.
974    ///
975    /// # Examples
976    /// See the [graph example](crate::sheet).
977    pub fn filter_args(&self, id: CellId) -> Option<&[CellId]> {
978        self.cells
979            .get(id)?
980            .filter
981            .as_ref()
982            .map(|f| f.args.as_slice())
983    }
984
985    /// Returns the live cells whose filter references `id` as one of its dynamic
986    /// arguments — the reverse of a filter's own argument list ([`Sheet::filter_args`]).
987    ///
988    /// - Postcondition: empty if no live cell's filter references `id`.
989    ///
990    /// # Examples
991    /// See the [graph example](crate::sheet).
992    pub fn filter_dependents(&self, id: CellId) -> &[CellId] {
993        self.filter_dependents
994            .get(&id)
995            .map(Vec::as_slice)
996            .unwrap_or(&[])
997    }
998
999    /// Returns the kind of validation/derivation `id`'s filter performs, if it has one.
1000    ///
1001    /// Returns `None` if `id` is not a live cell in this sheet, or has no filter.
1002    ///
1003    /// # Examples
1004    /// See the [graph example](crate::sheet).
1005    pub fn filter_kind(&self, id: CellId) -> Option<&FilterKind> {
1006        self.cells.get(id)?.filter.as_ref().map(|f| &f.kind)
1007    }
1008
1009    /// Returns `id`'s filter's current `(lo, hi)` bounds, if it has a [`FilterKind::Range`]
1010    /// filter.
1011    ///
1012    /// Resolves the filter's argument cells' current effective values via the same path
1013    /// [`Sheet::add_filter`] already uses, then calls the filter's `bounds` function.
1014    ///
1015    /// Returns `None` if `id` is not a live cell in this sheet, has no filter, its filter's
1016    /// kind isn't [`FilterKind::Range`], its bounds have a different type from `T`,
1017    /// or the range expression fails to evaluate against
1018    /// the filter's current argument values (e.g. a fallible arithmetic op in a range
1019    /// endpoint) — the same degraded-to-`None` outcome as any other reason no live bounds
1020    /// are available right now.
1021    ///
1022    /// - Complexity: O(a) where a is the number of the filter's argument cells.
1023    ///
1024    /// # Examples
1025    /// See the [graph example](crate::sheet).
1026    pub fn filter_range<T: Any>(&self, id: CellId) -> Option<(T, T)> {
1027        let filter = self.cells.get(id)?.filter.as_ref()?;
1028        let FilterKind::Range { bounds } = &filter.kind else {
1029            return None;
1030        };
1031        let args: Vec<&dyn Any> = filter
1032            .args
1033            .iter()
1034            .map(|&a| self.cells[a].effective())
1035            .collect();
1036        let (lo, hi) = bounds(&args)?;
1037        Some((*lo.downcast::<T>().ok()?, *hi.downcast::<T>().ok()?))
1038    }
1039
1040    /// Returns the filter violation recorded for `id` as of the last full
1041    /// `propagate()` call, if any.
1042    ///
1043    /// - Postcondition: `None` if `id` has no filter, `id`'s filter's last-checked
1044    ///   value held, or no full `propagate()` has run since `id` was last a plain
1045    ///   external write.
1046    ///
1047    /// # Examples
1048    /// See the [graph example](crate::sheet).
1049    pub fn filter_violation(&self, id: CellId) -> Option<&FilterViolation> {
1050        self.last_filter_violations.get(&id)
1051    }
1052
1053    /// Iterates cells whose filter is currently violated, as of the last full
1054    /// `propagate()` call.
1055    ///
1056    /// - Complexity: O(n) where n is the number of currently-violated filters.
1057    ///
1058    /// # Examples
1059    /// See the [graph example](crate::sheet).
1060    pub fn filter_violated_cells(&self) -> impl Iterator<Item = CellId> + '_ {
1061        self.last_filter_violations.keys().copied()
1062    }
1063
1064    /// Returns the set of root cells currently determining a violated filter's own
1065    /// value or any of its argument values, as of the last full `propagate()` call —
1066    /// the same "which upstream cells caused this" query
1067    /// `requirement_contributing_cells`/`requirement_violation_cells` already provide
1068    /// for `Requirement`.
1069    ///
1070    /// - Postcondition: empty if no filter is currently violated.
1071    /// - Complexity: O(sum of `contributing_cells` cost over every violated filter and
1072    ///   its argument cells).
1073    ///
1074    /// # Examples
1075    /// See the [graph example](crate::sheet).
1076    pub fn filter_violation_cells(&self) -> HashSet<CellId> {
1077        let mut result = HashSet::new();
1078        for cell_id in self.filter_violated_cells() {
1079            result.extend(self.contributing_cells(cell_id));
1080            if let Some(args) = self.filter_args(cell_id) {
1081                for &arg in args {
1082                    result.extend(self.contributing_cells(arg));
1083                }
1084            }
1085        }
1086        result
1087    }
1088
1089    /// Returns the requirements attached to `id`, in attachment order.
1090    ///
1091    /// Returns `None` if `id` is not a live cell in this sheet.
1092    ///
1093    /// # Examples
1094    /// See the [graph example](crate::sheet).
1095    pub fn cell_requirements(&self, id: CellId) -> Option<&[RequirementId]> {
1096        self.cells.get(id).map(|c| c.requirements.as_slice())
1097    }
1098
1099    /// Returns the cell requirement `id` is attached to.
1100    ///
1101    /// Returns `None` if `id` is not a live requirement in this sheet.
1102    ///
1103    /// # Examples
1104    /// See the [graph example](crate::sheet).
1105    pub fn requirement_cell(&self, id: RequirementId) -> Option<CellId> {
1106        self.requirements.get(id).map(|c| c.cell)
1107    }
1108
1109    /// Returns the cells requirement `id` reads.
1110    ///
1111    /// Returns `None` if `id` is not a live requirement in this sheet.
1112    ///
1113    /// # Examples
1114    /// See the [graph example](crate::sheet).
1115    pub fn requirement_inputs(&self, id: RequirementId) -> Option<&[CellId]> {
1116        self.requirements.get(id).map(|c| c.inputs.as_slice())
1117    }
1118
1119    /// Returns `true` if every requirement on `id` held as of the last `propagate()`
1120    /// call.
1121    ///
1122    /// Returns `false` if no propagation has run yet. Also returns `true` for an
1123    /// `id` that is not a live cell in this sheet, since no requirement can have
1124    /// failed for a cell that doesn't exist.
1125    ///
1126    /// # Examples
1127    /// See the [graph example](crate::sheet).
1128    pub fn cell_requirements_valid(&self, id: CellId) -> bool {
1129        if self.last_plan.is_none() {
1130            return false;
1131        }
1132        !self.last_requirement_violations.contains_key(&id)
1133    }
1134
1135    /// Iterates the requirements on `id` that evaluated to `false` as of the last
1136    /// `propagate()` call.
1137    ///
1138    /// - Postcondition: empty if `id`'s requirements all held, `id` is not a live
1139    ///   cell in this sheet, or no propagation has run yet.
1140    ///
1141    /// # Examples
1142    /// See the [graph example](crate::sheet).
1143    pub fn violated_requirements(&self, id: CellId) -> impl Iterator<Item = RequirementId> + '_ {
1144        self.last_requirement_violations
1145            .get(&id)
1146            .into_iter()
1147            .flatten()
1148            .copied()
1149    }
1150
1151    /// Returns the set of root cells that could determine `id`'s value for *some* choice of
1152    /// cell strengths, as of the last `propagate()` call.
1153    ///
1154    /// A cell is a root candidate for `current` whenever some *active* relationship
1155    /// adjacent to `current` has a method producing it — not just the one method the
1156    /// current strengths happen to have selected: a different strength ordering could pick
1157    /// a different method of that same relationship, making any of its other cells the
1158    /// source instead. So every method (of every active relationship touching `current`)
1159    /// with `current` among its outputs contributes its inputs to the walk, not only the
1160    /// currently-selected one. A cell outside [`Sheet::is_forced`]'s pure-output
1161    /// classification contributes its own stored aspiration. This includes a
1162    /// self-referencing input even when a mandatory writer prevents the cell from
1163    /// remaining unclaimed: its seed can still depend on that aspiration.
1164    ///
1165    /// Every visited cell is also checked against every conditional in the sheet: if any of
1166    /// that conditional's branches (or its default) has a method whose outputs include the
1167    /// visited cell, the conditional's match cell is added as a contributor too, and is
1168    /// itself traced recursively. This covers both an active producer that happens to
1169    /// belong to a conditional branch, and a cell with *no* active producer specifically
1170    /// because the branch that would define it isn't the one currently selected (that
1171    /// absence is itself a fact controlled by the match cell, not an indication that the
1172    /// match cell is irrelevant).
1173    ///
1174    /// A cell that can remain a source also contributes its dynamic filter arguments:
1175    /// the filter determines its effective value. Filters on outputs claimed in every
1176    /// acyclic assignment, including self-referencing outputs, only diagnose values
1177    /// and do not add value dependencies.
1178    ///
1179    /// Eligibility searches use the candidate's complete input/output relationship
1180    /// component within the last successful active set. That completed assignment
1181    /// witnesses feasibility of the independent components. Registered methods are
1182    /// never replaced or removed, so writes, appended structure and failed
1183    /// propagation preserve this witness; newly registered relationships stay outside
1184    /// these assignment searches until successful propagation publishes another
1185    /// active set. Filter arguments and potential conditional contributors still
1186    /// come from the current registered graph.
1187    ///
1188    /// - Postcondition: returns `{id}` if no propagation has run yet, or if `id` is not
1189    ///   forced and no active or conditional relationship or dynamic filter could produce it.
1190    ///
1191    /// - Complexity: O(N · (R·M·K² + B·M·K)) where N is the number of cells reachable from `id`
1192    ///   (including conditional match cells), R is the number of relationships adjacent to
1193    ///   a visited cell, M is the maximum number of methods per relationship, K is
1194    ///   the maximum input/output count per method, and B is the
1195    ///   total number of branch/default relationships across all conditionals, plus the
1196    ///   number of traversed filter argument edges. Each visited non-forced filtered
1197    ///   cell with dynamic arguments that is not currently a source adds at most one
1198    ///   exact eligibility search after expected linear traversal of that candidate's
1199    ///   component adjacency (including inactive adjacency entries). Each search takes
1200    ///   expected O(T + U · (1 + A · K²)) time, where T is relationship storage slots
1201    ///   scanned, A is active relationships in that component, and U counts that
1202    ///   search's recursive calls and examined method candidates. U is bounded by
1203    ///   O(1 + M + … + M^A), including partial checks when M = 1; disconnected
1204    ///   components do not multiply its search tree. Debug builds add O(G) validation
1205    ///   during each component discovery, where G is prepared active relationships.
1206    ///   Traversal storage is O(N + E) for visited cells and queued dependency edges E,
1207    ///   plus visited component cells/relationships and O(1 + A · (1 + K)) auxiliary
1208    ///   storage for one eligibility search. Repeated queries do not cache searches.
1209    ///
1210    /// # Examples
1211    /// See the [graph example](crate::sheet).
1212    pub fn contributing_cells(&self, id: CellId) -> HashSet<CellId> {
1213        if self.last_plan.is_none() {
1214            return HashSet::from([id]);
1215        }
1216        let mut result = HashSet::new();
1217        let mut visited: HashSet<CellId> = HashSet::new();
1218        let mut stack = vec![id];
1219        while let Some(current) = stack.pop() {
1220            if !visited.insert(current) {
1221                continue;
1222            }
1223
1224            for match_cell in self.conditionals_potentially_producing(current) {
1225                stack.push(match_cell);
1226            }
1227
1228            if !self.is_forced(current) {
1229                result.insert(current);
1230                if let Some(prepared) = &self.last_plan
1231                    && let Some(args) = self.filter_args(current)
1232                    && !args.is_empty()
1233                    && (self.is_source(current) || {
1234                        let component = crate::planner::active_relationship_component(
1235                            &self.cells,
1236                            &self.relationships,
1237                            &prepared.active,
1238                            current,
1239                        );
1240                        crate::planner::can_be_source(&self.relationships, &component, current)
1241                    })
1242                {
1243                    stack.extend(args.iter().copied());
1244                }
1245            }
1246
1247            let Some(cell) = self.cells.get(current) else {
1248                continue;
1249            };
1250            for &rel_id in &cell.adj {
1251                if !self.is_relationship_active(rel_id) {
1252                    continue;
1253                }
1254                for method in &self.relationships[rel_id].methods {
1255                    if !method.outputs.contains(&current) {
1256                        continue;
1257                    }
1258                    for &input in &method.inputs {
1259                        if method.outputs.contains(&input) {
1260                            result.insert(input);
1261                        } else {
1262                            stack.push(input);
1263                        }
1264                    }
1265                }
1266            }
1267        }
1268        result
1269    }
1270
1271    /// Returns `true` if `rel_id` was part of the active relationship set for the last
1272    /// successful `propagate()` call — an unconditional relationship is always active; a conditional
1273    /// branch/default relationship is active only while its conditional currently selects
1274    /// it.
1275    ///
1276    /// Returns `false` if no propagation has run yet.
1277    fn is_relationship_active(&self, rel_id: RelationshipId) -> bool {
1278        self.last_plan
1279            .as_ref()
1280            .is_some_and(|plan| plan.active.contains(&rel_id))
1281    }
1282
1283    /// Returns the match cells of every conditional with at least one branch (or default)
1284    /// relationship that touches `cell` (as an input or output of any of its methods) —
1285    /// every conditional whose branch choice currently determines, or could determine,
1286    /// `cell`'s value or whether it has an active producer at all.
1287    ///
1288    /// - Complexity: O(B) where B is the total number of branch/default relationships
1289    ///   across all conditionals.
1290    fn conditionals_potentially_producing(&self, cell: CellId) -> Vec<CellId> {
1291        self.conditionals
1292            .values()
1293            .filter(|cond| {
1294                cond.branches
1295                    .iter()
1296                    .flat_map(|branch| branch.relationships.iter())
1297                    .chain(cond.default.iter())
1298                    .any(|&rel_id| self.relationships[rel_id].adj.contains(&cell))
1299            })
1300            .flat_map(|cond| cond.match_cells().iter().copied())
1301            .collect()
1302    }
1303
1304    /// Returns the union of [`Sheet::contributing_cells`] over requirement `id`'s own
1305    /// declared inputs.
1306    ///
1307    /// Returns an empty set if `id` is not a live requirement in this sheet.
1308    ///
1309    /// - Complexity: The sum of [`Self::contributing_cells`] costs over the requirement's
1310    ///   inputs, with O(N) space for their union of N root cells.
1311    ///
1312    /// # Examples
1313    /// See the [graph example](crate::sheet).
1314    pub fn requirement_contributing_cells(&self, id: RequirementId) -> HashSet<CellId> {
1315        let Some(requirement) = self.requirements.get(id) else {
1316            return HashSet::new();
1317        };
1318        requirement
1319            .inputs
1320            .iter()
1321            .flat_map(|&input| self.contributing_cells(input))
1322            .collect()
1323    }
1324
1325    /// Returns the union of `contributing_cells` over every cell with at least one
1326    /// requirement — the set of cells currently determining at least one
1327    /// requirement-checked value, as of the last `propagate()` call.
1328    ///
1329    /// - Postcondition: empty if no cell in the sheet has any requirements.
1330    /// - Complexity: O(sum of `contributing_cells` cost over every cell with
1331    ///   requirements).
1332    ///
1333    /// # Examples
1334    /// See the [graph example](crate::sheet).
1335    pub fn requirement_relevant_cells(&self) -> HashSet<CellId> {
1336        self.cells
1337            .iter()
1338            .filter(|(_, c)| !c.requirements.is_empty())
1339            .flat_map(|(id, _)| self.contributing_cells(id))
1340            .collect()
1341    }
1342
1343    /// Returns the union of `requirement_contributing_cells` over every requirement
1344    /// that evaluated `false` as of the last `propagate()` call, across every cell
1345    /// in the sheet.
1346    ///
1347    /// - Postcondition: empty if no requirement anywhere in the sheet currently
1348    ///   fails.
1349    /// - Complexity: O(sum of `requirement_contributing_cells` cost over every
1350    ///   violated requirement).
1351    ///
1352    /// # Examples
1353    /// See the [graph example](crate::sheet).
1354    pub fn requirement_violation_cells(&self) -> HashSet<CellId> {
1355        self.cells
1356            .keys()
1357            .flat_map(|id| self.violated_requirements(id))
1358            .flat_map(|rid| self.requirement_contributing_cells(rid))
1359            .collect()
1360    }
1361
1362    /// Writes a value to a cell, incrementing the cell's write-recency strength.
1363    ///
1364    /// Each successful `write` increments a global monotonic counter and assigns
1365    /// the new value to `cell.strength`, so the most-recently-written cell always
1366    /// has the highest strength.
1367    ///
1368    /// - Postcondition: any pending derived override is cleared, so the written value is immediately visible via `read()`.
1369    /// - Complexity: Expected O(1) validation and phase-membership work, plus O(A)
1370    ///   when a claimed-cell write releases the final owners of prepared artifacts
1371    ///   of total size A, excluding destruction of replaced values.
1372    ///
1373    /// # Errors
1374    ///
1375    /// - `Error::InvalidId` — `id` is not a cell in this sheet.
1376    /// - `Error::TypeMismatch` — `T` does not match the cell's registered `TypeId`.
1377    /// - `Error::InvalidCellKind` — `id` is `Out`-kind.
1378    ///
1379    /// # Examples
1380    /// See the [graph example](crate::sheet).
1381    pub fn write<T: Any + 'static>(&mut self, id: CellId, value: T) -> Result<(), Error> {
1382        if self.cells.get(id).is_some_and(|c| c.kind == CellKind::Out) {
1383            return Err(Error::InvalidCellKind { sites: vec![] });
1384        }
1385        let cell_type = self.cells.get(id).ok_or(Error::InvalidId)?.type_id;
1386        if cell_type != TypeId::of::<T>() {
1387            return Err(Error::TypeMismatch {
1388                expected: cell_type,
1389                found: TypeId::of::<T>(),
1390                sites: vec![],
1391            });
1392        }
1393
1394        self.invalidate_after_write(id);
1395        self.last_filter_violations.remove(&id);
1396        self.next_strength += 1;
1397        let cell = &mut self.cells[id];
1398        cell.strength = self.next_strength | (1u64 << 63);
1399        if cell.remembered_strength.is_some() {
1400            cell.remembered_strength = Some(cell.strength);
1401        }
1402        cell.source = Box::new(value);
1403        cell.derived = None;
1404        Ok(())
1405    }
1406
1407    /// Returns a shared reference to the cell's effective current value: its derived
1408    /// override if one exists, otherwise its source (last written) value.
1409    ///
1410    /// # Errors
1411    ///
1412    /// - `Error::InvalidId` — `id` is not a cell in this sheet.
1413    /// - `Error::TypeMismatch` — `T` does not match the cell's registered `TypeId`.
1414    ///
1415    /// # Examples
1416    /// See the [graph example](crate::sheet).
1417    pub fn read<T: Any + 'static>(&self, id: CellId) -> Result<&T, Error> {
1418        let cell = self.cells.get(id).ok_or(Error::InvalidId)?;
1419        if cell.type_id != TypeId::of::<T>() {
1420            return Err(Error::TypeMismatch {
1421                expected: cell.type_id,
1422                found: TypeId::of::<T>(),
1423                sites: vec![],
1424            });
1425        }
1426        Ok(cell
1427            .effective()
1428            .downcast_ref::<T>()
1429            .expect("type checked above"))
1430    }
1431
1432    /// Returns the raw `source` slot: the last value written via `write()`/`add_cell`,
1433    /// ignoring any `derived` override produced by a self-referencing method or a
1434    /// conditionally forced relationship. For an ordinary (unshadowed) derived cell,
1435    /// `propagate()` writes straight into this same slot, so `source()` agrees with
1436    /// `read()`; the two diverge only for cells currently shadowed.
1437    ///
1438    /// # Errors
1439    ///
1440    /// - `Error::InvalidId` — `id` is not a cell in this sheet.
1441    /// - `Error::TypeMismatch` — `T` does not match the cell's registered `TypeId`.
1442    ///
1443    /// # Examples
1444    ///
1445    /// ```rust
1446    /// use adam_rs::Sheet;
1447    ///
1448    /// let mut sheet = Sheet::new();
1449    /// let a = sheet.add_cell(3_i32);
1450    /// sheet.write(a, 8_i32).unwrap();
1451    /// assert_eq!(*sheet.source::<i32>(a).unwrap(), 8);
1452    /// ```
1453    pub fn source<T: Any + 'static>(&self, id: CellId) -> Result<&T, Error> {
1454        let cell = self.cells.get(id).ok_or(Error::InvalidId)?;
1455        if cell.type_id != TypeId::of::<T>() {
1456            return Err(Error::TypeMismatch {
1457                expected: cell.type_id,
1458                found: TypeId::of::<T>(),
1459                sites: vec![],
1460            });
1461        }
1462        Ok(cell.source.downcast_ref::<T>().expect("type checked above"))
1463    }
1464
1465    /// Iterates over cells updated during the most recent successful `propagate()` call.
1466    ///
1467    /// This includes cells written by selected methods and cells that reverted to their
1468    /// source values because the relationship that had been shadowing them (self-referencing
1469    /// or conditionally forced) is no longer producing them this round (Phase 5), even though
1470    /// no method wrote to them this round. It does not attempt to compare old/new values for
1471    /// equality.
1472    ///
1473    /// - Complexity: O(n) where n is the number of changed cells.
1474    ///
1475    /// # Examples
1476    /// See the [graph example](crate::sheet).
1477    pub fn changed(&self) -> impl Iterator<Item = CellId> + '_ {
1478        self.changed_cells.iter().copied()
1479    }
1480
1481    /// Clears the changed-cell set and resets each cell's `changed` flag.
1482    ///
1483    /// Call after processing the results of `propagate()`.
1484    ///
1485    /// - Complexity: O(n) where n is the number of changed cells.
1486    ///
1487    /// # Examples
1488    /// See the [graph example](crate::sheet).
1489    pub fn clear_changed(&mut self) {
1490        for id in std::mem::take(&mut self.changed_cells) {
1491            if let Some(cell) = self.cells.get_mut(id) {
1492                cell.changed = false;
1493            }
1494        }
1495    }
1496
1497    /// Validates static guard independence for the current sheet structure.
1498    ///
1499    /// A filter's argument cells and a conditional's match cells must not depend on any
1500    /// cell governed by that filter or conditional in the static dependency graph. A
1501    /// successful call records the current structure as validated.
1502    ///
1503    /// # Errors
1504    ///
1505    /// - `Error::DependencyCycle` — a guard edge lies on a cycle in the static
1506    ///   dependency graph.
1507    ///
1508    /// # Examples
1509    ///
1510    /// ```rust
1511    /// use adam_rs::{Filter, Method, Sheet};
1512    ///
1513    /// let mut sheet = Sheet::new();
1514    /// let limit = sheet.add_cell(10_i32);
1515    /// let value = sheet.add_cell(5_i32);
1516    /// let copy = sheet.add_cell(0_i32);
1517    /// sheet
1518    ///     .add_relationship(vec![Method::from_fn_1_1(value, copy, |x: &i32| Ok(*x))])
1519    ///     .unwrap();
1520    /// sheet
1521    ///     .add_filter(value, Filter::from_fn_1(limit, |v: &i32, hi: &i32| Ok((*v).min(*hi))))
1522    ///     .unwrap();
1523    /// sheet.validate().unwrap();
1524    /// ```
1525    ///
1526    /// - Complexity: O(1) when no structural mutation has happened since the last
1527    ///   successful validation; otherwise expected O(V + E + C + I) time and space,
1528    ///   where V counts cells, E static method and guard edges, C conditionals, and
1529    ///   I their declared match inputs.
1530    pub fn validate(&mut self) -> Result<(), Error> {
1531        if self.guard_schedule.is_some() {
1532            return Ok(());
1533        }
1534        let schedule =
1535            self.analyze_guard_dependencies()
1536                .map_err(|path| Error::DependencyCycle {
1537                    sites: path.into_sites(),
1538                })?;
1539        debug_assert_eq!(
1540            schedule
1541                .batches
1542                .iter()
1543                .map(|batch| batch.conditionals.len())
1544                .sum::<usize>(),
1545            self.conditionals.len()
1546        );
1547        debug_assert!(schedule.batches.iter().all(|batch| {
1548            !batch.conditionals.is_empty()
1549                && batch.inputs.iter().all(|id| self.cells.contains_key(*id))
1550        }));
1551        self.guard_schedule = Some(Rc::new(schedule));
1552        Ok(())
1553    }
1554
1555    /// Iterates all live cell IDs in the sheet.
1556    ///
1557    /// - Complexity: O(n) where n is the number of cells.
1558    ///
1559    /// # Examples
1560    /// See the [graph example](crate::sheet).
1561    pub fn cells(&self) -> impl Iterator<Item = CellId> + '_ {
1562        self.cells.keys()
1563    }
1564
1565    /// Iterates all live relationship IDs in the sheet.
1566    ///
1567    /// - Complexity: O(n) where n is the number of relationships.
1568    ///
1569    /// # Examples
1570    /// See the [graph example](crate::sheet).
1571    pub fn relationships(&self) -> impl Iterator<Item = RelationshipId> + '_ {
1572        self.relationships.keys()
1573    }
1574
1575    /// Returns the relationships adjacent to `id`.
1576    ///
1577    /// Returns `None` if `id` is not a live cell in this sheet.
1578    ///
1579    /// - Complexity: O(1).
1580    ///
1581    /// # Examples
1582    /// See the [graph example](crate::sheet).
1583    pub fn cell_adj(&self, id: CellId) -> Option<&[RelationshipId]> {
1584        self.cells.get(id).map(|c| c.adj.as_slice())
1585    }
1586
1587    /// Returns the cells adjacent to `id` (union across all methods).
1588    ///
1589    /// Returns `None` if `id` is not a live relationship in this sheet.
1590    ///
1591    /// - Complexity: O(1).
1592    ///
1593    /// # Examples
1594    /// See the [graph example](crate::sheet).
1595    pub fn relationship_adj(&self, id: RelationshipId) -> Option<&[CellId]> {
1596        self.relationships.get(id).map(|r| r.adj.as_slice())
1597    }
1598
1599    /// Evaluates conditional `cond`'s current live match value.
1600    ///
1601    /// # Errors
1602    ///
1603    /// - `Error::MethodFailed` — the match subject is a [`MatchExpr`] whose function
1604    ///   returned an error; its site identifies the executing conditional.
1605    ///
1606    /// - Complexity: O(I) time and space for expression inputs I, plus callback cost.
1607    fn evaluate_match_source(
1608        &self,
1609        id: ConditionalId,
1610        cond: &ConditionalData,
1611    ) -> Result<MatchValue<'_>, Error> {
1612        match &cond.source {
1613            MatchSource::Cell(id) => Ok(MatchValue::Ref(self.cells[*id].effective())),
1614            MatchSource::Expr(expr) => {
1615                let args: Vec<&dyn Any> = expr
1616                    .inputs
1617                    .iter()
1618                    .map(|&id| self.cells[id].effective())
1619                    .collect();
1620                let value = (expr.function)(&args).map_err(|error| Error::MethodFailed {
1621                    error,
1622                    sites: vec![ErrorSite::Conditional(id)],
1623                })?;
1624                Ok(MatchValue::Owned(value))
1625            }
1626        }
1627    }
1628
1629    /// Evaluates conditional `cond` against staged propagation state.
1630    ///
1631    /// Uses `stage`'s writes first, then falls back to each cell's `source` value,
1632    /// matching the state visible after Phase 0 excludes old derived overrides and any
1633    /// pre-plan steps already staged.
1634    ///
1635    /// # Errors
1636    ///
1637    /// - `Error::MethodFailed` — the match subject is a [`MatchExpr`] whose function
1638    ///   returned an error; its site identifies the executing conditional.
1639    ///
1640    /// - Complexity: O(I) time and space for expression inputs I, plus callback cost.
1641    fn evaluate_match_source_staged<'a>(
1642        &'a self,
1643        id: ConditionalId,
1644        cond: &ConditionalData,
1645        stage: &'a PropagationStage,
1646    ) -> Result<MatchValue<'a>, Error> {
1647        match &cond.source {
1648            MatchSource::Cell(id) => Ok(MatchValue::Ref(stage.effective(&self.cells, *id))),
1649            MatchSource::Expr(expr) => {
1650                let args: Vec<&dyn Any> = expr
1651                    .inputs
1652                    .iter()
1653                    .map(|&id| stage.effective(&self.cells, id))
1654                    .collect();
1655                let value = (expr.function)(&args).map_err(|error| Error::MethodFailed {
1656                    error,
1657                    sites: vec![ErrorSite::Conditional(id)],
1658                })?;
1659                Ok(MatchValue::Owned(value))
1660            }
1661        }
1662    }
1663
1664    /// Returns the equality function used to compare `cond`'s match value against branch
1665    /// keys: the match cell's own `eq_fn` for a plain match subject, or the expression's
1666    /// captured `eq_fn` for a computed one.
1667    fn match_eq_fn(&self, cond: &ConditionalData) -> fn(&dyn Any, &dyn Any) -> bool {
1668        match &cond.source {
1669            MatchSource::Cell(id) => self.cells[*id].eq_fn,
1670            MatchSource::Expr(expr) => expr.eq_fn,
1671        }
1672    }
1673
1674    /// Adds a batch's selected relationships to the active set.
1675    ///
1676    /// Every conditional reads `stage`'s writes first and otherwise falls back to cell
1677    /// `source` values rather than any live
1678    /// `derived` override already present on the sheet.
1679    ///
1680    /// - Complexity: O(I + K + R), for declared match inputs I, tested keys K, and
1681    ///   selected relationships R, plus match callback and equality costs.
1682    ///
1683    /// # Errors
1684    ///
1685    /// - `Error::MethodFailed` — an expression-sourced conditional's function returned an
1686    ///   error.
1687    fn activate_conditional_batch(
1688        &self,
1689        conditionals: &[ConditionalId],
1690        stage: &PropagationStage,
1691        active: &mut HashSet<RelationshipId>,
1692    ) -> Result<(), Error> {
1693        for &id in conditionals {
1694            let cond = &self.conditionals[id];
1695            let value = self.evaluate_match_source_staged(id, cond, stage)?;
1696            let value_ref = value.as_dyn();
1697            let eq_fn = self.match_eq_fn(cond);
1698
1699            let mut matched = false;
1700            for branch in &cond.branches {
1701                if branch.keys.iter().any(|key| eq_fn(value_ref, key.as_ref())) {
1702                    for &rel_id in &branch.relationships {
1703                        active.insert(rel_id);
1704                    }
1705                    matched = true;
1706                    break;
1707                }
1708            }
1709            if !matched {
1710                for &rel_id in &cond.default {
1711                    active.insert(rel_id);
1712                }
1713            }
1714        }
1715
1716        Ok(())
1717    }
1718
1719    /// Records the actual dependency producers and write classifications for `plan`.
1720    ///
1721    /// - Complexity: expected O(V + E), where V is the number of selected steps and E is
1722    ///   the number of method inputs, outputs, and filter arguments.
1723    fn plan_provenance(&self, plan: &Plan) -> PlanProvenance {
1724        let mut provenance = PlanProvenance::default();
1725        let mut effective_producers = HashMap::new();
1726        let mut source_producers = HashMap::new();
1727
1728        for &step in &plan.execution_order {
1729            let step_provenance = match step {
1730                PlanStep::Method(rel_id, method_index) => {
1731                    let method = &self.relationships[rel_id].methods[method_index];
1732                    let method_inputs: HashSet<CellId> = method.inputs.iter().copied().collect();
1733                    let method_outputs: HashSet<CellId> = method.outputs.iter().copied().collect();
1734                    let mut input_producers = Vec::with_capacity(method.inputs.len());
1735                    let mut seed_inputs = Vec::new();
1736                    for &input in &method.inputs {
1737                        if method_outputs.contains(&input) {
1738                            seed_inputs.push(input);
1739                            input_producers.push(None);
1740                        } else {
1741                            input_producers.push(effective_producers.get(&input).copied());
1742                        }
1743                    }
1744                    let output_classes: Vec<_> = method
1745                        .outputs
1746                        .iter()
1747                        .map(|&output| {
1748                            (
1749                                output,
1750                                if method_inputs.contains(&output)
1751                                    || plan.forced_outputs.contains(&output)
1752                                {
1753                                    OutputClassification::Derived
1754                                } else {
1755                                    OutputClassification::Source
1756                                },
1757                            )
1758                        })
1759                        .collect();
1760                    for &(output, classification) in &output_classes {
1761                        effective_producers.insert(output, step);
1762                        if classification == OutputClassification::Source {
1763                            source_producers.insert(output, step);
1764                        }
1765                    }
1766                    StepProvenance {
1767                        input_producers,
1768                        seed_inputs,
1769                        source_producer: None,
1770                        output_classes,
1771                    }
1772                }
1773                PlanStep::FilterReclamp(cell) => {
1774                    let filter = self.cells[cell]
1775                        .filter
1776                        .as_ref()
1777                        .expect("plan() only emits FilterReclamp for a filtered cell");
1778                    let input_producers = filter
1779                        .args
1780                        .iter()
1781                        .map(|input| effective_producers.get(input).copied())
1782                        .collect();
1783                    let step_provenance = StepProvenance {
1784                        input_producers,
1785                        seed_inputs: Vec::new(),
1786                        source_producer: source_producers.get(&cell).copied(),
1787                        output_classes: vec![(cell, OutputClassification::Derived)],
1788                    };
1789                    effective_producers.insert(cell, step);
1790                    step_provenance
1791                }
1792            };
1793            provenance.steps.insert(step, step_provenance);
1794        }
1795        provenance.output_producers = effective_producers;
1796        provenance
1797    }
1798
1799    /// Checks that a staged prerequisite step has identical selected producer paths in both plans.
1800    ///
1801    /// - Postcondition: `true` implies the selected method/filter, its input producers,
1802    ///   seed inputs, source producer, and output classifications all match.
1803    /// - Complexity: O(I + O) for the step's input and output provenance lengths.
1804    fn prerequisite_step_is_compatible(
1805        &self,
1806        pre_plan: &PlanProvenance,
1807        final_plan: &PlanProvenance,
1808        step: PlanStep,
1809        stage: &PropagationStage,
1810    ) -> bool {
1811        let Some(staged) = stage.step_provenance.get(&step) else {
1812            return false;
1813        };
1814        pre_plan.steps.get(&step) == Some(staged) && final_plan.steps.get(&step) == Some(staged)
1815    }
1816
1817    /// Returns concrete cells and relationships implicated by a staged-step mismatch.
1818    ///
1819    /// - Complexity: O(K) sites for the step's cells and producer edges.
1820    fn conflict_sites_for_step(
1821        &self,
1822        step: PlanStep,
1823        pre_plan: &PlanProvenance,
1824        final_plan: &PlanProvenance,
1825    ) -> Vec<ErrorSite> {
1826        let mut sites = Vec::new();
1827        let mut seen_sites = HashSet::new();
1828        let mut add_site = |site| {
1829            if seen_sites.insert(site) {
1830                sites.push(site);
1831            }
1832        };
1833        let mut cells = Vec::new();
1834
1835        match step {
1836            PlanStep::Method(rel_id, method_index) => {
1837                add_site(ErrorSite::Relationship(rel_id));
1838                add_site(ErrorSite::Method(rel_id, method_index));
1839                let method = &self.relationships[rel_id].methods[method_index];
1840                cells.extend(method.inputs.iter().copied());
1841                cells.extend(method.outputs.iter().copied());
1842            }
1843            PlanStep::FilterReclamp(cell) => {
1844                cells.push(cell);
1845                if let Some(filter) = &self.cells[cell].filter {
1846                    cells.extend(filter.args.iter().copied());
1847                }
1848            }
1849        }
1850
1851        for provenance in [pre_plan.steps.get(&step), final_plan.steps.get(&step)]
1852            .into_iter()
1853            .flatten()
1854        {
1855            for producer in provenance
1856                .input_producers
1857                .iter()
1858                .copied()
1859                .flatten()
1860                .chain(provenance.source_producer)
1861            {
1862                Self::add_step_relationship_site(producer, &mut add_site);
1863            }
1864        }
1865        for cell in cells {
1866            add_site(ErrorSite::Cell(cell));
1867            for plan in [pre_plan, final_plan] {
1868                if let Some(&producer) = plan.output_producers.get(&cell) {
1869                    Self::add_step_relationship_site(producer, &mut add_site);
1870                }
1871            }
1872        }
1873        sites
1874    }
1875
1876    /// Adds the relationship site associated with a selected method producer.
1877    fn add_step_relationship_site(step: PlanStep, add_site: &mut impl FnMut(ErrorSite)) {
1878        match step {
1879            PlanStep::Method(rel_id, _) => add_site(ErrorSite::Relationship(rel_id)),
1880            PlanStep::FilterReclamp(cell) => add_site(ErrorSite::Cell(cell)),
1881        }
1882    }
1883
1884    /// Executes `execution_order` once into transactional staged state.
1885    ///
1886    /// A method or filter step already evaluated by the conditional pre-plan reuses
1887    /// its staged result when the general plan contains the same compatible step.
1888    /// This is an internal optimization, not a callback invocation guarantee.
1889    /// Filter failures remain non-fatal and leave the staged cell untouched.
1890    ///
1891    /// - Precondition: each step belongs to this graph and has matching plan provenance.
1892    /// - Complexity: O(s × k²) structural work for s steps with at most k input/output
1893    ///   cells, plus callback costs and storage for staged output values.
1894    ///
1895    /// # Errors
1896    ///
1897    /// - `Error::MethodFailed` — a `PlanStep::Method` step's function returned an error,
1898    ///   or the method produced a different number of outputs than declared.
1899    /// - `Error::TypeMismatch` — a `PlanStep::Method` step's output runtime type does
1900    ///   not match the cell's registered type.
1901    fn execute_plan_staged(
1902        &self,
1903        execution_order: &[PlanStep],
1904        seeds: &Seeds,
1905        forced_outputs: &HashSet<CellId>,
1906        plan_provenance: &PlanProvenance,
1907        stage: &mut PropagationStage,
1908        filter_violations: &mut Vec<(CellId, FilterViolation)>,
1909    ) -> Result<(), Error> {
1910        for step in execution_order {
1911            match *step {
1912                PlanStep::Method(rel_id, method_idx) => {
1913                    if stage.executed_methods.contains(&(rel_id, method_idx)) {
1914                        let method = &self.relationships[rel_id].methods[method_idx];
1915                        for &output in &method.outputs {
1916                            stage.reclassify(
1917                                output,
1918                                method.inputs.contains(&output) || forced_outputs.contains(&output),
1919                            );
1920                        }
1921                        continue;
1922                    }
1923                    let method = &self.relationships[rel_id].methods[method_idx];
1924                    let outputs = {
1925                        let inputs: Vec<&dyn Any> = method
1926                            .inputs
1927                            .iter()
1928                            .map(|&id| {
1929                                if method.outputs.contains(&id) {
1930                                    seeds
1931                                        .get(&id)
1932                                        .map(|value| value.as_ref())
1933                                        .unwrap_or_else(|| stage.source(&self.cells, id))
1934                                } else {
1935                                    stage.effective(&self.cells, id)
1936                                }
1937                            })
1938                            .collect();
1939                        (method.function)(&inputs).map_err(|error| Error::MethodFailed {
1940                            error,
1941                            sites: vec![ErrorSite::Method(rel_id, method_idx)],
1942                        })?
1943                    };
1944
1945                    if outputs.len() != method.outputs.len() {
1946                        return Err(Error::MethodFailed {
1947                            error: anyhow::anyhow!(
1948                                "method produced {} outputs but relationship expects {}",
1949                                outputs.len(),
1950                                method.outputs.len()
1951                            ),
1952                            sites: vec![ErrorSite::Method(rel_id, method_idx)],
1953                        });
1954                    }
1955
1956                    for (&cell_id, new_value) in method.outputs.iter().zip(outputs) {
1957                        let found = new_value.as_ref().type_id();
1958                        let cell = &self.cells[cell_id];
1959                        if found != cell.type_id {
1960                            return Err(Error::TypeMismatch {
1961                                expected: cell.type_id,
1962                                found,
1963                                sites: vec![ErrorSite::Method(rel_id, method_idx)],
1964                            });
1965                        }
1966                        stage.write(
1967                            cell_id,
1968                            new_value,
1969                            method.inputs.contains(&cell_id) || forced_outputs.contains(&cell_id),
1970                        );
1971                    }
1972                    stage.executed_methods.insert((rel_id, method_idx));
1973                    stage
1974                        .step_provenance
1975                        .insert(*step, plan_provenance.steps[step].clone());
1976                }
1977                PlanStep::FilterReclamp(id) => {
1978                    if stage.executed_filters.contains(&id) {
1979                        continue;
1980                    }
1981                    let filter = self.cells[id]
1982                        .filter
1983                        .as_ref()
1984                        .expect("plan() only emits FilterReclamp for a filtered cell");
1985                    let args: Vec<&dyn Any> = filter
1986                        .args
1987                        .iter()
1988                        .map(|&a| stage.effective(&self.cells, a))
1989                        .collect();
1990                    let current = stage.source(&self.cells, id);
1991                    match (filter.function)(current, &args) {
1992                        Ok(v) if v.as_ref().type_id() == self.cells[id].type_id => {
1993                            stage.write(id, v, true);
1994                        }
1995                        Ok(_) => filter_violations.push((
1996                            id,
1997                            FilterViolation::Failed(anyhow::anyhow!(
1998                                "filter returned a value of a different type than the cell"
1999                            )),
2000                        )),
2001                        Err(error) => {
2002                            filter_violations.push((id, FilterViolation::Failed(error)));
2003                        }
2004                    }
2005                    stage.executed_filters.insert(id);
2006                    stage
2007                        .step_provenance
2008                        .insert(*step, plan_provenance.steps[step].clone());
2009                }
2010            }
2011        }
2012        Ok(())
2013    }
2014
2015    /// Assigns derived-cell strengths after executing a selected plan.
2016    ///
2017    /// Walks `execution_order` and assigns a decrementing counter (starting at
2018    /// `0x7FFF_FFFF_FFFF_FFFF`) to each output cell of each selected method, in
2019    /// execution order. Cells evaluated first receive the highest derived strength.
2020    /// Source cells (not the output of any selected method) are not modified.
2021    ///
2022    /// A cell claimed *self-referencingly* (its claiming method reads the cell as one of
2023    /// its own inputs) keeps a live explicit strength rather than being demoted: such a
2024    /// method computes the cell from its own `source` aspiration (see
2025    /// [`crate::planner::evaluate_seeds`]), so an explicit `write()` to that cell is still
2026    /// the authority behind the value and must keep outranking never-written cells in
2027    /// later rounds. Demoting it would discard the edit the next time the cell is
2028    /// re-seeded.
2029    ///
2030    /// - Complexity: O(R·K²) where R is the number of entries and K is the maximum
2031    ///   inputs or outputs per method.
2032    /// - Postcondition: returns whether any cell's strength actually changed.
2033    fn post_process_strengths(&mut self, execution_order: &[PlanStep]) -> bool {
2034        let mut changed = false;
2035        let mut derived_strength = u64::MAX >> 1; // 0x7FFF_FFFF_FFFF_FFFF
2036        let mut seen: std::collections::HashSet<CellId> = std::collections::HashSet::new();
2037        for step in execution_order {
2038            let PlanStep::Method(rel_id, method_idx) = step else {
2039                continue;
2040            };
2041            if let Some(rel) = self.relationships.get(*rel_id)
2042                && let Some(method) = rel.methods.get(*method_idx)
2043            {
2044                for &output in &method.outputs {
2045                    let self_referencing = method.inputs.contains(&output);
2046                    if seen.insert(output)
2047                        && let Some(cell) = self.cells.get_mut(output)
2048                    {
2049                        if self_referencing && cell.has_explicit_strength() {
2050                            continue;
2051                        }
2052                        changed |= cell.strength != derived_strength;
2053                        cell.strength = derived_strength;
2054                        derived_strength = derived_strength.saturating_sub(1);
2055                    }
2056                }
2057            }
2058        }
2059        changed
2060    }
2061
2062    /// Publishes a fully validated propagation stage and returns previously derived cells.
2063    ///
2064    /// Clears every old derived override, applies staged source and derived writes, and
2065    /// records each staged output in [`Sheet::changed`]. No callback is evaluated here.
2066    ///
2067    /// - Complexity: O(cells).
2068    fn commit_stage(&mut self, stage: PropagationStage) -> Vec<CellId> {
2069        let previously_derived: Vec<CellId> = self
2070            .cells
2071            .iter()
2072            .filter(|(_, cell)| cell.derived.is_some())
2073            .map(|(id, _)| id)
2074            .collect();
2075        for (_, cell) in self.cells.iter_mut() {
2076            cell.derived = None;
2077        }
2078        for (id, value) in stage.sources {
2079            self.cells[id].source = value;
2080        }
2081        for (id, value) in stage.derived {
2082            self.cells[id].derived = Some(value);
2083        }
2084        for id in stage.changed {
2085            let cell = &mut self.cells[id];
2086            if !cell.changed {
2087                cell.changed = true;
2088                self.changed_cells.push(id);
2089            }
2090        }
2091        previously_derived
2092    }
2093
2094    /// Updates the sheet using eligible prepared plans or newly selected methods.
2095    ///
2096    /// Validates static guard independence before mutating state, then clears the
2097    /// changed-cell set from the previous `propagate()` call before staged planning.
2098    /// After propagation, call [`Sheet::changed`] to inspect which cells were updated,
2099    /// and [`Sheet::clear_changed`] when done.
2100    ///
2101    /// Method, filter, conditional-expression, and requirement callbacks must be
2102    /// purely functional. There is no guarantee that any callback executes, or when
2103    /// or how often it executes; results may be reused or recomputed while preserving
2104    /// cell values and diagnostics. The phases below describe the current algorithm,
2105    /// not a callback invocation contract.
2106    ///
2107    /// Retains one prepared plan per guard batch and one prepared main plan,
2108    /// each with its own released sources and active relationships. Successful writes
2109    /// to released sources preserve that phase's eligibility; writes to claimed cells
2110    /// (including self-referencing claimants) discard it. Filter reclamps do not claim
2111    /// released sources. Actual structural mutations discard every entry and the
2112    /// validated guard schedule.
2113    /// Prepared plans retain structural seed recipes, not values from earlier calls.
2114    ///
2115    /// **Phase 0 — Staging:** propagation starts from each cell's source value, excluding
2116    /// every derived override from the previous round, but does not mutate live cells.
2117    ///
2118    /// **Phase 1 — Guard prerequisites:** conditionals follow a validated dependency
2119    /// schedule, independent of registration order. Each batch obtains a prepared plan
2120    /// under the branches selected by earlier batches. Only its selected input cone
2121    /// executes, so guards read upstream forced effective values, not source aspirations.
2122    /// Unrelated filters remain deferred until the final active plan, after the relationships
2123    /// that produce their arguments.
2124    ///
2125    /// **Phase 2 — Conditional evaluation:** each batch's settled match values select
2126    /// branches whose relationships join the active set. Phases 1 and 2 repeat for each
2127    /// batch; independent conditionals share a batch. Shared relationships remain active
2128    /// when any owner selects them. Guard decisions never persist across propagation calls.
2129    ///
2130    /// **Phase 3 — General plan:** an eligible prepared main plan is obtained for the active
2131    /// set, or the Adam algorithm selects and prepares a new one. Seed-cycle
2132    /// validation and method execution consume staged Phase 1 values. A callback already
2133    /// evaluated in Phase 1 is reused only when the final plan preserves its selected
2134    /// method, input producers, and output classification. A mismatched plan returns a
2135    /// conservative conflict rather than committing stale values. This
2136    /// boundary may reject a sheet even when another assignment could have avoided the mismatch;
2137    /// propagation reports the implicated sites instead of attempting that alternate assignment.
2138    /// A Phase 1 seed callback is likewise reused only when every input reads the same staged
2139    /// source version, recursive seed result, or accumulated value; otherwise propagation
2140    /// returns a conflict instead of reusing a stale seed.
2141    ///
2142    /// **Phase 4 — Commit and strength post-processing:** after planning, seed
2143    /// validation, and staged method execution all succeed, staged writes are published
2144    /// atomically. Derived cells then receive low-order strengths in evaluation order,
2145    /// enforcing the stability invariant. A cell claimed self-referencingly keeps any
2146    /// live explicit strength instead, since its own written value is still the authority
2147    /// behind the result.
2148    ///
2149    /// **Phase 5 — Reversion change-tracking:** a cell whose derived override existed
2150    /// before this round but wasn't reclaimed by any method this round has effectively
2151    /// reverted to its source value (e.g. its forcing conditional went inactive); it is
2152    /// marked changed even though no method wrote to it this round.
2153    ///
2154    /// **Phase 6 — Requirement evaluation:** every registered requirement is evaluated
2155    /// against current cell values, rebuilding `last_requirement_violations` from
2156    /// scratch, so [`Sheet::cell_requirements_valid`] and [`Sheet::violated_requirements`]
2157    /// reflect this round.
2158    ///
2159    /// Filter failures remain diagnostics rather than propagation errors, and diagnostic
2160    /// results use current values.
2161    ///
2162    /// - Complexity: on a cache miss, prerequisite-cone indexing, traversal, and producer
2163    ///   preparation take O(V + E) per selected plan, distinct from assignment matching.
2164    ///   Cache hits omit this preparation, assignment matching, global strength sorting,
2165    ///   and complete seed-elimination replay. Active-set comparison takes expected O(R)
2166    ///   for R active relationships; a pending strength certificate takes O(C) for C cells.
2167    ///   Current strength gates and local sibling sorts still run (O(S log S) comparisons
2168    ///   for S siblings, with structural signature comparison costs). Fresh staged
2169    ///   execution, seed evaluation, commit, and diagnostics retain their costs.
2170    ///   B guard batches require B prerequisite plans plus the final plan; preparation
2171    ///   and active-set comparisons apply to each phase. Cached artifacts can occupy
2172    ///   O((B + 1)A) space for maximum single-plan artifact size A. Structural schedule
2173    ///   analysis takes O(V + E + N + I) time and space for N conditionals and I match inputs.
2174    ///   Discarding final owners of prepared artifacts of total size A can take O(A).
2175    ///
2176    /// # Errors
2177    ///
2178    /// - `Error::DependencyCycle` — a filter or conditional guard edge lies on a cycle in
2179    ///   the static dependency graph.
2180    /// - `Error::Conflict` — no valid method assignment exists, or a pre-executed guard
2181    ///   prerequisite is incompatible with the final selected plan.
2182    /// - `Error::SeedCycle` — sibling seed dependencies form a non-self cycle.
2183    /// - `Error::MethodFailed` — a method's function returned an error, a method
2184    ///   produced the wrong number of outputs, or a requirement's function returned
2185    ///   an error. A requirement error includes its governed cell as an error site.
2186    /// - `Error::TypeMismatch` — a method output's runtime type does not match the
2187    ///   cell's registered type.
2188    pub fn propagate(&mut self) -> Result<(), Error> {
2189        let mut pre = std::mem::take(&mut self.pre_plan_caches);
2190        let mut main = self.main_plan_cache.take();
2191        let result = self.propagate_with_caches(&mut pre, &mut main);
2192        if result.is_ok() {
2193            self.pre_plan_caches = pre;
2194            self.main_plan_cache = main;
2195        }
2196        result
2197    }
2198
2199    /// Returns the index of the method selected for `rel` in the last successful propagation.
2200    ///
2201    /// Returns `None` if no propagation has run yet, `rel` is not in the cached plan,
2202    /// or `rel` was added after the last `propagate()` call.
2203    ///
2204    /// - Complexity: O(S) worst-case time for S completed execution steps; O(1) space.
2205    ///
2206    /// # Examples
2207    /// See the [graph example](crate::sheet).
2208    pub fn selected_method(&self, rel: RelationshipId) -> Option<usize> {
2209        self.last_plan
2210            .as_ref()?
2211            .plan
2212            .execution_order
2213            .iter()
2214            .find_map(|step| match step {
2215                PlanStep::Method(r, idx) if *r == rel => Some(*idx),
2216                _ => None,
2217            })
2218    }
2219
2220    /// Returns the input cells of method `idx` in relationship `rel`.
2221    ///
2222    /// Returns `None` if `rel` is not a live relationship or `idx` is out of bounds.
2223    ///
2224    /// # Examples
2225    /// See the [graph example](crate::sheet).
2226    pub fn method_inputs(&self, rel: RelationshipId, idx: usize) -> Option<&[CellId]> {
2227        self.relationships
2228            .get(rel)?
2229            .methods
2230            .get(idx)
2231            .map(|m| m.inputs.as_slice())
2232    }
2233
2234    /// Returns the output cells of method `idx` in relationship `rel`.
2235    ///
2236    /// Returns `None` if `rel` is not a live relationship or `idx` is out of bounds.
2237    ///
2238    /// # Examples
2239    /// See the [graph example](crate::sheet).
2240    pub fn method_outputs(&self, rel: RelationshipId, idx: usize) -> Option<&[CellId]> {
2241        self.relationships
2242            .get(rel)?
2243            .methods
2244            .get(idx)
2245            .map(|m| m.outputs.as_slice())
2246    }
2247
2248    /// Returns `true` if `id` was not written by any selected method in the last successful propagation.
2249    ///
2250    /// Returns `false` if no propagation has succeeded yet. This display query does not
2251    /// determine prepared-plan eligibility.
2252    ///
2253    /// Cells absent from the completed plan, including newly added cells, return `true`.
2254    ///
2255    /// - Complexity: Expected O(1).
2256    ///
2257    /// # Examples
2258    /// See the [graph example](crate::sheet).
2259    pub fn is_source(&self, id: CellId) -> bool {
2260        let Some(plan) = &self.last_plan else {
2261            return false;
2262        };
2263        !plan.certificate.contains_cell(id) || plan.certificate.is_released(id)
2264    }
2265
2266    /// Iterates snapshot sources contributing to `results` in the last successful plan.
2267    ///
2268    /// An empty `results` slice selects the entire sheet: unclaimed cells and outputs
2269    /// read by their own selected method. Otherwise, selects only those sources in
2270    /// the requested cells' selected producer paths, including conforming filter
2271    /// arguments and conditional selectors governing those paths. Unselected methods'
2272    /// inputs and diagnostic-only filter arguments do not contribute.
2273    ///
2274    /// Each source appears once, in unspecified order, even when results repeat or
2275    /// share dependencies. Pure derived outputs and `Out` cells are excluded.
2276    /// Returns an empty iterator before any successful propagation. Like
2277    /// [`Self::is_source`], classification describes the last successful plan;
2278    /// newly added non-`Out` cells count as unclaimed.
2279    ///
2280    /// To capture a settled result, iterate after successful propagation and before
2281    /// further edits, reading effective values with [`Self::read`], not the
2282    /// aspirations returned by [`Self::source`]. Clients own baseline comparison,
2283    /// relevance filtering, stable cell identity, and typed serialization.
2284    ///
2285    /// Replay writes all captured values in any order as one batch before
2286    /// propagation. For a settled solution satisfying its relationships and filters,
2287    /// a compatible graph with matching uncaptured inputs reproduces the requested
2288    /// effective values (or all values when `results` is empty). Relationship methods
2289    /// must preserve an already-satisfied assignment, and self-referencing methods
2290    /// and filters must be idempotent;
2291    /// these caller contracts make the solution a fixed point even if replay
2292    /// selects different methods. No strengths or write history need to be captured.
2293    /// A snapshot does not preserve original aspirations, priority history,
2294    /// diagnostics, or behavior under subsequent edits, including spring-back.
2295    ///
2296    /// - Precondition: every result is a live cell belonging to this sheet.
2297    /// - Complexity: empty results take O(C + S + Σ(I × O)) traversal time and O(1)
2298    ///   auxiliary space, for C cells, S selected steps, and each selected method's
2299    ///   I inputs and O outputs. Nonempty results add expected O(N + V + E + V × G)
2300    ///   time and O(N + V + E) auxiliary space, for N requested results, V reachable
2301    ///   value/producer pairs, E their dependency edges, and G the total size of the
2302    ///   registered conditional graph. Does not copy cell values.
2303    ///
2304    /// # Examples
2305    ///
2306    /// ```
2307    /// use adam_rs::Sheet;
2308    /// let mut sheet = Sheet::new();
2309    /// let width = sheet.add_source(10_i32);
2310    /// sheet.add_source(false);
2311    /// sheet.propagate()?;
2312    /// assert_eq!(sheet.source_cells(&[]).count(), 2);
2313    /// let capture = sheet.source_cells(&[width])
2314    ///     .map(|id| Ok((id, *sheet.read::<i32>(id)?)))
2315    ///     .collect::<Result<Vec<_>, adam_rs::Error>>()?;
2316    /// assert_eq!(capture, [(width, 10)]);
2317    /// // Use host-defined names or schema keys, not live CellIds, for persistence.
2318    /// # Ok::<(), adam_rs::Error>(())
2319    /// ```
2320    pub fn source_cells(&self, results: &[CellId]) -> impl Iterator<Item = CellId> + use<'_> {
2321        debug_assert!(results.iter().all(|id| self.cells.contains_key(*id)));
2322        let contributors = (!results.is_empty()).then(|| self.capture_contributors(results));
2323        let unclaimed = self.cells.keys().filter(|&id| self.is_source(id));
2324        let self_referencing = self
2325            .last_plan
2326            .iter()
2327            .flat_map(|prepared| &prepared.plan.execution_order)
2328            .filter_map(|step| match *step {
2329                PlanStep::Method(id, index) => Some(&self.relationships[id].methods[index]),
2330                PlanStep::FilterReclamp(_) => None,
2331            })
2332            .flat_map(|method| {
2333                method
2334                    .outputs
2335                    .iter()
2336                    .copied()
2337                    .filter(|id| method.inputs.contains(id))
2338            });
2339        unclaimed.chain(self_referencing).filter(move |&id| {
2340            self.cells[id].kind != CellKind::Out
2341                && contributors
2342                    .as_ref()
2343                    .is_none_or(|cells| cells.contains(&id))
2344        })
2345    }
2346
2347    /// Returns the source leaves of `results`' selected value and control dependencies.
2348    ///
2349    /// Producer identities distinguish a filter's incoming source from its effective
2350    /// output. Self-referencing inputs terminate at their captured effective value,
2351    /// rather than introducing a cycle or following alternative seed methods.
2352    ///
2353    /// - Precondition: every result is a live cell belonging to this sheet.
2354    /// - Complexity: expected O(N + V + E + V × G) time and O(N + V + E) space,
2355    ///   for N results, V reachable value/producer pairs, E dependency edges, and
2356    ///   G the total size of the registered conditional graph.
2357    fn capture_contributors(&self, results: &[CellId]) -> HashSet<CellId> {
2358        let Some(prepared) = &self.last_plan else {
2359            return HashSet::new();
2360        };
2361        let provenance = &prepared.provenance;
2362        let current_value = |cell| (cell, provenance.output_producers.get(&cell).copied());
2363        let mut pending: Vec<_> = results.iter().copied().map(current_value).collect();
2364        let mut visited = HashSet::new();
2365        let mut contributors = HashSet::new();
2366
2367        while let Some((cell, producer)) = pending.pop() {
2368            if !visited.insert((cell, producer)) {
2369                continue;
2370            }
2371            pending.extend(
2372                self.conditionals
2373                    .values()
2374                    .filter(|conditional| {
2375                        conditional
2376                            .branches
2377                            .iter()
2378                            .flat_map(|branch| branch.relationships.iter())
2379                            .chain(conditional.default.iter())
2380                            .any(|&relationship| {
2381                                matches!(
2382                                    producer,
2383                                    Some(PlanStep::Method(selected, _)) if selected == relationship
2384                                ) || (!prepared.active.contains(&relationship)
2385                                    && self.relationships[relationship]
2386                                        .methods
2387                                        .iter()
2388                                        .any(|method| method.outputs.contains(&cell)))
2389                            })
2390                    })
2391                    .flat_map(|conditional| conditional.match_cells().iter().copied())
2392                    .map(current_value),
2393            );
2394            let Some(step) = producer else {
2395                contributors.insert(cell);
2396                continue;
2397            };
2398            let step_provenance = &provenance.steps[&step];
2399            let inputs = match step {
2400                PlanStep::Method(relationship, index) => {
2401                    &self.relationships[relationship].methods[index].inputs
2402                }
2403                PlanStep::FilterReclamp(filtered) => {
2404                    pending.push((filtered, step_provenance.source_producer));
2405                    &self.cells[filtered]
2406                        .filter
2407                        .as_ref()
2408                        .expect("planned filter reclamps have an attached filter")
2409                        .args
2410                }
2411            };
2412            pending.extend(
2413                inputs
2414                    .iter()
2415                    .copied()
2416                    .zip(step_provenance.input_producers.iter().copied()),
2417            );
2418        }
2419        contributors
2420    }
2421
2422    /// Returns whether `id` belongs to the last successful plan's forced pure-output set.
2423    ///
2424    /// The planner intersects pure outputs across viable methods and eliminates
2425    /// alternatives that conflict with another relationship's forced outputs until
2426    /// the classification stabilizes. A forced pure output's producer does not read
2427    /// that cell as a self-referencing input.
2428    ///
2429    /// A conditionally forced cell retains its pre-forcing priority and source
2430    /// aspiration for release; see [the forcing outcomes](crate::sheet#forced-self-referencing-and-reversible-outcomes).
2431    ///
2432    /// This does not decide whether some assignment can leave the cell unclaimed.
2433    /// A mandatory self-referencing writer claims its output exclusively but remains
2434    /// outside this classification; its editable source aspiration can affect its seed.
2435    ///
2436    /// Returns `false` if no propagation has run yet.
2437    ///
2438    /// # Examples
2439    /// See the [graph example](crate::sheet).
2440    pub fn is_forced(&self, id: CellId) -> bool {
2441        self.last_plan
2442            .as_ref()
2443            .is_some_and(|prepared| prepared.plan.forced_outputs.contains(&id))
2444    }
2445
2446    /// Iterates cells that are forced (see [`Sheet::is_forced`]) as of the last
2447    /// successful `propagate()` call.
2448    ///
2449    /// - Complexity: O(n) where n is the number of forced cells.
2450    ///
2451    /// # Examples
2452    /// See the [graph example](crate::sheet).
2453    pub fn forced_cells(&self) -> impl Iterator<Item = CellId> + '_ {
2454        self.last_plan
2455            .iter()
2456            .flat_map(|prepared| prepared.plan.forced_outputs.iter().copied())
2457    }
2458
2459    /// Returns `true` if `id` had exactly one viable method as of the last successful
2460    /// `propagate()` call — the planner has no alternative method to choose for this
2461    /// relationship, regardless of cell strength.
2462    ///
2463    /// Returns `false` if no propagation has run yet.
2464    ///
2465    /// # Examples
2466    /// See the [graph example](crate::sheet).
2467    pub fn is_relationship_forced(&self, id: RelationshipId) -> bool {
2468        self.last_plan
2469            .as_ref()
2470            .is_some_and(|prepared| prepared.plan.forced_relationships.contains(&id))
2471    }
2472
2473    /// Iterates relationships that are forced (see [`Sheet::is_relationship_forced`])
2474    /// as of the last successful `propagate()` call.
2475    ///
2476    /// - Complexity: O(n) where n is the number of forced relationships.
2477    ///
2478    /// # Examples
2479    /// See the [graph example](crate::sheet).
2480    pub fn forced_relationships(&self) -> impl Iterator<Item = RelationshipId> + '_ {
2481        self.last_plan
2482            .iter()
2483            .flat_map(|prepared| prepared.plan.forced_relationships.iter().copied())
2484    }
2485
2486    /// Iterates all live conditional IDs in the sheet.
2487    ///
2488    /// - Complexity: O(n) where n is the number of conditionals.
2489    ///
2490    /// # Examples
2491    /// See the [graph example](crate::sheet).
2492    pub fn conditionals(&self) -> impl Iterator<Item = ConditionalId> + '_ {
2493        self.conditionals.keys()
2494    }
2495
2496    /// Iterates all live `Out`-kind cells in the sheet.
2497    ///
2498    /// - Complexity: O(n) where n is the number of cells.
2499    ///
2500    /// # Examples
2501    /// See the [graph example](crate::sheet).
2502    pub fn out_cells(&self) -> impl Iterator<Item = CellId> + '_ {
2503        self.cells
2504            .iter()
2505            .filter(|(_, c)| c.kind == CellKind::Out)
2506            .map(|(id, _)| id)
2507    }
2508
2509    /// Returns the match cells for conditional `id`: a single cell for a plain match
2510    /// subject, or every input of a [`MatchExpr`] match subject.
2511    ///
2512    /// Returns `None` if `id` is not a live conditional in this sheet.
2513    ///
2514    /// # Examples
2515    /// See the [graph example](crate::sheet).
2516    pub fn conditional_match_cells(&self, id: ConditionalId) -> Option<&[CellId]> {
2517        self.conditionals.get(id).map(|c| c.match_cells())
2518    }
2519
2520    /// Returns the number of named branches in conditional `id`.
2521    ///
2522    /// Returns `None` if `id` is not a live conditional in this sheet.
2523    ///
2524    /// # Examples
2525    /// See the [graph example](crate::sheet).
2526    pub fn conditional_branch_count(&self, id: ConditionalId) -> Option<usize> {
2527        self.conditionals.get(id).map(|c| c.branches.len())
2528    }
2529
2530    /// Returns the relationship IDs for branch `branch` of conditional `id`.
2531    ///
2532    /// Returns `None` if `id` is not a live conditional, or `branch` is out of bounds.
2533    ///
2534    /// # Examples
2535    /// See the [graph example](crate::sheet).
2536    pub fn conditional_branch_relationships(
2537        &self,
2538        id: ConditionalId,
2539        branch: usize,
2540    ) -> Option<&[RelationshipId]> {
2541        self.conditionals
2542            .get(id)?
2543            .branches
2544            .get(branch)
2545            .map(|b| b.relationships.as_slice())
2546    }
2547
2548    /// Returns the default relationship IDs for conditional `id`.
2549    ///
2550    /// These relationships are active when no named branch key matches the match cell.
2551    /// Returns `None` if `id` is not a live conditional in this sheet.
2552    ///
2553    /// # Examples
2554    /// See the [graph example](crate::sheet).
2555    pub fn conditional_default_relationships(
2556        &self,
2557        id: ConditionalId,
2558    ) -> Option<&[RelationshipId]> {
2559        self.conditionals.get(id).map(|c| c.default.as_slice())
2560    }
2561
2562    /// Returns the index of the currently matching branch for conditional `id`.
2563    ///
2564    /// Evaluates branch keys against the match subject's current value in definition
2565    /// order; returns the index of the first matching branch. Returns `Ok(None)` if no
2566    /// branch key matches (the default branch is active) or if `id` is not a live
2567    /// conditional.
2568    ///
2569    /// # Errors
2570    ///
2571    /// - `Error::MethodFailed` — `id` is a live, expression-sourced conditional whose
2572    ///   function returned an error. The original cause and `ErrorSite::Conditional(id)`
2573    ///   identify the failing execution.
2574    ///
2575    /// - Complexity: O(B·K) where B = branches, K = keys per branch.
2576    ///
2577    /// # Examples
2578    /// See the [graph example](crate::sheet).
2579    pub fn conditional_active_branch(&self, id: ConditionalId) -> Result<Option<usize>, Error> {
2580        let Some(cond) = self.conditionals.get(id) else {
2581            return Ok(None);
2582        };
2583        let value = self.evaluate_match_source(id, cond)?;
2584        let value_ref = value.as_dyn();
2585        let eq_fn = self.match_eq_fn(cond);
2586        Ok(cond
2587            .branches
2588            .iter()
2589            .enumerate()
2590            .find(|(_, branch)| branch.keys.iter().any(|key| eq_fn(value_ref, key.as_ref())))
2591            .map(|(i, _)| i))
2592    }
2593}
2594
2595impl Default for Sheet {
2596    /// Returns `Sheet::new()`.
2597    fn default() -> Self {
2598        Self::new()
2599    }
2600}
2601
2602#[cfg(test)]
2603mod tests {
2604    use crate::{
2605        CellKind, ConditionalId, Error, MatchExpr, Method, Requirement, Sheet,
2606        cell::CellId,
2607        error::ErrorSite,
2608        filter::{Filter, FilterKind, FilterViolation},
2609        planner::{PlanStep, Seeds},
2610        relationship::RelationshipId,
2611    };
2612    use std::any::{Any, TypeId};
2613    use std::collections::{HashMap, HashSet};
2614
2615    /// Starts an empty default sheet and reports registered concrete identities.
2616    #[test]
2617    fn default_and_type_id_obey_empty_and_registration_contracts() {
2618        let mut sheet = Sheet::default();
2619        assert_eq!(sheet.cells().count(), 0);
2620        assert_eq!(sheet.relationships().count(), 0);
2621        assert_eq!(sheet.conditionals().count(), 0);
2622        assert_eq!(sheet.changed().count(), 0);
2623        assert_eq!(sheet.cell_type_id(CellId::default()), None);
2624        let cell = sheet.add_cell(String::new());
2625        assert_eq!(sheet.cell_type_id(cell), Some(TypeId::of::<String>()));
2626    }
2627
2628    /// Rebuilds a fresh sheet after a staged type error.
2629    #[test]
2630    fn late_output_type_failure_requires_rebuilding_the_sheet() {
2631        let make_sheet = |source_value| {
2632            let mut sheet = Sheet::new();
2633            let source = sheet.add_cell(source_value);
2634            let a = sheet.add_cell(0_i32);
2635            let b = sheet.add_cell(0_i32);
2636            sheet
2637                .add_relationship(vec![Method::new(
2638                    vec![source],
2639                    vec![a, b],
2640                    vec![TypeId::of::<i32>()],
2641                    vec![TypeId::of::<i32>(); 2],
2642                    |args| {
2643                        let value = *args[0].downcast_ref::<i32>().unwrap();
2644                        let last: Box<dyn Any> = if value < 0 {
2645                            Box::new(false)
2646                        } else {
2647                            Box::new(value)
2648                        };
2649                        Ok(vec![Box::new(value), last])
2650                    },
2651                )])
2652                .unwrap();
2653            (sheet, source, a, b)
2654        };
2655
2656        let (mut sheet, source, _, _) = make_sheet(5_i32);
2657        sheet.propagate().unwrap();
2658        sheet.write(source, -9_i32).unwrap();
2659        assert!(matches!(sheet.propagate(), Err(Error::TypeMismatch { .. })));
2660        drop(sheet);
2661
2662        let (mut rebuilt, _, a, b) = make_sheet(12_i32);
2663        rebuilt.propagate().unwrap();
2664        assert_eq!(*rebuilt.read::<i32>(a).unwrap(), 12);
2665        assert_eq!(*rebuilt.read::<i32>(b).unwrap(), 12);
2666    }
2667
2668    #[test]
2669    /// Checks the ordinary kind assigned to a new editable cell.
2670    fn add_cell_has_cell_kind() {
2671        let mut sheet = Sheet::new();
2672        let a = sheet.add_cell(0_i32);
2673        assert_eq!(sheet.cell_kind(a), Some(CellKind::Cell));
2674    }
2675
2676    #[test]
2677    /// Checks the source-only kind assigned to a new source.
2678    fn add_source_has_source_kind() {
2679        let mut sheet = Sheet::new();
2680        let a = sheet.add_source(0_i32);
2681        assert_eq!(sheet.cell_kind(a), Some(CellKind::Source));
2682    }
2683
2684    #[test]
2685    /// Checks absence of kind metadata for an unknown cell.
2686    fn cell_kind_returns_none_for_invalid_id() {
2687        let mut sheet = Sheet::new();
2688        sheet.add_cell(0_i32); // occupies slotmap index 0 in `sheet`
2689        let mut other = Sheet::new();
2690        other.add_cell(0_i32); // index 0 in `other`
2691        let bogus = other.add_cell(0_i32); // index 1 in `other` -- out of range for `sheet`,
2692        // which only ever allocated index 0, so this is
2693        // guaranteed invalid regardless of generation
2694        // (a same-index key from a second fresh SlotMap
2695        // would otherwise collide with `sheet`'s own key)
2696        assert_eq!(sheet.cell_kind(bogus), None);
2697    }
2698
2699    #[test]
2700    /// Checks that a later plain staged write replaces an earlier derived override.
2701    fn execute_plan_staged_clears_a_stale_override_on_a_later_plain_write() {
2702        let mut sheet = Sheet::new();
2703        let x = sheet.add_cell(8_i32);
2704        let y = sheet.add_cell(2_i32);
2705        let z = sheet.add_cell(10_i32);
2706        let self_ref = sheet
2707            .add_relationship(vec![
2708                Method::from_fn_2_1([x, y], x, |a: &i32, b: &i32| Ok((*a).min(*b))),
2709                Method::from_fn_2_1([x, y], y, |a: &i32, b: &i32| Ok((*a).max(*b))),
2710            ])
2711            .unwrap();
2712        let plain = sheet
2713            .add_relationship(vec![Method::from_fn_1_1(z, x, |v: &i32| {
2714                v.checked_add(1).ok_or_else(|| anyhow::anyhow!("overflow"))
2715            })])
2716            .unwrap();
2717
2718        let no_seeds: Seeds = HashMap::new();
2719        let no_forced: HashSet<CellId> = HashSet::new();
2720        let mut stage = super::PropagationStage::default();
2721        let mut plan = crate::planner::plan(
2722            &sheet.cells,
2723            &sheet.relationships,
2724            &HashSet::from([self_ref]),
2725        )
2726        .unwrap();
2727        plan.execution_order = vec![PlanStep::Method(self_ref, 0)];
2728        plan.forced_outputs.clear();
2729        let provenance = sheet.plan_provenance(&plan);
2730        sheet
2731            .execute_plan_staged(
2732                &[PlanStep::Method(self_ref, 0)],
2733                &no_seeds,
2734                &no_forced,
2735                &provenance,
2736                &mut stage,
2737                &mut Vec::new(),
2738            )
2739            .unwrap();
2740        assert_eq!(
2741            stage.effective(&sheet.cells, x).downcast_ref::<i32>(),
2742            Some(&2)
2743        );
2744        assert_eq!(*sheet.read::<i32>(x).unwrap(), 8);
2745
2746        sheet.write(z, 41_i32).unwrap();
2747        let mut plan =
2748            crate::planner::plan(&sheet.cells, &sheet.relationships, &HashSet::from([plain]))
2749                .unwrap();
2750        plan.forced_outputs.clear();
2751        let provenance = sheet.plan_provenance(&plan);
2752        sheet
2753            .execute_plan_staged(
2754                &[PlanStep::Method(plain, 0)],
2755                &no_seeds,
2756                &no_forced,
2757                &provenance,
2758                &mut stage,
2759                &mut Vec::new(),
2760            )
2761            .unwrap();
2762        assert_eq!(
2763            stage.effective(&sheet.cells, x).downcast_ref::<i32>(),
2764            Some(&42)
2765        );
2766        sheet.commit_stage(stage);
2767        assert_eq!(*sheet.read::<i32>(x).unwrap(), 42);
2768    }
2769
2770    #[test]
2771    /// Checks rejection of an unknown conditional match cell.
2772    fn add_conditional_returns_error_for_invalid_cell() {
2773        let mut sheet = Sheet::new();
2774        let result = sheet.add_conditional(
2775            MatchExpr::cell(CellId::default()),
2776            vec![(vec![0_i32], vec![])],
2777            vec![],
2778        );
2779        assert!(matches!(result, Err(Error::InvalidId)));
2780    }
2781
2782    #[test]
2783    /// Checks rejection of branch keys with the wrong match type.
2784    fn add_conditional_returns_invalid_conditional_for_type_mismatch() {
2785        let mut sheet = Sheet::new();
2786        let a = sheet.add_cell(0_i32);
2787        // Branch keys are f64 but cell holds i32.
2788        let result =
2789            sheet.add_conditional(MatchExpr::cell(a), vec![(vec![0.0_f64], vec![])], vec![]);
2790        assert!(matches!(result, Err(Error::InvalidConditional { .. })));
2791    }
2792
2793    #[test]
2794    /// Checks rejection of an unknown conditional relationship.
2795    fn add_conditional_returns_invalid_conditional_for_missing_relationship() {
2796        let mut sheet = Sheet::new();
2797        let a = sheet.add_cell(0_i32);
2798        let result = sheet.add_conditional(
2799            MatchExpr::cell(a),
2800            vec![(vec![0_i32], vec![RelationshipId::default()])],
2801            vec![],
2802        );
2803        assert!(matches!(result, Err(Error::InvalidConditional { .. })));
2804    }
2805
2806    #[test]
2807    /// Checks the match-cell site in a conditional dependency-cycle error.
2808    fn dependency_cycle_from_a_conditional_names_the_match_cell() {
2809        let mut sheet = Sheet::new();
2810        let a = sheet.add_cell(0_i32);
2811        let b = sheet.add_cell(0_i32);
2812        // Relationship has two methods and involves `a` (the match cell).
2813        let rel = sheet
2814            .add_relationship(vec![
2815                Method::from_fn_1_1(a, b, |x: &i32| Ok(*x)),
2816                Method::from_fn_1_1(b, a, |x: &i32| Ok(*x)),
2817            ])
2818            .unwrap();
2819        sheet
2820            .add_conditional(MatchExpr::cell(a), vec![(vec![0_i32], vec![rel])], vec![])
2821            .unwrap();
2822        let err = sheet.validate().unwrap_err();
2823        assert!(matches!(err, Error::DependencyCycle { .. }));
2824        assert!(err.sites().contains(&ErrorSite::Cell(a)));
2825    }
2826
2827    #[test]
2828    /// Checks rejection of a branch that can derive an upstream match dependency.
2829    fn add_conditional_returns_error_when_branch_rel_writes_a_cell_upstream_of_match_cell() {
2830        let mut sheet = Sheet::new();
2831        let a = sheet.add_cell(0_i32);
2832        let b = sheet.add_cell(0_i32);
2833        let p = sheet.add_cell(0_i32);
2834        // Unconditional: a → p  (a contributes to match cell p).
2835        sheet
2836            .add_relationship(vec![Method::from_fn_1_1(a, p, |x: &i32| Ok(*x))])
2837            .unwrap();
2838        // Branch relationship has two methods and involves `a`, which feeds p.
2839        let rel = sheet
2840            .add_relationship(vec![
2841                Method::from_fn_1_1(a, b, |x: &i32| Ok(*x)),
2842                Method::from_fn_1_1(b, a, |x: &i32| Ok(*x)),
2843            ])
2844            .unwrap();
2845        sheet
2846            .add_conditional(MatchExpr::cell(p), vec![(vec![0_i32], vec![rel])], vec![])
2847            .unwrap();
2848        assert!(matches!(
2849            sheet.validate(),
2850            Err(Error::DependencyCycle { .. })
2851        ));
2852    }
2853
2854    #[test]
2855    /// Checks guard independence for every computed-match input.
2856    fn add_conditional_returns_error_when_branch_rel_writes_a_cell_upstream_of_either_expr_input() {
2857        let mut sheet = Sheet::new();
2858        let a = sheet.add_cell(0_i32);
2859        let b = sheet.add_cell(0_i32);
2860        let p = sheet.add_cell(0_i32);
2861        let q = sheet.add_cell(0_i32);
2862        // Unconditional: a → q  (a contributes to expr input q).
2863        sheet
2864            .add_relationship(vec![Method::from_fn_1_1(a, q, |x: &i32| Ok(*x))])
2865            .unwrap();
2866        // Branch relationship has two methods and involves `a`, which feeds q, one of the
2867        // match expression's two inputs (p, q).
2868        let rel = sheet
2869            .add_relationship(vec![
2870                Method::from_fn_1_1(a, b, |x: &i32| Ok(*x)),
2871                Method::from_fn_1_1(b, a, |x: &i32| Ok(*x)),
2872            ])
2873            .unwrap();
2874        let expr = MatchExpr::from_fn_2([p, q], |x: &i32, y: &i32| Ok(*x + *y));
2875        sheet
2876            .add_conditional(expr, vec![(vec![0_i32], vec![rel])], vec![])
2877            .unwrap();
2878        assert!(matches!(
2879            sheet.validate(),
2880            Err(Error::DependencyCycle { .. })
2881        ));
2882    }
2883
2884    #[test]
2885    /// Checks branch selection from a computed two-input subject.
2886    fn add_conditional_activates_branch_from_two_cell_expression() {
2887        let mut sheet = Sheet::new();
2888        let a = sheet.add_cell(false);
2889        let b = sheet.add_cell(false);
2890        let x = sheet.add_cell(0_i32);
2891        let y = sheet.add_cell(0_i32);
2892        let rel_true = sheet
2893            .add_relationship(vec![Method::from_fn_1_1(x, y, |v: &i32| Ok(*v))])
2894            .unwrap();
2895        let expr = MatchExpr::from_fn_2([a, b], |p: &bool, q: &bool| Ok(*p && *q));
2896        let cid = sheet
2897            .add_conditional(expr, vec![(vec![true], vec![rel_true])], vec![])
2898            .unwrap();
2899
2900        sheet.write(a, true).unwrap();
2901        sheet.write(b, false).unwrap();
2902        assert_eq!(sheet.conditional_active_branch(cid).unwrap(), None);
2903
2904        sheet.write(b, true).unwrap();
2905        assert_eq!(sheet.conditional_active_branch(cid).unwrap(), Some(0));
2906        assert_eq!(sheet.conditional_match_cells(cid).unwrap(), &[a, b]);
2907    }
2908
2909    #[test]
2910    /// Checks rejection of keys incompatible with the computed subject's output type.
2911    fn add_conditional_returns_invalid_conditional_for_expr_output_type_mismatch() {
2912        let mut sheet = Sheet::new();
2913        let a = sheet.add_cell(0_i32);
2914        let b = sheet.add_cell(0_i32);
2915        // Expression computes an i32, but branch keys below are f64.
2916        let expr = MatchExpr::from_fn_2([a, b], |x: &i32, y: &i32| Ok(x + y));
2917        let result = sheet.add_conditional::<f64>(expr, vec![(vec![0.0], vec![])], vec![]);
2918        assert!(matches!(result, Err(Error::InvalidConditional { .. })));
2919    }
2920
2921    #[test]
2922    /// Checks rejection of an unknown computed-subject input.
2923    fn add_conditional_returns_invalid_id_for_bad_expr_input_cell() {
2924        let mut sheet = Sheet::new();
2925        let a = sheet.add_cell(0_i32);
2926        let expr = MatchExpr::from_fn_2([a, CellId::default()], |x: &i32, y: &i32| Ok(x + y));
2927        let result = sheet.add_conditional::<i32>(expr, vec![], vec![]);
2928        assert!(matches!(result, Err(Error::InvalidId)));
2929    }
2930
2931    #[test]
2932    /// Checks propagation of a computed subject's callback failure.
2933    fn propagate_surfaces_method_failed_from_a_failing_match_expression() {
2934        let mut sheet = Sheet::new();
2935        let a = sheet.add_cell(0_i32);
2936        let expr = MatchExpr::from_fn_1(a, |_x: &i32| -> Result<i32, anyhow::Error> {
2937            Err(anyhow::anyhow!("boom"))
2938        });
2939        sheet
2940            .add_conditional::<i32>(expr, vec![(vec![0], vec![])], vec![])
2941            .unwrap();
2942        let result = sheet.propagate();
2943        assert!(matches!(result, Err(Error::MethodFailed { .. })));
2944    }
2945
2946    #[test]
2947    /// Checks acceptance of multi-method branches independent of the match cell.
2948    fn add_conditional_allows_multi_method_rel_not_involving_match_cell() {
2949        let mut sheet = Sheet::new();
2950        let mode = sheet.add_cell(0_i32);
2951        let a = sheet.add_cell(0_i32);
2952        let b = sheet.add_cell(0_i32);
2953        // Relationship has two methods but does not involve `mode` (the match cell).
2954        // Branch relationships whose outputs do not reach the match cell may have any
2955        // number of methods.
2956        let rel = sheet
2957            .add_relationship(vec![
2958                Method::from_fn_1_1(a, b, |x: &i32| Ok(*x)),
2959                Method::from_fn_1_1(b, a, |x: &i32| Ok(*x)),
2960            ])
2961            .unwrap();
2962        let result = sheet.add_conditional(
2963            MatchExpr::cell(mode),
2964            vec![(vec![0_i32], vec![rel])],
2965            vec![],
2966        );
2967        assert!(result.is_ok());
2968    }
2969
2970    #[test]
2971    /// Checks rejection of an explicit branch without keys.
2972    fn add_conditional_returns_invalid_conditional_for_empty_branch_keys() {
2973        let mut sheet = Sheet::new();
2974        let a = sheet.add_cell(0_i32);
2975        let b = sheet.add_cell(0_i32);
2976        let rel = sheet
2977            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x))])
2978            .unwrap();
2979        // Empty key list is invalid.
2980        let result =
2981            sheet.add_conditional::<i32>(MatchExpr::cell(a), vec![(vec![], vec![rel])], vec![]);
2982        assert!(matches!(result, Err(Error::InvalidConditional { .. })));
2983    }
2984
2985    #[test]
2986    /// Checks duplicate relationships within one conditional and their diagnostic site.
2987    fn invalid_conditional_duplicate_relationship_names_that_relationship() {
2988        let mut sheet = Sheet::new();
2989        let a = sheet.add_cell(0_i32);
2990        let b = sheet.add_cell(0_i32);
2991        let dup_rel = sheet
2992            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x))])
2993            .unwrap();
2994        let result = sheet.add_conditional(
2995            MatchExpr::cell(a),
2996            vec![(vec![0_i32], vec![dup_rel])],
2997            vec![dup_rel],
2998        );
2999        let err = result.unwrap_err();
3000        assert!(matches!(err, Error::InvalidConditional { .. }));
3001        assert!(err.sites().contains(&ErrorSite::Relationship(dup_rel)));
3002    }
3003
3004    #[test]
3005    /// Checks registration and lookup of a valid conditional identity.
3006    fn add_conditional_returns_id_for_valid_input() {
3007        let mut sheet = Sheet::new();
3008        let a = sheet.add_cell(0_i32);
3009        let b = sheet.add_cell(0_i32);
3010        let rel = sheet
3011            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x))])
3012            .unwrap();
3013        let cid = sheet
3014            .add_conditional(MatchExpr::cell(a), vec![(vec![0_i32], vec![rel])], vec![])
3015            .unwrap();
3016        assert_eq!(sheet.conditionals().collect::<Vec<_>>(), vec![cid]);
3017        assert_eq!(sheet.conditional_match_cells(cid), Some([a].as_slice()));
3018    }
3019
3020    #[test]
3021    /// Checks distinct identities for separate cell declarations.
3022    fn add_cell_returns_distinct_ids() {
3023        let mut sheet = Sheet::new();
3024        let a = sheet.add_cell(1_i32);
3025        let b = sheet.add_cell(2_i32);
3026        assert_ne!(a, b);
3027    }
3028
3029    #[test]
3030    /// Checks rejection of external writes to fixed Out cells.
3031    fn write_returns_invalid_cell_kind_for_an_output_cell() {
3032        let mut sheet = Sheet::new();
3033        let writer_input = sheet.add_cell(1_i32);
3034        let out_cell = sheet.add_cell(0_i32);
3035        let out = sheet
3036            .add_out(
3037                Method::from_fn_1_1(writer_input, out_cell, |x: &i32| Ok(*x)),
3038                vec![],
3039            )
3040            .unwrap();
3041        assert!(matches!(
3042            sheet.write(out, 5_i32),
3043            Err(Error::InvalidCellKind { .. })
3044        ));
3045    }
3046
3047    #[test]
3048    /// Checks rejection of method outputs targeting source-only cells.
3049    fn add_relationship_returns_invalid_cell_kind_when_a_source_cell_is_an_output() {
3050        let mut sheet = Sheet::new();
3051        let a = sheet.add_source(0_i32);
3052        let b = sheet.add_cell(0_i32);
3053        let result = sheet.add_relationship(vec![Method::from_fn_1_1(b, a, |x: &i32| Ok(*x))]);
3054        assert!(matches!(result, Err(Error::InvalidCellKind { .. })));
3055        assert_eq!(
3056            result.unwrap_err().sites().first().copied(),
3057            Some(ErrorSite::MethodIndex(0))
3058        );
3059    }
3060
3061    #[test]
3062    /// Checks method and cell sites for a rejected source-only output.
3063    fn invalid_cell_kind_names_the_method_and_the_source_output_cell() {
3064        let mut sheet = Sheet::new();
3065        let s = sheet.add_source(0_i32); // Source-kind cell
3066        // A Source-kind output is rejected.
3067        let err = sheet
3068            .add_relationship(vec![Method::from_fn_1_1(s, s, |x: &i32| Ok(*x))])
3069            .unwrap_err();
3070        let sites = err.sites();
3071        assert_eq!(sites[0], ErrorSite::MethodIndex(0));
3072        assert!(sites[1..].contains(&ErrorSite::Cell(s)));
3073    }
3074
3075    #[test]
3076    /// Checks acceptance of source-only cells as method inputs.
3077    fn add_relationship_allows_a_source_cell_as_an_input() {
3078        let mut sheet = Sheet::new();
3079        let a = sheet.add_source(5_i32);
3080        let b = sheet.add_cell(0_i32);
3081        let result = sheet.add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x))]);
3082        assert!(result.is_ok());
3083    }
3084
3085    #[test]
3086    /// Checks external editing of source-only cells.
3087    fn write_succeeds_on_a_source_cell() {
3088        let mut sheet = Sheet::new();
3089        let a = sheet.add_source(0_i32);
3090        assert!(sheet.write(a, 5_i32).is_ok());
3091    }
3092
3093    #[test]
3094    /// Checks immediate reads of a successfully written value.
3095    fn write_read_roundtrip() {
3096        let mut sheet = Sheet::new();
3097        let id = sheet.add_cell(42_i32);
3098        sheet.write(id, 99_i32).unwrap();
3099        assert_eq!(*sheet.read::<i32>(id).unwrap(), 99);
3100    }
3101
3102    #[test]
3103    /// Checks typed-write rejection for an incompatible value.
3104    fn write_wrong_type_returns_type_mismatch() {
3105        let mut sheet = Sheet::new();
3106        let id = sheet.add_cell(0_i32);
3107        assert!(matches!(
3108            sheet.write(id, 1.0_f64),
3109            Err(Error::TypeMismatch { .. })
3110        ));
3111    }
3112
3113    #[test]
3114    /// Checks typed-read rejection for an incompatible requested type.
3115    fn read_wrong_type_returns_type_mismatch() {
3116        let mut sheet = Sheet::new();
3117        let id = sheet.add_cell(0_i32);
3118        assert!(matches!(
3119            sheet.read::<f64>(id),
3120            Err(Error::TypeMismatch { .. })
3121        ));
3122    }
3123
3124    #[test]
3125    /// Checks source/effective agreement without a derived override.
3126    fn source_matches_read_for_a_plain_unshadowed_cell() {
3127        let mut sheet = Sheet::new();
3128        let a = sheet.add_cell(3_i32);
3129        assert_eq!(*sheet.source::<i32>(a).unwrap(), 3);
3130        assert_eq!(*sheet.read::<i32>(a).unwrap(), 3);
3131
3132        sheet.write(a, 8_i32).unwrap();
3133        assert_eq!(*sheet.source::<i32>(a).unwrap(), 8);
3134        assert_eq!(*sheet.read::<i32>(a).unwrap(), 8);
3135    }
3136
3137    #[test]
3138    /// Checks source lookup rejection for an unknown cell.
3139    fn source_returns_invalid_id_for_unknown_cell() {
3140        let sheet = Sheet::new();
3141        assert!(matches!(
3142            sheet.source::<i32>(CellId::default()),
3143            Err(Error::InvalidId)
3144        ));
3145    }
3146
3147    #[test]
3148    /// Checks source lookup rejection for an incompatible requested type.
3149    fn source_wrong_type_returns_type_mismatch() {
3150        let mut sheet = Sheet::new();
3151        let id = sheet.add_cell(0_i32);
3152        assert!(matches!(
3153            sheet.source::<f64>(id),
3154            Err(Error::TypeMismatch { .. })
3155        ));
3156    }
3157
3158    #[test]
3159    /// Checks rejection of a relationship without methods.
3160    fn add_relationship_empty_methods_returns_invalid_method() {
3161        let mut sheet = Sheet::new();
3162        let result = sheet.add_relationship(vec![]);
3163        assert!(matches!(result, Err(Error::InvalidMethod { .. })));
3164        assert!(result.unwrap_err().sites().is_empty());
3165    }
3166
3167    #[test]
3168    /// Checks rejection of a method signature inconsistent with registered cell types.
3169    fn add_relationship_type_mismatch_returns_error() {
3170        let mut sheet = Sheet::new();
3171        let a = sheet.add_cell(0_i32);
3172        let b = sheet.add_cell(0_i32);
3173        // Method declares f64 input but cell holds i32.
3174        let method = Method::from_fn_1_1(a, b, |x: &f64| Ok(*x * 2.0));
3175        let result = sheet.add_relationship(vec![method]);
3176        assert!(matches!(result, Err(Error::TypeMismatch { .. })));
3177        assert_eq!(
3178            result.unwrap_err().sites().first().copied(),
3179            Some(ErrorSite::MethodIndex(0))
3180        );
3181    }
3182
3183    #[test]
3184    /// Checks the producing method's site for a runtime output-type mismatch.
3185    fn execute_plan_type_mismatch_reports_the_method_that_produced_it() {
3186        let mut sheet = Sheet::new();
3187        let a = sheet.add_cell(0_i32);
3188        let b = sheet.add_cell(false); // bool cell
3189        // Declares an i32 output (matching nothing about `b`'s actual bool type at
3190        // add_relationship time -- add_relationship validates output_types against the cell,
3191        // so declare bool here to pass that check, then lie about it at runtime below).
3192        let method = Method::new(
3193            vec![a],
3194            vec![b],
3195            vec![TypeId::of::<i32>()],
3196            vec![TypeId::of::<bool>()],
3197            |args| {
3198                let x = *args[0].downcast_ref::<i32>().unwrap();
3199                // Lies: returns an i32 though output_types declared bool, reproducing the
3200                // execute_plan runtime type-mismatch path (add_relationship can't catch this --
3201                // it only checks the declared TypeId, not what the closure actually returns).
3202                Ok(vec![Box::new(x) as Box<dyn std::any::Any>])
3203            },
3204        );
3205        let rel_id = sheet.add_relationship(vec![method]).unwrap();
3206        let result = sheet.propagate();
3207        assert!(matches!(result, Err(Error::TypeMismatch { .. })));
3208        assert_eq!(
3209            result.unwrap_err().sites().first().copied(),
3210            Some(ErrorSite::Method(rel_id, 0))
3211        );
3212    }
3213
3214    #[test]
3215    /// Checks the producing method's site for a callback failure.
3216    fn execute_plan_method_failed_reports_the_method_that_produced_it() {
3217        let mut sheet = Sheet::new();
3218        let a = sheet.add_cell(0_i32);
3219        let b = sheet.add_cell(0_i32);
3220        let method = Method::from_fn_1_1(a, b, |_: &i32| -> Result<i32, anyhow::Error> {
3221            Err(anyhow::anyhow!("boom"))
3222        });
3223        let rel_id = sheet.add_relationship(vec![method]).unwrap();
3224        let result = sheet.propagate();
3225        assert!(matches!(result, Err(Error::MethodFailed { .. })));
3226        assert_eq!(
3227            result.unwrap_err().sites().first().copied(),
3228            Some(ErrorSite::Method(rel_id, 0))
3229        );
3230    }
3231
3232    #[test]
3233    /// Checks evaluation of a constant-producing zero-input method.
3234    fn add_relationship_zero_input_method_defines_a_fixed_point() {
3235        // A method with no inputs is a valid degenerate case: it always produces the
3236        // same value, independent of every other cell in the sheet.
3237        let mut sheet = Sheet::new();
3238        let b = sheet.add_cell(0_i32);
3239        let method = Method::new(vec![], vec![b], vec![], vec![TypeId::of::<i32>()], |_| {
3240            Ok(vec![Box::new(42_i32)])
3241        });
3242        let rel = sheet.add_relationship(vec![method]).unwrap();
3243        sheet.propagate().unwrap();
3244        assert_eq!(*sheet.read::<i32>(b).unwrap(), 42);
3245        assert!(sheet.is_forced(b));
3246        assert!(sheet.is_relationship_forced(rel));
3247    }
3248
3249    #[test]
3250    /// Checks rejection of a method without outputs.
3251    fn add_relationship_empty_outputs_returns_invalid_method() {
3252        let mut sheet = Sheet::new();
3253        let a = sheet.add_cell(0_i32);
3254        let method = Method::new(
3255            vec![a],
3256            vec![], // no outputs
3257            vec![TypeId::of::<i32>()],
3258            vec![],
3259            |_| Ok(vec![]),
3260        );
3261        let result = sheet.add_relationship(vec![method]);
3262        assert!(matches!(result, Err(Error::InvalidMethod { .. })));
3263        assert_eq!(
3264            result.unwrap_err().sites().first().copied(),
3265            Some(ErrorSite::MethodIndex(0))
3266        );
3267    }
3268
3269    #[test]
3270    /// Checks acceptance of distinct output alternatives sharing one complete cell set.
3271    fn add_relationship_consistent_cell_sets_across_methods_succeeds() {
3272        let mut sheet = Sheet::new();
3273        let a = sheet.add_cell(0_i32);
3274        let b = sheet.add_cell(0_i32);
3275        let c = sheet.add_cell(0_i32);
3276        // Triangle relationship: every method references {a, b, c}.
3277        let result = sheet.add_relationship(vec![
3278            Method::from_fn_2_1([a, b], c, |x: &i32, y: &i32| Ok(x + y)),
3279            Method::from_fn_2_1([a, c], b, |x: &i32, y: &i32| Ok(y - x)),
3280            Method::from_fn_2_1([b, c], a, |x: &i32, y: &i32| Ok(y - x)),
3281        ]);
3282        assert!(result.is_ok());
3283    }
3284
3285    #[test]
3286    /// Checks rejection of alternatives with different complete cell sets.
3287    fn add_relationship_inconsistent_cell_sets_across_methods_returns_mismatched_method_cells() {
3288        let mut sheet = Sheet::new();
3289        let a = sheet.add_cell(0_i32);
3290        let b = sheet.add_cell(0_i32);
3291        let c = sheet.add_cell(0_i32);
3292        // Method 0 references {a, b}; method 1 references {b, c} -- inconsistent.
3293        let result = sheet.add_relationship(vec![
3294            Method::from_fn_1_1(a, b, |v: &i32| Ok(*v)),
3295            Method::from_fn_1_1(b, c, |v: &i32| Ok(*v)),
3296        ]);
3297        assert!(matches!(result, Err(Error::MismatchedMethodCells { .. })));
3298        assert_eq!(
3299            result.unwrap_err().sites().first().copied(),
3300            Some(ErrorSite::MethodIndex(1))
3301        );
3302    }
3303
3304    #[test]
3305    /// Checks rejection of alternatives with identical output sets.
3306    fn add_relationship_duplicate_output_set_across_methods_returns_invalid_method_outputs() {
3307        let mut sheet = Sheet::new();
3308        let a = sheet.add_cell(0_i32);
3309        let b = sheet.add_cell(0_i32);
3310        // Both methods reference {a, b} (so the cell-set-consistency check passes) but
3311        // both output {b} from different inputs -- their output sets are identical,
3312        // which must be rejected.
3313        let result = sheet.add_relationship(vec![
3314            Method::from_fn_2_1([a, b], b, |x: &i32, _y: &i32| Ok(*x)),
3315            Method::from_fn_2_1([a, b], b, |_x: &i32, y: &i32| Ok(*y)),
3316        ]);
3317        assert!(matches!(result, Err(Error::InvalidMethodOutputs { .. })));
3318        assert_eq!(
3319            result.unwrap_err().sites().first().copied(),
3320            Some(ErrorSite::MethodIndex(1))
3321        );
3322    }
3323
3324    #[test]
3325    /// Checks rejection of strictly nested alternative output sets.
3326    fn add_relationship_rejects_strictly_nested_method_outputs() {
3327        let mut sheet = Sheet::new();
3328        let a = sheet.add_cell(0_i32);
3329        let b = sheet.add_cell(0_i32);
3330        let c = sheet.add_cell(0_i32);
3331        // Both methods span {a, b, c}; one outputs {b}, the other outputs {b, c}.
3332        let result = sheet.add_relationship(vec![
3333            Method::from_fn_2_1([a, c], b, |x: &i32, y: &i32| Ok(x + y)),
3334            Method::new(
3335                vec![a],
3336                vec![b, c],
3337                vec![std::any::TypeId::of::<i32>()],
3338                vec![std::any::TypeId::of::<i32>(), std::any::TypeId::of::<i32>()],
3339                |args| {
3340                    let x = *args[0].downcast_ref::<i32>().unwrap();
3341                    Ok(vec![Box::new(x), Box::new(x)])
3342                },
3343            ),
3344        ]);
3345        let err = result.unwrap_err();
3346        assert!(matches!(err, Error::InvalidMethodOutputs { .. }));
3347        let sites = err.sites();
3348        assert_eq!(sites[0], ErrorSite::MethodIndex(1));
3349        assert_eq!(sites[1], ErrorSite::MethodIndex(0));
3350        assert_eq!(sites[2..], [ErrorSite::Cell(b)]);
3351    }
3352
3353    #[test]
3354    /// Checks acceptance of overlapping output alternatives without nesting.
3355    fn add_relationship_accepts_overlapping_non_nested_method_outputs() {
3356        let mut sheet = Sheet::new();
3357        let a = sheet.add_cell(0_i32);
3358        let b = sheet.add_cell(0_i32);
3359        let c = sheet.add_cell(0_i32);
3360        // Both methods span {a, b, c}; outputs overlap at b but neither set nests the other.
3361        let result = sheet.add_relationship(vec![
3362            Method::new(
3363                vec![a, c],
3364                vec![a, b],
3365                vec![std::any::TypeId::of::<i32>(), std::any::TypeId::of::<i32>()],
3366                vec![std::any::TypeId::of::<i32>(), std::any::TypeId::of::<i32>()],
3367                |args| {
3368                    let x = *args[0].downcast_ref::<i32>().unwrap();
3369                    let y = *args[1].downcast_ref::<i32>().unwrap();
3370                    Ok(vec![Box::new(x), Box::new(y)])
3371                },
3372            ),
3373            Method::new(
3374                vec![a, b],
3375                vec![b, c],
3376                vec![std::any::TypeId::of::<i32>(), std::any::TypeId::of::<i32>()],
3377                vec![std::any::TypeId::of::<i32>(), std::any::TypeId::of::<i32>()],
3378                |args| {
3379                    let x = *args[0].downcast_ref::<i32>().unwrap();
3380                    let y = *args[1].downcast_ref::<i32>().unwrap();
3381                    Ok(vec![Box::new(y), Box::new(x)])
3382                },
3383            ),
3384        ]);
3385        assert!(result.is_ok());
3386    }
3387
3388    #[test]
3389    /// Checks distinct identities for separate relationship declarations.
3390    fn add_relationship_returns_distinct_ids() {
3391        let mut sheet = Sheet::new();
3392        let a = sheet.add_cell(0_i32);
3393        let b = sheet.add_cell(0_i32);
3394        let r1 = sheet
3395            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x))])
3396            .unwrap();
3397        let c = sheet.add_cell(0_i32);
3398        let r2 = sheet
3399            .add_relationship(vec![Method::from_fn_1_1(b, c, |x: &i32| Ok(*x))])
3400            .unwrap();
3401        assert_ne!(r1, r2);
3402    }
3403
3404    #[test]
3405    /// Checks rejection of inconsistent positional cell sets.
3406    fn add_relationship_mismatched_cells_returns_error() {
3407        let mut sheet = Sheet::new();
3408        let a = sheet.add_cell(0_i32);
3409        let b = sheet.add_cell(0_i32);
3410        let c = sheet.add_cell(0_i32);
3411        let d = sheet.add_cell(0_i32);
3412        // Method 0 spans {a, b}; Method 1 spans {c, d} — mismatched cell sets.
3413        let result = sheet.add_relationship(vec![
3414            Method::from_fn_1_1(a, b, |x: &i32| Ok(*x)),
3415            Method::from_fn_1_1(c, d, |x: &i32| Ok(*x)),
3416        ]);
3417        assert!(matches!(result, Err(Error::MismatchedMethodCells { .. })));
3418        assert_eq!(
3419            result.unwrap_err().sites().first().copied(),
3420            Some(ErrorSite::MethodIndex(1))
3421        );
3422    }
3423
3424    #[test]
3425    /// Checks rejection of duplicate alternative output sets.
3426    fn add_relationship_duplicate_output_sets_across_methods_returns_error() {
3427        let mut sheet = Sheet::new();
3428        let a = sheet.add_cell(0_i32);
3429        let b = sheet.add_cell(0_i32);
3430        let c = sheet.add_cell(0_i32);
3431        // Both methods span {a, b, c} and both output {c} — identical output sets.
3432        let result = sheet.add_relationship(vec![
3433            Method::from_fn_2_1([a, b], c, |x: &i32, y: &i32| Ok(*x + *y)),
3434            Method::from_fn_2_1([a, b], c, |x: &i32, y: &i32| Ok(*x - *y)),
3435        ]);
3436        assert!(matches!(result, Err(Error::InvalidMethodOutputs { .. })));
3437        assert_eq!(
3438            result.unwrap_err().sites().first().copied(),
3439            Some(ErrorSite::MethodIndex(1))
3440        );
3441    }
3442
3443    #[test]
3444    /// Checks rejection of a repeated output identity within one method.
3445    fn add_relationship_duplicate_cell_within_own_outputs_returns_error() {
3446        let mut sheet = Sheet::new();
3447        let a = sheet.add_cell(0_i32);
3448        let b = sheet.add_cell(0_i32);
3449        // The method's own outputs list names `b` twice.
3450        let method = Method::new(
3451            vec![a],
3452            vec![b, b],
3453            vec![TypeId::of::<i32>()],
3454            vec![TypeId::of::<i32>(), TypeId::of::<i32>()],
3455            |args| {
3456                let x = args[0].downcast_ref::<i32>().unwrap();
3457                Ok(vec![Box::new(*x), Box::new(*x)])
3458            },
3459        );
3460        let result = sheet.add_relationship(vec![method]);
3461        assert!(matches!(result, Err(Error::InvalidMethodOutputs { .. })));
3462        assert_eq!(
3463            result.unwrap_err().sites().first().copied(),
3464            Some(ErrorSite::MethodIndex(0))
3465        );
3466    }
3467
3468    #[test]
3469    /// Checks both method sites and the differing cell in a cell-set mismatch.
3470    fn mismatched_method_cells_names_both_methods_and_the_differing_cell() {
3471        let mut sheet = Sheet::new();
3472        let a = sheet.add_cell(0_i32);
3473        let b = sheet.add_cell(0_i32);
3474        let c = sheet.add_cell(0_i32);
3475        // method 0 references {a,b}; method 1 references {a,c}: c (and b) diverge.
3476        let err = sheet
3477            .add_relationship(vec![
3478                Method::from_fn_1_1(a, b, |x: &i32| Ok(*x)),
3479                Method::from_fn_1_1(a, c, |x: &i32| Ok(*x)),
3480            ])
3481            .unwrap_err();
3482        let sites = err.sites();
3483        assert_eq!(sites[0], ErrorSite::MethodIndex(1));
3484        assert_eq!(sites[1], ErrorSite::MethodIndex(0));
3485        assert!(sites[2..].contains(&ErrorSite::Cell(c)));
3486    }
3487
3488    #[test]
3489    /// Checks both method sites and the shared cell in a duplicate-output error.
3490    fn duplicate_output_set_across_methods_names_both_methods_and_the_shared_cell() {
3491        let mut sheet = Sheet::new();
3492        let a = sheet.add_cell(0_i32);
3493        let b = sheet.add_cell(0_i32);
3494        // both methods reference {a,b} and both output b.
3495        let err = sheet
3496            .add_relationship(vec![
3497                Method::from_fn_1_1(a, b, |x: &i32| Ok(*x)),
3498                Method::from_fn_1_1(a, b, |x: &i32| Ok(*x + 1)),
3499            ])
3500            .unwrap_err();
3501        let sites = err.sites();
3502        assert_eq!(sites[0], ErrorSite::MethodIndex(1));
3503        assert_eq!(sites[1], ErrorSite::MethodIndex(0));
3504        assert!(sites[2..].contains(&ErrorSite::Cell(b)));
3505    }
3506
3507    #[test]
3508    /// Checks the method and repeated-cell sites for duplicate positional outputs.
3509    fn duplicate_cell_within_own_outputs_names_the_method_and_the_repeated_cell() {
3510        let mut sheet = Sheet::new();
3511        let a = sheet.add_cell(0_i32);
3512        let b = sheet.add_cell(0_i32);
3513        let i32_ty = std::any::TypeId::of::<i32>();
3514        // one method whose outputs name b twice.
3515        let err = sheet
3516            .add_relationship(vec![Method::new(
3517                vec![a],
3518                vec![b, b],
3519                vec![i32_ty],
3520                vec![i32_ty, i32_ty],
3521                |args| {
3522                    let v = *args[0].downcast_ref::<i32>().unwrap();
3523                    Ok(vec![Box::new(v), Box::new(v)])
3524                },
3525            )])
3526            .unwrap_err();
3527        let sites = err.sites();
3528        assert_eq!(sites[0], ErrorSite::MethodIndex(0));
3529        assert!(sites[1..].contains(&ErrorSite::Cell(b)));
3530    }
3531
3532    #[test]
3533    /// Checks deduplication of diagnostic cell sites for repeated outputs.
3534    fn duplicate_cell_repeated_three_times_reports_cell_once() {
3535        let mut sheet = Sheet::new();
3536        let a = sheet.add_cell(0_i32);
3537        let b = sheet.add_cell(0_i32);
3538        let i32_ty = std::any::TypeId::of::<i32>();
3539        // one method whose outputs name b three times.
3540        let err = sheet
3541            .add_relationship(vec![Method::new(
3542                vec![a],
3543                vec![b, b, b],
3544                vec![i32_ty],
3545                vec![i32_ty, i32_ty, i32_ty],
3546                |args| {
3547                    let v = *args[0].downcast_ref::<i32>().unwrap();
3548                    Ok(vec![Box::new(v), Box::new(v), Box::new(v)])
3549                },
3550            )])
3551            .unwrap_err();
3552        let sites = err.sites();
3553        assert_eq!(sites[0], ErrorSite::MethodIndex(0));
3554        let cell_sites: Vec<_> = sites[1..]
3555            .iter()
3556            .filter(|&&s| s == ErrorSite::Cell(b))
3557            .collect();
3558        assert_eq!(
3559            cell_sites.len(),
3560            1,
3561            "expected exactly one Cell(b) site for a triple repeat, got {sites:?}"
3562        );
3563    }
3564
3565    #[test]
3566    /// Checks an empty changed set before propagation.
3567    fn changed_is_empty_before_propagate() {
3568        let sheet = Sheet::new();
3569        assert_eq!(sheet.changed().count(), 0);
3570    }
3571
3572    #[test]
3573    /// Checks changed membership for committed method outputs.
3574    fn changed_after_propagate_contains_method_outputs() {
3575        let mut sheet = Sheet::new();
3576        let a = sheet.add_cell(0_i32);
3577        let b = sheet.add_cell(0_i32);
3578        sheet
3579            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x * 2))])
3580            .unwrap();
3581        sheet.write(a, 3_i32).unwrap();
3582        sheet.propagate().unwrap();
3583        let changed: Vec<_> = sheet.changed().collect();
3584        assert_eq!(changed, vec![b]);
3585    }
3586
3587    #[test]
3588    /// Checks explicit clearing of changed membership.
3589    fn clear_changed_empties_changed_set() {
3590        let mut sheet = Sheet::new();
3591        let a = sheet.add_cell(0_i32);
3592        let b = sheet.add_cell(0_i32);
3593        sheet
3594            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x * 2))])
3595            .unwrap();
3596        sheet.write(a, 3_i32).unwrap();
3597        sheet.propagate().unwrap();
3598        sheet.clear_changed();
3599        assert_eq!(sheet.changed().count(), 0);
3600    }
3601
3602    #[test]
3603    /// Checks replacement of previous changed membership after reversing method direction.
3604    fn propagate_clears_previous_changed_set() {
3605        let mut sheet = Sheet::new();
3606        let a = sheet.add_cell(0_i32);
3607        let b = sheet.add_cell(0_i32);
3608        sheet
3609            .add_relationship(vec![
3610                Method::from_fn_1_1(a, b, |x: &i32| Ok(*x)),
3611                Method::from_fn_1_1(b, a, |x: &i32| Ok(*x)),
3612            ])
3613            .unwrap();
3614        sheet.write(a, 3_i32).unwrap();
3615        sheet.propagate().unwrap();
3616        assert_eq!(sheet.changed().collect::<Vec<_>>(), vec![b]);
3617        sheet.write(b, 5_i32).unwrap();
3618        sheet.propagate().unwrap();
3619        let changed: Vec<_> = sheet.changed().collect();
3620        assert_eq!(changed, vec![a]);
3621    }
3622
3623    #[test]
3624    /// Checks enumeration of every live cell identity.
3625    fn cells_returns_all_cell_ids() {
3626        let mut sheet = Sheet::new();
3627        let a = sheet.add_cell(0_i32);
3628        let b = sheet.add_cell(0_i32);
3629        let ids: Vec<_> = sheet.cells().collect();
3630        assert!(ids.contains(&a));
3631        assert!(ids.contains(&b));
3632        assert_eq!(ids.len(), 2);
3633    }
3634
3635    #[test]
3636    /// Checks empty cell enumeration on a new sheet.
3637    fn cells_returns_empty_for_empty_sheet() {
3638        let sheet = Sheet::new();
3639        assert_eq!(sheet.cells().count(), 0);
3640    }
3641
3642    #[test]
3643    /// Checks enumeration of every live relationship identity.
3644    fn relationships_returns_all_relationship_ids() {
3645        let mut sheet = Sheet::new();
3646        let a = sheet.add_cell(0_i32);
3647        let b = sheet.add_cell(0_i32);
3648        let r = sheet
3649            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x))])
3650            .unwrap();
3651        let ids: Vec<_> = sheet.relationships().collect();
3652        assert_eq!(ids, vec![r]);
3653    }
3654
3655    #[test]
3656    /// Checks empty relationship enumeration on a new sheet.
3657    fn relationships_returns_empty_for_empty_sheet() {
3658        let sheet = Sheet::new();
3659        assert_eq!(sheet.relationships().count(), 0);
3660    }
3661
3662    #[test]
3663    /// Checks a cell's adjacent relationship identities.
3664    fn cell_adj_returns_adjacent_relationships() {
3665        let mut sheet = Sheet::new();
3666        let a = sheet.add_cell(0_i32);
3667        let b = sheet.add_cell(0_i32);
3668        let r = sheet
3669            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x))])
3670            .unwrap();
3671        assert!(sheet.cell_adj(a).unwrap().contains(&r));
3672        assert!(sheet.cell_adj(b).unwrap().contains(&r));
3673    }
3674
3675    #[test]
3676    /// Checks absent adjacency for an unknown cell.
3677    fn cell_adj_returns_none_for_invalid_id() {
3678        let sheet = Sheet::new();
3679        assert!(sheet.cell_adj(CellId::default()).is_none());
3680    }
3681
3682    #[test]
3683    /// Checks a relationship's complete adjacent cell set.
3684    fn relationship_adj_returns_adjacent_cells() {
3685        let mut sheet = Sheet::new();
3686        let a = sheet.add_cell(0_i32);
3687        let b = sheet.add_cell(0_i32);
3688        let r = sheet
3689            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x))])
3690            .unwrap();
3691        let adj = sheet.relationship_adj(r).unwrap();
3692        assert!(adj.contains(&a));
3693        assert!(adj.contains(&b));
3694    }
3695
3696    #[test]
3697    /// Checks absent adjacency for an unknown relationship.
3698    fn relationship_adj_returns_none_for_invalid_id() {
3699        let sheet = Sheet::new();
3700        assert!(sheet.relationship_adj(RelationshipId::default()).is_none());
3701    }
3702
3703    #[test]
3704    /// Checks absence of a selected method before propagation.
3705    fn selected_method_returns_none_before_propagate() {
3706        let mut sheet = Sheet::new();
3707        let a = sheet.add_cell(0_i32);
3708        let b = sheet.add_cell(0_i32);
3709        let rel = sheet
3710            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x))])
3711            .unwrap();
3712        assert!(sheet.selected_method(rel).is_none());
3713    }
3714
3715    #[test]
3716    /// Checks the completed plan's selected method index.
3717    fn selected_method_returns_index_after_propagate() {
3718        let mut sheet = Sheet::new();
3719        let a = sheet.add_cell(0_i32);
3720        let b = sheet.add_cell(0_i32);
3721        let rel = sheet
3722            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x))])
3723            .unwrap();
3724        // Write to `a` so it has the highest strength and becomes the source,
3725        // making the a → b method eligible.
3726        sheet.write(a, 0_i32).unwrap();
3727        sheet.propagate().unwrap();
3728        assert_eq!(sheet.selected_method(rel), Some(0));
3729    }
3730
3731    #[test]
3732    /// Checks positional input lookup for a live method.
3733    fn method_inputs_returns_inputs_for_valid_method() {
3734        let mut sheet = Sheet::new();
3735        let a = sheet.add_cell(0_i32);
3736        let b = sheet.add_cell(0_i32);
3737        let rel = sheet
3738            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x))])
3739            .unwrap();
3740        assert_eq!(sheet.method_inputs(rel, 0), Some([a].as_slice()));
3741    }
3742
3743    #[test]
3744    /// Checks positional output lookup for a live method.
3745    fn method_outputs_returns_outputs_for_valid_method() {
3746        let mut sheet = Sheet::new();
3747        let a = sheet.add_cell(0_i32);
3748        let b = sheet.add_cell(0_i32);
3749        let rel = sheet
3750            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x))])
3751            .unwrap();
3752        assert_eq!(sheet.method_outputs(rel, 0), Some([b].as_slice()));
3753    }
3754
3755    #[test]
3756    /// Checks absent input metadata for an invalid method index.
3757    fn method_inputs_returns_none_for_out_of_bounds_idx() {
3758        let mut sheet = Sheet::new();
3759        let a = sheet.add_cell(0_i32);
3760        let b = sheet.add_cell(0_i32);
3761        let rel = sheet
3762            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x))])
3763            .unwrap();
3764        assert!(sheet.method_inputs(rel, 99).is_none());
3765    }
3766
3767    #[test]
3768    /// Checks absent output metadata for an invalid method index.
3769    fn method_outputs_returns_none_for_out_of_bounds_idx() {
3770        let mut sheet = Sheet::new();
3771        let a = sheet.add_cell(0_i32);
3772        let b = sheet.add_cell(0_i32);
3773        let rel = sheet
3774            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x))])
3775            .unwrap();
3776        assert!(sheet.method_outputs(rel, 99).is_none());
3777    }
3778
3779    #[test]
3780    /// Checks absence of completed-plan source classification before propagation.
3781    fn is_source_returns_false_before_propagate() {
3782        let mut sheet = Sheet::new();
3783        let a = sheet.add_cell(0_i32);
3784        let b = sheet.add_cell(0_i32);
3785        sheet
3786            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x))])
3787            .unwrap();
3788        assert!(!sheet.is_source(a));
3789    }
3790
3791    #[test]
3792    /// Checks source classification of an unclaimed input after propagation.
3793    fn is_source_returns_true_for_input_cell_after_propagate() {
3794        let mut sheet = Sheet::new();
3795        let a = sheet.add_cell(0_i32);
3796        let b = sheet.add_cell(0_i32);
3797        sheet
3798            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x))])
3799            .unwrap();
3800        // Write to `a` so it has the highest strength and becomes the source.
3801        sheet.write(a, 0_i32).unwrap();
3802        sheet.propagate().unwrap();
3803        assert!(sheet.is_source(a));
3804    }
3805
3806    #[test]
3807    /// Checks non-source classification of a selected method's output.
3808    fn is_source_returns_false_for_output_cell_after_propagate() {
3809        let mut sheet = Sheet::new();
3810        let a = sheet.add_cell(0_i32);
3811        let b = sheet.add_cell(0_i32);
3812        sheet
3813            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x))])
3814            .unwrap();
3815        // Write to `a` so it has the highest strength and becomes the source.
3816        sheet.write(a, 0_i32).unwrap();
3817        sheet.propagate().unwrap();
3818        assert!(!sheet.is_source(b));
3819    }
3820
3821    // ── Conditional accessor tests ─────────────────────────────────────────
3822
3823    /// Builds a sheet with two keyed branches and returns its conditional identity.
3824    fn sheet_with_two_branch_conditional() -> (Sheet, ConditionalId) {
3825        let mut sheet = Sheet::new();
3826        let a = sheet.add_cell(0_i32);
3827        let b = sheet.add_cell(0_i32);
3828        let p = sheet.add_cell(0_i32);
3829
3830        let rel0 = sheet
3831            .add_relationship(vec![Method::from_fn_1_1(a, b, |v: &i32| Ok(*v))])
3832            .unwrap();
3833        let rel1 = sheet
3834            .add_relationship(vec![Method::from_fn_1_1(b, a, |v: &i32| Ok(*v))])
3835            .unwrap();
3836
3837        let cid = sheet
3838            .add_conditional(
3839                MatchExpr::cell(p),
3840                vec![(vec![0_i32], vec![rel0]), (vec![1_i32], vec![rel1])],
3841                vec![],
3842            )
3843            .unwrap();
3844        (sheet, cid)
3845    }
3846
3847    /// Builds a conditional fixture and identifies its default relationship.
3848    fn sheet_with_default_conditional() -> (Sheet, ConditionalId, RelationshipId) {
3849        let mut sheet = Sheet::new();
3850        let a = sheet.add_cell(0_i32);
3851        let b = sheet.add_cell(0_i32);
3852        let p = sheet.add_cell(99_i32); // no branch matches → default
3853
3854        let rel_default = sheet
3855            .add_relationship(vec![Method::from_fn_1_1(a, b, |v: &i32| Ok(*v))])
3856            .unwrap();
3857
3858        let cid = sheet
3859            .add_conditional::<i32>(MatchExpr::cell(p), vec![], vec![rel_default])
3860            .unwrap();
3861        (sheet, cid, rel_default)
3862    }
3863
3864    #[test]
3865    /// Checks enumeration of a registered conditional identity.
3866    fn conditionals_returns_registered_id() {
3867        let (sheet, cid) = sheet_with_two_branch_conditional();
3868        assert!(sheet.conditionals().any(|id| id == cid));
3869    }
3870
3871    #[test]
3872    /// Checks empty conditional enumeration on a new sheet.
3873    fn conditionals_empty_on_new_sheet() {
3874        let sheet = Sheet::new();
3875        assert_eq!(sheet.conditionals().count(), 0);
3876    }
3877
3878    #[test]
3879    /// Checks the registered conditional's match-cell identity.
3880    fn conditional_match_cells_returns_correct_cell() {
3881        let mut sheet = Sheet::new();
3882        let p = sheet.add_cell(0_i32);
3883        let cid = sheet
3884            .add_conditional::<i32>(MatchExpr::cell(p), vec![], vec![])
3885            .unwrap();
3886        assert_eq!(sheet.conditional_match_cells(cid), Some([p].as_slice()));
3887    }
3888
3889    #[test]
3890    /// Checks absent match inputs for an unknown conditional.
3891    fn conditional_match_cells_returns_none_for_invalid_id() {
3892        let sheet = Sheet::new();
3893        assert_eq!(
3894            sheet.conditional_match_cells(ConditionalId::default()),
3895            None
3896        );
3897    }
3898
3899    #[test]
3900    /// Checks the authored explicit-branch count.
3901    fn conditional_branch_count_returns_correct_count() {
3902        let (sheet, cid) = sheet_with_two_branch_conditional();
3903        assert_eq!(sheet.conditional_branch_count(cid), Some(2));
3904    }
3905
3906    #[test]
3907    /// Checks absent branch counts for an unknown conditional.
3908    fn conditional_branch_count_returns_none_for_invalid_id() {
3909        let sheet = Sheet::new();
3910        assert_eq!(
3911            sheet.conditional_branch_count(ConditionalId::default()),
3912            None
3913        );
3914    }
3915
3916    #[test]
3917    /// Checks the exact authored relationship identities of both explicit branches.
3918    fn conditional_branch_relationships_returns_correct_rels() {
3919        let (sheet, cid) = sheet_with_two_branch_conditional();
3920        let rels0 = sheet.conditional_branch_relationships(cid, 0).unwrap();
3921        let rels1 = sheet.conditional_branch_relationships(cid, 1).unwrap();
3922        let authored: Vec<_> = sheet.relationships().collect();
3923        assert_eq!(rels0, [authored[0]]);
3924        assert_eq!(rels1, [authored[1]]);
3925    }
3926
3927    #[test]
3928    /// Checks absent relationship metadata for an invalid branch index.
3929    fn conditional_branch_relationships_returns_none_for_out_of_bounds() {
3930        let (sheet, cid) = sheet_with_two_branch_conditional();
3931        assert!(sheet.conditional_branch_relationships(cid, 2).is_none());
3932    }
3933
3934    #[test]
3935    /// Checks absent branch relationships for an unknown conditional.
3936    fn conditional_branch_relationships_returns_none_for_invalid_id() {
3937        let sheet = Sheet::new();
3938        assert!(
3939            sheet
3940                .conditional_branch_relationships(ConditionalId::default(), 0)
3941                .is_none()
3942        );
3943    }
3944
3945    #[test]
3946    /// Checks the exact authored default-relationship identity.
3947    fn conditional_default_relationships_returns_correct_rels() {
3948        let (sheet, cid, rel_default) = sheet_with_default_conditional();
3949        let rels = sheet.conditional_default_relationships(cid).unwrap();
3950        assert_eq!(rels, [rel_default]);
3951    }
3952
3953    #[test]
3954    /// Checks empty default membership when no default is declared.
3955    fn conditional_default_relationships_empty_when_no_default() {
3956        let (sheet, cid) = sheet_with_two_branch_conditional();
3957        assert_eq!(sheet.conditional_default_relationships(cid).unwrap(), &[]);
3958    }
3959
3960    #[test]
3961    /// Checks absent default metadata for an unknown conditional.
3962    fn conditional_default_relationships_returns_none_for_invalid_id() {
3963        let sheet = Sheet::new();
3964        assert!(
3965            sheet
3966                .conditional_default_relationships(ConditionalId::default())
3967                .is_none()
3968        );
3969    }
3970
3971    #[test]
3972    /// Checks branch-index lookup for a matching subject.
3973    fn conditional_active_branch_returns_matching_branch_index() {
3974        let (mut sheet, cid) = sheet_with_two_branch_conditional();
3975        let p = sheet.conditional_match_cells(cid).unwrap()[0];
3976        sheet.write(p, 0_i32).unwrap();
3977        assert_eq!(sheet.conditional_active_branch(cid).unwrap(), Some(0));
3978        sheet.write(p, 1_i32).unwrap();
3979        assert_eq!(sheet.conditional_active_branch(cid).unwrap(), Some(1));
3980    }
3981
3982    #[test]
3983    /// Checks absent explicit-branch selection for an unmatched subject.
3984    fn conditional_active_branch_returns_none_when_no_branch_matches() {
3985        let (mut sheet, cid) = sheet_with_two_branch_conditional();
3986        let p = sheet.conditional_match_cells(cid).unwrap()[0];
3987        sheet.write(p, 99_i32).unwrap();
3988        assert_eq!(sheet.conditional_active_branch(cid).unwrap(), None);
3989    }
3990
3991    #[test]
3992    /// Checks absent branch selection for an unknown conditional.
3993    fn conditional_active_branch_returns_none_for_invalid_id() {
3994        let sheet = Sheet::new();
3995        assert_eq!(
3996            sheet
3997                .conditional_active_branch(ConditionalId::default())
3998                .unwrap(),
3999            None
4000        );
4001    }
4002
4003    #[test]
4004    /// Checks filter attachment rejection for an unknown governed cell.
4005    fn add_filter_returns_invalid_id_for_missing_cell() {
4006        let mut sheet = Sheet::new();
4007        let result = sheet.add_filter(CellId::default(), Filter::from_fn_0(|x: &i32| Ok(*x)));
4008        assert!(matches!(result, Err(Error::InvalidId)));
4009    }
4010
4011    #[test]
4012    /// Checks that attachment alone preserves the cell's current value.
4013    fn add_filter_does_not_change_the_cells_current_value() {
4014        let mut sheet = Sheet::new();
4015        let a = sheet.add_cell(500_i32);
4016        sheet
4017            .add_filter(a, Filter::from_fn_0(|x: &i32| Ok((*x).clamp(0, 100))))
4018            .unwrap();
4019        // add_filter never evaluates the function against the current value: the raw
4020        // out-of-range value survives until the next propagate().
4021        assert_eq!(*sheet.read::<i32>(a).unwrap(), 500);
4022    }
4023
4024    #[test]
4025    /// Checks conformance of the initial value at propagation rather than attachment.
4026    fn propagate_after_add_filter_conforms_the_initial_value() {
4027        let mut sheet = Sheet::new();
4028        let a = sheet.add_cell(500_i32);
4029        sheet
4030            .add_filter(a, Filter::from_fn_0(|x: &i32| Ok((*x).clamp(0, 100))))
4031            .unwrap();
4032        assert_eq!(*sheet.read::<i32>(a).unwrap(), 500);
4033        sheet.propagate().unwrap();
4034        // `a` has no filter args and belongs to no relationship — this is the ordinary
4035        // first-round case of Task 1's fix, not a special "cold start" path.
4036        assert_eq!(*sheet.read::<i32>(a).unwrap(), 100);
4037    }
4038
4039    #[test]
4040    /// Checks rejection of a second filter on the same cell.
4041    fn add_filter_returns_invalid_filter_when_cell_already_has_a_filter() {
4042        let mut sheet = Sheet::new();
4043        let a = sheet.add_cell(5_i32);
4044        sheet
4045            .add_filter(a, Filter::from_fn_0(|x: &i32| Ok(*x)))
4046            .unwrap();
4047        let result = sheet.add_filter(a, Filter::from_fn_0(|x: &i32| Ok(*x)));
4048        assert!(matches!(result, Err(Error::InvalidFilter)));
4049    }
4050
4051    #[test]
4052    /// Checks rejection of a filter declaring the wrong governed-value type.
4053    fn add_filter_returns_invalid_filter_for_mismatched_value_type() {
4054        let mut sheet = Sheet::new();
4055        let a = sheet.add_cell(5_i32);
4056        let result = sheet.add_filter(a, Filter::from_fn_0(|x: &f64| Ok(*x)));
4057        assert!(matches!(result, Err(Error::InvalidFilter)));
4058    }
4059
4060    #[test]
4061    /// Checks rejection of a filter's direct dynamic self-dependency.
4062    fn add_filter_returns_invalid_filter_when_args_name_the_filtered_cell_itself() {
4063        let mut sheet = Sheet::new();
4064        let a = sheet.add_cell(5_i32);
4065        let result = sheet.add_filter(
4066            a,
4067            Filter::from_fn_1(a, |x: &i32, bound: &i32| Ok((*x).min(*bound))),
4068        );
4069        assert!(matches!(result, Err(Error::InvalidFilter)));
4070    }
4071
4072    #[test]
4073    /// Checks filter attachment rejection for an unknown argument.
4074    fn add_filter_returns_invalid_id_for_missing_arg_cell() {
4075        let mut sheet = Sheet::new();
4076        let a = sheet.add_cell(5_i32);
4077        let result = sheet.add_filter(
4078            a,
4079            Filter::from_fn_1(CellId::default(), |x: &i32, bound: &i32| {
4080                Ok((*x).min(*bound))
4081            }),
4082        );
4083        assert!(matches!(result, Err(Error::InvalidId)));
4084    }
4085
4086    #[test]
4087    /// Checks filter attachment rejection for an incompatible argument type.
4088    fn add_filter_returns_type_mismatch_for_wrong_arg_cell_type() {
4089        let mut sheet = Sheet::new();
4090        let a = sheet.add_cell(5_i32);
4091        let bound = sheet.add_cell(1.0_f64); // wrong type: filter declares i32
4092        let result = sheet.add_filter(
4093            a,
4094            Filter::from_fn_1(bound, |x: &i32, bound: &i32| Ok((*x).min(*bound))),
4095        );
4096        assert!(matches!(result, Err(Error::TypeMismatch { .. })));
4097    }
4098
4099    #[test]
4100    /// Checks filter attachment to a source-only cell.
4101    fn add_filter_succeeds_on_a_source_kind_cell() {
4102        let mut sheet = Sheet::new();
4103        let a = sheet.add_source(5_i32);
4104        assert!(
4105            sheet
4106                .add_filter(a, Filter::from_fn_0(|x: &i32| Ok((*x).clamp(0, 10))))
4107                .is_ok()
4108        );
4109    }
4110
4111    #[test]
4112    /// Checks that both dynamic bounds affect a binary filter's conformed value.
4113    fn from_fn_2_conforms_values_through_sheet_using_both_dynamic_arguments() {
4114        let mut sheet = Sheet::new();
4115        let a = sheet.add_cell(500_i32);
4116        let lo = sheet.add_cell(0_i32);
4117        let hi = sheet.add_cell(100_i32);
4118        sheet
4119            .add_filter(
4120                a,
4121                Filter::from_fn_2([lo, hi], |x: &i32, lo: &i32, hi: &i32| {
4122                    Ok((*x).clamp(*lo, *hi))
4123                }),
4124            )
4125            .unwrap();
4126        sheet.propagate().unwrap();
4127        assert_eq!(*sheet.read::<i32>(a).unwrap(), 100);
4128
4129        sheet.write(a, -10_i32).unwrap();
4130        sheet.propagate().unwrap();
4131        assert_eq!(*sheet.read::<i32>(a).unwrap(), 0);
4132    }
4133
4134    #[test]
4135    /// Checks direct source/effective publication by an unfiltered write.
4136    fn write_without_a_filter_behaves_exactly_as_before() {
4137        let mut sheet = Sheet::new();
4138        let a = sheet.add_cell(0_i32);
4139        sheet.write(a, 42_i32).unwrap();
4140        assert_eq!(*sheet.read::<i32>(a).unwrap(), 42);
4141    }
4142
4143    #[test]
4144    /// Checks preservation of the raw aspiration across deferred filtering.
4145    fn write_leaves_the_raw_value_in_source_until_propagate_conforms_it() {
4146        let mut sheet = Sheet::new();
4147        let a = sheet.add_cell(0_i32);
4148        sheet
4149            .add_filter(a, Filter::from_fn_0(|x: &i32| Ok((*x).clamp(0, 100))))
4150            .unwrap();
4151        sheet.write(a, 500_i32).unwrap();
4152        // write() no longer runs the filter: the raw value stands until propagate().
4153        assert_eq!(*sheet.read::<i32>(a).unwrap(), 500);
4154        sheet.propagate().unwrap();
4155        assert_eq!(*sheet.read::<i32>(a).unwrap(), 100);
4156    }
4157
4158    #[test]
4159    /// Checks absence of diagnostics for a conforming derived value.
4160    fn propagate_reports_no_violation_when_a_derived_value_conforms() {
4161        let mut sheet = Sheet::new();
4162        let a = sheet.add_cell(10_i32);
4163        let b = sheet.add_cell(0_i32);
4164        sheet
4165            .add_filter(b, Filter::from_fn_0(|x: &i32| Ok((*x).clamp(0, 100))))
4166            .unwrap();
4167        sheet
4168            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x))])
4169            .unwrap();
4170        sheet.propagate().unwrap();
4171        assert_eq!(*sheet.read::<i32>(b).unwrap(), 10);
4172        assert!(sheet.last_filter_violations.is_empty());
4173    }
4174
4175    #[test]
4176    /// Checks a soft nonconformance diagnostic without rewriting a derived value.
4177    fn propagate_reports_not_conformed_when_a_derived_value_violates_its_filter() {
4178        let mut sheet = Sheet::new();
4179        let a = sheet.add_cell(60_i32);
4180        let b = sheet.add_cell(0_i32);
4181        sheet
4182            .add_filter(b, Filter::from_fn_0(|x: &i32| Ok((*x).clamp(0, 100))))
4183            .unwrap();
4184        sheet
4185            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x * 2))])
4186            .unwrap();
4187        sheet.propagate().unwrap();
4188        // 60 * 2 = 120, clamp(0, 100) => 100 != 120.
4189        assert_eq!(*sheet.read::<i32>(b).unwrap(), 120);
4190        assert!(matches!(
4191            sheet.last_filter_violations.get(&b),
4192            Some(FilterViolation::NotConformed)
4193        ));
4194    }
4195
4196    #[test]
4197    /// Checks a soft callback-failure diagnostic for a derived value.
4198    fn propagate_reports_failed_when_the_filter_errors_on_a_derived_value() {
4199        let mut sheet = Sheet::new();
4200        let a = sheet.add_cell(1_i32);
4201        let b = sheet.add_cell(0_i32);
4202        // Accept exactly 0 (b's initial value) so this filter's shape is exercised
4203        // only by the relationship's derived value (1, copied from `a`), not by
4204        // anything add_filter itself does — add_filter no longer evaluates a filter's
4205        // function at all.
4206        sheet
4207            .add_filter(
4208                b,
4209                Filter::from_fn_0(|x: &i32| {
4210                    if *x == 0 {
4211                        Ok(*x)
4212                    } else {
4213                        Err(anyhow::anyhow!("cannot conform"))
4214                    }
4215                }),
4216            )
4217            .unwrap();
4218        sheet
4219            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x))])
4220            .unwrap();
4221        // propagate() must not abort even though the filter errors.
4222        sheet.propagate().unwrap();
4223        assert!(matches!(
4224            sheet.last_filter_violations.get(&b),
4225            Some(FilterViolation::Failed(_))
4226        ));
4227    }
4228
4229    #[test]
4230    /// Checks a soft type-failure diagnostic for a malformed derived-value filter result.
4231    fn propagate_reports_failed_when_the_filter_returns_the_wrong_type_on_a_derived_value() {
4232        let mut sheet = Sheet::new();
4233        let a = sheet.add_cell(1_i32);
4234        let b = sheet.add_cell(0_i32);
4235        // Returns a `f64` for a nonzero derived value, tripping
4236        // propagate()'s diagnostic-phase defensive check once `a`'s value (1) is
4237        // copied into `b` this round.
4238        let filter = Filter::new(TypeId::of::<i32>(), vec![], vec![], |value, _args| {
4239            let v = *value.downcast_ref::<i32>().unwrap();
4240            if v == 0 {
4241                Ok(Box::new(v) as Box<dyn Any>)
4242            } else {
4243                Ok(Box::new(1.5_f64) as Box<dyn Any>)
4244            }
4245        });
4246        sheet.add_filter(b, filter).unwrap();
4247        sheet
4248            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x))])
4249            .unwrap();
4250        // propagate() must not abort even though the filter's function returns the
4251        // wrong type.
4252        sheet.propagate().unwrap();
4253        assert!(matches!(
4254            sheet.filter_violation(b),
4255            Some(FilterViolation::Failed(_))
4256        ));
4257    }
4258
4259    #[test]
4260    /// Checks absence of nonconformance diagnostics for a successfully conformed source.
4261    fn propagate_never_flags_a_filtered_cell_that_stayed_a_plain_source() {
4262        let mut sheet = Sheet::new();
4263        let a = sheet.add_cell(60_i32);
4264        sheet
4265            .add_filter(a, Filter::from_fn_0(|x: &i32| Ok((*x).clamp(0, 100))))
4266            .unwrap();
4267        sheet.propagate().unwrap();
4268        assert!(sheet.last_filter_violations.is_empty());
4269    }
4270
4271    #[test]
4272    /// Checks reclamping of a source after its dynamic argument changes.
4273    fn propagate_reclamps_a_filtered_source_cell_when_its_argument_changes() {
4274        // Issue #132's exact repro.
4275        let mut sheet = Sheet::new();
4276        let a = sheet.add_cell(50_i32);
4277        let bound = sheet.add_cell(100_i32);
4278        sheet
4279            .add_filter(
4280                a,
4281                Filter::from_fn_1(bound, |v: &i32, b: &i32| Ok((*v).min(*b))),
4282            )
4283            .unwrap();
4284        sheet.write(bound, 10_i32).unwrap();
4285        sheet.propagate().unwrap();
4286        assert_eq!(*sheet.read::<i32>(a).unwrap(), 10);
4287    }
4288
4289    #[test]
4290    /// Checks that downstream methods consume the settled conformed source.
4291    fn propagate_reclamps_before_a_relationship_consumes_the_reclamped_value() {
4292        // The inequality.adm2-shaped case: a and b are linked by a two-method mutual
4293        // relationship (b := min(a, b); a := max(a, b)); a is the currently-source cell
4294        // of the pair and is filtered against a bound that just shrank. b (derived) must
4295        // reflect the corrected a, not the pre-reclamp one, within a single propagate().
4296        //
4297        // b is created before a so that a (created later) outranks b in strength —
4298        // release::resolve keeps the higher-strength cell a source (see
4299        // release::tests::strength_prefers_the_higher_strength_cell_as_source) — making a
4300        // the source and b the derived cell of the pair, as this test needs.
4301        let mut sheet = Sheet::new();
4302        let b = sheet.add_cell(20_i32);
4303        let a = sheet.add_cell(50_i32);
4304        let bound = sheet.add_cell(100_i32);
4305        sheet
4306            .add_filter(
4307                a,
4308                Filter::from_fn_1(bound, |v: &i32, bnd: &i32| Ok((*v).min(*bnd))),
4309            )
4310            .unwrap();
4311        sheet
4312            .add_relationship(vec![
4313                Method::from_fn_2_1([a, b], b, |x: &i32, y: &i32| Ok((*x).min(*y))),
4314                Method::from_fn_2_1([a, b], a, |x: &i32, y: &i32| Ok((*x).max(*y))),
4315            ])
4316            .unwrap();
4317        sheet.propagate().unwrap();
4318
4319        sheet.write(bound, 5_i32).unwrap();
4320        sheet.propagate().unwrap();
4321
4322        // a reclamps to min(50, 5) = 5; b's method (a.min(b)) then reads the reclamped
4323        // a, not the stale 50.
4324        assert_eq!(*sheet.read::<i32>(a).unwrap(), 5);
4325        assert_eq!(*sheet.read::<i32>(b).unwrap(), 5);
4326    }
4327
4328    #[test]
4329    /// Checks restoration of the stored aspiration when a dynamic bound loosens.
4330    fn filtered_source_cell_springs_back_to_its_original_value_when_a_bound_loosens() {
4331        let mut sheet = Sheet::new();
4332        let a = sheet.add_cell(50_i32);
4333        let bound = sheet.add_cell(100_i32);
4334        sheet
4335            .add_filter(
4336                a,
4337                Filter::from_fn_1(bound, |v: &i32, b: &i32| Ok((*v).min(*b))),
4338            )
4339            .unwrap();
4340
4341        sheet.write(bound, 10_i32).unwrap();
4342        sheet.propagate().unwrap();
4343        assert_eq!(*sheet.read::<i32>(a).unwrap(), 10);
4344
4345        sheet.write(bound, 100_i32).unwrap();
4346        sheet.propagate().unwrap();
4347        // a's original 50 must survive in `source` across the whole round-trip: it
4348        // springs back once the bound loosens again, rather than staying stuck at the
4349        // intermediate clamp.
4350        assert_eq!(*sheet.read::<i32>(a).unwrap(), 50);
4351    }
4352
4353    #[test]
4354    /// Checks a soft diagnostic for a malformed successful source-filter result.
4355    fn filter_reclamp_records_failed_violation_when_the_filters_function_returns_the_wrong_type() {
4356        let mut sheet = Sheet::new();
4357        let a = sheet.add_cell(5_i32);
4358        let trigger = sheet.add_cell(0_i32);
4359        // Returns an f64 when trigger becomes non-zero,
4360        // tripping FilterReclamp's check once `trigger` is updated.
4361        let filter = Filter::new(
4362            TypeId::of::<i32>(),
4363            vec![trigger],
4364            vec![TypeId::of::<i32>()],
4365            |value, args| {
4366                let v = *value.downcast_ref::<i32>().unwrap();
4367                let t = *args[0].downcast_ref::<i32>().unwrap();
4368                if t == 0 {
4369                    Ok(Box::new(v) as Box<dyn Any>)
4370                } else {
4371                    Ok(Box::new(1.5_f64) as Box<dyn Any>)
4372                }
4373            },
4374        );
4375        sheet.add_filter(a, filter).unwrap();
4376
4377        // trigger changes, causing reclamp where the filter returns wrong type
4378        sheet.write(trigger, 1_i32).unwrap();
4379        sheet.propagate().unwrap();
4380
4381        assert!(matches!(
4382            sheet.filter_violation(a),
4383            Some(FilterViolation::Failed(_))
4384        ));
4385        // The wrong-type result is discarded: the cell's stored value is unchanged.
4386        assert_eq!(*sheet.read::<i32>(a).unwrap(), 5);
4387    }
4388
4389    #[test]
4390    /// Checks that a failed reclamp preserves the cell and does not abort propagation.
4391    fn filter_reclamp_failure_is_recorded_without_aborting_propagate_or_changing_the_cell() {
4392        let mut sheet = Sheet::new();
4393        let a = sheet.add_cell(5_i32);
4394        let bound = sheet.add_cell(100_i32);
4395        // Accept anything up to `bound` (a's initial 5 is within bound's initial 100);
4396        // the write to `bound` below is what trips the filter's next live reclamp.
4397        sheet
4398            .add_filter(
4399                a,
4400                Filter::from_fn_1(bound, |v: &i32, b: &i32| {
4401                    if *v <= *b {
4402                        Ok(*v)
4403                    } else {
4404                        Err(anyhow::anyhow!("cannot conform"))
4405                    }
4406                }),
4407            )
4408            .unwrap();
4409        sheet.write(bound, 0_i32).unwrap();
4410
4411        sheet.propagate().unwrap();
4412
4413        assert!(matches!(
4414            sheet.filter_violation(a),
4415            Some(FilterViolation::Failed(_))
4416        ));
4417        // Rejected reclamp: the cell's stored value is left completely unchanged.
4418        assert_eq!(*sheet.read::<i32>(a).unwrap(), 5);
4419    }
4420
4421    #[test]
4422    /// Checks positional lookup of a filter's dynamic argument identities.
4423    fn filter_args_returns_the_filters_argument_cells() {
4424        let mut sheet = Sheet::new();
4425        let a = sheet.add_cell(5_i32);
4426        let bound = sheet.add_cell(10_i32);
4427        sheet
4428            .add_filter(
4429                a,
4430                Filter::from_fn_1(bound, |x: &i32, bound: &i32| Ok((*x).min(*bound))),
4431            )
4432            .unwrap();
4433        assert_eq!(sheet.filter_args(a), Some(&[bound][..]));
4434    }
4435
4436    #[test]
4437    /// Checks absent argument metadata on an unfiltered cell.
4438    fn filter_args_returns_none_for_a_cell_with_no_filter() {
4439        let mut sheet = Sheet::new();
4440        let a = sheet.add_cell(5_i32);
4441        assert_eq!(sheet.filter_args(a), None);
4442    }
4443
4444    #[test]
4445    /// Checks absent filter arguments for an unknown cell.
4446    fn filter_args_returns_none_for_an_invalid_cell() {
4447        let sheet = Sheet::new();
4448        assert_eq!(sheet.filter_args(CellId::default()), None);
4449    }
4450
4451    #[test]
4452    /// Checks absence of filter diagnostics before propagation.
4453    fn filter_violation_returns_none_before_any_propagate() {
4454        let mut sheet = Sheet::new();
4455        let cell = sheet.add_cell(100_i32);
4456        sheet
4457            .add_filter(
4458                cell,
4459                Filter::from_fn_0(|value: &i32| Ok((*value).clamp(0, 10))),
4460            )
4461            .unwrap();
4462        assert!(sheet.filter_violation(cell).is_none());
4463        assert!(sheet.filter_violation(CellId::default()).is_none());
4464    }
4465
4466    #[test]
4467    /// Checks enumeration of a currently nonconforming filtered cell.
4468    fn filter_violated_cells_reports_a_currently_violated_filter() {
4469        let mut sheet = Sheet::new();
4470        let a = sheet.add_cell(60_i32);
4471        let b = sheet.add_cell(0_i32);
4472        sheet
4473            .add_filter(b, Filter::from_fn_0(|x: &i32| Ok((*x).clamp(0, 100))))
4474            .unwrap();
4475        sheet
4476            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x * 2))])
4477            .unwrap();
4478        sheet.propagate().unwrap();
4479        assert!(sheet.filter_violated_cells().any(|id| id == b));
4480        assert!(matches!(
4481            sheet.filter_violation(b),
4482            Some(FilterViolation::NotConformed)
4483        ));
4484    }
4485
4486    #[test]
4487    /// Checks an empty diagnostic-contributor set when all filters conform.
4488    fn filter_violation_cells_is_empty_when_nothing_is_violated() {
4489        let mut sheet = Sheet::new();
4490        let a = sheet.add_cell(10_i32);
4491        sheet
4492            .add_filter(a, Filter::from_fn_0(|x: &i32| Ok((*x).clamp(0, 100))))
4493            .unwrap();
4494        sheet.propagate().unwrap();
4495        assert!(sheet.filter_violation_cells().is_empty());
4496    }
4497
4498    #[test]
4499    /// Checks root contributors of a nonconforming derived value.
4500    fn filter_violation_cells_includes_root_causes_of_a_violation() {
4501        let mut sheet = Sheet::new();
4502        let a = sheet.add_cell(60_i32);
4503        let bound = sheet.add_cell(100_i32);
4504        let b = sheet.add_cell(0_i32);
4505        sheet
4506            .add_filter(
4507                b,
4508                Filter::from_fn_1(bound, |x: &i32, bound: &i32| Ok((*x).min(*bound))),
4509            )
4510            .unwrap();
4511        sheet
4512            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x * 2))])
4513            .unwrap();
4514        sheet.propagate().unwrap();
4515        let violation_cells = sheet.filter_violation_cells();
4516        // `b` is forced (its relationship has only one method), so — mirroring
4517        // `contributing_cells`'s existing semantics — it is `a` and `bound` that
4518        // appear as the upstream root causes, not `b` itself. `b`'s own membership
4519        // is already answered by `filter_violated_cells()`, tested separately above.
4520        assert!(violation_cells.contains(&a));
4521        assert!(violation_cells.contains(&bound));
4522    }
4523
4524    #[test]
4525    /// Checks root contributors of a failed filter diagnostic.
4526    fn filter_violation_cells_includes_root_causes_of_a_failed_violation() {
4527        let mut sheet = Sheet::new();
4528        let a = sheet.add_cell(1_i32);
4529        let bound = sheet.add_cell(100_i32);
4530        let b = sheet.add_cell(0_i32);
4531        // Errors on a nonzero input so the relationship's derived value (copied from `a`) trips a
4532        // `Failed` violation instead of `NotConformed`.
4533        sheet
4534            .add_filter(
4535                b,
4536                Filter::from_fn_1(bound, |x: &i32, _bound: &i32| {
4537                    if *x == 0 {
4538                        Ok(*x)
4539                    } else {
4540                        Err(anyhow::anyhow!("cannot conform"))
4541                    }
4542                }),
4543            )
4544            .unwrap();
4545        sheet
4546            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x))])
4547            .unwrap();
4548        sheet.propagate().unwrap();
4549        assert!(matches!(
4550            sheet.filter_violation(b),
4551            Some(FilterViolation::Failed(_))
4552        ));
4553        let violation_cells = sheet.filter_violation_cells();
4554        // Mirroring the `NotConformed` case above: `b` is forced, so `a` and `bound`
4555        // are the upstream root causes, not `b` itself.
4556        assert!(violation_cells.contains(&a));
4557        assert!(violation_cells.contains(&bound));
4558    }
4559
4560    #[test]
4561    /// Checks reverse lookup of filter-argument dependents.
4562    fn filter_dependents_returns_the_cells_whose_filter_references_this_one() {
4563        let mut sheet = Sheet::new();
4564        let bound = sheet.add_cell(10_i32);
4565        let a = sheet.add_cell(5_i32);
4566        sheet
4567            .add_filter(
4568                a,
4569                Filter::from_fn_1(bound, |v: &i32, b: &i32| Ok((*v).min(*b))),
4570            )
4571            .unwrap();
4572        assert_eq!(sheet.filter_dependents(bound), &[a]);
4573    }
4574
4575    #[test]
4576    /// Checks empty reverse-filter membership for an unreferenced cell.
4577    fn filter_dependents_is_empty_for_a_cell_no_filter_references() {
4578        let mut sheet = Sheet::new();
4579        let bound = sheet.add_cell(10_i32);
4580        let a = sheet.add_cell(5_i32);
4581        sheet
4582            .add_filter(a, Filter::from_fn_0(|v: &i32| Ok((*v).clamp(0, 100))))
4583            .unwrap();
4584        assert!(sheet.filter_dependents(bound).is_empty());
4585    }
4586
4587    #[test]
4588    /// Checks empty reverse-filter membership for an unknown cell.
4589    fn filter_dependents_is_empty_for_an_invalid_cell() {
4590        let sheet = Sheet::new();
4591        assert!(sheet.filter_dependents(CellId::default()).is_empty());
4592    }
4593
4594    #[test]
4595    /// Checks complete reverse membership when several filters share an argument.
4596    fn filter_dependents_aggregates_multiple_dependents_of_the_same_argument() {
4597        let mut sheet = Sheet::new();
4598        let bound = sheet.add_cell(10_i32);
4599        let a = sheet.add_cell(5_i32);
4600        let b = sheet.add_cell(5_i32);
4601        sheet
4602            .add_filter(
4603                a,
4604                Filter::from_fn_1(bound, |v: &i32, bd: &i32| Ok((*v).min(*bd))),
4605            )
4606            .unwrap();
4607        sheet
4608            .add_filter(
4609                b,
4610                Filter::from_fn_1(bound, |v: &i32, bd: &i32| Ok((*v).min(*bd))),
4611            )
4612            .unwrap();
4613        let dependents = sheet.filter_dependents(bound);
4614        assert_eq!(dependents.len(), 2);
4615        assert!(dependents.contains(&a));
4616        assert!(dependents.contains(&b));
4617    }
4618
4619    #[test]
4620    /// Checks absent presentation metadata on an unfiltered cell.
4621    fn filter_kind_returns_none_for_a_cell_with_no_filter() {
4622        let mut sheet = Sheet::new();
4623        let a = sheet.add_cell(0_i32);
4624        assert!(sheet.filter_kind(a).is_none());
4625    }
4626
4627    #[test]
4628    /// Checks opaque metadata for an ordinary filter.
4629    fn filter_kind_returns_opaque_for_a_plain_filter() {
4630        let mut sheet = Sheet::new();
4631        let a = sheet.add_cell(0_i32);
4632        sheet
4633            .add_filter(a, Filter::from_fn_0(|x: &i32| Ok(*x)))
4634            .unwrap();
4635        assert!(matches!(sheet.filter_kind(a), Some(FilterKind::Opaque)));
4636    }
4637
4638    #[test]
4639    /// Checks range metadata for a range filter.
4640    fn filter_kind_returns_range_for_a_range_filter() {
4641        let mut sheet = Sheet::new();
4642        let a = sheet.add_cell(0_i32);
4643        let filter = Filter::range(
4644            TypeId::of::<i32>(),
4645            vec![],
4646            vec![],
4647            |value, _args| Ok(Box::new(*value.downcast_ref::<i32>().unwrap()) as Box<dyn Any>),
4648            |_args| {
4649                Some((
4650                    Box::new(0i32) as Box<dyn Any>,
4651                    Box::new(100i32) as Box<dyn Any>,
4652                ))
4653            },
4654        );
4655        sheet.add_filter(a, filter).unwrap();
4656        assert!(matches!(
4657            sheet.filter_kind(a),
4658            Some(FilterKind::Range { .. })
4659        ));
4660    }
4661
4662    #[test]
4663    /// Checks live range-bound values read from dynamic argument cells.
4664    fn filter_range_returns_live_bounds_from_argument_cells() {
4665        let mut sheet = Sheet::new();
4666        let a = sheet.add_cell(0_i32);
4667        let lo = sheet.add_cell(0_i32);
4668        let hi = sheet.add_cell(100_i32);
4669        let filter = Filter::range(
4670            TypeId::of::<i32>(),
4671            vec![lo, hi],
4672            vec![TypeId::of::<i32>(), TypeId::of::<i32>()],
4673            |value, args| {
4674                let v = *value.downcast_ref::<i32>().unwrap();
4675                let lo = *args[0].downcast_ref::<i32>().unwrap();
4676                let hi = *args[1].downcast_ref::<i32>().unwrap();
4677                Ok(Box::new(v.clamp(lo, hi)) as Box<dyn Any>)
4678            },
4679            |args| {
4680                Some((
4681                    Box::new(*args[0].downcast_ref::<i32>().unwrap()) as Box<dyn Any>,
4682                    Box::new(*args[1].downcast_ref::<i32>().unwrap()) as Box<dyn Any>,
4683                ))
4684            },
4685        );
4686        sheet.add_filter(a, filter).unwrap();
4687        assert_eq!(sheet.filter_range::<i32>(a), Some((0, 100)));
4688        sheet.write(hi, 10_i32).unwrap();
4689        assert_eq!(sheet.filter_range::<i32>(a), Some((0, 10)));
4690    }
4691
4692    #[test]
4693    /// Checks range introspection of a relationship-derived bound.
4694    fn filter_range_reflects_a_bound_derived_by_a_relationship_not_just_a_direct_write() {
4695        // `hi` isn't itself written — its value is derived from `hi_source` via a relationship —
4696        // exercising `filter_range`'s use of `effective()` (which sees a relationship's derived
4697        // override), not just `source`.
4698        let mut sheet = Sheet::new();
4699        let a = sheet.add_cell(0_i32);
4700        let lo = sheet.add_cell(0_i32);
4701        let hi = sheet.add_cell(100_i32);
4702        let hi_source = sheet.add_cell(100_i32);
4703        sheet
4704            .add_relationship(vec![Method::from_fn_1_1(hi_source, hi, |v: &i32| Ok(*v))])
4705            .unwrap();
4706        let filter = Filter::range(
4707            TypeId::of::<i32>(),
4708            vec![lo, hi],
4709            vec![TypeId::of::<i32>(), TypeId::of::<i32>()],
4710            |value, args| {
4711                let v = *value.downcast_ref::<i32>().unwrap();
4712                let lo = *args[0].downcast_ref::<i32>().unwrap();
4713                let hi = *args[1].downcast_ref::<i32>().unwrap();
4714                Ok(Box::new(v.clamp(lo, hi)) as Box<dyn Any>)
4715            },
4716            |args| {
4717                Some((
4718                    Box::new(*args[0].downcast_ref::<i32>().unwrap()) as Box<dyn Any>,
4719                    Box::new(*args[1].downcast_ref::<i32>().unwrap()) as Box<dyn Any>,
4720                ))
4721            },
4722        );
4723        sheet.add_filter(a, filter).unwrap();
4724        sheet.write(hi_source, 20_i32).unwrap();
4725        sheet.propagate().unwrap();
4726        assert_eq!(sheet.filter_range::<i32>(a), Some((0, 20)));
4727    }
4728
4729    #[test]
4730    /// Checks absence of range bounds for an opaque filter.
4731    fn filter_range_returns_none_for_an_opaque_filter() {
4732        let mut sheet = Sheet::new();
4733        let a = sheet.add_cell(0_i32);
4734        sheet
4735            .add_filter(a, Filter::from_fn_0(|x: &i32| Ok(*x)))
4736            .unwrap();
4737        assert!(sheet.filter_range::<i32>(a).is_none());
4738    }
4739
4740    #[test]
4741    /// Attaches each check independently and returns IDs in registration order.
4742    fn add_requirement_returns_distinct_ids_on_same_cell() {
4743        let mut sheet = Sheet::new();
4744        let a = sheet.add_cell(5_i32);
4745        let first = sheet
4746            .add_requirement(a, Requirement::from_fn_1(a, |x: &i32| Ok(*x > 0)))
4747            .unwrap();
4748        let result = sheet.add_requirement(a, Requirement::from_fn_1(a, |x: &i32| Ok(*x < 100)));
4749        let second = result.unwrap();
4750        assert_ne!(first, second);
4751        assert_eq!(sheet.cell_requirements(a), Some([first, second].as_slice()));
4752    }
4753
4754    #[test]
4755    /// Reports an ordinary cell's false requirement after propagation.
4756    fn add_requirement_defers_false_cell_requirement_until_propagation() {
4757        let mut sheet = Sheet::new();
4758        let a = sheet.add_cell(-5_i32);
4759        let requirement = sheet
4760            .add_requirement(a, Requirement::from_fn_1(a, |x: &i32| Ok(*x > 0)))
4761            .unwrap();
4762        sheet.propagate().unwrap();
4763        assert!(!sheet.cell_requirements_valid(a));
4764        assert_eq!(
4765            sheet.violated_requirements(a).collect::<Vec<_>>(),
4766            [requirement]
4767        );
4768    }
4769
4770    #[test]
4771    /// Reports a source cell's false requirement after propagation.
4772    fn add_requirement_defers_false_source_requirement_until_propagation() {
4773        let mut sheet = Sheet::new();
4774        let a = sheet.add_source(-5_i32);
4775        let requirement = sheet
4776            .add_requirement(a, Requirement::from_fn_1(a, |x: &i32| Ok(*x > 0)))
4777            .unwrap();
4778        sheet.propagate().unwrap();
4779        assert!(!sheet.cell_requirements_valid(a));
4780        assert_eq!(
4781            sheet.violated_requirements(a).collect::<Vec<_>>(),
4782            [requirement]
4783        );
4784    }
4785
4786    #[test]
4787    /// Propagates requirement-evaluation failure during propagation.
4788    fn add_requirement_defers_evaluation_error_until_propagation() {
4789        let mut sheet = Sheet::new();
4790        let a = sheet.add_cell(5_i32);
4791        sheet
4792            .add_requirement(
4793                a,
4794                Requirement::from_fn_1(a, |_: &i32| Err(anyhow::anyhow!("boom"))),
4795            )
4796            .unwrap();
4797        assert!(matches!(
4798            sheet.propagate(),
4799            Err(Error::MethodFailed { sites, .. }) if sites == [ErrorSite::Cell(a)]
4800        ));
4801    }
4802
4803    #[test]
4804    /// Checks lookup of the requirement attached to a cell.
4805    fn cell_has_the_requirement_it_was_given() {
4806        let mut sheet = Sheet::new();
4807        let a = sheet.add_cell(5_i32);
4808        let rid = sheet
4809            .add_requirement(a, Requirement::from_fn_1(a, |x: &i32| Ok(*x > 0)))
4810            .unwrap();
4811        assert_eq!(sheet.cells[a].requirements, vec![rid]);
4812    }
4813
4814    #[test]
4815    /// Checks that Out declaration returns its governed cell identity.
4816    fn add_out_returns_the_cell_id_directly() {
4817        let mut sheet = Sheet::new();
4818        let width = sheet.add_cell(4_i32);
4819        let height = sheet.add_cell(5_i32);
4820        let area = sheet.add_cell(0_i32);
4821        let cell = sheet
4822            .add_out(
4823                Method::from_fn_2_1([width, height], area, |w: &i32, h: &i32| Ok(w * h)),
4824                vec![],
4825            )
4826            .unwrap();
4827        assert_eq!(cell, area);
4828        assert_eq!(sheet.cell_kind(area), Some(CellKind::Out));
4829    }
4830
4831    #[test]
4832    /// Checks downstream use of a fixed Out cell as an ordinary input.
4833    fn out_cell_is_referenceable_as_another_relationships_input() {
4834        let mut sheet = Sheet::new();
4835        let width = sheet.add_cell(4_i32);
4836        let height = sheet.add_cell(5_i32);
4837        let area = sheet.add_cell(0_i32);
4838        let doubled = sheet.add_cell(0_i32);
4839        sheet
4840            .add_out(
4841                Method::from_fn_2_1([width, height], area, |w: &i32, h: &i32| Ok(w * h)),
4842                vec![],
4843            )
4844            .unwrap();
4845        let result =
4846            sheet.add_relationship(vec![Method::from_fn_1_1(
4847                area,
4848                doubled,
4849                |a: &i32| Ok(a * 2),
4850            )]);
4851        assert!(result.is_ok());
4852    }
4853
4854    #[test]
4855    /// Checks use of a fixed Out cell as a conditional subject.
4856    fn out_cell_is_referenceable_as_a_conditional_match_subject() {
4857        let mut sheet = Sheet::new();
4858        let flag = sheet.add_cell(0_i32);
4859        let derived_flag = sheet.add_cell(0_i32);
4860        sheet
4861            .add_out(
4862                Method::from_fn_1_1(flag, derived_flag, |f: &i32| Ok(*f)),
4863                vec![],
4864            )
4865            .unwrap();
4866        let result = sheet.add_conditional(
4867            MatchExpr::cell(derived_flag),
4868            Vec::<(Vec<i32>, Vec<RelationshipId>)>::new(),
4869            vec![],
4870        );
4871        assert!(result.is_ok());
4872    }
4873
4874    #[test]
4875    /// Checks rejection of a second fixed writer for an Out cell.
4876    fn add_out_returns_invalid_cell_kind_for_a_second_writer() {
4877        let mut sheet = Sheet::new();
4878        let width = sheet.add_cell(4_i32);
4879        let height = sheet.add_cell(5_i32);
4880        let area = sheet.add_cell(0_i32);
4881        sheet
4882            .add_out(Method::from_fn_1_1(width, area, |w: &i32| Ok(*w)), vec![])
4883            .unwrap();
4884        let result = sheet.add_out(Method::from_fn_1_1(height, area, |h: &i32| Ok(*h)), vec![]);
4885        assert!(matches!(result, Err(Error::InvalidCellKind { .. })));
4886    }
4887
4888    #[test]
4889    /// Checks legal Out promotion of a previously input-only cell.
4890    fn add_out_succeeds_when_target_cell_was_previously_used_only_as_an_input() {
4891        let mut sheet = Sheet::new();
4892        let a = sheet.add_cell(1_i32);
4893        let b = sheet.add_cell(2_i32);
4894        sheet
4895            .add_relationship(vec![Method::from_fn_1_1(a, b, |x: &i32| Ok(*x))])
4896            .unwrap();
4897        let c = sheet.add_cell(0_i32);
4898        sheet
4899            .add_out(
4900                Method::from_fn_1_1(c, a, |x: &i32| {
4901                    x.checked_mul(2).ok_or_else(|| anyhow::anyhow!("overflow"))
4902                }),
4903                vec![],
4904            )
4905            .unwrap();
4906        assert_eq!(sheet.cell_kind(a), Some(CellKind::Out));
4907        sheet.write(c, 9_i32).unwrap();
4908        sheet.propagate().unwrap();
4909        assert_eq!(*sheet.read::<i32>(a).unwrap(), 18);
4910        assert_eq!(*sheet.read::<i32>(b).unwrap(), 18);
4911    }
4912
4913    #[test]
4914    /// Checks deferred requirement evaluation on a newly declared Out cell.
4915    fn add_out_with_a_requirement_that_would_fail_still_succeeds_and_propagate_reports_it() {
4916        let mut sheet = Sheet::new();
4917        let width = sheet.add_cell(4_i32);
4918        let area = sheet.add_cell(0_i32);
4919        let area_cell = sheet
4920            .add_out(
4921                Method::from_fn_1_1(width, area, |w: &i32| Ok(*w)),
4922                vec![Requirement::from_fn_1(area, |a: &i32| Ok(*a > 100))],
4923            )
4924            .unwrap();
4925        sheet.propagate().unwrap();
4926        assert!(!sheet.cell_requirements_valid(area_cell));
4927        assert_eq!(sheet.violated_requirements(area_cell).count(), 1);
4928    }
4929
4930    #[test]
4931    /// Checks exclusion of ordinary cells from Out enumeration.
4932    fn out_cells_iterates_only_out_kind_cells() {
4933        let mut sheet = Sheet::new();
4934        let a = sheet.add_cell(1_i32);
4935        let b = sheet.add_cell(0_i32);
4936        let out_id = sheet
4937            .add_out(Method::from_fn_1_1(a, b, |x: &i32| Ok(*x)), vec![])
4938            .unwrap();
4939        let ids: Vec<CellId> = sheet.out_cells().collect();
4940        assert_eq!(ids, vec![out_id]);
4941    }
4942
4943    #[test]
4944    /// Checks legal diagnostic-filter attachment to a fixed Out cell.
4945    fn add_filter_succeeds_on_a_real_out_kind_cell() {
4946        let mut sheet = Sheet::new();
4947        let width = sheet.add_cell(4_i32);
4948        let area = sheet.add_cell(0_i32);
4949        let out_cell = sheet
4950            .add_out(Method::from_fn_1_1(width, area, |w: &i32| Ok(*w)), vec![])
4951            .unwrap();
4952        let result = sheet.add_filter(out_cell, Filter::from_fn_0(|x: &i32| Ok((*x).clamp(0, 10))));
4953        assert!(result.is_ok());
4954    }
4955
4956    #[test]
4957    /// Checks relevance contributors for a requirement on an ordinary cell.
4958    fn requirement_relevant_cells_covers_a_plain_cells_requirement_too() {
4959        let mut sheet = Sheet::new();
4960        let a = sheet.add_cell(5_i32);
4961        sheet
4962            .add_requirement(a, Requirement::from_fn_1(a, |x: &i32| Ok(*x > 0)))
4963            .unwrap();
4964        sheet.propagate().unwrap();
4965        assert!(sheet.requirement_relevant_cells().contains(&a));
4966    }
4967
4968    #[test]
4969    /// Checks violation contributors for a failed requirement on an ordinary cell.
4970    fn requirement_violation_cells_covers_a_plain_cells_violation_too() {
4971        let mut sheet = Sheet::new();
4972        let a = sheet.add_cell(200_i32);
4973        sheet
4974            .add_requirement(a, Requirement::from_fn_1(a, |x: &i32| Ok(*x > 100)))
4975            .unwrap();
4976        sheet.write(a, 5_i32).unwrap();
4977        sheet.propagate().unwrap();
4978        assert!(sheet.requirement_violation_cells().contains(&a));
4979    }
4980}