rustio-core 1.9.0

RustIO runtime library: HTTP, router, Postgres ORM, admin, RBAC, search, migrations, AI planner.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
//! Phase 14, commit 6 — bridge from `ModelSchema` to search.
//!
//! Schema-first: `ModelSchema` is the single source of truth for
//! which attributes the engine tokenises, filters, and sorts. No
//! manual `Searchable::SEARCHABLE_ATTRIBUTES` declaration is
//! required when using this path.
//!
//! # What stays untouched
//!
//! - The existing `Searchable` trait (`search/traits.rs`) is
//!   **not** modified. Models that hand-implement `Searchable`
//!   keep working unchanged.
//! - `MeiliClient`, `Indexer`, `client.rs`, `indexer.rs` are
//!   not modified — the bridge produces values that drop into
//!   their existing argument shapes (`configure_index(index,
//!   &searchable, &filterable, &sortable)`).
//! - Nothing in `admin/`, `migrations`, `cli/`, `macros/`, or
//!   the contract / validator / doctor modules is touched.
//!
//! # Validator gate
//!
//! Search is enabled only when [`validate_schema`](crate::contract_validator::validate_schema)
//! returns `Ok` or `Warning`:
//!
//! | Validator status | Bridge behaviour                      |
//! |------------------|---------------------------------------|
//! | `Ok`             | enable search                         |
//! | `Warning`        | enable search (warnings logged)       |
//! | `Error`          | refuse to enable — return diagnostics |
//!
//! The rationale: a schema that drifts from the DB will produce
//! Meili documents with the wrong shape (missing fields, wrong
//! types). Better to disable search loudly than to silently index
//! garbage.
//!
//! # Mapping rules
//!
//! For each `ModelColumn`:
//!
//! | Column flag         | Becomes part of                      |
//! |---------------------|--------------------------------------|
//! | `flags.searchable`  | `searchable_attributes`              |
//! | `flags.filterable`  | `filterable_attributes`              |
//! | `flags.sortable`    | `sortable_attributes`                |
//!
//! Plus:
//!
//! - `schema.search_index` → `SearchConfig.index`. `None` means
//!   "model isn't searchable", and the bridge returns
//!   [`SearchEnablement::NotSearchable`] without touching the
//!   validator.
//! - `schema.primary_key` → `SearchConfig.primary_key`. Meili
//!   requires one unique key per document; the contract names it.
//!
//! # Order, exhaustiveness, no silent defaults
//!
//! - Output order matches `schema.columns` declaration order
//!   exactly. Reordering would silently change which fields a
//!   user-typed query weights highest in Meili.
//! - No hardcoded field names. Every name flows from the schema.
//! - Empty searchable set is allowed (and tested) — Meili treats
//!   an empty list as "search over all fields by default", which
//!   is its own answer to "no fields flagged"; the bridge honours
//!   the empty list rather than synthesising defaults.

use std::sync::Arc;

use crate::contract::{HasSchema, ModelSchema};
use crate::contract_validator::{validate_schema, ReportStatus, SchemaReport};
use crate::orm::Db;
use crate::search::{Indexer, MeiliClient};

// ---------------------------------------------------------------------------
// SearchConfig
// ---------------------------------------------------------------------------

/// Search configuration derived from a `ModelSchema`. Designed
/// to feed directly into [`MeiliClient::configure_index`] and
/// [`Indexer`] without touching the existing `Searchable` trait.
///
/// All names are `&'static str` because they come from
/// `ModelColumn`'s static-only fields (the contract is built at
/// compile time by `#[derive(RustioModel)]`). No allocation on
/// the lookup hot path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchConfig {
    /// Meili index name. Sourced from `ModelSchema.search_index`.
    pub index: &'static str,
    /// Primary-key field on every document. Sourced from
    /// `ModelSchema.primary_key`.
    pub primary_key: &'static str,
    /// Attributes Meili tokenises for full-text queries. Order
    /// matches the schema's declaration order — Meili weights
    /// the first attribute highest by default, so order matters.
    pub searchable_attributes: Vec<&'static str>,
    /// Attributes available for `filter=` queries.
    pub filterable_attributes: Vec<&'static str>,
    /// Attributes available for `sort=` queries.
    pub sortable_attributes: Vec<&'static str>,
}

// ---------------------------------------------------------------------------
// Pure derivation
// ---------------------------------------------------------------------------

/// Derive a `SearchConfig` from a schema **without** running the
/// validator. Returns `None` when `schema.search_index` is `None`
/// (the model isn't declared searchable in the contract).
///
/// Pure / synchronous. Safe to call from tests, build scripts,
/// or any non-async context. Used by [`enable_search`] under the
/// hood, and exposed publicly so callers that have already done
/// their own validation can skip the gate.
pub fn search_config_from_schema(schema: &ModelSchema) -> Option<SearchConfig> {
    let index = schema.search_index?;
    Some(SearchConfig {
        index,
        primary_key: schema.primary_key,
        searchable_attributes: schema
            .columns
            .iter()
            .filter(|c| c.flags.searchable)
            .map(|c| c.name)
            .collect(),
        filterable_attributes: schema
            .columns
            .iter()
            .filter(|c| c.flags.filterable)
            .map(|c| c.name)
            .collect(),
        sortable_attributes: schema
            .columns
            .iter()
            .filter(|c| c.flags.sortable)
            .map(|c| c.name)
            .collect(),
    })
}

// ---------------------------------------------------------------------------
// SearchEnablement — the validator-gated outcome
// ---------------------------------------------------------------------------

/// Result of asking "should search be enabled for this model?".
///
/// Three distinct outcomes so callers can log meaningfully:
///
/// - [`Self::NotSearchable`] — the contract declares no
///   `search_index`. Not a failure; the model simply isn't
///   indexed.
/// - [`Self::Disabled`] — the validator returned errors. Search
///   is refused; the report is included so operators can see why.
/// - [`Self::Enabled`] — search is enabled. The config is ready
///   to feed into Meili; the report is attached so any warnings
///   can be logged.
#[derive(Debug, Clone)]
pub enum SearchEnablement {
    NotSearchable,
    Disabled { report: SchemaReport },
    Enabled {
        config: SearchConfig,
        report: SchemaReport,
    },
}

impl SearchEnablement {
    /// Convenience: `true` iff search is enabled. Use when only
    /// the gate decision matters (logging, metrics).
    pub fn is_enabled(&self) -> bool {
        matches!(self, SearchEnablement::Enabled { .. })
    }

    /// The derived [`SearchConfig`] when search is enabled.
    /// `None` for `NotSearchable` and `Disabled`.
    pub fn config(&self) -> Option<&SearchConfig> {
        match self {
            SearchEnablement::Enabled { config, .. } => Some(config),
            _ => None,
        }
    }

    /// The validator [`SchemaReport`], if one was produced. `None`
    /// for `NotSearchable` (the gate short-circuits before
    /// validating).
    pub fn report(&self) -> Option<&SchemaReport> {
        match self {
            SearchEnablement::NotSearchable => None,
            SearchEnablement::Disabled { report }
            | SearchEnablement::Enabled { report, .. } => Some(report),
        }
    }
}

// ---------------------------------------------------------------------------
// Validator-gated entry points
// ---------------------------------------------------------------------------

/// Ask the validator about `M`'s schema and return whether search
/// should be enabled. The async boundary; production callers use
/// this from server bootstrap.
///
/// Implementation note: this is a thin wrapper around
/// [`validate_schema`] + [`enablement_from`]. Unit tests should
/// target [`enablement_from`] directly to avoid needing a Postgres
/// connection.
pub async fn enable_search<M: HasSchema>(db: &Db) -> SearchEnablement {
    let schema = M::SCHEMA;
    let report = validate_schema::<M>(db).await;
    enablement_from(&schema, report)
}

/// Pure decision helper splitting the validator-gated logic out
/// of the async boundary. Given a schema and a (presumably already-
/// produced) [`SchemaReport`], decide whether search should be
/// enabled.
///
/// Three branches:
///
/// 1. `report.status == Error` → [`SearchEnablement::Disabled`].
///    Refuse before deriving the config; the schema is broken,
///    indexing it would silently produce malformed documents.
/// 2. Schema has no `search_index` → [`SearchEnablement::NotSearchable`].
///    The contract opted out of search; honour it.
/// 3. Otherwise → [`SearchEnablement::Enabled`] with the config
///    derived from the schema and the report attached for
///    warning-level diagnostics.
pub fn enablement_from(schema: &ModelSchema, report: SchemaReport) -> SearchEnablement {
    match report.status {
        ReportStatus::Error => SearchEnablement::Disabled { report },
        ReportStatus::Ok | ReportStatus::Warning => match search_config_from_schema(schema) {
            Some(config) => SearchEnablement::Enabled { config, report },
            None => SearchEnablement::NotSearchable,
        },
    }
}

// ---------------------------------------------------------------------------
// Phase 14, commit 8 — runtime indexer integration
// ---------------------------------------------------------------------------

/// Validator-gated indexer construction. Combines:
///
/// 1. [`enable_search::<T>`] — produce a [`SearchEnablement`]
///    by validating the schema.
/// 2. When `Enabled`: configure the Meili index's
///    searchable / filterable / sortable attributes
///    (`MeiliClient::configure_index`).
/// 3. Spawn an [`Indexer`] backed by `client`.
///
/// Returns `None` when:
/// - The validator returned errors (`Disabled`) — fail-safe;
///   indexing against a drifted schema produces malformed
///   documents.
/// - The schema isn't searchable (`NotSearchable`) — the
///   contract opted out.
///
/// Errors during the `configure_index` call are logged and
/// treated as non-fatal: the indexer is still spawned (so
/// pending documents can queue up while Meili is reachable
/// later), but a return of `Some(_)` does not guarantee the
/// index settings are current. Operators should monitor logs
/// for `meili configure_index` failures.
pub async fn indexer_from_schema<T: HasSchema>(
    client: Arc<MeiliClient>,
    db: &Db,
    capacity: usize,
) -> Option<Indexer> {
    let outcome = enable_search::<T>(db).await;
    match outcome {
        SearchEnablement::Enabled { config, report } => {
            // Capture warnings so operators see them once at
            // startup; errors don't reach this branch.
            for w in &report.warnings {
                log::warn!(
                    "search: schema warning on `{}`: {}",
                    report.table, w.message
                );
            }
            let searchable: Vec<&str> = config.searchable_attributes.to_vec();
            let filterable: Vec<&str> = config.filterable_attributes.to_vec();
            let sortable: Vec<&str> = config.sortable_attributes.to_vec();
            if let Err(e) = client
                .configure_index(config.index, &searchable, &filterable, &sortable)
                .await
            {
                log::warn!(
                    "search: configure_index({}) failed at startup: {e} \
                     (indexer still spawned; documents will queue)",
                    config.index
                );
            } else {
                log::info!(
                    "search: index `{}` configured (searchable={} filterable={} sortable={})",
                    config.index,
                    searchable.len(),
                    filterable.len(),
                    sortable.len()
                );
            }
            Some(Indexer::spawn(client, capacity))
        }
        SearchEnablement::Disabled { report } => {
            log::warn!(
                "search: disabled for `{}` — validator reported {} error(s); \
                 indexer NOT spawned (fail-safe)",
                report.table,
                report.errors.len()
            );
            None
        }
        SearchEnablement::NotSearchable => None,
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::contract::{ModelColumn, RustType, SchemaFlags};
    use crate::contract_validator::{IssueKind, SchemaIssue};

    // ----- Fixture builders ------------------------------------------------

    /// A schema with a mix of searchable / filterable / sortable
    /// columns plus a non-flagged column. Drives the "only flagged
    /// columns are indexed" and "ordering preserved" tests.
    fn fixture_schema() -> ModelSchema {
        static COLS: &[ModelColumn] = &[
            // Primary key — sortable + readonly. Not searchable.
            ModelColumn {
                name: "id",
                sql_decl: "BIGSERIAL PRIMARY KEY",
                rust_type: RustType::I64,
                nullable: false,
                primary_key: true,
                flags: SchemaFlags {
                    searchable: false,
                    filterable: false,
                    sortable: true,
                    readonly: true,
                },
                admin_label: None,
                admin_widget: None,
            },
            // Searchable + filterable.
            ModelColumn {
                name: "title",
                sql_decl: "TEXT NOT NULL",
                rust_type: RustType::String,
                nullable: false,
                primary_key: false,
                flags: SchemaFlags {
                    searchable: true,
                    filterable: true,
                    sortable: false,
                    readonly: false,
                },
                admin_label: None,
                admin_widget: None,
            },
            // Searchable only — second searchable to verify order.
            ModelColumn {
                name: "body",
                sql_decl: "TEXT",
                rust_type: RustType::String,
                nullable: true,
                primary_key: false,
                flags: SchemaFlags {
                    searchable: true,
                    filterable: false,
                    sortable: false,
                    readonly: false,
                },
                admin_label: None,
                admin_widget: None,
            },
            // No flags — must be excluded from every list.
            ModelColumn {
                name: "internal_note",
                sql_decl: "TEXT",
                rust_type: RustType::String,
                nullable: true,
                primary_key: false,
                flags: SchemaFlags::empty(),
                admin_label: None,
                admin_widget: None,
            },
            // Filterable + sortable, not searchable. Verifies the
            // three lists are independent.
            ModelColumn {
                name: "published_at",
                sql_decl: "TIMESTAMPTZ",
                rust_type: RustType::DateTimeUtc,
                nullable: true,
                primary_key: false,
                flags: SchemaFlags {
                    searchable: false,
                    filterable: true,
                    sortable: true,
                    readonly: false,
                },
                admin_label: None,
                admin_widget: None,
            },
        ];
        ModelSchema {
            table: "posts",
            columns: COLS,
            primary_key: "id",
            search_index: Some("posts"),
        }
    }

    /// A schema with no `search_index` — the contract opts out of
    /// search entirely. Drives the `NotSearchable` branch.
    fn fixture_unsearchable_schema() -> ModelSchema {
        static COLS: &[ModelColumn] = &[ModelColumn {
            name: "id",
            sql_decl: "BIGSERIAL PRIMARY KEY",
            rust_type: RustType::I64,
            nullable: false,
            primary_key: true,
            flags: SchemaFlags::empty(),
            admin_label: None,
            admin_widget: None,
        }];
        ModelSchema {
            table: "audit_logs",
            columns: COLS,
            primary_key: "id",
            search_index: None,
        }
    }

    /// A schema with a `search_index` but zero columns flagged
    /// `searchable` / `filterable` / `sortable`. The bridge must
    /// honour the empty lists (no synthesised defaults).
    fn fixture_empty_searchable_schema() -> ModelSchema {
        static COLS: &[ModelColumn] = &[
            ModelColumn {
                name: "id",
                sql_decl: "BIGSERIAL PRIMARY KEY",
                rust_type: RustType::I64,
                nullable: false,
                primary_key: true,
                flags: SchemaFlags::empty(),
                admin_label: None,
                admin_widget: None,
            },
            ModelColumn {
                name: "value",
                sql_decl: "TEXT NOT NULL",
                rust_type: RustType::String,
                nullable: false,
                primary_key: false,
                flags: SchemaFlags::empty(),
                admin_label: None,
                admin_widget: None,
            },
        ];
        ModelSchema {
            table: "items",
            columns: COLS,
            primary_key: "id",
            search_index: Some("items"),
        }
    }

    fn ok_report(table: &str) -> SchemaReport {
        SchemaReport {
            table: table.to_string(),
            status: ReportStatus::Ok,
            errors: vec![],
            warnings: vec![],
        }
    }

    fn warning_report(table: &str) -> SchemaReport {
        SchemaReport {
            table: table.to_string(),
            status: ReportStatus::Warning,
            errors: vec![],
            warnings: vec![SchemaIssue {
                column: Some("legacy_code".into()),
                kind: IssueKind::ExtraDbColumn,
                message: "extra DB column `legacy_code` not declared in Rust contract".into(),
                expected: None,
                actual: Some("legacy_code".into()),
            }],
        }
    }

    fn error_report(table: &str) -> SchemaReport {
        SchemaReport {
            table: table.to_string(),
            status: ReportStatus::Error,
            errors: vec![SchemaIssue {
                column: Some("amount".into()),
                kind: IssueKind::MissingColumn,
                message: "column `posts.amount` declared in Rust contract not present in database"
                    .into(),
                expected: Some("NUMERIC NOT NULL".into()),
                actual: None,
            }],
            warnings: vec![],
        }
    }

    // ----- Spec gate: searchable columns come ONLY from schema -------------

    /// Spec gate: only fields with `flags.searchable == true` are
    /// indexed. Verifies the bridge does not include any other
    /// columns and does not invent any field names.
    #[test]
    fn searchable_attributes_drawn_only_from_flagged_columns() {
        let schema = fixture_schema();
        let cfg = search_config_from_schema(&schema).expect("schema is searchable");

        // Only `title` and `body` are flagged searchable.
        assert_eq!(cfg.searchable_attributes, vec!["title", "body"]);

        // Negative: every other column stays out.
        for excluded in ["id", "internal_note", "published_at"] {
            assert!(
                !cfg.searchable_attributes.contains(&excluded),
                "column `{excluded}` should not appear in searchable_attributes"
            );
        }
    }

    /// Spec gate: non-searchable fields excluded. Sister assertion
    /// to the previous test — frames the negative case directly.
    #[test]
    fn non_searchable_fields_excluded_from_search_list() {
        let schema = fixture_schema();
        let cfg = search_config_from_schema(&schema).unwrap();

        // The `internal_note` column has all flags off — it must
        // not appear in any list.
        for list_name in [
            ("searchable", &cfg.searchable_attributes),
            ("filterable", &cfg.filterable_attributes),
            ("sortable", &cfg.sortable_attributes),
        ] {
            let (name, list) = list_name;
            assert!(
                !list.contains(&"internal_note"),
                "internal_note must be excluded from {name}"
            );
        }
    }

    // ----- Spec gate: ordering preserved ----------------------------------

    /// Spec gate: order matches schema declaration order. Meili
    /// weights the first searchable attribute highest, so a
    /// stable order is part of the contract.
    #[test]
    fn ordering_preserved_within_searchable_attributes() {
        let schema = fixture_schema();
        let cfg = search_config_from_schema(&schema).unwrap();

        // `title` comes before `body` in `schema.columns`.
        let title_idx = cfg.searchable_attributes.iter().position(|s| *s == "title");
        let body_idx = cfg.searchable_attributes.iter().position(|s| *s == "body");
        assert_eq!(title_idx, Some(0));
        assert_eq!(body_idx, Some(1));
    }

    /// `filterable_attributes` and `sortable_attributes` follow
    /// the same order rule.
    #[test]
    fn ordering_preserved_within_filterable_and_sortable() {
        let schema = fixture_schema();
        let cfg = search_config_from_schema(&schema).unwrap();

        // `title` (col idx 1) before `published_at` (col idx 4).
        assert_eq!(cfg.filterable_attributes, vec!["title", "published_at"]);
        // `id` (col idx 0) before `published_at` (col idx 4).
        assert_eq!(cfg.sortable_attributes, vec!["id", "published_at"]);
    }

    // ----- Spec gate: empty searchable set handled safely -----------------

    /// Spec gate: empty searchable set handled safely. A schema
    /// that's nominally indexed but has zero flagged columns must
    /// still produce a valid (empty-attribute-list) `SearchConfig`,
    /// not panic, not synthesise defaults.
    #[test]
    fn empty_searchable_set_yields_empty_lists_not_panic() {
        let schema = fixture_empty_searchable_schema();
        let cfg = search_config_from_schema(&schema).expect("search_index is set");

        assert_eq!(cfg.index, "items");
        assert_eq!(cfg.primary_key, "id");
        assert!(cfg.searchable_attributes.is_empty());
        assert!(cfg.filterable_attributes.is_empty());
        assert!(cfg.sortable_attributes.is_empty());
    }

    /// A schema that explicitly opts out of search (no
    /// `search_index`) returns `None` from the pure derivation.
    /// The validator gate treats this as `NotSearchable`.
    #[test]
    fn schema_with_no_search_index_yields_none() {
        let schema = fixture_unsearchable_schema();
        assert!(search_config_from_schema(&schema).is_none());
    }

    // ----- Spec gate: validator gating ------------------------------------

    /// Spec gate: search disabled when validator returns errors.
    /// The bridge refuses to enable search and surfaces the report
    /// for diagnostics.
    #[test]
    fn search_disabled_when_validator_returns_errors() {
        let schema = fixture_schema();
        let report = error_report(schema.table);

        let outcome = enablement_from(&schema, report.clone());
        match outcome {
            SearchEnablement::Disabled { report: r } => {
                assert_eq!(r, report);
                assert_eq!(r.status, ReportStatus::Error);
            }
            other => panic!("expected Disabled, got {:?}", other),
        }

        // is_enabled / config / report convenience methods agree.
        let outcome = enablement_from(&schema, error_report(schema.table));
        assert!(!outcome.is_enabled());
        assert!(outcome.config().is_none());
        assert!(outcome.report().is_some());
    }

    /// Spec gate: search allowed with warnings. A `Warning`-status
    /// report is informational; the bridge still enables search.
    #[test]
    fn search_allowed_when_validator_returns_warnings_only() {
        let schema = fixture_schema();
        let report = warning_report(schema.table);

        let outcome = enablement_from(&schema, report);
        match outcome {
            SearchEnablement::Enabled { config, report: r } => {
                assert_eq!(r.status, ReportStatus::Warning);
                assert_eq!(config.index, "posts");
                assert_eq!(config.searchable_attributes, vec!["title", "body"]);
            }
            other => panic!("expected Enabled, got {:?}", other),
        }
    }

    /// `Ok` status enables search with the report attached.
    #[test]
    fn search_enabled_when_validator_returns_ok() {
        let schema = fixture_schema();
        let outcome = enablement_from(&schema, ok_report(schema.table));
        match outcome {
            SearchEnablement::Enabled { config, report } => {
                assert_eq!(report.status, ReportStatus::Ok);
                assert_eq!(config.index, "posts");
                assert_eq!(config.primary_key, "id");
                assert_eq!(config.searchable_attributes, vec!["title", "body"]);
                assert_eq!(config.filterable_attributes, vec!["title", "published_at"]);
                assert_eq!(config.sortable_attributes, vec!["id", "published_at"]);
            }
            other => panic!("expected Enabled, got {:?}", other),
        }
    }

    /// A schema without a `search_index` short-circuits to
    /// `NotSearchable` regardless of the validator's verdict —
    /// the contract opts out before validation matters.
    #[test]
    fn unsearchable_schema_short_circuits_to_not_searchable() {
        let schema = fixture_unsearchable_schema();

        // Even an `Ok` report doesn't enable search if the schema
        // declares `search_index = None`.
        let outcome = enablement_from(&schema, ok_report(schema.table));
        match outcome {
            SearchEnablement::NotSearchable => {}
            other => panic!("expected NotSearchable, got {:?}", other),
        }

        // is_enabled / config / report convenience methods agree.
        let outcome = enablement_from(&schema, ok_report(schema.table));
        assert!(!outcome.is_enabled());
        assert!(outcome.config().is_none());
        assert!(outcome.report().is_none(), "NotSearchable carries no report");
    }

    // ----- SearchConfig invariants ----------------------------------------

    /// Index name and primary key flow from schema verbatim. No
    /// rewrites, no defaults.
    #[test]
    fn search_config_carries_schema_index_and_primary_key() {
        let schema = fixture_schema();
        let cfg = search_config_from_schema(&schema).unwrap();
        assert_eq!(cfg.index, "posts");
        assert_eq!(cfg.primary_key, "id");
    }

    /// Static slice usability: the produced lists are
    /// `Vec<&'static str>`, so they can feed directly into Meili
    /// API methods that take `&[&str]` without further allocation
    /// of intermediate string buffers.
    #[test]
    fn search_config_lists_are_static_str_borrowable_as_str_slices() {
        let schema = fixture_schema();
        let cfg = search_config_from_schema(&schema).unwrap();
        // Compile-time gate: this won't compile if the type
        // changes from `Vec<&'static str>` to something else.
        fn assert_static_strs(_: &[&'static str]) {}
        assert_static_strs(&cfg.searchable_attributes);
        assert_static_strs(&cfg.filterable_attributes);
        assert_static_strs(&cfg.sortable_attributes);
    }

    // ----- Phase 14, commit 8 — runtime indexer integration -------------

    /// `Indexer::from_schema` is exercised end-to-end by the
    /// freelance example's runtime path; PG-gated tests cover
    /// the live-DB branches. The pure / non-DB decision logic
    /// is covered by `enablement_from` tests above. This test
    /// pins the existence of the public symbol — a rename or
    /// signature change fails to compile here rather than only
    /// at downstream call sites.
    #[test]
    fn indexer_from_schema_symbol_visible() {
        // Reference the function pointer to force symbol
        // resolution. We never call it (would need a live DB
        // + Meili); reaching this line proves the symbol is
        // visible with the expected generic shape.
        let _f = super::indexer_from_schema::<DummyHasSchema>;
    }

    // Stand-in `HasSchema` for the symbol-pinning test above.
    struct DummyHasSchema;
    impl crate::contract::HasSchema for DummyHasSchema {
        const SCHEMA: ModelSchema = ModelSchema {
            table: "dummy",
            columns: &[],
            primary_key: "id",
            search_index: None,
        };
    }

    /// `is_enabled` is the only branch that carries a config.
    #[test]
    fn enablement_accessor_invariants() {
        let schema = fixture_schema();
        let enabled = enablement_from(&schema, ok_report("posts"));
        let disabled = enablement_from(&schema, error_report("posts"));
        let none = enablement_from(&fixture_unsearchable_schema(), ok_report("audit_logs"));

        assert!(enabled.is_enabled());
        assert!(!disabled.is_enabled());
        assert!(!none.is_enabled());

        assert!(enabled.config().is_some());
        assert!(disabled.config().is_none());
        assert!(none.config().is_none());
    }
}