heliosdb-proxy 0.4.2

HeliosProxy - Intelligent connection router and failover manager for HeliosDB and PostgreSQL
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
//! Schema-Aware Router
//!
//! Routes queries based on schema semantics and workload characteristics.

use std::sync::Arc;

use super::{
    NodeInfo, SyncMode, SchemaRoutingConfig,
    registry::{SchemaRegistry, NodeCapabilities, DataTemperature, WorkloadType, AccessPattern},
    analyzer::{QueryAnalyzer, QueryAnalysis},
};

/// Schema-aware query router
#[derive(Debug)]
pub struct SchemaAwareRouter {
    /// Configuration
    config: SchemaRoutingConfig,
    /// Schema registry
    schema: Arc<SchemaRegistry>,
    /// Query analyzer
    analyzer: QueryAnalyzer,
    /// Available nodes
    nodes: Vec<NodeInfo>,
    /// AI workload detector
    ai_detector: AIWorkloadDetector,
    /// RAG router
    rag_router: RAGRouter,
}

impl SchemaAwareRouter {
    /// Create a new schema-aware router
    pub fn new(config: SchemaRoutingConfig, schema: Arc<SchemaRegistry>) -> Self {
        Self {
            analyzer: QueryAnalyzer::new(schema.clone()),
            schema,
            config,
            nodes: Vec::new(),
            ai_detector: AIWorkloadDetector::new(),
            rag_router: RAGRouter::new(),
        }
    }

    /// Add a node to the router
    pub fn add_node(&mut self, node: NodeInfo) {
        self.nodes.push(node);
    }

    /// Remove a node from the router
    pub fn remove_node(&mut self, node_id: &str) {
        self.nodes.retain(|n| n.id != node_id);
    }

    /// Update node status
    pub fn update_node(&mut self, node_id: &str, load: f64, latency_ms: u64) {
        if let Some(node) = self.nodes.iter_mut().find(|n| n.id == node_id) {
            node.current_load = load;
            node.current_latency_ms = latency_ms;
        }
    }

    /// Route a query
    pub fn route(&self, query: &str) -> RoutingDecision {
        if !self.config.enabled {
            return RoutingDecision::default_routing();
        }

        let analysis = self.analyzer.analyze(query);

        // 1. Check for AI workload patterns
        if let Some(ai_workload) = self.ai_detector.detect(query) {
            let preference = self.ai_detector.get_optimal_routing(ai_workload);
            return self.apply_preference(preference, &analysis);
        }

        // 2. Determine required capabilities
        let required_caps = self.get_required_capabilities(&analysis);

        // 3. Filter eligible nodes
        let eligible = self.filter_by_capabilities(&required_caps);

        // 4. Check sharding
        if let Some(shard_routing) = self.try_shard_routing(&analysis) {
            return shard_routing;
        }

        // 5. Route based on workload type
        match analysis.workload_type {
            WorkloadType::OLTP => self.route_oltp(&eligible, &analysis),
            WorkloadType::OLAP => self.route_olap(&eligible, &analysis),
            WorkloadType::Vector => self.route_vector(&eligible, &analysis),
            WorkloadType::HTAP | WorkloadType::Mixed => self.route_mixed(&eligible, &analysis),
        }
    }

    /// Route with branch context
    pub fn route_with_branch(&self, query: &str, branch: &str) -> RoutingDecision {
        let analysis = self.analyzer.analyze(query);

        // Get nodes that have the branch data
        let branch_nodes = self.schema.get_branch_locations(branch);

        // Filter by query requirements
        let required_caps = self.get_required_capabilities(&analysis);
        let eligible = self.filter_by_capabilities(&required_caps);

        // Intersection with branch nodes
        let available: Vec<_> = eligible
            .iter()
            .filter(|n| branch_nodes.contains(&n.id))
            .cloned()
            .collect();

        if available.is_empty() {
            // Branch not replicated to eligible nodes
            return RoutingDecision {
                target: RouteTarget::Primary,
                reason: RoutingReason::BranchNotAvailable,
                branch: Some(branch.to_string()),
                ..Default::default()
            };
        }

        self.select_best(&available, &analysis)
    }

    /// Route for time-travel query
    pub fn route_time_travel(&self, query: &str, age_days: i64) -> RoutingDecision {
        let analysis = self.analyzer.analyze(query);

        // Recent data on hot nodes
        if age_days < 7 {
            return self.route_to_temperature_nodes(DataTemperature::Hot, &analysis);
        }

        // Older data on warm nodes
        if age_days < 30 {
            return self.route_to_temperature_nodes(DataTemperature::Warm, &analysis);
        }

        // Historical data on cold/archive nodes
        self.route_to_temperature_nodes(DataTemperature::Cold, &analysis)
    }

    /// Route RAG query
    pub fn route_rag(&self, stage: RAGStage, query: &str) -> RoutingDecision {
        let analysis = self.analyzer.analyze(query);
        self.rag_router.route_rag_query(stage, &analysis, &self.nodes)
    }

    /// Get required capabilities based on query analysis
    fn get_required_capabilities(&self, analysis: &QueryAnalysis) -> NodeCapabilities {
        let mut caps = NodeCapabilities::default();

        // Vector queries need vector-capable nodes
        if analysis.access_patterns.contains(&AccessPattern::VectorSearch) {
            caps.vector_search = true;
            caps.gpu_acceleration = true; // Prefer GPU nodes
        }

        // OLAP queries prefer columnar storage
        if analysis.workload_type == WorkloadType::OLAP {
            caps.columnar_storage = true;
        }

        // Hot tables need in-memory nodes
        for table in &analysis.tables {
            if let Some(schema) = &table.schema {
                if schema.temperature == DataTemperature::Hot {
                    caps.in_memory = true;
                }
            }
        }

        caps
    }

    /// Filter nodes by capabilities
    fn filter_by_capabilities(&self, required: &NodeCapabilities) -> Vec<NodeInfo> {
        self.nodes
            .iter()
            .filter(|n| n.capabilities.satisfies(required) || !required.has_requirements())
            .cloned()
            .collect()
    }

    /// Try to route to specific shard
    fn try_shard_routing(&self, analysis: &QueryAnalysis) -> Option<RoutingDecision> {
        for table in &analysis.tables {
            if let Some(schema) = &table.schema {
                if let Some(shard_key) = &schema.shard_key {
                    if let Some(shard_value) = analysis.shard_keys.get(shard_key) {
                        let value = match shard_value {
                            super::analyzer::ShardKeyValue::Single(v) => v.clone(),
                            super::analyzer::ShardKeyValue::Multiple(v) => {
                                // Multiple values = scatter-gather
                                return Some(RoutingDecision {
                                    target: RouteTarget::ScatterGather,
                                    shards: v.iter().filter_map(|val| {
                                        self.schema.get_shard(shard_key, val)
                                    }).collect(),
                                    reason: RoutingReason::ShardKey,
                                    ..Default::default()
                                });
                            }
                        };

                        if let Some(shard) = self.schema.get_shard(shard_key, &value) {
                            return Some(RoutingDecision {
                                target: RouteTarget::Shard(shard),
                                reason: RoutingReason::ShardKey,
                                ..Default::default()
                            });
                        }
                    }
                }
            }
        }
        None
    }

    /// Route OLTP workload
    fn route_oltp(&self, nodes: &[NodeInfo], analysis: &QueryAnalysis) -> RoutingDecision {
        // Write queries must go to primary
        if !analysis.is_read_only {
            return RoutingDecision {
                target: RouteTarget::Primary,
                reason: RoutingReason::WriteQuery,
                ..Default::default()
            };
        }

        // OLTP: Low latency, prefer primary or sync standbys
        let mut preferred: Vec<_> = nodes
            .iter()
            .filter(|n| n.sync_mode == SyncMode::Sync || n.is_primary)
            .cloned()
            .collect();

        preferred.sort_by_key(|n| n.current_latency_ms);

        if let Some(node) = preferred.first() {
            RoutingDecision {
                target: RouteTarget::Node(node.id.clone()),
                reason: RoutingReason::LowLatency,
                node_info: Some(node.clone()),
                ..Default::default()
            }
        } else {
            RoutingDecision::default_routing()
        }
    }

    /// Route OLAP workload
    fn route_olap(&self, nodes: &[NodeInfo], _analysis: &QueryAnalysis) -> RoutingDecision {
        // OLAP: Throughput over latency, prefer async standbys with columnar storage
        let mut preferred: Vec<_> = nodes
            .iter()
            .filter(|n| n.capabilities.columnar_storage)
            .cloned()
            .collect();

        if preferred.is_empty() {
            // Fall back to any async standby
            preferred = nodes
                .iter()
                .filter(|n| n.sync_mode == SyncMode::Async)
                .cloned()
                .collect();
        }

        preferred.sort_by(|a, b| a.current_load.partial_cmp(&b.current_load).unwrap());

        if let Some(node) = preferred.first() {
            RoutingDecision {
                target: RouteTarget::Node(node.id.clone()),
                reason: RoutingReason::ColumnarStorage,
                node_info: Some(node.clone()),
                ..Default::default()
            }
        } else {
            RoutingDecision::default_routing()
        }
    }

    /// Route vector workload
    fn route_vector(&self, nodes: &[NodeInfo], _analysis: &QueryAnalysis) -> RoutingDecision {
        // Vector: Need vector-capable nodes, prefer GPU
        let mut vector_nodes: Vec<_> = nodes
            .iter()
            .filter(|n| n.capabilities.vector_search)
            .cloned()
            .collect();

        // Sort by: GPU first, then lower load
        vector_nodes.sort_by(|a, b| {
            b.capabilities.gpu_acceleration
                .cmp(&a.capabilities.gpu_acceleration)
                .then_with(|| a.current_load.partial_cmp(&b.current_load).unwrap())
        });

        if let Some(node) = vector_nodes.first() {
            RoutingDecision {
                target: RouteTarget::Node(node.id.clone()),
                reason: RoutingReason::VectorCapable,
                node_info: Some(node.clone()),
                ..Default::default()
            }
        } else {
            // No vector-capable nodes, fall back to primary
            RoutingDecision {
                target: RouteTarget::Primary,
                reason: RoutingReason::NoVectorNodes,
                ..Default::default()
            }
        }
    }

    /// Route mixed workload
    fn route_mixed(&self, nodes: &[NodeInfo], analysis: &QueryAnalysis) -> RoutingDecision {
        // Mixed: Balance between latency and throughput
        if !analysis.is_read_only {
            return RoutingDecision {
                target: RouteTarget::Primary,
                reason: RoutingReason::WriteQuery,
                ..Default::default()
            };
        }

        // Sort by weighted score: latency + load
        let mut scored: Vec<_> = nodes
            .iter()
            .map(|n| {
                let score = (n.current_latency_ms as f64) + (n.current_load * 100.0);
                (n, score)
            })
            .collect();

        scored.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());

        if let Some((node, _)) = scored.first() {
            RoutingDecision {
                target: RouteTarget::Node(node.id.clone()),
                reason: RoutingReason::LowestScore,
                node_info: Some((*node).clone()),
                ..Default::default()
            }
        } else {
            RoutingDecision::default_routing()
        }
    }

    /// Route to nodes with specific temperature
    fn route_to_temperature_nodes(&self, temp: DataTemperature, analysis: &QueryAnalysis) -> RoutingDecision {
        // Find nodes that host tables with matching temperature
        let matching_nodes: Vec<_> = self.nodes
            .iter()
            .filter(|n| {
                match temp {
                    DataTemperature::Hot => n.capabilities.in_memory,
                    DataTemperature::Warm => !n.capabilities.in_memory && !self.is_cold_storage(n),
                    DataTemperature::Cold | DataTemperature::Frozen => self.is_cold_storage(n),
                }
            })
            .cloned()
            .collect();

        if matching_nodes.is_empty() {
            return self.route_mixed(&self.nodes, analysis);
        }

        self.select_best(&matching_nodes, analysis)
    }

    /// Check if node is cold storage
    fn is_cold_storage(&self, node: &NodeInfo) -> bool {
        // Heuristic: cold storage nodes have no in-memory capability
        // and are not primary/sync
        !node.capabilities.in_memory && node.sync_mode == SyncMode::Async && !node.is_primary
    }

    /// Select best node from candidates
    fn select_best(&self, nodes: &[NodeInfo], analysis: &QueryAnalysis) -> RoutingDecision {
        if nodes.is_empty() {
            return RoutingDecision::default_routing();
        }

        // Sort by latency for read queries, load for analytics
        let mut sorted = nodes.to_vec();
        if analysis.workload_type == WorkloadType::OLAP {
            sorted.sort_by(|a, b| a.current_load.partial_cmp(&b.current_load).unwrap());
        } else {
            sorted.sort_by_key(|n| n.current_latency_ms);
        }

        let node = &sorted[0];
        RoutingDecision {
            target: RouteTarget::Node(node.id.clone()),
            reason: RoutingReason::BestCandidate,
            node_info: Some(node.clone()),
            ..Default::default()
        }
    }

    /// Apply routing preference
    fn apply_preference(&self, preference: RoutingPreference, analysis: &QueryAnalysis) -> RoutingDecision {
        match preference {
            RoutingPreference::VectorNodes { prefer_gpu } => {
                let nodes: Vec<_> = self.nodes
                    .iter()
                    .filter(|n| n.capabilities.vector_search)
                    .filter(|n| !prefer_gpu || n.capabilities.gpu_acceleration)
                    .cloned()
                    .collect();
                self.select_best(&nodes, analysis)
            }
            RoutingPreference::LowLatency { max_lag_ms } => {
                let nodes: Vec<_> = self.nodes
                    .iter()
                    .filter(|n| n.current_latency_ms <= max_lag_ms)
                    .cloned()
                    .collect();
                self.select_best(&nodes, analysis)
            }
            RoutingPreference::HighThroughput => {
                let nodes: Vec<_> = self.nodes
                    .iter()
                    .filter(|n| n.sync_mode == SyncMode::Async)
                    .cloned()
                    .collect();
                self.select_best(&nodes, analysis)
            }
            RoutingPreference::Primary => {
                RoutingDecision {
                    target: RouteTarget::Primary,
                    reason: RoutingReason::AIWorkload,
                    ..Default::default()
                }
            }
        }
    }
}

impl NodeCapabilities {
    /// Check if there are any requirements
    fn has_requirements(&self) -> bool {
        self.vector_search || self.gpu_acceleration || self.columnar_storage
            || self.in_memory || self.content_addressed
    }
}

/// Routing decision
#[derive(Debug, Clone, Default)]
pub struct RoutingDecision {
    /// Target for routing
    pub target: RouteTarget,
    /// Reason for decision
    pub reason: RoutingReason,
    /// Target shards (for scatter-gather)
    pub shards: Vec<u32>,
    /// Branch context
    pub branch: Option<String>,
    /// Selected node info
    pub node_info: Option<NodeInfo>,
}

impl RoutingDecision {
    /// Create a shard routing decision
    pub fn shard(shard_id: u32) -> Self {
        Self {
            target: RouteTarget::Shard(shard_id),
            reason: RoutingReason::ShardKey,
            ..Default::default()
        }
    }

    /// Create a single node routing decision
    pub fn single(node: NodeInfo) -> Self {
        Self {
            target: RouteTarget::Node(node.id.clone()),
            reason: RoutingReason::BestCandidate,
            node_info: Some(node),
            ..Default::default()
        }
    }

    /// Create default routing (to primary)
    pub fn default_routing() -> Self {
        Self {
            target: RouteTarget::Primary,
            reason: RoutingReason::Default,
            ..Default::default()
        }
    }

    /// Check if routing to primary
    pub fn is_primary(&self) -> bool {
        matches!(self.target, RouteTarget::Primary)
    }

    /// Check if scatter-gather needed
    pub fn is_scatter_gather(&self) -> bool {
        matches!(self.target, RouteTarget::ScatterGather)
    }
}

/// Route target
#[derive(Debug, Clone, Default)]
pub enum RouteTarget {
    /// Route to primary
    #[default]
    Primary,
    /// Route to specific node
    Node(String),
    /// Route to specific shard
    Shard(u32),
    /// Scatter-gather across shards
    ScatterGather,
}

/// Routing reason
#[derive(Debug, Clone, Default)]
pub enum RoutingReason {
    /// Default routing
    #[default]
    Default,
    /// Write query must go to primary
    WriteQuery,
    /// Shard key present in query
    ShardKey,
    /// Lowest latency node
    LowLatency,
    /// Node with columnar storage
    ColumnarStorage,
    /// Vector-capable node
    VectorCapable,
    /// No vector-capable nodes available
    NoVectorNodes,
    /// Branch not available on eligible nodes
    BranchNotAvailable,
    /// Best candidate from scoring
    BestCandidate,
    /// Lowest combined score
    LowestScore,
    /// AI workload routing
    AIWorkload,
}

/// Routing preference for AI workloads
#[derive(Debug, Clone)]
pub enum RoutingPreference {
    /// Prefer vector-capable nodes
    VectorNodes { prefer_gpu: bool },
    /// Prefer low-latency nodes
    LowLatency { max_lag_ms: u64 },
    /// Prefer high-throughput nodes
    HighThroughput,
    /// Must route to primary
    Primary,
}

/// AI workload type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AIWorkloadType {
    /// Embedding retrieval (vector search)
    EmbeddingRetrieval,
    /// Context/conversation lookup
    ContextLookup,
    /// Knowledge base query
    KnowledgeBase,
    /// Tool execution (writes)
    ToolExecution,
}

/// AI workload detector
#[derive(Debug, Default)]
pub struct AIWorkloadDetector {
    /// Patterns for detection
    patterns: Vec<AIPattern>,
}

#[derive(Debug)]
struct AIPattern {
    keyword: String,
    workload_type: AIWorkloadType,
}

impl AIWorkloadDetector {
    /// Create a new detector
    pub fn new() -> Self {
        Self {
            patterns: vec![
                AIPattern { keyword: "<->".to_string(), workload_type: AIWorkloadType::EmbeddingRetrieval },
                AIPattern { keyword: "VECTOR".to_string(), workload_type: AIWorkloadType::EmbeddingRetrieval },
                AIPattern { keyword: "EMBEDDING".to_string(), workload_type: AIWorkloadType::EmbeddingRetrieval },
                AIPattern { keyword: "CONVERSATION".to_string(), workload_type: AIWorkloadType::ContextLookup },
                AIPattern { keyword: "TURNS".to_string(), workload_type: AIWorkloadType::ContextLookup },
                AIPattern { keyword: "DOCUMENTS".to_string(), workload_type: AIWorkloadType::KnowledgeBase },
                AIPattern { keyword: "CHUNKS".to_string(), workload_type: AIWorkloadType::KnowledgeBase },
                AIPattern { keyword: "TOOL_RESULTS".to_string(), workload_type: AIWorkloadType::ToolExecution },
                AIPattern { keyword: "ACTIONS".to_string(), workload_type: AIWorkloadType::ToolExecution },
            ],
        }
    }

    /// Detect AI workload type
    pub fn detect(&self, query: &str) -> Option<AIWorkloadType> {
        let upper = query.to_uppercase();

        for pattern in &self.patterns {
            if upper.contains(&pattern.keyword) {
                return Some(pattern.workload_type);
            }
        }

        None
    }

    /// Get optimal routing for AI workload
    pub fn get_optimal_routing(&self, workload: AIWorkloadType) -> RoutingPreference {
        match workload {
            AIWorkloadType::EmbeddingRetrieval => {
                RoutingPreference::VectorNodes { prefer_gpu: true }
            }
            AIWorkloadType::ContextLookup => {
                RoutingPreference::LowLatency { max_lag_ms: 100 }
            }
            AIWorkloadType::KnowledgeBase => {
                RoutingPreference::HighThroughput
            }
            AIWorkloadType::ToolExecution => {
                RoutingPreference::Primary
            }
        }
    }
}

/// RAG stage
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RAGStage {
    /// Retrieval stage (vector search)
    Retrieval,
    /// Fetch stage (document lookup)
    Fetch,
    /// Rerank stage
    Rerank,
    /// Generation stage
    Generate,
}

/// RAG router
#[derive(Debug, Default)]
pub struct RAGRouter {}

impl RAGRouter {
    /// Create a new RAG router
    pub fn new() -> Self {
        Self {}
    }

    /// Route RAG query based on stage
    pub fn route_rag_query(&self, stage: RAGStage, analysis: &QueryAnalysis, nodes: &[NodeInfo]) -> RoutingDecision {
        match stage {
            RAGStage::Retrieval => {
                // Vector search on embeddings
                let vector_nodes: Vec<_> = nodes
                    .iter()
                    .filter(|n| n.capabilities.vector_search)
                    .cloned()
                    .collect();

                if let Some(node) = vector_nodes.first() {
                    RoutingDecision::single(node.clone())
                } else {
                    RoutingDecision::default_routing()
                }
            }
            RAGStage::Fetch => {
                // Bulk fetch - high throughput
                let throughput_nodes: Vec<_> = nodes
                    .iter()
                    .filter(|n| n.sync_mode == SyncMode::Async)
                    .cloned()
                    .collect();

                if let Some(node) = throughput_nodes.first() {
                    RoutingDecision::single(node.clone())
                } else {
                    RoutingDecision::default_routing()
                }
            }
            RAGStage::Rerank => {
                // Light computation - lowest latency
                let mut sorted = nodes.to_vec();
                sorted.sort_by_key(|n| n.current_latency_ms);

                if let Some(node) = sorted.first() {
                    RoutingDecision::single(node.clone())
                } else {
                    RoutingDecision::default_routing()
                }
            }
            RAGStage::Generate => {
                // May write to cache - check if write
                if !analysis.is_read_only {
                    RoutingDecision::default_routing()
                } else {
                    let mut sorted = nodes.to_vec();
                    sorted.sort_by_key(|n| n.current_latency_ms);

                    if let Some(node) = sorted.first() {
                        RoutingDecision::single(node.clone())
                    } else {
                        RoutingDecision::default_routing()
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema_routing::registry::TableSchema;

    fn create_test_setup() -> SchemaAwareRouter {
        let registry = Arc::new(SchemaRegistry::new());

        registry.register_table(
            TableSchema::new("users")
                .with_workload(WorkloadType::OLTP)
                .with_access_pattern(AccessPattern::PointLookup)
                .with_primary_key(vec!["id".to_string()])
        );

        registry.register_table(
            TableSchema::new("events")
                .with_workload(WorkloadType::OLAP)
                .with_temperature(DataTemperature::Cold)
        );

        registry.register_table(
            TableSchema::new("embeddings")
                .with_workload(WorkloadType::Vector)
        );

        let config = SchemaRoutingConfig::default();
        let mut router = SchemaAwareRouter::new(config, registry);

        // Add test nodes
        router.add_node(NodeInfo::new("primary", "primary").as_primary());
        router.add_node(NodeInfo::new("standby-sync", "standby-sync")
            .with_sync_mode(SyncMode::Sync));
        router.add_node(NodeInfo::new("standby-async", "standby-async")
            .with_sync_mode(SyncMode::Async)
            .with_capabilities(NodeCapabilities::analytics_node()));
        router.add_node(NodeInfo::new("vector-node", "vector-node")
            .with_sync_mode(SyncMode::Async)
            .with_capabilities(NodeCapabilities::vector_node()));

        router
    }

    #[test]
    fn test_route_oltp_read() {
        let router = create_test_setup();
        let decision = router.route("SELECT * FROM users WHERE id = 1");

        assert!(!decision.is_primary() || matches!(decision.reason, RoutingReason::LowLatency));
    }

    #[test]
    fn test_route_write_to_primary() {
        let router = create_test_setup();
        let decision = router.route("INSERT INTO users (name) VALUES ('test')");

        assert!(decision.is_primary());
        assert!(matches!(decision.reason, RoutingReason::WriteQuery));
    }

    #[test]
    fn test_route_vector_query() {
        let router = create_test_setup();
        let decision = router.route("SELECT * FROM embeddings ORDER BY embedding <-> '[1,2,3]' LIMIT 10");

        assert!(matches!(decision.reason, RoutingReason::VectorCapable | RoutingReason::BestCandidate) || decision.is_primary());
    }

    #[test]
    fn test_route_olap_query() {
        let router = create_test_setup();
        let decision = router.route("SELECT COUNT(*), SUM(amount) FROM events GROUP BY date");

        // Should prefer columnar storage or async nodes
        assert!(!decision.is_primary() || matches!(decision.reason, RoutingReason::ColumnarStorage | RoutingReason::Default));
    }

    #[test]
    fn test_ai_workload_detection() {
        let detector = AIWorkloadDetector::new();

        let embedding = "SELECT * FROM embeddings ORDER BY vector <-> $1";
        let context = "SELECT * FROM conversation WHERE session_id = $1";
        let tool = "INSERT INTO tool_results (result) VALUES ($1)";

        assert_eq!(detector.detect(embedding), Some(AIWorkloadType::EmbeddingRetrieval));
        assert_eq!(detector.detect(context), Some(AIWorkloadType::ContextLookup));
        assert_eq!(detector.detect(tool), Some(AIWorkloadType::ToolExecution));
    }

    #[test]
    fn test_rag_routing() {
        let router = create_test_setup();

        let retrieval = router.route_rag(RAGStage::Retrieval, "SELECT embedding FROM docs");
        let fetch = router.route_rag(RAGStage::Fetch, "SELECT content FROM docs WHERE id IN (1,2,3)");

        // Retrieval should prefer vector nodes
        // Fetch should prefer high throughput
        assert!(retrieval.node_info.is_some() || retrieval.is_primary());
        assert!(fetch.node_info.is_some() || fetch.is_primary());
    }

    #[test]
    fn test_routing_decision_helpers() {
        let decision = RoutingDecision::shard(3);
        assert!(matches!(decision.target, RouteTarget::Shard(3)));

        let default = RoutingDecision::default_routing();
        assert!(default.is_primary());
    }
}