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