Skip to main content

ff_core/
capability.rs

1//! RFC-018 Stage A — backend capability discovery surface.
2//!
3//! Consumers of `Arc<dyn EngineBackend>` (and HTTP clients hitting
4//! `ff-server`) historically had no typed way to ask "what can this
5//! backend actually do?" before dispatching — they discovered
6//! capability gaps empirically, by trying a trait method and catching
7//! [`crate::engine_error::EngineError::Unavailable`]. This module
8//! adds a first-class discovery primitive: a [`Supports`] flat-bool
9//! struct, a [`BackendIdentity`] tuple, and a [`Capabilities`]
10//! container that [`crate::engine_backend::EngineBackend`] exposes
11//! via `capabilities()`.
12//!
13//! Stage A (this module) is additive: the trait method has a default
14//! impl that returns a `Capabilities` tagged `family = "unknown"` with
15//! every `supports.*` bool `false`, so out-of-tree backends keep
16//! compiling. Concrete in-tree backends (`ValkeyBackend`,
17//! `PostgresBackend`) override to report real caps.
18//!
19//! **Shape history.** v0.9 shipped a `BTreeMap<Capability,
20//! CapabilityStatus>` map; v0.10 reshaped to the flat [`Supports`]
21//! struct below per cairn's original #277 ask (flat named-field
22//! dot-access, no enum + no map lookup). `Partial`-status nuance
23//! (e.g. non-durable cursor on Valkey `subscribe_completion`) now
24//! lives in rustdoc on the trait method and
25//! `docs/POSTGRES_PARITY_MATRIX.md`; the flat bool answers "is this
26//! callable at all."
27//!
28//! Stages B + C (follow-up PRs) derive `docs/POSTGRES_PARITY_MATRIX.md`
29//! from the runtime value and expose `GET /v1/capabilities` on
30//! `ff-server`.
31//!
32//! See `rfcs/RFC-018-backend-capability-discovery.md` for the full
33//! design, the four owner-adjudicated open questions, and the
34//! Alternatives-considered record.
35
36/// Per-capability boolean support surface. Flat named-field shape so
37/// consumers can dot-access (e.g. `caps.supports.cancel_execution`)
38/// instead of map lookup. `#[non_exhaustive]` protects future
39/// additions from source-breaking consumers; construct via
40/// [`Supports::none`] or by returning one from
41/// [`crate::engine_backend::EngineBackend::capabilities`].
42///
43/// # Grouping policy
44///
45/// One bool per operator-visible HTTP surface; admin-only surfaces
46/// with many sibling methods roll up to a single bool (e.g.
47/// [`Self::budget_admin`] covers `create_budget` / `report_usage` /
48/// `reset_budget` / `get_budget_status` / `report_usage_admin`;
49/// [`Self::quota_admin`] covers `create_quota_policy`). Cairn's
50/// operator UI grey-renders at the group level; fine-grained
51/// pre-dispatch checks still use
52/// [`crate::engine_error::EngineError::Unavailable`].
53///
54/// # Field order
55///
56/// Per cairn #277 "in the same order as the parity matrix so cairn
57/// can consume by copy-paste." Keep in sync with
58/// `docs/POSTGRES_PARITY_MATRIX.md`.
59#[non_exhaustive]
60#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
61pub struct Supports {
62    // ── Execution operator control ──
63    /// `cancel_execution`.
64    pub cancel_execution: bool,
65    /// `change_priority`.
66    pub change_priority: bool,
67    /// `replay_execution`.
68    pub replay_execution: bool,
69    /// `revoke_lease`.
70    pub revoke_lease: bool,
71
72    // ── Execution reads ──
73    /// `read_execution_state`.
74    pub read_execution_state: bool,
75    /// `read_execution_info`.
76    pub read_execution_info: bool,
77    /// `get_execution_result`.
78    pub get_execution_result: bool,
79
80    // ── Budget + quota (group-level, rolls up siblings) ──
81    /// Covers `create_budget` + `report_usage` + `reset_budget` +
82    /// `get_budget_status` + `report_usage_admin`.
83    pub budget_admin: bool,
84    /// Covers `create_quota_policy`.
85    pub quota_admin: bool,
86
87    // ── Waitpoint admin ──
88    /// `rotate_waitpoint_hmac_secret_all`.
89    pub rotate_waitpoint_hmac_secret_all: bool,
90    /// `seed_waitpoint_hmac_secret` (#280).
91    pub seed_waitpoint_hmac_secret: bool,
92    /// `list_pending_waitpoints`.
93    pub list_pending_waitpoints: bool,
94
95    // ── Flow control ──
96    /// `cancel_flow_header`.
97    pub cancel_flow_header: bool,
98    /// `cancel_flow` with `CancelFlowWait::WaitTimeout(..)`.
99    pub cancel_flow_wait_timeout: bool,
100    /// `cancel_flow` with `CancelFlowWait::WaitIndefinite`.
101    pub cancel_flow_wait_indefinite: bool,
102    /// `ack_cancel_member`.
103    pub ack_cancel_member: bool,
104
105    // ── Scheduler ──
106    /// `claim_for_worker` (requires a wired scheduler on Valkey;
107    /// Postgres-native on Postgres).
108    pub claim_for_worker: bool,
109
110    // ── Reclaim (RFC-024) ──
111    /// `issue_reclaim_grant` + `reclaim_execution` (rolled up — both
112    /// land together on every in-tree backend per RFC-024 §3.6, so
113    /// one bool covers the consumer-visible reclaim surface).
114    /// `false` on out-of-tree backends via `Supports::none()`; `true`
115    /// on Valkey (v0.11.0 per RFC-024 PR-F), Postgres (PR-D), SQLite
116    /// (PR-E).
117    pub issue_reclaim_grant: bool,
118
119    // ── Boot ──
120    /// `prepare` does non-trivial work (e.g. Valkey `FUNCTION LOAD`).
121    /// Postgres reports `false` — `prepare` returns `NoOp` there.
122    pub prepare: bool,
123
124    // ── Stream subscriptions (RFC-019) ──
125    /// `subscribe_lease_history`.
126    pub subscribe_lease_history: bool,
127    /// `subscribe_completion`. On Valkey this is pubsub-backed
128    /// (non-durable cursor, at-most-once over the live subscription
129    /// window); Postgres is durable via outbox + cursor. Both report
130    /// `true`; see the trait method rustdoc for the non-durable-cursor
131    /// caveat and `docs/POSTGRES_PARITY_MATRIX.md` for the per-backend
132    /// semantic.
133    pub subscribe_completion: bool,
134    /// `subscribe_signal_delivery`.
135    pub subscribe_signal_delivery: bool,
136    /// `subscribe_instance_tags`. Deferred per #311 (cairn's `instance_tag_backfill`
137    /// pattern is served by `list_executions` + `ScannerFilter::with_instance_tag(..)`);
138    /// reported `false` on both backends today.
139    pub subscribe_instance_tags: bool,
140
141    // ── Streaming (RFC-015) ──
142    /// `read_summary` + durable-summary frames.
143    pub stream_durable_summary: bool,
144    /// `tail_stream` (best-effort live tail).
145    pub stream_best_effort_live: bool,
146    // Add new fields here, preserving parity-matrix order.
147}
148
149impl Supports {
150    /// Construct a [`Supports`] with every field `false`. Alias for
151    /// [`Self::none`] — provided so external consumers have a
152    /// conventional `new` constructor against this `#[non_exhaustive]`
153    /// struct. Equivalent to [`Self::default`].
154    pub const fn new() -> Self {
155        Self::none()
156    }
157
158    /// Construct a `Supports` with every field `false`. Useful as a
159    /// starting point when assembling a backend-specific capability
160    /// snapshot. Consumers should never see this directly —
161    /// `capabilities()` on a real backend always returns a populated
162    /// instance.
163    pub const fn none() -> Self {
164        Self {
165            cancel_execution: false,
166            change_priority: false,
167            replay_execution: false,
168            revoke_lease: false,
169            read_execution_state: false,
170            read_execution_info: false,
171            get_execution_result: false,
172            budget_admin: false,
173            quota_admin: false,
174            rotate_waitpoint_hmac_secret_all: false,
175            seed_waitpoint_hmac_secret: false,
176            list_pending_waitpoints: false,
177            cancel_flow_header: false,
178            cancel_flow_wait_timeout: false,
179            cancel_flow_wait_indefinite: false,
180            ack_cancel_member: false,
181            claim_for_worker: false,
182            issue_reclaim_grant: false,
183            prepare: false,
184            subscribe_lease_history: false,
185            subscribe_completion: false,
186            subscribe_signal_delivery: false,
187            subscribe_instance_tags: false,
188            stream_durable_summary: false,
189            stream_best_effort_live: false,
190        }
191    }
192}
193
194/// Backend crate version. Kept as a struct (not a semver string) per
195/// RFC-018 §9 Q2: consumers can write
196/// `if backend.capabilities().identity.version >= Version::new(0, 10, 0) { .. }`
197/// without pulling a semver-parsing dep.
198#[non_exhaustive]
199#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
200pub struct Version {
201    /// Major version number.
202    pub major: u32,
203    /// Minor version number.
204    pub minor: u32,
205    /// Patch version number.
206    pub patch: u32,
207}
208
209impl Version {
210    /// Const constructor so concrete backends can declare a `const`
211    /// [`BackendIdentity`] without a function-call overhead in
212    /// `capabilities()`.
213    pub const fn new(major: u32, minor: u32, patch: u32) -> Self {
214        Self {
215            major,
216            minor,
217            patch,
218        }
219    }
220}
221
222/// Minimal-identity triple for a backend. Consumers that only need
223/// the family label + version (e.g. for metrics dimensioning) read
224/// this rather than the full [`Capabilities`].
225///
226/// `#[non_exhaustive]`: future stages may add fields (e.g. a
227/// backend-assigned `instance_id` or a `deployment_topology`
228/// hint); construct via [`Self::new`] or by returning one from
229/// [`crate::engine_backend::EngineBackend::capabilities`].
230#[non_exhaustive]
231#[derive(Clone, Copy, Debug, Eq, PartialEq)]
232pub struct BackendIdentity {
233    /// Stable backend family name. `"valkey"`, `"postgres"`, or a
234    /// concrete string set by an out-of-tree backend. `"unknown"`
235    /// is the pre-RFC-018 default.
236    pub family: &'static str,
237    /// Backend crate version at build time.
238    pub version: Version,
239    /// RFC-017 migration stage this backend reports itself certified
240    /// at. One of `"A"`, `"B"`, `"C"`, `"D"`, `"E"`, `"E-shipped"`,
241    /// or `"unknown"` for backends that predate the RFC-017 staging.
242    pub rfc017_stage: &'static str,
243}
244
245impl BackendIdentity {
246    /// Direct-field constructor. Prefer this over struct-literal
247    /// syntax in consumer code: `#[non_exhaustive]` forbids literal
248    /// construction from outside the defining crate.
249    pub const fn new(
250        family: &'static str,
251        version: Version,
252        rfc017_stage: &'static str,
253    ) -> Self {
254        Self {
255            family,
256            version,
257            rfc017_stage,
258        }
259    }
260}
261
262/// Full capability snapshot for a backend: its [`BackendIdentity`]
263/// plus a flat [`Supports`] surface of per-method bools.
264///
265/// Consumers typically read `caps.supports.<field>` to gate a UI
266/// surface or choose between two code paths before dispatching; the
267/// [`Self::identity`] side exists for metrics dimensioning + UI
268/// labelling.
269#[non_exhaustive]
270#[derive(Clone, Copy, Debug, Eq, PartialEq)]
271pub struct Capabilities {
272    /// Backend identity tuple this snapshot was assembled for.
273    pub identity: BackendIdentity,
274    /// Per-capability support bools.
275    pub supports: Supports,
276}
277
278impl Capabilities {
279    /// Construct a `Capabilities` value from an identity + a populated
280    /// [`Supports`]. Backends typically build one in `capabilities()`
281    /// without going through a constructor; this exists for
282    /// out-of-tree backends that prefer the explicit call.
283    pub const fn new(identity: BackendIdentity, supports: Supports) -> Self {
284        Self { identity, supports }
285    }
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291
292    #[test]
293    fn version_new_is_const_and_ordered() {
294        const V: Version = Version::new(0, 9, 0);
295        assert_eq!(V.major, 0);
296        assert_eq!(V.minor, 9);
297        assert_eq!(V.patch, 0);
298        assert!(Version::new(0, 10, 0) > V);
299        assert!(Version::new(0, 9, 1) > V);
300        assert!(Version::new(1, 0, 0) > V);
301    }
302
303    #[test]
304    fn backend_identity_new_populates_fields() {
305        let id = BackendIdentity::new("valkey", Version::new(0, 9, 0), "E-shipped");
306        assert_eq!(id.family, "valkey");
307        assert_eq!(id.version, Version::new(0, 9, 0));
308        assert_eq!(id.rfc017_stage, "E-shipped");
309    }
310
311    #[test]
312    fn supports_none_is_all_false() {
313        let s = Supports::none();
314        // Spot-check a handful across the grouping policy; `Default`
315        // covers the exhaustive guarantee via `assert_eq!` below.
316        assert!(!s.cancel_execution);
317        assert!(!s.budget_admin);
318        assert!(!s.quota_admin);
319        assert!(!s.subscribe_instance_tags);
320        assert!(!s.stream_durable_summary);
321        // `Default::default()` must match `none()` so consumers that
322        // lean on `..Default::default()` get the same zero state.
323        assert_eq!(s, Supports::default());
324    }
325
326    #[test]
327    fn capabilities_new_wires_identity_and_supports() {
328        let mut s = Supports::none();
329        s.cancel_execution = true;
330        let caps = Capabilities::new(
331            BackendIdentity::new("valkey", Version::new(0, 10, 0), "E-shipped"),
332            s,
333        );
334        assert_eq!(caps.identity.family, "valkey");
335        assert!(caps.supports.cancel_execution);
336        assert!(!caps.supports.change_priority);
337    }
338}