Skip to main content

relate_executor/
frontier_decline.rs

1//! The frontier rung's decline vocabulary — the typed reasons the PROFILE
2//! record names when a clause's frontier rung did not serve it. Lives at
3//! the crate root, below the matcher that constructs the plan-time half
4//! and the rider wiring that records both halves: the plan-time gates' vocabulary
5//! ([`FrontierDecline`], ADR-0478), the run-time declines' vocabulary
6//! ([`FrontierRunDecline`], ADR-0516/ADR-0521), and the one sum the
7//! record carries ([`FrontierDeclineReason`]).
8
9/// Declares one decline vocabulary from a single table: the enum, its
10/// declaration-ordered `ALL` (the parity pin's iteration source against
11/// the wire table `plan_keys::DECLINE_REASONS`), and its stable wire
12/// name `as_str` (the `StartReason::as_str` pattern). Each variant
13/// carries its wire name beside its docs, so the three cannot drift.
14macro_rules! decline_vocabulary {
15    (
16        $(#[$enum_meta:meta])*
17        $vis:vis enum $name:ident {
18            $( $(#[$meta:meta])* $variant:ident => $wire:path, )+
19        }
20    ) => {
21        $(#[$enum_meta])*
22        $vis enum $name {
23            $( $(#[$meta])* $variant, )+
24        }
25
26        impl $name {
27            /// Every decline of this vocabulary, in declaration order —
28            /// the parity pin's iteration source against the wire table
29            /// (`plan_keys::DECLINE_REASONS`).
30            pub const ALL: [$name; [$($wire),+].len()] = [$($name::$variant),+];
31
32            /// The decline's stable wire name: the vocabulary the plan
33            /// args and the renderers spell, read from its single source
34            /// (`plan_keys`'s `DECLINE_*` constants, which the wire table
35            /// derives from too).
36            pub fn as_str(self) -> &'static str {
37                match self {
38                    $( $name::$variant => $wire, )+
39                }
40            }
41        }
42    };
43}
44
45decline_vocabulary! {
46    /// Every plan-time gate's decline, typed so a test or plan dump names the
47    /// gate that kept the DFS. The decline is always safe: the per-row DFS
48    /// answers identically. Every gate decides before a single walk — the
49    /// rung's run-time declines are their own type ([`FrontierRunDecline`]:
50    /// the re-arrival budget and the table ceiling). The PROFILE record
51    /// carries either one as a [`FrontierDeclineReason`].
52    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
53    pub enum FrontierDecline {
54        /// The clause does not carry exactly one pattern: the frontier is a
55        /// single-pattern, single-quantifier family (a UNION's arms are
56        /// separate clauses, each decided on its own — the non-quantified arm
57        /// needs no kernel at all).
58        MultiplePatterns => relate_model::wire::plan_keys::DECLINE_MULTIPLE_PATTERNS,
59        /// The entering row binds anything but the pattern's seed-side
60        /// variable: a prebound group-list pin (the legacy exact-trail rule),
61        /// a prebound target or path variable, or a mid-statement clause's
62        /// outer bindings — per-row semantics the single-seed frontier does
63        /// not reproduce.
64        CarryingRow => relate_model::wire::plan_keys::DECLINE_CARRYING_ROW,
65        /// The mode is outside the family: an explicit TRAIL/ACYCLIC/SIMPLE
66        /// path mode outside the capped consumer (the capped emission's
67        /// per-witness cycle checks serve exactly that consumer —
68        /// `frontier_emit`; full enumeration and distinct-endpoint answers
69        /// stay per-path under these modes), any trail-enforcing mode under
70        /// the REPEATABLE pool (rel reuse is that pool's semantics), or an
71        /// unbounded quantifier under the WALK
72        /// pool — REPEATABLE ELEMENTS keeps its authored
73        /// `UnsafeRepeatableElements` rejection (ADR-0478 §5), and the
74        /// bounded-WALK answer shape is bounded by definition.
75        Mode => relate_model::wire::plan_keys::DECLINE_MODE,
76        /// A nested quantifier inside the quantified spine — a var-length
77        /// rel or a quantified group among its inner elements. The spine
78        /// then unrolls (variable round length) or accumulates
79        /// list-of-list groups, and the emission's fixed-round
80        /// reconstruction (`frontier_emit`) cannot bind those rows; the DFS
81        /// keeps the shape, answers identical. Parser-unreachable (the
82        /// front end's `NestedQuantification` rule rejects both spellings):
83        /// the gate is the defensive bound for hand-built IR.
84        NestedSpine => relate_model::wire::plan_keys::DECLINE_NESTED_SPINE,
85        /// A MATCH-WHERE allReduce the inliner runs over one of this
86        /// quantification's groups — ADR-0478 §2's hard decline: the
87        /// inliner's per-branch prefix semantics cannot survive pair dedup
88        /// (one (node, state) pair stands for many prefixes with different
89        /// accumulator values), so that shape keeps the DFS with its
90        /// inliner.
91        AllReduceGroup => relate_model::wire::plan_keys::DECLINE_ALL_REDUCE_GROUP,
92        /// A repeated element variable pins a binding the pair-dedup cannot
93        /// reconcile: the target (or an interior node) repeating another
94        /// node's variable, a rel variable repeated across hops or colliding
95        /// with a node name — the walker's pre-bound reconciliation
96        /// semantics.
97        PinnedBinding => relate_model::wire::plan_keys::DECLINE_PINNED_BINDING,
98        /// A MATCH-WHERE conjunct outside the closed predicate vocabulary on
99        /// the boundary nodes: it does not decode (a function over the row,
100        /// `OR`, a nondeterministic bound), it names a group list, the path
101        /// variable, a rel, an interior or an outer variable, or it is a
102        /// second predicate on one boundary variable. The one exception is
103        /// `<>` between the two boundary variables, admitted for the
104        /// distinct-endpoint consumer alone (`BoundaryPair`).
105        Conjunct => relate_model::wire::plan_keys::DECLINE_CONJUNCT,
106        /// The NFA compiler declined the shape — its declines are this arm's
107        /// declines: a second top-level quantified element, a subpath
108        /// variable, a pattern WHERE or a selector, rel-predicate inner
109        /// hops, admission-bearing interior nodes (the auto rung; the
110        /// forced rung compiles them as guards), the 64-state ceiling, a
111        /// nested unbounded quantifier, broken alternation, an uninterned
112        /// type name, overflowing bounds.
113        NfaShape => relate_model::wire::plan_keys::DECLINE_NFA_SHAPE,
114        /// A quantified group whose `WHERE` references its own pattern
115        /// variables (the fraud f03 shape) — the forced rung compiles it
116        /// (the predicate rides the round-closing transition, each
117        /// referenced variable read at its last binding), but no consumer
118        /// proof covers serving a predicate-guarded run: the pair-dedup
119        /// answers these shapes approximately, so every consumer declines
120        /// and the DFS answers exactly.
121        GuardedGroup => relate_model::wire::plan_keys::DECLINE_GUARDED_GROUP,
122        /// The consumer needs every row, not a pair-shaped answer: no cap and
123        /// no distinct/aggregate fold — full enumeration (two trails to one
124        /// node are two answers), a grouped or filtered suffix, a suffix that
125        /// is not a RETURN/WITH, or a `LIMIT 0`/overflowing cap the cap rider
126        /// itself declines.
127        FullEnumeration => relate_model::wire::plan_keys::DECLINE_FULL_ENUMERATION,
128        /// `ORDER BY` with `LIMIT`: ordered truncation needs the full
129        /// candidate set to sort (ADR-0478 §2 — ordered caps keep the DFS,
130        /// exactly as they keep full enumeration in ADR-0475).
131        OrderedCap => relate_model::wire::plan_keys::DECLINE_ORDERED_CAP,
132        /// The answer counts or folds the path multiset, not the endpoint
133        /// set: `count(p)`, `count(*)`, a non-DISTINCT `count`/`collect`, or
134        /// a multiplicity-sensitive fold (`sum`, `avg`, …) — path counts are
135        /// exponential by nature; the DFS keeps them on this rung (the one
136        /// path count the family serves, the WALK pool's plain `count`, is
137        /// the walk-count fold's — `frontier_count`, ADR-0523).
138        PathCount => relate_model::wire::plan_keys::DECLINE_PATH_COUNT,
139        /// A non-capped consumer consumes the path variable or a group list —
140        /// only the ≤ `want` reconstructed witnesses of the capped shape
141        /// carry those bindings, so a distinct/aggregate answer over them
142        /// would read bindings the frontier never produced.
143        PathConsumer => relate_model::wire::plan_keys::DECLINE_PATH_CONSUMER,
144        /// The cost gate: a bounded recursion whose estimated trails cost the
145        /// DFS less than the frontier's pairs and probes (or whose hops the
146        /// statistics cannot price) — the DFS is cheaper (no reconstruction
147        /// pass, the existing row plumbing) and keeps the clause.
148        Cost => relate_model::wire::plan_keys::DECLINE_COST,
149    }
150}
151
152decline_vocabulary! {
153    /// The frontier rung's run-time declines (ADR-0516): the reasons a rung
154    /// that engaged and ran still falls through, typed so the PROFILE record
155    /// names the one that kept the DFS. The plan-time gates' own
156    /// vocabulary ([`FrontierDecline`]) is the other half of the record's
157    /// [`FrontierDeclineReason`] — every one of those decides before a
158    /// single walk. The rider wiring records it and the metric record
159    /// carries it. Two today: the re-arrival budget's exhaustion (ADR-0516)
160    /// and the sparse tables' allocation ceiling (ADR-0521); a later
161    /// run-time decline adds its variant (and its wire name) here.
162    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
163    pub enum FrontierRunDecline {
164        /// The re-arrival rule's shared work budget cut a search — the
165        /// endpoint set is unproven, so the run's buffered rows are
166        /// discarded and the clause falls through to the next rung
167        /// unchanged (the DFS answers these shapes exactly). Constructed on
168        /// the production decline path — the run's outcome carries it
169        /// (`frontier::RunOutcome::Declined`) and the rider wiring records
170        /// it for the PROFILE record.
171        RearrivalBudget => relate_model::wire::plan_keys::DECLINE_REARRIVAL_BUDGET,
172        /// The run's sparse tables — sized by the (node, state) pairs it
173        /// touched, never by the store's node-id span — plus the re-arrival
174        /// rule's buffers crossed the allocation ceiling
175        /// (`FRONTIER_TABLE_BUDGET`, ADR-0521) at a level boundary. A
176        /// run-time decline like [`Self::RearrivalBudget`] — the rung ran, so
177        /// its counters stay recorded beside the reason — never a compile
178        /// gate: the run's buffered rows are discarded and the DFS, with its
179        /// own caps, answers the clause.
180        TableBudget => relate_model::wire::plan_keys::DECLINE_TABLE_BUDGET,
181    }
182}
183
184/// Why a clause's frontier rung did not serve it, as the PROFILE record
185/// carries it (ADR-0516, extended): either a plan-time gate kept the
186/// clause off the rung before a single walk ([`FrontierDecline`]), or the
187/// rung engaged, ran, and fell through ([`FrontierRunDecline`], its
188/// counters recorded beside). One typed sum, so the record's one field
189/// names the first reason whichever half decided; the wire spells the
190/// same names (`plan_keys::DECLINE_REASONS`).
191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
192pub enum FrontierDeclineReason {
193    /// A plan-time gate declined: the rung never ran (zero counters).
194    Plan(FrontierDecline),
195    /// The rung ran and fell through: its counters stay recorded.
196    Run(FrontierRunDecline),
197}
198
199impl FrontierDeclineReason {
200    /// The reason's stable wire name — the inner decline's own spelling,
201    /// never a second table.
202    pub fn as_str(self) -> &'static str {
203        match self {
204            FrontierDeclineReason::Plan(decline) => decline.as_str(),
205            FrontierDeclineReason::Run(decline) => decline.as_str(),
206        }
207    }
208}
209
210impl From<FrontierDecline> for FrontierDeclineReason {
211    fn from(decline: FrontierDecline) -> Self {
212        FrontierDeclineReason::Plan(decline)
213    }
214}
215
216impl From<FrontierRunDecline> for FrontierDeclineReason {
217    fn from(decline: FrontierRunDecline) -> Self {
218        FrontierDeclineReason::Run(decline)
219    }
220}