ppoppo_schema_constrained/lib.rs
1//! **NOT a stable public API.** Engine-tier binding primitive — published to
2//! crates.io only because the SDK closure requires it on the registry; 3rd
3//! parties never name this crate. They meet the value-sets it binds through an
4//! SDK product facade or a wire contract, never here.
5//!
6//! # Schema-Constrained Value-Sets (the enum ↔ `CHECK` anchor)
7//!
8//! A *schema-constrained* enum is a domain value-set whose members are also
9//! enumerated by a PostgreSQL `CHECK (col IN (…))` constraint. The enum and the
10//! constraint are two reifications of one fact ("the legal values of this
11//! column"); left unbound they drift independently — a migration widens the
12//! `CHECK`, or a variant is added, and the other side silently goes stale.
13//!
14//! This crate is the single seam that binds them. The same drift class exists
15//! on both sides of the monorepo (PAS `scaccounts`, PCS `scchat`) and neither
16//! core may depend on the other, so the binding primitive is hoisted out of
17//! both — a pure, dependency-free trait + macro (`std::BTreeSet` only), which
18//! both cores (that ban IO/transport crates) can depend on.
19//!
20//! ## Why engine tier and not `crates/shared/`
21//!
22//! It sat in `crates/shared/` (`publish = false`) until `RFC_202607252223`
23//! T-03, which is when the placement was first *tested* rather than assumed:
24//! `ppoppo-identity` needs to enroll its own `EntityType`, and `engine →
25//! shared` is forbidden by the crate lattice (`xtask::policy::rules::taxonomy`)
26//! — so the enrollment was unreachable, and the vocabulary had to keep a
27//! second PAS-local enum alive just to carry it.
28//!
29//! The fix was to notice that the folder was wrong, not the lattice. Engine
30//! tier means *published substrate that no 3rd party names* — a dependency-free
31//! trait + macro consumed by two service cores and one vocabulary crate is
32//! exactly that. The move corrected a misfile that predates the tier; it did
33//! not trade a principle for convenience.
34//!
35//! ## The anchor triple (per `STS_SSOT_GOVERNANCE`)
36//!
37//! - **Owner**: the domain enum in `accounts-core` / `accounts-api` /
38//! `chat-core` (the closest reified form of the value-set decision).
39//! - **Anchor**: domain-specific — these are tuned domain vocabularies with no
40//! external standard, so *this crate doc-comment is the anchor of record*
41//! (governance §4). (Formerly PAS
42//! `ADR_202605242324_schema-constrained-value-sets.md`, folded into
43//! `accounts-core` on its retirement, then hoisted here when PCS adopted the
44//! same gate.)
45//! - **Verification**: [`bindings`](SchemaConstrained::bindings) feeds each
46//! service's `schema_check_drift.rs` DB test
47//! (`accounts-api/tests/` for `scaccounts`, `chat-api/tests/` for `scchat`),
48//! which reads each `CHECK` from the *materialized* schema
49//! (`pg_get_constraintdef`) and asserts set-equality with `ALL`. The
50//! compile-time half lives in the [`impl_schema_constrained!`] macro: it
51//! emits an exhaustive `match`, so adding a variant without listing it fails
52//! to build.
53//!
54//! ## Why a DB test and not a file parse
55//!
56//! The value-sets evolve through `ALTER … DROP/ADD CONSTRAINT` migrations (e.g.
57//! `lifecycle_state` gained `tombstoned`; `oauth_audit_events.event_type`
58//! gained `otp_issue`/`otp_verify`). The authoritative set is therefore the
59//! *result of applying every migration*, which only the database knows —
60//! parsing the baseline `.sql` would report phantom drift. Asking Postgres via
61//! `pg_get_constraintdef` is the only correct anchor (and avoids the brittle
62//! bespoke-parser ops-tax rejected in `STS_RATE_LIMITS_PPOPPO` §Anchor
63//! "Rationale" option A).
64//!
65//! ## Two more rejected alternatives
66//!
67//! - **`#[sqlx::Type]` alone.** Binds the column *type* (text), not the
68//! `CHECK`'s value-set — a typo in the enum still compiles and the set still
69//! drifts. Complementary at the query boundary, not a substitute for the
70//! verification.
71//! - **Accept drift under human review.** Leaves security-adjacent value-sets
72//! (audit taxonomy, lifecycle, step-up purpose) under governance §2's
73//! "aspiration, not enforcement" gate. Rejected.
74//!
75//! ## Caveat — the value-equality half is integration-tier
76//!
77//! The compile-time exhaustiveness guard covers the Rust side on every build.
78//! The `ALL`-vs-`CHECK` set-equality half needs a live database, and there is
79//! no CI job running DB-backed tests — so it bites via each service's
80//! `just test-integration` and the `/deploy-ppoppo` pre-flight, not on a plain
81//! `cargo test`.
82
83#![deny(rust_2018_idioms)]
84#![warn(missing_debug_implementations)]
85
86use std::collections::BTreeSet;
87
88/// One `(constraint, allowed-value-set)` pair, erased of the originating enum
89/// type so the drift test can iterate heterogeneous value-sets.
90#[derive(Debug, Clone)]
91pub struct SchemaBinding {
92 /// The `pg_constraint.conname` (e.g. `"ck_ppnums_entity_type_enum"`).
93 pub constraint: &'static str,
94 /// The DB-text values the owning enum permits — must equal the constraint's
95 /// `IN (…)` set in the materialized schema.
96 pub allowed: BTreeSet<&'static str>,
97}
98
99/// A domain value-set whose members are mirrored by one or more SQL `CHECK`
100/// constraints.
101///
102/// Implemented via [`impl_schema_constrained!`]; never hand-written, so the
103/// compile-time exhaustiveness guard is always emitted alongside.
104pub trait SchemaConstrained: Sized + 'static {
105 /// Every variant, in any order. The macro hand-lists these (no `strum`);
106 /// the exhaustiveness guard makes an omission a build error and the DB test
107 /// makes a stale list a pre-flight failure.
108 const ALL: &'static [Self];
109
110 /// The `CHECK` constraint(s) whose `IN (…)` set must equal
111 /// `{ ALL.map(db_value) }`. More than one when several columns share the
112 /// value-set (e.g. `lifecycle_state` on three columns).
113 const CHECK_CONSTRAINTS: &'static [&'static str];
114
115 /// The DB-text form of a variant — the literal stored in the column and
116 /// named in the `CHECK`. Delegates to the enum's inherent `as_str` /
117 /// `as_wire`.
118 fn db_value(&self) -> &'static str;
119
120 /// Erased `(constraint, allowed)` pairs for the drift test — one per entry
121 /// in [`CHECK_CONSTRAINTS`](Self::CHECK_CONSTRAINTS).
122 fn bindings() -> Vec<SchemaBinding> {
123 let allowed: BTreeSet<&'static str> = Self::ALL.iter().map(Self::db_value).collect();
124 Self::CHECK_CONSTRAINTS
125 .iter()
126 .map(|&constraint| SchemaBinding {
127 constraint,
128 allowed: allowed.clone(),
129 })
130 .collect()
131 }
132}
133
134/// Implement [`SchemaConstrained`] for a unit-variant enum and emit a
135/// compile-time exhaustiveness guard from the same variant list.
136///
137/// ```ignore
138/// ppoppo_schema_constrained::impl_schema_constrained!(EntityType via as_str {
139/// all: [Human, AiAgent, Enterprise, Programmable, Mask],
140/// constraints: ["ck_ppnums_entity_type_enum"],
141/// });
142/// ```
143///
144/// `via $method` is the enum's inherent value accessor (`as_str` for most,
145/// `as_db_str` / `as_wire` for others). Place the invocation next to the enum
146/// so the constraint name lives *on the fact* (governance §6 carrier).
147///
148/// `non_stored` lists render-only variants that exist in the enum but are never
149/// persisted (and so never appear in the `CHECK`) — e.g. `EntityType::Delegated`.
150/// They are excluded from `ALL` yet still covered by the exhaustiveness guard,
151/// so the asymmetry is declared, not hidden.
152#[macro_export]
153macro_rules! impl_schema_constrained {
154 (
155 $ty:ident via $method:ident {
156 all: [ $( $variant:ident ),+ $(,)? ],
157 $( non_stored: [ $( $ns:ident ),+ $(,)? ], )?
158 constraints: [ $( $constraint:literal ),+ $(,)? ] $(,)?
159 }
160 ) => {
161 impl $crate::SchemaConstrained for $ty {
162 const ALL: &'static [Self] = &[ $( $ty::$variant ),+ ];
163 const CHECK_CONSTRAINTS: &'static [&'static str] = &[ $( $constraint ),+ ];
164 fn db_value(&self) -> &'static str {
165 self.$method()
166 }
167 }
168
169 // Compile-time half: if a variant is added to the enum but listed in
170 // neither `all` nor `non_stored`, this match is non-exhaustive and the
171 // build fails — pointing the author at the enrollment.
172 const _: fn($ty) = |x| match x {
173 $( $ty::$variant => () ),+
174 $( , $( $ty::$ns => () ),+ )?
175 };
176 };
177}