razeri-plugin-api 0.20.3

Extension traits and registries for Razeri plugins
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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
// Copyright (C) 2026 Gabriel Shea
// Licensed under either of the Apache License, Version 2.0 or the MIT
// license, at your option.

//! Fluent builder for constructing a [`PluginRegistry`] at application startup.
//!
//! Also includes `inventory` registration types for compile-time plugin discovery.

use crate::dialect::{PlatformDialect, PlatformRegistry};
use crate::event::{EventRegistry, EventSink, RazeriEvent};
use crate::language::{LanguageRegistry, LanguageRendererFactory};
use crate::llm::{LlmClientFactory, LlmRegistry};
use crate::model::{LlmModelAdapter, ModelRegistry};
use crate::registry::PluginRegistry;
use crate::storage::{StorageProviderFactory, StorageRegistry};
use chrono::Utc;
use razeri_plugin_contract::StoragePlatform;
use std::sync::Arc;

/// Fluent builder for constructing a [`PluginRegistry`] at application startup.
///
/// # Example
///
/// ```ignore
/// let registry = PluginRegistryBuilder::new()
///     .with_dialect("postgres", Arc::new(PostgresDialect))
///     .with_llm("ollama".into(), Arc::new(OllamaFactory::new()))
///     .with_auto_discovered()
///     .build();
/// ```
pub struct PluginRegistryBuilder {
    dialects: PlatformRegistry,
    storage: StorageRegistry,
    llm: LlmRegistry,
    models: ModelRegistry,
    language: LanguageRegistry,
    events: EventRegistry,
}

impl PluginRegistryBuilder {
    /// Create a new empty builder.
    #[must_use]
    pub fn new() -> Self {
        Self {
            dialects: PlatformRegistry::new(),
            storage: StorageRegistry::new(),
            llm: LlmRegistry::new(),
            models: ModelRegistry::new(),
            language: LanguageRegistry::new(),
            events: EventRegistry::new(),
        }
    }

    // ── Dialect registration ───────────────────────────────────────

    /// Register a dialect by its canonical string name.
    #[must_use]
    pub fn with_dialect(mut self, name: &str, dialect: Arc<dyn PlatformDialect>) -> Self {
        self.dialects.register(name.to_string(), dialect);
        self
    }

    /// Register one dialect under the name it declares for itself.
    ///
    /// The `&mut self` form of [`with_dialect`](Self::with_dialect), for the
    /// one caller that cannot use a builder chain: a plugin's registration
    /// function, which is handed a `&mut PluginRegistryBuilder` the host owns.
    pub fn register_dialect(&mut self, dialect: Arc<dyn PlatformDialect>) {
        let name = dialect.info().name.to_string();
        self.dialects.register(name, dialect);
    }

    // ── Storage registration ───────────────────────────────────────

    /// Register a storage provider for a known (enum) storage platform.
    #[must_use]
    pub fn with_storage(
        mut self,
        platform: StoragePlatform,
        factory: Arc<dyn StorageProviderFactory>,
    ) -> Self {
        self.storage.register_known(platform, factory);
        self
    }

    /// Register a storage provider for an extension (string-named) platform.
    #[must_use]
    pub fn with_storage_extension(
        mut self,
        name: String,
        factory: Arc<dyn StorageProviderFactory>,
    ) -> Self {
        self.storage.register_extension(name, factory);
        self
    }

    // ── LLM registration ──────────────────────────────────────────

    /// Register an LLM provider factory by name.
    #[must_use]
    pub fn with_llm(mut self, name: String, factory: Arc<dyn LlmClientFactory>) -> Self {
        self.llm.register(name, factory);
        self
    }

    // ── Model registration ────────────────────────────────────────

    /// Register a model adapter (keyed by provider + `model_id`).
    #[must_use]
    pub fn with_model(mut self, adapter: Arc<dyn LlmModelAdapter>) -> Self {
        self.models.register(adapter);
        self
    }

    // ── Language renderer registration ────────────────────────────

    /// Register a language renderer factory by language name.
    #[must_use]
    pub fn with_language(
        mut self,
        language: String,
        factory: Arc<dyn LanguageRendererFactory>,
    ) -> Self {
        self.language.register(language, factory);
        self
    }

    // ── Event sink registration ───────────────────────────────────

    /// Register an event sink for observability.
    #[must_use]
    pub fn with_event_sink(mut self, sink: Arc<dyn EventSink>) -> Self {
        self.events.register(sink);
        self
    }

    // ── Auto-discovery ────────────────────────────────────────────

    /// Discover and register all plugins submitted via `inventory::submit!`.
    #[must_use]
    pub fn with_auto_discovered(mut self) -> Self {
        for reg in inventory::iter::<DialectRegistration> {
            let dialect = (reg.factory)();
            let name = dialect.info().name.to_string();
            self.dialects.register(name, dialect);
            self.record_plugin_loaded(reg.name, "dialect", "inventory");
        }
        for reg in inventory::iter::<StorageRegistration> {
            let factory = (reg.factory)();
            if let Some(platform) = factory.known_platform() {
                self.storage.register_known(platform, factory);
            } else {
                self.storage.register_extension(reg.name.to_string(), factory);
            }
            self.record_plugin_loaded(reg.name, "storage", "inventory");
        }
        for reg in inventory::iter::<LlmRegistration> {
            let factory = (reg.factory)();
            self.llm.register(reg.name.to_string(), factory);
            self.record_plugin_loaded(reg.name, "llm", "inventory");
        }
        for reg in inventory::iter::<ModelRegistration> {
            let adapter = (reg.factory)();
            self.models.register(adapter);
            self.record_plugin_loaded(reg.model_id, "model", "inventory");
        }
        for reg in inventory::iter::<LanguageRegistration> {
            let factory = (reg.factory)();
            self.language.register(reg.language.to_string(), factory);
            self.record_plugin_loaded(reg.language, "language", "inventory");
        }
        for reg in inventory::iter::<EventSinkRegistration> {
            let sink = (reg.factory)();
            self.events.register(sink);
            self.record_plugin_loaded(reg.name, "event_sink", "inventory");
        }
        // Plugin crates linked into this binary with `export_plugin!`.
        for reg in inventory::iter::<PluginRegistration> {
            (reg.register)(&mut self);
        }
        self
    }

    /// Record a `PluginLoaded` event into the event history.
    fn record_plugin_loaded(&self, name: &str, plugin_type: &str, source: &str) {
        if let Ok(event) = RazeriEvent::plugin_loaded(
            format!("plugin_loaded:{plugin_type}:{name}"),
            Utc::now(),
            name,
            plugin_type,
            source,
        ) {
            self.events.record(event);
        }
    }

    // ── Dynamic loading ─────────────────────────────────────────

    /// Discover and load all plugin shared libraries from `plugin_dir`.
    ///
    /// Scans the directory for `.so`/`.dylib`/`.dll` files, checks their
    /// API version, and calls their registration function. Invalid or
    /// incompatible plugins are logged and skipped.
    ///
    /// Requires the `dynamic` feature. Native-only: shared-library loading does
    /// not exist on wasm32-unknown-unknown (a browser cannot dlopen `.so`s).
    #[cfg(all(feature = "dynamic", not(target_arch = "wasm32")))]
    #[must_use]
    pub fn with_dynamic_plugins(mut self, plugin_dir: &std::path::Path) -> Self {
        let results = crate::dynamic::load_plugins_from_dir(plugin_dir, &mut self);
        for result in &results {
            match result {
                crate::dynamic::PluginLoadResult::Loaded { name, path } => {
                    tracing::info!("Loaded dynamic plugin '{name}' from {}", path.display());
                    self.record_plugin_loaded(name, "dynamic", &path.display().to_string());
                }
                crate::dynamic::PluginLoadResult::Refused { path, refusal } => {
                    tracing::warn!("Plugin {} was not loaded: {refusal}", path.display());
                }
                crate::dynamic::PluginLoadResult::Failed { path, error } => {
                    tracing::warn!("Failed to load plugin from {}: {error}", path.display());
                }
            }
        }
        self
    }

    // ── Build ─────────────────────────────────────────────────────

    /// Consume the builder and produce the final [`PluginRegistry`].
    pub fn build(self) -> PluginRegistry {
        PluginRegistry {
            dialects: self.dialects,
            storage: self.storage,
            llm: self.llm,
            models: self.models,
            language: self.language,
            events: self.events,
        }
    }
}

impl Default for PluginRegistryBuilder {
    /// Create a fresh plugin-registry builder with empty sub-registries.
    /// Parameters:
    /// - none: Returns a new builder equivalent to `PluginRegistryBuilder::new()`.
    fn default() -> Self {
        Self::new()
    }
}

// ── Inventory registration types ──────────────────────────────────────
// Third-party crates submit these via `inventory::submit!` for automatic
// discovery at startup.

/// Registration entry for auto-discovered dialects.
pub struct DialectRegistration {
    /// Canonical dialect name (e.g. `"postgres"`).
    pub name: &'static str,
    /// Factory function that constructs the dialect plugin.
    pub factory: fn() -> Arc<dyn PlatformDialect>,
}

impl DialectRegistration {
    /// Create a new dialect registration entry.
    pub const fn new(name: &'static str, factory: fn() -> Arc<dyn PlatformDialect>) -> Self {
        Self { name, factory }
    }
}

inventory::collect!(DialectRegistration);

/// Registration entry for a whole plugin: the function that registers
/// everything the plugin provides.
///
/// [`export_plugin!`](crate::export_plugin) submits one of these, so a plugin
/// crate linked into a razeri binary is found at start-up with no other line.
pub struct PluginRegistration {
    /// The plugin's registration function.
    pub register: fn(&mut PluginRegistryBuilder),
}

impl PluginRegistration {
    /// Create a new plugin registration entry.
    pub const fn new(register: fn(&mut PluginRegistryBuilder)) -> Self {
        Self { register }
    }
}

inventory::collect!(PluginRegistration);

/// Registration entry for auto-discovered storage providers.
pub struct StorageRegistration {
    /// Canonical storage platform name (e.g. `"s3"`).
    pub name: &'static str,
    /// Factory function that constructs the storage provider.
    pub factory: fn() -> Arc<dyn StorageProviderFactory>,
}

impl StorageRegistration {
    /// Create a new storage registration entry.
    pub const fn new(name: &'static str, factory: fn() -> Arc<dyn StorageProviderFactory>) -> Self {
        Self { name, factory }
    }
}

inventory::collect!(StorageRegistration);

/// Registration entry for auto-discovered LLM providers.
pub struct LlmRegistration {
    /// Canonical provider name (e.g. `"ollama"`).
    pub name: &'static str,
    /// Factory function that constructs the LLM client factory.
    pub factory: fn() -> Arc<dyn LlmClientFactory>,
}

impl LlmRegistration {
    /// Create a new LLM provider registration entry.
    pub const fn new(name: &'static str, factory: fn() -> Arc<dyn LlmClientFactory>) -> Self {
        Self { name, factory }
    }
}

inventory::collect!(LlmRegistration);

/// Registration entry for auto-discovered model adapters.
pub struct ModelRegistration {
    /// Canonical model identifier (e.g. `"llama3"`).
    pub model_id: &'static str,
    /// Factory function that constructs the model adapter.
    pub factory: fn() -> Arc<dyn LlmModelAdapter>,
}

impl ModelRegistration {
    /// Create a new model adapter registration entry.
    pub const fn new(model_id: &'static str, factory: fn() -> Arc<dyn LlmModelAdapter>) -> Self {
        Self { model_id, factory }
    }
}

inventory::collect!(ModelRegistration);

/// Registration entry for auto-discovered language renderers.
pub struct LanguageRegistration {
    /// Target language name (e.g. `"python"`).
    pub language: &'static str,
    /// Factory function that constructs the language renderer factory.
    pub factory: fn() -> Arc<dyn LanguageRendererFactory>,
}

impl LanguageRegistration {
    /// Create a new language renderer registration entry.
    pub const fn new(
        language: &'static str,
        factory: fn() -> Arc<dyn LanguageRendererFactory>,
    ) -> Self {
        Self { language, factory }
    }
}

inventory::collect!(LanguageRegistration);

/// Registration entry for auto-discovered event sinks.
pub struct EventSinkRegistration {
    /// Canonical sink name (e.g. `"stdout"`).
    pub name: &'static str,
    /// Factory function that constructs the event sink.
    pub factory: fn() -> Arc<dyn EventSink>,
}

impl EventSinkRegistration {
    /// Create a new event sink registration entry.
    pub const fn new(name: &'static str, factory: fn() -> Arc<dyn EventSink>) -> Self {
        Self { name, factory }
    }
}

inventory::collect!(EventSinkRegistration);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dialect::{DialectInfo, PlatformDialect};
    use crate::error::{EventSinkError, LanguageError, LlmError};
    use crate::event::RazeriEvent;
    use crate::llm::{ChatResponse, LlmClient, Message, ModelInfo, ToolDefinition};
    use crate::model::ModelCapabilities;
    use async_trait::async_trait;
    use razeri_plugin_contract::DataType;
    use razeri_plugin_contract::DialectFamily;
    use razeri_plugin_contract::{
        DdlRenderer, DialectCapabilities, DmlRenderer, ExpressionRenderer, FormulaRenderer,
        ProcedureRenderer, ReplicationRenderer, SqlRenderer, StorageRenderer, TaskRenderer,
    };
    use std::collections::HashMap;

    // ── Test doubles ──────────────────────────────────────────────

    struct TestDialect;

    impl SqlRenderer for TestDialect {
        /// Render a placeholder data type for test dialect behavior.
        /// Parameters:
        /// - self: Test dialect instance.
        /// - _dt: Data type to render (ignored in test double).
        fn render_data_type(&self, _dt: &DataType) -> String {
            "TEXT".to_string()
        }
        /// Quote an identifier using double quotes in test dialect output.
        /// Parameters:
        /// - self: Test dialect instance.
        /// - name: Identifier text to quote.
        fn quote_identifier(&self, name: &str) -> String {
            format!("\"{name}\"")
        }
        /// Render a qualified name for test dialect output.
        /// Parameters:
        /// - self: Test dialect instance.
        /// - _schema: Optional schema segment (ignored in test double).
        /// - name: Object name segment to render.
        fn qualify_name(&self, _schema: Option<&str>, name: &str) -> String {
            name.to_string()
        }
        /// Render current timestamp expression for test dialect output.
        /// Parameters:
        /// - self: Test dialect instance.
        fn render_current_timestamp(&self) -> String {
            "NOW()".to_string()
        }
    }

    impl ExpressionRenderer for TestDialect {}
    impl DdlRenderer for TestDialect {}
    impl DmlRenderer for TestDialect {}
    impl ProcedureRenderer for TestDialect {}
    impl FormulaRenderer for TestDialect {}
    impl TaskRenderer for TestDialect {}
    impl ReplicationRenderer for TestDialect {}
    impl StorageRenderer for TestDialect {}

    impl DialectCapabilities for TestDialect {
        /// State this test dialect's upsert shape.
        /// Parameters:
        /// - self: Test dialect instance.
        fn merge_shape(&self) -> razeri_plugin_contract::MergeShape {
            razeri_plugin_contract::MergeShape::Merge(
                razeri_plugin_contract::MergeRestrictions::none(),
            )
        }
        /// Indicate test dialect support for identity columns.
        /// Parameters:
        /// - self: Test dialect instance.
        fn supports_identity(&self) -> bool {
            true
        }
        /// Indicate test dialect support for sequences.
        /// Parameters:
        /// - self: Test dialect instance.
        fn supports_sequences(&self) -> bool {
            true
        }
        /// Indicate test dialect support for stored procedures.
        /// Parameters:
        /// - self: Test dialect instance.
        fn supports_stored_procedures(&self) -> bool {
            true
        }
    }

    impl PlatformDialect for TestDialect {
        /// Return static dialect metadata for the test dialect.
        /// Parameters:
        /// - self: Test dialect instance.
        fn info(&self) -> DialectInfo {
            DialectInfo {
                name: "test",
                display_name: "Test DB",
                aliases: &[],
                dialect_family: DialectFamily::PostgreSql,
                family: "PostgreSQL",
                is_cloud_native: false,
                is_olap: false,
                is_postgres_compatible: false,
                versions: &[],
                deploy_script: None,
            }
        }
    }

    struct TestStorageFactory;
    #[async_trait]
    impl StorageProviderFactory for TestStorageFactory {
        /// Return canonical name for test storage provider.
        /// Parameters:
        /// - self: Test storage factory instance.
        fn name(&self) -> &'static str {
            "test-storage"
        }
        /// Return display name for test storage provider.
        /// Parameters:
        /// - self: Test storage factory instance.
        fn display_name(&self) -> &'static str {
            "Test Storage"
        }
        /// Return known platform mapping for test storage provider.
        /// Parameters:
        /// - self: Test storage factory instance.
        fn known_platform(&self) -> Option<StoragePlatform> {
            None
        }
        async fn create(
            &self,
            _config: &HashMap<String, String>,
        ) -> Result<Box<dyn crate::storage::StorageOps>, crate::error::StorageError> {
            unimplemented!("test only")
        }
        /// Validate test storage config payload.
        /// Parameters:
        /// - self: Test storage factory instance.
        /// - _config: Storage config payload (unused in test double).
        fn validate_config(&self, _config: &HashMap<String, String>) -> Vec<String> {
            vec![]
        }
        /// Return required test storage configuration keys.
        /// Parameters:
        /// - self: Test storage factory instance.
        fn required_config_keys(&self) -> Vec<&str> {
            vec![]
        }
    }

    struct TestLlmFactory;
    impl LlmClientFactory for TestLlmFactory {
        /// Return canonical name for test LLM provider.
        /// Parameters:
        /// - self: Test LLM factory instance.
        fn name(&self) -> &'static str {
            "test-llm"
        }
        /// Return display name for test LLM provider.
        /// Parameters:
        /// - self: Test LLM factory instance.
        fn display_name(&self) -> &'static str {
            "Test LLM"
        }
        /// Construct a test LLM client instance.
        /// Parameters:
        /// - self: Test LLM factory instance.
        /// - _config: Provider config payload (unused in test double).
        fn create(
            &self,
            _config: &HashMap<String, String>,
        ) -> Result<Arc<dyn LlmClient>, LlmError> {
            Ok(Arc::new(TestLlmClient))
        }
        /// Validate test LLM config payload.
        /// Parameters:
        /// - self: Test LLM factory instance.
        /// - _config: Provider config payload (unused in test double).
        fn validate_config(&self, _config: &HashMap<String, String>) -> Vec<String> {
            vec![]
        }
        /// Return required test LLM configuration keys.
        /// Parameters:
        /// - self: Test LLM factory instance.
        fn required_config_keys(&self) -> Vec<&str> {
            vec![]
        }
    }

    struct TestLlmClient;
    #[async_trait]
    impl LlmClient for TestLlmClient {
        async fn chat(
            &self,
            _messages: &[Message],
            _model: Option<&str>,
            _tools: Option<Vec<ToolDefinition>>,
        ) -> Result<ChatResponse, LlmError> {
            Ok(ChatResponse { content: "ok".into(), model: "test".into(), usage: None })
        }
        async fn chat_json(
            &self,
            _messages: &[Message],
            _model: Option<&str>,
            _tools: Option<Vec<ToolDefinition>>,
        ) -> Result<serde_json::Value, LlmError> {
            Ok(serde_json::json!({}))
        }
        async fn list_models(&self) -> Result<Vec<ModelInfo>, LlmError> {
            Ok(vec![])
        }
        async fn health_check(&self) -> Result<bool, LlmError> {
            Ok(true)
        }
    }

    struct TestModelAdapter;
    impl LlmModelAdapter for TestModelAdapter {
        /// Return canonical identifier for the test model adapter.
        /// Parameters:
        /// - self: Test model adapter instance.
        fn model_id(&self) -> &'static str {
            "test-model"
        }
        /// Return owning provider name for the test model adapter.
        /// Parameters:
        /// - self: Test model adapter instance.
        fn provider_name(&self) -> &'static str {
            "test-llm"
        }
        /// Return display name for the test model adapter.
        /// Parameters:
        /// - self: Test model adapter instance.
        fn display_name(&self) -> &'static str {
            "Test Model"
        }
        /// Return static capabilities for the test model adapter.
        /// Parameters:
        /// - self: Test model adapter instance.
        fn capabilities(&self) -> ModelCapabilities {
            ModelCapabilities {
                max_context_tokens: 4096,
                supports_json_mode: true,
                supports_tools: false,
                supports_streaming: false,
            }
        }
    }

    struct TestLanguageFactory;
    impl LanguageRendererFactory for TestLanguageFactory {
        /// Return canonical language key for the test language factory.
        /// Parameters:
        /// - self: Test language factory instance.
        fn language(&self) -> &'static str {
            "test-lang"
        }
        /// Return display name for the test language factory.
        /// Parameters:
        /// - self: Test language factory instance.
        fn display_name(&self) -> &'static str {
            "Test Language"
        }
        /// Construct a language renderer in test contexts.
        /// Parameters:
        /// - self: Test language factory instance.
        /// - _config: Language renderer config payload (unused in test double).
        fn create(
            &self,
            _config: &HashMap<String, String>,
        ) -> Result<Arc<dyn crate::language::LanguageRenderer>, LanguageError> {
            unimplemented!("test only")
        }
    }

    struct TestEventSink;
    #[async_trait]
    impl crate::event::EventSink for TestEventSink {
        /// Return canonical sink name for the test event sink.
        /// Parameters:
        /// - self: Test event sink instance.
        fn name(&self) -> &'static str {
            "test-sink"
        }
        async fn on_event(&self, _event: &RazeriEvent) -> Result<(), EventSinkError> {
            Ok(())
        }
        async fn flush(&self) -> Result<(), EventSinkError> {
            Ok(())
        }
    }

    // ── Tests ─────────────────────────────────────────────────────

    /// Verify builder produces a registry populated across all plugin sub-registries.
    /// Parameters:
    /// - none: Uses in-test test-double plugin registrations.
    #[test]
    fn builder_creates_registry_with_all_sub_registries() {
        let registry = PluginRegistryBuilder::new()
            .with_dialect("postgres", Arc::new(TestDialect))
            .with_storage_extension("test".into(), Arc::new(TestStorageFactory))
            .with_llm("test-llm".into(), Arc::new(TestLlmFactory))
            .with_model(Arc::new(TestModelAdapter))
            .with_language("test-lang".into(), Arc::new(TestLanguageFactory))
            .with_event_sink(Arc::new(TestEventSink))
            .build();

        assert!(registry.dialects.get_by_name("postgres").is_some());
        assert!(registry.llm.get("test-llm").is_some());
        assert!(registry.models.get("test-llm", "test-model").is_some());
        assert!(registry.language.get("test-lang").is_some());
        assert!(!registry.events.is_empty());
    }

    /// Verify fluent builder chaining remains ergonomic and type-safe.
    /// Parameters:
    /// - none: Uses in-test chained builder calls across plugin categories.
    #[test]
    fn builder_chaining_is_ergonomic() {
        // Verify fluent API compiles and works without clone/move issues
        let _registry = PluginRegistryBuilder::new()
            .with_dialect("postgres", Arc::new(TestDialect))
            .with_dialect("snowflake", Arc::new(TestDialect))
            .with_llm("a".into(), Arc::new(TestLlmFactory))
            .with_llm("b".into(), Arc::new(TestLlmFactory))
            .with_event_sink(Arc::new(TestEventSink))
            .with_event_sink(Arc::new(TestEventSink))
            .build();
    }

    /// Verify builder supports mixed known-platform and extension registrations.
    /// Parameters:
    /// - none: Uses in-test mixed dialect/storage registration fixture.
    #[test]
    fn builder_with_mixed_known_and_extension() {
        let registry = PluginRegistryBuilder::new()
            .with_dialect("postgres", Arc::new(TestDialect))
            .with_dialect("teradata", Arc::new(TestDialect))
            .with_storage(StoragePlatform::S3, Arc::new(TestStorageFactory))
            .with_storage_extension("minio".into(), Arc::new(TestStorageFactory))
            .build();

        assert!(registry.dialects.get_by_name("postgres").is_some());
        assert!(registry.dialects.get_by_name("teradata").is_some());
    }

    /// Verify auto-discovery finds exactly the dialects this test binary
    /// submitted.
    /// Parameters:
    /// - none: Uses the one dialect the conformance fixtures submit.
    #[test]
    fn builder_with_auto_discovered_finds_inventory_entries() {
        // Two dialects reach this binary's registry: one submitted directly —
        // the conformance report is graded against a registered plugin, so it
        // needs one registered — and one exported with `export_plugin!`.
        let registry = PluginRegistryBuilder::new().with_auto_discovered().build();
        let mut names = registry.dialects.registered_names();
        names.sort();
        assert_eq!(names, vec!["linked_by_export".to_owned(), "outsidedb".to_owned()]);
    }

    /// Verify manual plugin-loaded event recording is captured in the event registry.
    /// Parameters:
    /// - none: Uses in-test direct event-recording fixture.
    #[test]
    fn manual_registration_records_plugin_loaded_events() {
        let builder = PluginRegistryBuilder::new()
            .with_dialect("postgres", Arc::new(TestDialect))
            .with_llm("test-llm".into(), Arc::new(TestLlmFactory));

        // record_plugin_loaded is only called from auto-discovery and dynamic loading,
        // so manual registration does not emit events.
        // We test the method directly.
        builder.record_plugin_loaded("TestDialect", "dialect", "manual");
        builder.record_plugin_loaded("TestLlm", "llm", "manual");

        let registry = builder.build();
        let events = registry.events.events();
        assert_eq!(events.len(), 2);

        assert_eq!(events[0].category(), crate::event::EventCategory::Plugin);
        assert_eq!(events[0].summary().title, "Plugin loaded");
        assert!(events[0].summary().detail.contains("dialect"));

        assert_eq!(events[1].category(), crate::event::EventCategory::Plugin);
        assert!(events[1].summary().detail.contains("llm"));
    }

    /// Verify auto-discovery registers built-in sinks and emits load events.
    /// Parameters:
    /// - none: Uses in-test auto-discovery run against built-in inventory entries.
    #[test]
    fn auto_discovery_registers_built_in_sinks() {
        let registry = PluginRegistryBuilder::new().with_auto_discovered().build();
        // The jsonl and webhook placeholders register via inventory::submit!;
        // the console sink registers only when a host asks for it
        // (`fr-1019-90`).
        assert!(
            registry.events.len() >= 2,
            "Expected at least 2 built-in sinks, found {}",
            registry.events.len()
        );
        assert!(!registry.events.sink_names().iter().any(|name| name == "stdout"));

        // Verify auto-discovery emitted PluginLoaded events for sinks
        let events = registry.events.events();
        let sink_events: Vec<_> =
            events.iter().filter(|e| e.summary().detail.contains("event_sink")).collect();
        assert!(
            sink_events.len() >= 2,
            "Expected at least 2 event_sink load events, found {}",
            sink_events.len()
        );
    }

    /// A dialect that reaches the registry only through `export_plugin!`.
    struct Linked;

    impl SqlRenderer for Linked {
        fn render_data_type(&self, _dt: &DataType) -> String {
            "TEXT".to_string()
        }
        fn quote_identifier(&self, name: &str) -> String {
            format!("\"{name}\"")
        }
        fn qualify_name(&self, _schema: Option<&str>, name: &str) -> String {
            name.to_string()
        }
        fn render_current_timestamp(&self) -> String {
            "NOW()".to_string()
        }
    }
    impl ExpressionRenderer for Linked {}
    impl DdlRenderer for Linked {}
    impl DmlRenderer for Linked {}
    impl ProcedureRenderer for Linked {}
    impl FormulaRenderer for Linked {}
    impl TaskRenderer for Linked {}
    impl ReplicationRenderer for Linked {}
    impl StorageRenderer for Linked {}
    impl DialectCapabilities for Linked {}
    impl PlatformDialect for Linked {
        fn info(&self) -> DialectInfo {
            DialectInfo {
                name: "linked_by_export",
                display_name: "Linked by export",
                aliases: &[],
                dialect_family: DialectFamily::PostgreSql,
                family: "PostgreSQL",
                is_cloud_native: false,
                is_olap: false,
                is_postgres_compatible: false,
                versions: &[],
                deploy_script: None,
            }
        }
    }

    fn register_linked(builder: &mut PluginRegistryBuilder) {
        builder.register_dialect(Arc::new(Linked));
    }

    crate::export_plugin!(register_linked);

    /// **A crate exported with the macro and linked in is found at start-up**,
    /// by the builder and by the dialect registry every by-name lookup reads,
    /// with no other line — the same way razeri's own dialects are found.
    #[test]
    fn a_plugin_exported_with_the_macro_and_linked_in_is_discovered() {
        let registry = PluginRegistryBuilder::new().with_auto_discovered().build();
        assert!(
            registry.dialects.get_by_name("linked_by_export").is_some(),
            "the builder did not find the linked plugin: {:?}",
            registry.dialects.registered_names()
        );
        assert!(
            PlatformRegistry::with_auto_discovered().get_by_name("linked_by_export").is_some(),
            "the dialect registry did not find the linked plugin"
        );
    }

    /// **The macro exports the build this crate was made with.**
    #[test]
    fn the_macro_exports_this_build() {
        // SAFETY: the pointer is to the static record the macro exported.
        let exported = unsafe { crate::dynamic::read_declaration(razeri_plugin_build()) };
        assert_eq!(exported, Ok(crate::dynamic::BuildDeclaration::this_build()));
    }
}