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