Skip to main content

fraiseql_cli/schema/converter/
mod.rs

1//! Schema Converter
2//!
3//! Converts `IntermediateSchema` (language-agnostic) to `CompiledSchema` (Rust-specific)
4
5mod cascade_types;
6mod directives;
7pub mod functions;
8mod identity;
9mod interface_conformance;
10mod mutation_error_union;
11mod mutations;
12mod queries;
13mod relay;
14mod subscriptions;
15pub(crate) mod tenancy;
16mod types;
17
18#[cfg(test)]
19mod tests;
20
21use std::collections::HashSet;
22
23use anyhow::{Context, Result};
24use fraiseql_core::{
25    compiler::fact_table::{
26        DimensionColumn, DimensionPath, FactTableMetadata, FilterColumn, MeasureColumn, SqlType,
27    },
28    schema::{CompiledSchema, FieldType},
29    validation::CustomTypeRegistry,
30};
31use fraiseql_functions::FunctionsConfig;
32use tracing::{info, warn};
33
34use super::{
35    artifact::CompiledArtifact,
36    intermediate::{IntermediateFactTable, IntermediateInjectDefaults, IntermediateSchema},
37};
38
39/// The directory a project's function modules live in when nothing says otherwise.
40///
41/// The default lives here, in the compiler, rather than on the wire type: every
42/// compiled artifact carries an explicit `module_dir`, so a *hand-written*
43/// `schema.compiled.json` that omits it still fails loudly instead of quietly
44/// resolving somewhere its author did not choose.
45const DEFAULT_FUNCTION_MODULE_DIR: &str = "functions";
46
47/// Converts intermediate format to compiled format
48pub struct SchemaConverter;
49
50/// The author-declared enum, interface, union and custom-scalar names of one schema
51/// (`#923`, extended by `#1018`).
52///
53/// `parse_field_type` matched the twelve builtin scalar names and routed everything else
54/// to `FieldType::Object`, because it is a free function with no view of the document it
55/// is parsing a name from. So `status: OrderStatus`, where the same file declares
56/// `enum OrderStatus`, compiled to `{"Object": "OrderStatus"}` — and
57/// `FieldType::Enum`/`Interface`/`Union` had **no producer at all** for authored schemas;
58/// their only writers were the compiler's own synthesized cascade types.
59///
60/// Everything downstream branches on the variant:
61///
62/// * introspection (`field_resolver`) reports `TypeKind::Object` for an enum-typed field, so an
63///   introspection-driven client (Apollo, Relay, graphql-codegen) is told a scalar enum is an
64///   object with no fields;
65/// * the TypeScript client generator treats `Object` as requiring a nested selection and emits
66///   `status { … }` for a scalar value;
67/// * `--emit-ddl` maps `Object` to `JSONB` rather than to the enum's own Postgres type.
68///
69/// `#1018` is the same defect one variant over: a name declared in `custom_scalars` also
70/// fell through to `Object`, so `FieldType::Scalar` had no producer either.
71///
72/// Held by name rather than by definition because that is all resolution needs, and
73/// because it must be built *before* the type arrays are consumed by conversion.
74#[derive(Debug, Default)]
75pub(crate) struct DeclaredTypeNames {
76    enums:      HashSet<String>,
77    interfaces: HashSet<String>,
78    unions:     HashSet<String>,
79    scalars:    HashSet<String>,
80}
81
82impl DeclaredTypeNames {
83    /// Collect the names an intermediate schema declares.
84    fn collect(schema: &IntermediateSchema) -> Self {
85        Self {
86            enums:      schema.enums.iter().map(|e| e.name.clone()).collect(),
87            interfaces: schema.interfaces.iter().map(|i| i.name.clone()).collect(),
88            unions:     schema.unions.iter().map(|u| u.name.clone()).collect(),
89            scalars:    schema.custom_scalars.iter().flatten().map(|s| s.name.clone()).collect(),
90        }
91    }
92
93    /// Resolve a non-builtin type name to the variant the rest of the codebase branches on.
94    ///
95    /// Falls back to `FieldType::Object` for a name declared nowhere. That fallback is
96    /// deliberate and is **not** the silent drop this fixes: `SchemaValidator` already
97    /// reports an undeclared field type by name, and #724 chose a warning there rather than
98    /// an error because a `--schema-dir` author can legitimately declare a custom scalar in
99    /// a file this pass cannot see. Reversing that decision belongs with #724's reasoning,
100    /// not here.
101    ///
102    /// A name declared in `custom_scalars` resolves to `FieldType::Scalar` (#1018). Without
103    /// it that variant had no producer for an authored schema — the #923 defect, one variant
104    /// over — and three consumers branched on the wrong answer: `--emit-ddl` emitted `JSONB`
105    /// where `TEXT` is correct, introspection reported `OBJECT` for a leaf, and the
106    /// TypeScript generator emitted a sub-selection for a scalar.
107    fn resolve(&self, name: &str) -> FieldType {
108        let owned = || name.to_string();
109        if self.enums.contains(name) {
110            FieldType::Enum(owned())
111        } else if self.interfaces.contains(name) {
112            FieldType::Interface(owned())
113        } else if self.unions.contains(name) {
114            FieldType::Union(owned())
115        } else if self.scalars.contains(name) {
116            FieldType::Scalar(owned())
117        } else {
118            FieldType::Object(owned())
119        }
120    }
121}
122
123/// Optional, default-off behaviours for [`SchemaConverter::convert_with_options`].
124///
125/// Threaded here rather than on [`IntermediateSchema`] so adding an option never
126/// breaks the many full-literal `IntermediateSchema { .. }` constructions, and
127/// the plain [`SchemaConverter::convert`] keeps its historical signature.
128#[derive(Debug, Clone, Default)]
129pub struct ConvertOptions {
130    /// Auto-synthesize a shared `MutationError` type + per-mutation result unions
131    /// and rewrite object-returning mutations to those unions (`[fraiseql.mutations]
132    /// auto_error_union`).
133    pub auto_error_union: bool,
134}
135
136impl SchemaConverter {
137    /// Convert `IntermediateSchema` to `CompiledSchema` with default options.
138    ///
139    /// # Errors
140    ///
141    /// See [`SchemaConverter::convert_with_options`].
142    pub fn convert(intermediate: IntermediateSchema) -> Result<CompiledSchema> {
143        Self::convert_with_options(intermediate, &ConvertOptions::default())
144    }
145
146    /// Convert `IntermediateSchema` into the whole compiled **artifact** — the
147    /// schema plus the platform sections written beside it (#1325).
148    ///
149    /// [`convert_with_options`](Self::convert_with_options) produces only the
150    /// `CompiledSchema`, which is what almost every caller wants. The sections that
151    /// are *siblings* of it in `schema.compiled.json` — currently `functions` — are
152    /// assembled here, so there is exactly one place where an authored section
153    /// becomes a compiled one and exactly one place a probe has to look.
154    ///
155    /// The `[functions]` TOML settings (`module_dir`, `dlq_store`) are paired with
156    /// the authored definitions here; the two halves have one owner each.
157    ///
158    /// # Errors
159    ///
160    /// See [`convert_with_options`](Self::convert_with_options).
161    pub fn convert_artifact(
162        mut intermediate: IntermediateSchema,
163        options: &ConvertOptions,
164    ) -> Result<CompiledArtifact> {
165        let functions = Self::take_functions_section(&mut intermediate)?;
166        let schema = Self::convert_with_options(intermediate, options)?;
167        // Unconditional, including when the project declares no function at all:
168        // a query whose `function = "<name>"` names nothing is exactly the case an
169        // `if let Some(functions)` here would wave through, and it is the one an
170        // author hits by deleting a function and forgetting the query (#1329).
171        functions::validate_against_schema(functions.as_ref(), &schema)?;
172        Ok(CompiledArtifact { schema, functions })
173    }
174
175    /// Pair the authored function declarations with their `[functions]` settings.
176    ///
177    /// Returns `None` when the project declares no functions and no enabled source, so
178    /// a schema that has never heard of them serialises exactly as it did before.
179    ///
180    /// # Errors
181    ///
182    /// Refuses a `[functions]` table when neither a function nor an enabled source would
183    /// use it.
184    /// There is nothing to apply the settings to, so carrying them would write a
185    /// section the server reads and cannot act on, and dropping them would be the
186    /// silent-default failure this whole seam exists to remove (#1008 refuses a
187    /// `storage` section on the same grounds).
188    fn take_functions_section(
189        intermediate: &mut IntermediateSchema,
190    ) -> Result<Option<FunctionsConfig>> {
191        let settings = intermediate.functions_config.take().unwrap_or_default();
192        // An empty list is absence, not an empty section, and two producers reach this.
193        // Some SDKs always emit the key and some omit it, so without this rule the same
194        // project compiled through two of them yields different artifacts. More
195        // importantly `seam::empty_accumulator` seeds EVERY array section with `[]`, so
196        // every TOML-workflow compile arrives here with an empty list whether or not the
197        // project has ever heard of functions — and an emitted section is one #1326
198        // refuses to boot on a build that cannot serve it.
199        let definitions = intermediate.functions.take().unwrap_or_default();
200        // An enabled source's connector is loaded from `module_dir` too (#1399), so a
201        // project whose only code is a connector still needs the section — with no
202        // definitions in it. Refusing the table here made the documented connector
203        // layout impossible to compile.
204        let runs_a_connector = intermediate.sources.iter().flatten().any(|source| source.enabled);
205        if definitions.is_empty() && !runs_a_connector {
206            anyhow::ensure!(
207                settings.module_dir.is_none() && settings.dlq_store.is_none(),
208                "the `[functions]` table configures the functions subsystem but the schema \
209                 declares no function and no enabled source, so nothing would use it. Declare \
210                 a function or a source, or remove the table."
211            );
212            return Ok(None);
213        }
214
215        Ok(Some(FunctionsConfig {
216            module_dir: settings
217                .module_dir
218                .unwrap_or_else(|| std::path::PathBuf::from(DEFAULT_FUNCTION_MODULE_DIR)),
219            definitions,
220            dlq_store: settings.dlq_store,
221        }))
222    }
223
224    /// Convert `IntermediateSchema` to `CompiledSchema`.
225    ///
226    /// This performs:
227    /// 1. Type conversion (intermediate types → compiled types)
228    /// 2. Field name normalization (type → `field_type`)
229    /// 3. Optional mutation-error-union synthesis (`options.auto_error_union`)
230    /// 4. Validation (type references, circular refs, etc.)
231    ///
232    /// # Errors
233    ///
234    /// Returns an error if any type, query, mutation, interface, subscription,
235    /// or directive conversion fails, if federation/security/observer config JSON
236    /// cannot be deserialized, or if compiled schema validation detects unknown
237    /// type references.
238    pub fn convert_with_options(
239        intermediate: IntermediateSchema,
240        options: &ConvertOptions,
241    ) -> Result<CompiledSchema> {
242        info!("Converting intermediate schema to compiled format");
243
244        // Aggregate the per-type `@subscribable(tables=[...])` annotations (#366)
245        // into the top-level `CompiledSchema.subscribable` list BEFORE the types
246        // are consumed below. Empty `tables` is treated as "not subscribable".
247        let subscribable: Vec<fraiseql_core::schema::SubscribableEntity> = intermediate
248            .types
249            .iter()
250            .filter_map(|t| {
251                t.subscribable_tables
252                    .as_ref()
253                    .filter(|tables| !tables.is_empty())
254                    .map(|tables| fraiseql_core::schema::SubscribableEntity {
255                        entity_type: t.name.clone(),
256                        tables:      tables.clone(),
257                        pre_image:   t.subscribable_pre_image,
258                    })
259            })
260            .collect();
261
262        // Refuse a schema that declares observers, rather than validating them and throwing
263        // them away (#779).
264        //
265        // The `observers` block is emitted by the Python SDK's `@fraiseql.observer` (its
266        // shipped example declares five), it binds to `IntermediateSchema.observers`, and
267        // `SchemaValidator` spends ~220 lines checking names, entities, events, actions and
268        // retry policy — a typo in any of them fails the compile, which tells the author
269        // emphatically that the block is honoured. It was not: this function set
270        // `observers: Vec::new()` under a comment claiming they were "populated from
271        // IntermediateSchema", nothing else ever wrote the field, and no webhook, Slack
272        // message or email ever fired for any declared event.
273        //
274        // The runtime loads observers exclusively from `tb_observer` / the admin API and
275        // reads nothing from the compiled schema. So *carrying* them here would only move
276        // the silent drop one layer down and produce a compiled artifact whose `observers`
277        // array is decoration. Until a runtime consumer exists, the honest outcome is to
278        // fail and name the mechanism that does work.
279        if let Some(observers) = intermediate.observers.as_ref().filter(|o| !o.is_empty()) {
280            let names: Vec<&str> = observers.iter().map(|o| o.name.as_str()).collect();
281            anyhow::bail!(
282                "This schema declares {} observer(s) ({}), but declared observers are not \
283                 loaded by the runtime — it reads them from the `tb_observer` table and the \
284                 admin API only, so compiling them would produce a schema whose observers \
285                 never fire.\n\nDefine them in `tb_observer`, or register them at runtime \
286                 with `POST /api/observers`, and remove the `observers` block from the \
287                 authored schema.",
288                observers.len(),
289                names.join(", ")
290            );
291        }
292
293        // Refuse a schema that declares `aggregate_queries`, rather than carrying it through
294        // the seam and dropping it (#956).
295        //
296        // `aggregate_queries` is listed in `AUTHORABLE_ARRAY_SECTIONS`, so it is valid input
297        // on every compile path and every loader and merger carries it faithfully — and then
298        // this converter maps `fact_tables` and never reads it. `CompiledSchema` has no
299        // corresponding field, so the definitions reach the end of the seam and evaporate
300        // under a `✓ Schema compiled successfully`. That is the #755 shape surviving inside
301        // the very seam built to kill it.
302        //
303        // #624 gave `[[analytics.queries]]` real semantics by lowering each entry onto an
304        // ordinary `QueryDefinition`, so the capability exists and has a supported spelling.
305        // Refusing here — the `#779` disposition — names it, instead of accepting a second
306        // spelling that does nothing.
307        if let Some(aggregates) = intermediate.aggregate_queries.as_ref().filter(|a| !a.is_empty())
308        {
309            let names: Vec<&str> = aggregates.iter().map(|a| a.name.as_str()).collect();
310            anyhow::bail!(
311                "This schema declares {} aggregate_queries entry/entries ({}), which no \
312                 compile path lowers into the compiled schema — `CompiledSchema` has no \
313                 field for them, so they would vanish silently.\n\nDeclare them as \
314                 `[[analytics.queries]]` in fraiseql.toml instead (#624): each entry \
315                 becomes a real list-returning, view-backed query. Then remove the \
316                 `aggregate_queries` block from the authored schema.",
317                aggregates.len(),
318                names.join(", ")
319            );
320        }
321
322        // #923: collect the declared enum / interface / union names BEFORE the arrays are
323        // consumed below, so a field or argument naming one resolves to that kind instead of
324        // to a phantom `FieldType::Object`.
325        let declared = DeclaredTypeNames::collect(&intermediate);
326
327        // Split the authored `types` array on `is_input` before converting anything (#848).
328        //
329        // A type marked `is_input` is an input object that four SDKs happen to declare in
330        // the `types` array — Elixir's exporter emits no `input_types` key at all, so this
331        // is its only route. Routing it here rather than converting it as an object type is
332        // what keeps the compiled schema GraphQL-legal: an argument may only be typed with
333        // an input type (§3.10).
334        let (input_marked_types, object_types): (Vec<_>, Vec<_>) =
335            intermediate.types.into_iter().partition(|t| t.is_input);
336
337        let types = object_types
338            .into_iter()
339            .map(|t| Self::convert_type(t, &declared))
340            .collect::<Result<Vec<_>>>()
341            .context("Failed to convert types")?;
342
343        // Extract query_defaults before consuming intermediate.queries.
344        // unwrap_or_default() → all-true, matching historical behaviour when no
345        // [query_defaults] section is present in fraiseql.toml.
346        let defaults = intermediate.query_defaults.unwrap_or_default();
347
348        // Apply `[inject_defaults]` (#847) to any operation that has not named the
349        // parameter itself.
350        //
351        // This runs here, in the converter, rather than in `commands::compile` — the
352        // converter is the single path every caller of the public API goes through, so a
353        // default cannot be lost by reaching the compiled schema some other way.
354        //
355        // It is also deliberately *after* `[fraiseql.tenancy]` validation (which
356        // `commands::compile` performs on the intermediate schema before calling this).
357        // Tenancy auto-injects when `inject_params` is empty and errors when it is
358        // non-empty but lacks the annotated field, so applying defaults first would make a
359        // single unrelated default break every tenancy-annotated operation.
360        let inject_defaults = intermediate.inject_defaults.unwrap_or_default();
361        let query_defaults_inject = inject_defaults.for_queries();
362        let mutation_defaults_inject = inject_defaults.for_mutations();
363
364        // Convert queries. A query that opted into `count` emits a second,
365        // derived `<name>Count` definition (#938) — built by `count_sibling` so
366        // its tenancy, role and filter inheritance has exactly one definition.
367        let mut queries: Vec<fraiseql_core::schema::QueryDefinition> =
368            Vec::with_capacity(intermediate.queries.len());
369        for mut q in intermediate.queries {
370            IntermediateInjectDefaults::apply_to(
371                &query_defaults_inject,
372                &mut q.inject,
373                &q.exclude_inject_defaults,
374                &q.name,
375            )?;
376            let wants_count = q.count;
377            let converted = Self::convert_query(q, &defaults, &declared)
378                .context("Failed to convert queries")?;
379            let sibling = wants_count.then(|| converted.count_sibling());
380            queries.push(converted);
381            queries.extend(sibling);
382        }
383
384        // A generated sibling must not silently displace an author's own query of
385        // the same name — whichever won, the other would vanish from the schema
386        // with no diagnostic.
387        let mut seen: HashSet<&str> = HashSet::new();
388        for q in &queries {
389            if !seen.insert(q.name.as_str()) {
390                anyhow::bail!(
391                    "Query name '{}' is declared twice. A `count = true` query generates \
392                     '<name>Count'; rename the conflicting query or drop count=true.",
393                    q.name
394                );
395            }
396        }
397
398        // Convert mutations
399        let mutations = intermediate
400            .mutations
401            .into_iter()
402            .map(|mut m| {
403                IntermediateInjectDefaults::apply_to(
404                    &mutation_defaults_inject,
405                    &mut m.inject,
406                    &m.exclude_inject_defaults,
407                    &m.name,
408                )?;
409                Self::convert_mutation(m, &declared)
410            })
411            .collect::<Result<Vec<_>>>()
412            .context("Failed to convert mutations")?;
413
414        // Convert enums
415        let enums = intermediate.enums.into_iter().map(Self::convert_enum).collect::<Vec<_>>();
416
417        // Convert input types — the `input_types` array plus the `is_input`-marked entries
418        // lifted out of `types` above. Both routes land in one registry, so a duplicate
419        // between them is an authoring conflict and is refused rather than shadowed.
420        let mut input_objects = intermediate.input_types;
421        for marked in input_marked_types {
422            let lifted = Self::input_object_from_marked_type(marked)?;
423            if input_objects.iter().any(|existing| existing.name == lifted.name) {
424                anyhow::bail!(
425                    "'{}' is declared both in `input_types` and as a type marked \
426                     `is_input: true`. Keep exactly one declaration — two definitions of one \
427                     input object cannot be reconciled, and whichever won would depend on \
428                     compile order.",
429                    lifted.name
430                );
431            }
432            input_objects.push(lifted);
433        }
434        let input_types =
435            input_objects.into_iter().map(Self::convert_input_object).collect::<Vec<_>>();
436
437        // Convert interfaces
438        let interfaces = intermediate
439            .interfaces
440            .into_iter()
441            .map(|i| Self::convert_interface(i, &declared))
442            .collect::<Result<Vec<_>>>()
443            .context("Failed to convert interfaces")?;
444
445        // Convert unions
446        let unions = intermediate.unions.into_iter().map(Self::convert_union).collect::<Vec<_>>();
447
448        // Convert subscriptions
449        let subscriptions = intermediate
450            .subscriptions
451            .into_iter()
452            .map(|s| Self::convert_subscription(s, &declared))
453            .collect::<Result<Vec<_>>>()
454            .context("Failed to convert subscriptions")?;
455
456        // Convert custom directives
457        let directives = intermediate
458            .directives
459            .unwrap_or_default()
460            .into_iter()
461            .map(|d| Self::convert_directive(d, &declared))
462            .collect::<Result<Vec<_>>>()
463            .context("Failed to convert directives")?;
464
465        // Convert fact tables from Vec<IntermediateFactTable> to HashMap<String, FactTableMetadata>
466        let fact_tables = intermediate
467            .fact_tables
468            .unwrap_or_default()
469            .into_iter()
470            .map(|ft| {
471                let name = ft.table_name.clone();
472                let metadata = Self::convert_fact_table(ft);
473                (name, metadata)
474            })
475            .collect();
476
477        let mut compiled = CompiledSchema {
478            types,
479            enums,
480            input_types,
481            interfaces,
482            unions,
483            queries,
484            mutations,
485            subscriptions,
486            directives,
487            fact_tables, // Analytics metadata
488            // Refused above when non-empty (#779); an empty vector is the only reachable
489            // value, so this is not a drop.
490            observers: Vec::new(),
491            sources: intermediate.sources.clone().unwrap_or_default(), /* #573 scheduled ingress
492                                                                        * sources */
493            subscribable, // @subscribable capture-trigger declarations (#366)
494            federation: intermediate
495                .federation_config
496                .map(serde_json::from_value)
497                .transpose()
498                .context("federation_config: invalid JSON structure")?,
499            security: intermediate
500                .security
501                .map(serde_json::from_value)
502                .transpose()
503                .context("security: invalid JSON structure")?,
504            auth: intermediate
505                .auth
506                .map(serde_json::from_value)
507                .transpose()
508                .context("auth: invalid PKCE OAuth-client structure (#621)")?,
509            observers_config: intermediate
510                .observers_config
511                .map(|mut oc| {
512                    // #631: `handlers` reaching this seam (SDK-authored
513                    // `observers_config.handlers`, bypassing the TOML
514                    // validator's #612 bail) must fail the compile, not land in
515                    // the compiled schema as decoration the runtime never
516                    // reads. tb_observer / the admin API is the single observer
517                    // concept. An EMPTY array is inert boilerplate some
518                    // exporters emit — strip it so `deny_unknown_fields` on the
519                    // compiled type does not reject it.
520                    match oc.get("handlers").and_then(serde_json::Value::as_array) {
521                        Some(handlers) if !handlers.is_empty() => {
522                            anyhow::bail!(
523                                "observers_config declares {} handler(s), but compiled \
524                                 handlers are not a runtime concept (#631): the runtime \
525                                 loads observers only from the `tb_observer` table and the \
526                                 admin API. Define them in `tb_observer` or via \
527                                 `POST /api/observers`, and remove `handlers` from the \
528                                 authored schema.",
529                                handlers.len()
530                            );
531                        },
532                        Some(_) => {
533                            if let Some(map) = oc.as_object_mut() {
534                                map.remove("handlers");
535                            }
536                        },
537                        None => {},
538                    }
539                    serde_json::from_value(oc).context("observers_config: invalid JSON structure")
540                })
541                .transpose()?,
542            subscriptions_config: intermediate.subscriptions_config, /* Subscriptions config from
543                                                                      * TOML */
544            validation_config: intermediate.validation_config, // Validation limits from TOML
545            debug_config: intermediate.debug_config,           // Debug config from TOML
546            mcp_config: intermediate.mcp_config,               // MCP config from TOML
547            rest_config: intermediate.rest_config,             // REST config from TOML
548            grpc_config: intermediate.grpc_config,             // gRPC config from TOML (#780)
549            naming_convention: intermediate.naming_convention, // Naming convention from TOML
550            session_variables: intermediate.session_variables.unwrap_or_default(),
551            hierarchies_config: intermediate.hierarchies_config,
552            changelog: intermediate.changelog_config, // Changelog exposure config from TOML
553            schema_sdl: None,                         // Raw GraphQL SDL
554            custom_scalars: CustomTypeRegistry::default(), // Custom scalar registry
555            ..Default::default()
556        };
557
558        // Populate custom scalars from intermediate schema
559        if let Some(custom_scalars_vec) = intermediate.custom_scalars {
560            for scalar_def in custom_scalars_vec {
561                let custom_type = Self::convert_custom_scalar(scalar_def)?;
562                compiled
563                    .custom_scalars
564                    .register(custom_type.name.clone(), custom_type)
565                    .context("Failed to register custom scalar")?;
566            }
567        }
568
569        // Changelog exposure requires the observer system: the views it exposes read
570        // from tables (`tb_entity_change_log`, `tb_transport_checkpoint`) that the
571        // observer install convention supplies. Emitting GraphQL types over absent
572        // tables would only fail later, at runtime — reject it here instead.
573        if let Some(ref cl) = compiled.changelog {
574            if cl.expose && !compiled.observers_config.as_ref().is_some_and(|o| o.enabled) {
575                anyhow::bail!(
576                    "[changelog] expose = true requires [observers] to be enabled: the tables \
577                     it exposes (tb_entity_change_log, tb_transport_checkpoint) are installed by \
578                     the observer system."
579                );
580            }
581            // #497: the change-log surface is a per-database stream, not a federated
582            // value type — the injected `EntityChangeLog` type and `entity_change_logs`
583            // root query are not `@shareable`. Two subgraphs in one supergraph that both
584            // `expose` it inject the identical type/root field, which `rover supergraph
585            // compose` rejects with INVALID_FIELD_SHARING. We can't detect the collision
586            // here (each subgraph compiles alone), so warn on the federated+exposed combo
587            // and point at the single-owner pattern. This is a reminder, not an error —
588            // the owning subgraph legitimately sets both.
589            if cl.expose && compiled.federation.as_ref().is_some_and(|f| f.enabled) {
590                warn!(
591                    "[changelog] expose = true on a federation subgraph: EntityChangeLog / \
592                     entity_change_logs are not @shareable, so expose the change-log in exactly \
593                     one subgraph per supergraph (others keep capturing via [changelog] \
594                     write_enabled). Two exposing subgraphs fail `rover supergraph compose` with \
595                     INVALID_FIELD_SHARING. See the changelog-graphql guide for the single-owner \
596                     pattern."
597                );
598            }
599        }
600
601        // Canonicalize the Trinity external identity (`id: UUID` → `id: ID`, ADR-0017)
602        // before the interface-forcing passes, so Relay `Node` / `CascadeNode` see a
603        // conformant `id: ID` on every entity. Wire-transparent (a UUID is an `ID`).
604        identity::normalize_entity_identity(&mut compiled);
605
606        // Inject synthetic Relay types (PageInfo, Node interface, XxxConnection, XxxEdge).
607        relay::inject_relay_types(&mut compiled)?;
608
609        // Inject the changelog GraphQL surface (EntityChangeLog / TransportCheckpoint
610        // types + cursor query + point lookup + upsert mutation) when opted in.
611        fraiseql_core::schema::inject_changelog(&mut compiled);
612
613        // Synthesize the typed cascade surface (CascadeNode interface + envelope
614        // types + per-mutation `<Name>Payload` wrappers) for mutations that opt in
615        // via `cascade = true`. Runs BEFORE error-union synthesis so a cascade
616        // payload becomes the success member of the result union
617        // (`<Name>Result = <Name>Payload | MutationError`). Inert with no cascade
618        // mutations.
619        cascade_types::synthesize_cascade_types(&mut compiled)?;
620
621        // Auto-synthesize a shared MutationError type + per-mutation result unions
622        // when opted in (`[fraiseql.mutations] auto_error_union`), so the runtime's
623        // success/error discrimination has a union to resolve against.
624        if options.auto_error_union {
625            mutation_error_union::synthesize_mutation_error_unions(&mut compiled);
626        }
627
628        // IR honesty (#456): `parse_field_type` has no `Input` variant, so an
629        // argument referencing a declared input type was resolved to
630        // `FieldType::Object`. Rewrite those argument types to `FieldType::Input`
631        // now that every input type is registered (after relay / rich-filter /
632        // changelog / error-union injection) so the IR honestly represents the
633        // GraphQL input position — which also makes introspection report the correct
634        // `INPUT_OBJECT` kind for those args. The runtime already accepts both
635        // shapes, so this is purely representational.
636        Self::promote_input_type_args(&mut compiled);
637
638        // Validate the compiled schema
639        Self::validate(&compiled)?;
640
641        info!("Schema conversion successful");
642        Ok(compiled)
643    }
644
645    /// Rewrite mutation/query argument types of the form `Object(name)` (and lists
646    /// thereof) to `Input(name)` when `name` is a registered input type, so the IR
647    /// honestly represents input-position references (#456). Input type names are
648    /// disjoint from output type names per the GraphQL spec, so the lookup is exact
649    /// — an output-object argument is never misclassified.
650    fn promote_input_type_args(schema: &mut CompiledSchema) {
651        fn promote(ft: &mut FieldType, input_names: &HashSet<String>) {
652            match ft {
653                FieldType::Object(name) if input_names.contains(name) => {
654                    *ft = FieldType::Input(name.clone());
655                },
656                FieldType::List(inner) => promote(inner, input_names),
657                _ => {},
658            }
659        }
660
661        let input_names: HashSet<String> =
662            schema.input_types.iter().map(|i| i.name.clone()).collect();
663        if input_names.is_empty() {
664            return;
665        }
666
667        for mutation in &mut schema.mutations {
668            for arg in &mut mutation.arguments {
669                promote(&mut arg.arg_type, &input_names);
670            }
671        }
672        for query in &mut schema.queries {
673            for arg in &mut query.arguments {
674                promote(&mut arg.arg_type, &input_names);
675            }
676        }
677    }
678
679    #[allow(clippy::cognitive_complexity)] // Reason: comprehensive schema validation with many field-level checks
680    fn validate(schema: &CompiledSchema) -> Result<()> {
681        info!("Validating compiled schema");
682
683        // Build type registry
684        let mut type_names: HashSet<String> = HashSet::new();
685        for type_def in &schema.types {
686            type_names.insert(type_def.name.to_string());
687        }
688
689        // Build interface registry. Interfaces are *also* valid query/mutation
690        // return types (a field may return an interface, narrowed via inline
691        // fragments), so register them in `type_names` too — previously omitted,
692        // which made a query/mutation returning an interface silently fail the
693        // reference check below.
694        let mut interface_names = HashSet::new();
695        for interface_def in &schema.interfaces {
696            interface_names.insert(interface_def.name.clone());
697            type_names.insert(interface_def.name.clone());
698        }
699
700        // Add input types — valid as mutation argument types (fraiseql/fraiseql#190)
701        for input_type in &schema.input_types {
702            type_names.insert(input_type.name.clone());
703        }
704
705        // Add union type names — valid as mutation/query return types
706        for union_def in &schema.unions {
707            type_names.insert(union_def.name.clone());
708        }
709
710        // Add enum type names — valid as field and argument types
711        for enum_def in &schema.enums {
712            type_names.insert(enum_def.name.clone());
713        }
714
715        // Add built-in scalars
716        for scalar in crate::schema::builtin_scalar_names() {
717            type_names.insert(scalar.to_string());
718        }
719
720        // Add **declared** custom scalars, from the registry the compiler actually carries.
721        //
722        // This used to register every type name appearing in any object field, which made a
723        // field-type typo legalize itself as a return type too (#724 item 2) — the same
724        // blindness as `SchemaValidator`, duplicated here.
725        for (name, _) in schema.custom_scalars.list_all() {
726            type_names.insert(name);
727        }
728
729        // Collect every problem, then report them together.
730        //
731        // This tier used to `bail!` on the first error, with no suggestion, after redundantly
732        // `warn!`ing the same text (#724 item 4). Errors that only surface after synthesis —
733        // relay, cascade, changelog-injected types — are validated *here*, so the same class
734        // of mistake got a materially worse experience depending on which tier caught it, and
735        // a user with three typos needed three compile cycles for information the compiler
736        // had in hand on the first.
737        let mut problems: Vec<String> = Vec::new();
738        let mut known: Vec<&str> = type_names.iter().map(String::as_str).collect();
739        known.sort_unstable();
740
741        let describe = |name: &str| -> String {
742            let similar = fraiseql_core::runtime::suggest_similar(name, &known);
743            if similar.is_empty() {
744                String::new()
745            } else {
746                format!(" (did you mean: {}?)", similar.join(", "))
747            }
748        };
749
750        // Validate queries
751        for query in &schema.queries {
752            if !type_names.contains(&query.return_type) {
753                problems.push(format!(
754                    "Query '{}' references unknown type '{}'{}",
755                    query.name,
756                    query.return_type,
757                    describe(&query.return_type)
758                ));
759            }
760
761            for arg in &query.arguments {
762                let type_name = Self::extract_type_name(&arg.arg_type);
763                if !type_names.contains(&type_name) {
764                    problems.push(format!(
765                        "Query '{}' argument '{}' references unknown type '{}'{}",
766                        query.name,
767                        arg.name,
768                        type_name,
769                        describe(&type_name)
770                    ));
771                }
772            }
773        }
774
775        // Validate mutations
776        for mutation in &schema.mutations {
777            if !type_names.contains(&mutation.return_type) {
778                problems.push(format!(
779                    "Mutation '{}' references unknown type '{}'{}",
780                    mutation.name,
781                    mutation.return_type,
782                    describe(&mutation.return_type)
783                ));
784            }
785
786            for arg in &mutation.arguments {
787                let type_name = Self::extract_type_name(&arg.arg_type);
788                if !type_names.contains(&type_name) {
789                    problems.push(format!(
790                        "Mutation '{}' argument '{}' references unknown type '{}'{}",
791                        mutation.name,
792                        arg.name,
793                        type_name,
794                        describe(&type_name)
795                    ));
796                }
797            }
798        }
799
800        // Validate interface implementations
801        for type_def in &schema.types {
802            for interface_name in &type_def.implements {
803                if !interface_names.contains(interface_name) {
804                    let mut candidates: Vec<&str> =
805                        interface_names.iter().map(String::as_str).collect();
806                    candidates.sort_unstable();
807                    let similar =
808                        fraiseql_core::runtime::suggest_similar(interface_name, &candidates);
809                    let hint = if similar.is_empty() {
810                        String::new()
811                    } else {
812                        format!(" (did you mean: {}?)", similar.join(", "))
813                    };
814                    problems.push(format!(
815                        "Type '{}' implements unknown interface '{interface_name}'{hint}",
816                        type_def.name
817                    ));
818                    continue;
819                }
820
821                // Validate that the type has all fields required by the interface
822                if let Some(interface) = schema.find_interface(interface_name) {
823                    for interface_field in &interface.fields {
824                        let type_has_field = type_def.fields.iter().any(|f| {
825                            f.name == interface_field.name
826                                && f.field_type == interface_field.field_type
827                        });
828                        if !type_has_field {
829                            problems.push(format!(
830                                "Type '{}' implements interface '{interface_name}' but is \
831                                 missing field '{}'",
832                                type_def.name, interface_field.name
833                            ));
834                        }
835                    }
836                }
837            }
838        }
839
840        // Relationships the REST embed executor could not follow (#1266) — an undeclared
841        // target, a join column no field publishes, a target no list query returns.
842        //
843        // Borrowed wholesale from the load-time check rather than restated here: the two
844        // must agree, and the way they stop agreeing is one of them being taught a rule
845        // the other is not. `CompiledSchema::finish_load` runs the same function, which
846        // is what covers the hand-edited artifact this compile-time refusal cannot reach.
847        problems.extend(schema.relationship_violations());
848
849        // Federation `@key`s the router would refuse (#1395) — the same function the load
850        // path runs, for the same reason as the relationship check above.
851        problems.extend(schema.federation_key_violations());
852
853        if !problems.is_empty() {
854            let count = problems.len();
855            let noun = if count == 1 { "problem" } else { "problems" };
856            anyhow::bail!(
857                "Schema validation found {count} {noun}:\n{}",
858                problems.iter().map(|p| format!("  - {p}")).collect::<Vec<_>>().join("\n")
859            );
860        }
861
862        info!("Schema validation passed");
863        Ok(())
864    }
865
866    /// Extract type name from `FieldType` for validation
867    ///
868    /// Built-in types return their scalar name, Object types return the object name
869    fn extract_type_name(field_type: &FieldType) -> String {
870        // A built-in scalar's name is the one the author wrote, from the same
871        // table `parse_field_type` reads — this is that function's inverse.
872        if let Some(name) = field_type.authoring_name() {
873            return name.to_string();
874        }
875        match field_type {
876            FieldType::Scalar(name) => name.clone(),
877            FieldType::Object(name) => name.clone(),
878            FieldType::Enum(name) => name.clone(),
879            FieldType::Input(name) => name.clone(),
880            FieldType::Interface(name) => name.clone(),
881            FieldType::Union(name) => name.clone(),
882            FieldType::List(inner) => Self::extract_type_name(inner),
883            // Reason: non_exhaustive requires catch-all for cross-crate matches
884            _ => "Unknown".to_string(),
885        }
886    }
887
888    /// Convert `IntermediateFactTable` to `FactTableMetadata`.
889    fn convert_fact_table(ft: IntermediateFactTable) -> FactTableMetadata {
890        FactTableMetadata {
891            table_name:               ft.table_name,
892            type_name:                ft.type_name,
893            measures:                 ft
894                .measures
895                .into_iter()
896                .map(|m| MeasureColumn {
897                    name:     m.name,
898                    sql_type: Self::parse_sql_type(&m.sql_type),
899                    nullable: m.nullable,
900                })
901                .collect(),
902            dimensions:               DimensionColumn {
903                name:  ft.dimensions.name,
904                paths: ft
905                    .dimensions
906                    .paths
907                    .into_iter()
908                    .map(|p| DimensionPath {
909                        name:      p.name,
910                        json_path: p.json_path,
911                        data_type: p.data_type,
912                    })
913                    .collect(),
914            },
915            denormalized_filters:     ft
916                .denormalized_filters
917                .into_iter()
918                .map(|f| FilterColumn {
919                    name:      f.name,
920                    sql_type:  Self::parse_sql_type(&f.sql_type),
921                    indexed:   f.indexed,
922                    hierarchy: f.hierarchy,
923                })
924                .collect(),
925            calendar_dimensions:      vec![],
926            partial_period:           None,
927            native_measures:          ft.native_measures,
928            native_dimension_mapping: ft.native_dimension_mapping,
929        }
930    }
931
932    /// Parse a SQL type string into a `SqlType` enum variant.
933    fn parse_sql_type(s: &str) -> SqlType {
934        match s.to_uppercase().as_str() {
935            "INT" | "INTEGER" | "SMALLINT" | "INT4" | "INT2" => SqlType::Int,
936            "BIGINT" | "INT8" => SqlType::BigInt,
937            "DECIMAL" | "NUMERIC" | "MONEY" => SqlType::Decimal,
938            "REAL" | "FLOAT" | "DOUBLE" | "FLOAT8" | "FLOAT4" | "DOUBLE PRECISION" => {
939                SqlType::Float
940            },
941            "JSONB" => SqlType::Jsonb,
942            "JSON" => SqlType::Json,
943            "TEXT" | "VARCHAR" | "STRING" | "CHAR" | "CHARACTER VARYING" => SqlType::Text,
944            "UUID" => SqlType::Uuid,
945            "TIMESTAMP" | "TIMESTAMPTZ" | "TIMESTAMP WITH TIME ZONE" | "DATETIME" => {
946                SqlType::Timestamp
947            },
948            "DATE" => SqlType::Date,
949            "BOOLEAN" | "BOOL" => SqlType::Boolean,
950            "LTREE" => SqlType::Ltree,
951            _ => SqlType::Other(s.to_string()),
952        }
953    }
954}
955
956/// Parse an authored `requires_actor` list into [`ActorType`]s (#966).
957///
958/// One parser for queries and mutations, so the two cannot disagree about which
959/// tokens exist.
960///
961/// # Why an unknown token is an error
962///
963/// `requires_actor` is an allow-list, so a dropped entry does not open the
964/// operation — it *closes* it further, and a typo'd `"human"` would refuse every
965/// human user while the schema reads as though it admits them. And a whole list
966/// that failed to parse would leave the field empty, which means *unrestricted*:
967/// the failure mode of silence is a security gate that is not there. Naming the
968/// bad token at compile time is the only reading where the author finds out.
969///
970/// # Errors
971///
972/// Returns an error naming the offending token and listing the valid ones.
973pub(crate) fn parse_requires_actor(
974    operation_kind: &str,
975    operation_name: &str,
976    tokens: &[String],
977) -> Result<Vec<fraiseql_core::security::ActorType>> {
978    use fraiseql_core::security::ActorType;
979
980    tokens
981        .iter()
982        .map(|token| {
983            ActorType::from_token(token).ok_or_else(|| {
984                anyhow::anyhow!(
985                    "{operation_kind} '{operation_name}': requires_actor entry '{token}' is not a \
986                     known actor type. Valid values: {}",
987                    ActorType::ALL.map(ActorType::as_str).join(", ")
988                )
989            })
990        })
991        .collect()
992}