vecstore 1.0.0

The perfect vector database - 100/100 score, embeddable, high-performance, production-ready with RAG toolkit
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
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
//! HTTP/REST API server implementation using axum

use crate::store::VecStore;
use axum::{
    extract::{
        ws::{Message, WebSocket, WebSocketUpgrade},
        Path, State,
    },
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::{delete, get, post},
    Json, Router,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use tower_http::cors::CorsLayer;
use tower_http::trace::TraceLayer;

/// HTTP server wrapper around VecStore
#[derive(Clone)]
pub struct VecStoreHttpServer {
    store: Arc<RwLock<VecStore>>,
}

impl VecStoreHttpServer {
    /// Create a new HTTP server
    pub fn new(store: VecStore) -> Self {
        Self {
            store: Arc::new(RwLock::new(store)),
        }
    }

    /// Create a new HTTP server with shared store
    pub fn with_store(store: Arc<RwLock<VecStore>>) -> Self {
        Self { store }
    }

    /// Build the router
    pub fn router(&self) -> Router {
        Router::new()
            // Vector operations
            .route("/v1/upsert", post(upsert))
            .route("/v1/batch-upsert", post(batch_upsert))
            .route("/v1/batch-execute", post(batch_execute))
            .route("/v1/query", post(query))
            .route("/v1/query-explain", post(query_explain))
            .route("/v1/query-estimate", post(query_estimate))
            .route("/v1/delete/:id", delete(delete_vector))
            .route("/v1/soft-delete/:id", post(soft_delete))
            .route("/v1/restore/:id", post(restore))
            // Database operations
            .route("/v1/compact", post(compact))
            .route("/v1/stats", get(get_stats))
            // Snapshot operations
            .route("/v1/snapshots", post(create_snapshot))
            .route("/v1/snapshots", get(list_snapshots))
            .route("/v1/snapshots/:name/restore", post(restore_snapshot))
            // Hybrid search
            .route("/v1/hybrid-query", post(hybrid_query))
            // WebSocket streaming
            .route("/ws/query-stream", get(query_stream_ws))
            // Metrics
            .route("/metrics", get(metrics_endpoint))
            // Health check
            .route("/health", get(health_check))
            .route("/ready", get(ready_check))
            .with_state(self.clone())
            .layer(CorsLayer::permissive())
            .layer(TraceLayer::new_for_http())
    }

    /// Get the store reference
    pub fn store(&self) -> Arc<RwLock<VecStore>> {
        self.store.clone()
    }
}

// ============================================================================
// Request/Response types
// ============================================================================

#[derive(Debug, Serialize, Deserialize)]
pub struct UpsertRequest {
    pub id: String,
    pub vector: Vec<f32>,
    pub metadata: HashMap<String, serde_json::Value>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct UpsertResponse {
    pub success: bool,
    pub error: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct BatchUpsertRequest {
    pub records: Vec<UpsertRequest>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct BatchUpsertResponse {
    pub inserted: i32,
    pub updated: i32,
    pub errors: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct QueryRequest {
    pub vector: Vec<f32>,
    pub limit: i32,
    pub filter: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct QueryResult {
    pub id: String,
    pub score: f32,
    pub metadata: HashMap<String, serde_json::Value>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct QueryResponse {
    pub results: Vec<QueryResult>,
    pub stats: Option<QueryStats>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct QueryStats {
    pub total_candidates: i32,
    pub filtered_count: i32,
    pub duration_ms: f64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ExplainedQueryResult {
    pub id: String,
    pub score: f32,
    pub metadata: HashMap<String, serde_json::Value>,
    pub explanation: ExplanationDto,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ExplanationDto {
    pub raw_score: f32,
    pub distance_metric: String,
    pub filter_passed: bool,
    pub filter_details: Option<FilterEvaluationDto>,
    pub graph_stats: Option<GraphStatsDto>,
    pub rank: usize,
    pub explanation_text: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FilterEvaluationDto {
    pub filter_expr: String,
    pub matched_conditions: Vec<String>,
    pub failed_conditions: Vec<String>,
    pub passed: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct GraphStatsDto {
    pub distance_calculations: usize,
    pub nodes_visited: usize,
    pub found_at_layer: Option<usize>,
    pub hops_from_entry: Option<usize>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct QueryExplainResponse {
    pub results: Vec<ExplainedQueryResult>,
    pub stats: Option<QueryStats>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct DeleteResponse {
    pub found: bool,
    pub deleted: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SoftDeleteResponse {
    pub found: bool,
    pub marked_deleted: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct RestoreResponse {
    pub found: bool,
    pub restored: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct CompactResponse {
    pub removed_count: i32,
    pub freed_bytes: i64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct StatsResponse {
    pub total_vectors: i64,
    pub active_vectors: i64,
    pub deleted_vectors: i64,
    pub dimension: i32,
    pub storage_bytes: i64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SnapshotRequest {
    pub name: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SnapshotResponse {
    pub success: bool,
    pub path: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SnapshotInfo {
    pub name: String,
    pub created_at: i64,
    pub size_bytes: i64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ListSnapshotsResponse {
    pub snapshots: Vec<SnapshotInfo>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct RestoreSnapshotResponse {
    pub success: bool,
    pub vectors_restored: i64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct HybridQueryRequest {
    pub vector: Vec<f32>,
    pub text_query: String,
    pub limit: i32,
    pub alpha: Option<f32>,
    pub filter: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct HealthCheckResponse {
    pub status: String,
    pub message: Option<String>,
}

// Batch operations DTOs
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum BatchOperationDto {
    Upsert {
        id: String,
        vector: Vec<f32>,
        metadata: HashMap<String, serde_json::Value>,
    },
    Delete {
        id: String,
    },
    SoftDelete {
        id: String,
    },
    Restore {
        id: String,
    },
    UpdateMetadata {
        id: String,
        metadata: HashMap<String, serde_json::Value>,
    },
}

#[derive(Debug, Serialize, Deserialize)]
pub struct BatchExecuteRequest {
    pub operations: Vec<BatchOperationDto>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct BatchExecuteResponse {
    pub succeeded: usize,
    pub failed: usize,
    pub errors: Vec<BatchErrorDto>,
    pub duration_ms: f64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct BatchErrorDto {
    pub index: usize,
    pub operation: String,
    pub error: String,
}

// Query estimation DTOs
#[derive(Debug, Serialize, Deserialize)]
pub struct QueryEstimateRequest {
    pub vector: Vec<f32>,
    pub limit: i32,
    pub filter: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct QueryEstimateResponse {
    pub valid: bool,
    pub errors: Vec<String>,
    pub cost_estimate: f32,
    pub estimated_distance_calculations: usize,
    pub estimated_nodes_visited: usize,
    pub will_overfetch: bool,
    pub recommendations: Vec<String>,
    pub estimated_duration_ms: f32,
}

// ============================================================================
// Error handling
// ============================================================================

struct ApiError(anyhow::Error);

impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        let error_msg = format!("{}", self.0);
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(serde_json::json!({
                "error": error_msg
            })),
        )
            .into_response()
    }
}

impl<E> From<E> for ApiError
where
    E: Into<anyhow::Error>,
{
    fn from(err: E) -> Self {
        Self(err.into())
    }
}

// ============================================================================
// Handler functions
// ============================================================================

async fn upsert(
    State(server): State<VecStoreHttpServer>,
    Json(req): Json<UpsertRequest>,
) -> Result<Json<UpsertResponse>, ApiError> {
    let start = std::time::Instant::now();

    let metadata = crate::store::Metadata {
        fields: req.metadata,
    };

    let mut store = server.store.write().await;
    store.upsert(req.id, req.vector, metadata)?;

    let duration = start.elapsed().as_secs_f64();
    super::metrics::record_upsert(false);
    super::metrics::record_request("/v1/upsert", "POST", duration);

    Ok(Json(UpsertResponse {
        success: true,
        error: None,
    }))
}

async fn batch_upsert(
    State(server): State<VecStoreHttpServer>,
    Json(req): Json<BatchUpsertRequest>,
) -> Result<Json<BatchUpsertResponse>, ApiError> {
    let start = std::time::Instant::now();

    let mut store = server.store.write().await;
    let mut inserted = 0;
    let mut errors = Vec::new();

    for upsert_req in req.records {
        let metadata = crate::store::Metadata {
            fields: upsert_req.metadata,
        };

        match store.upsert(upsert_req.id.clone(), upsert_req.vector, metadata) {
            Ok(_) => inserted += 1,
            Err(e) => errors.push(format!("{}: {}", upsert_req.id, e)),
        }
    }

    let duration = start.elapsed().as_secs_f64();
    super::metrics::record_upsert(true);
    super::metrics::record_request("/v1/batch-upsert", "POST", duration);

    Ok(Json(BatchUpsertResponse {
        inserted,
        updated: 0,
        errors,
    }))
}

async fn batch_execute(
    State(server): State<VecStoreHttpServer>,
    Json(req): Json<BatchExecuteRequest>,
) -> Result<Json<BatchExecuteResponse>, ApiError> {
    // Convert DTOs to internal BatchOperation types
    let operations: Vec<crate::store::BatchOperation> = req
        .operations
        .into_iter()
        .map(|op_dto| match op_dto {
            BatchOperationDto::Upsert {
                id,
                vector,
                metadata,
            } => crate::store::BatchOperation::Upsert {
                id,
                vector,
                metadata: crate::store::Metadata { fields: metadata },
            },
            BatchOperationDto::Delete { id } => crate::store::BatchOperation::Delete { id },
            BatchOperationDto::SoftDelete { id } => crate::store::BatchOperation::SoftDelete { id },
            BatchOperationDto::Restore { id } => crate::store::BatchOperation::Restore { id },
            BatchOperationDto::UpdateMetadata { id, metadata } => {
                crate::store::BatchOperation::UpdateMetadata {
                    id,
                    metadata: crate::store::Metadata { fields: metadata },
                }
            }
        })
        .collect();

    let mut store = server.store.write().await;
    let result = store.batch_execute(operations)?;

    // Convert result errors to DTOs
    let errors_dto: Vec<BatchErrorDto> = result
        .errors
        .into_iter()
        .map(|e| BatchErrorDto {
            index: e.index,
            operation: e.operation,
            error: e.error,
        })
        .collect();

    super::metrics::record_upsert(true);
    super::metrics::record_request("/v1/batch-execute", "POST", result.duration_ms / 1000.0);

    Ok(Json(BatchExecuteResponse {
        succeeded: result.succeeded,
        failed: result.failed,
        errors: errors_dto,
        duration_ms: result.duration_ms,
    }))
}

async fn query(
    State(server): State<VecStoreHttpServer>,
    Json(req): Json<QueryRequest>,
) -> Result<Json<QueryResponse>, ApiError> {
    let start = std::time::Instant::now();

    let filter = if let Some(ref filter_str) = req.filter {
        Some(crate::store::parse_filter(filter_str)?)
    } else {
        None
    };

    let query = crate::store::Query {
        vector: req.vector,
        k: req.limit as usize,
        filter,
    };

    let store = server.store.read().await;

    let neighbors = store.query(query)?;

    let duration = start.elapsed().as_secs_f64();
    let duration_ms = duration * 1000.0;

    // Record metrics
    super::metrics::record_query("vector", neighbors.len(), duration);
    super::metrics::record_request("/v1/query", "POST", duration);

    let results = neighbors
        .iter()
        .map(|n| QueryResult {
            id: n.id.clone(),
            score: n.score,
            metadata: n.metadata.fields.clone(),
        })
        .collect();

    let stats = Some(QueryStats {
        total_candidates: neighbors.len() as i32,
        filtered_count: 0,
        duration_ms,
    });

    Ok(Json(QueryResponse { results, stats }))
}

async fn query_explain(
    State(server): State<VecStoreHttpServer>,
    Json(req): Json<QueryRequest>,
) -> Result<Json<QueryExplainResponse>, ApiError> {
    let start = std::time::Instant::now();

    let filter = if let Some(ref filter_str) = req.filter {
        Some(crate::store::parse_filter(filter_str)?)
    } else {
        None
    };

    let query = crate::store::Query {
        vector: req.vector,
        k: req.limit as usize,
        filter,
    };

    let store = server.store.read().await;

    let explained_neighbors = store.query_explain(query)?;

    let duration = start.elapsed().as_secs_f64();
    let duration_ms = duration * 1000.0;

    // Record metrics
    super::metrics::record_query("vector_explain", explained_neighbors.len(), duration);
    super::metrics::record_request("/v1/query-explain", "POST", duration);

    let results = explained_neighbors
        .iter()
        .map(|n| ExplainedQueryResult {
            id: n.id.clone(),
            score: n.score,
            metadata: n.metadata.fields.clone(),
            explanation: ExplanationDto {
                raw_score: n.explanation.raw_score,
                distance_metric: n.explanation.distance_metric.clone(),
                filter_passed: n.explanation.filter_passed,
                filter_details: n.explanation.filter_details.as_ref().map(|fd| {
                    FilterEvaluationDto {
                        filter_expr: fd.filter_expr.clone(),
                        matched_conditions: fd.matched_conditions.clone(),
                        failed_conditions: fd.failed_conditions.clone(),
                        passed: fd.passed,
                    }
                }),
                graph_stats: n.explanation.graph_stats.as_ref().map(|gs| GraphStatsDto {
                    distance_calculations: gs.distance_calculations,
                    nodes_visited: gs.nodes_visited,
                    found_at_layer: gs.found_at_layer,
                    hops_from_entry: gs.hops_from_entry,
                }),
                rank: n.explanation.rank,
                explanation_text: n.explanation.explanation_text.clone(),
            },
        })
        .collect();

    let stats = Some(QueryStats {
        total_candidates: explained_neighbors.len() as i32,
        filtered_count: 0,
        duration_ms,
    });

    Ok(Json(QueryExplainResponse { results, stats }))
}

async fn query_estimate(
    State(server): State<VecStoreHttpServer>,
    Json(req): Json<QueryEstimateRequest>,
) -> Result<Json<QueryEstimateResponse>, ApiError> {
    let filter = if let Some(ref filter_str) = req.filter {
        Some(crate::store::parse_filter(filter_str)?)
    } else {
        None
    };

    let query = crate::store::Query {
        vector: req.vector,
        k: req.limit as usize,
        filter,
    };

    let store = server.store.read().await;
    let estimate = store.estimate_query(&query);

    // Record metrics
    super::metrics::record_request("/v1/query-estimate", "POST", 0.001); // Estimate is very fast

    Ok(Json(QueryEstimateResponse {
        valid: estimate.valid,
        errors: estimate.errors,
        cost_estimate: estimate.cost_estimate,
        estimated_distance_calculations: estimate.estimated_distance_calculations,
        estimated_nodes_visited: estimate.estimated_nodes_visited,
        will_overfetch: estimate.will_overfetch,
        recommendations: estimate.recommendations,
        estimated_duration_ms: estimate.estimated_duration_ms,
    }))
}

async fn delete_vector(
    State(server): State<VecStoreHttpServer>,
    Path(id): Path<String>,
) -> Result<Json<DeleteResponse>, ApiError> {
    let mut store = server.store.write().await;
    store.remove(&id)?;

    Ok(Json(DeleteResponse {
        found: true,
        deleted: true,
    }))
}

async fn soft_delete(
    State(server): State<VecStoreHttpServer>,
    Path(id): Path<String>,
) -> Result<Json<SoftDeleteResponse>, ApiError> {
    let mut store = server.store.write().await;
    let marked = store.soft_delete(&id)?;

    Ok(Json(SoftDeleteResponse {
        found: marked,
        marked_deleted: marked,
    }))
}

async fn restore(
    State(server): State<VecStoreHttpServer>,
    Path(id): Path<String>,
) -> Result<Json<RestoreResponse>, ApiError> {
    let mut store = server.store.write().await;
    let restored = store.restore(&id)?;

    Ok(Json(RestoreResponse {
        found: restored,
        restored,
    }))
}

async fn compact(
    State(server): State<VecStoreHttpServer>,
) -> Result<Json<CompactResponse>, ApiError> {
    let mut store = server.store.write().await;
    let removed_count = store.compact()?;

    Ok(Json(CompactResponse {
        removed_count: removed_count as i32,
        freed_bytes: 0,
    }))
}

async fn get_stats(
    State(server): State<VecStoreHttpServer>,
) -> Result<Json<StatsResponse>, ApiError> {
    let store = server.store.read().await;

    Ok(Json(StatsResponse {
        total_vectors: store.len() as i64 + store.deleted_count() as i64,
        active_vectors: store.active_count() as i64,
        deleted_vectors: store.deleted_count() as i64,
        dimension: store.dimension() as i32,
        storage_bytes: 0,
    }))
}

async fn create_snapshot(
    State(server): State<VecStoreHttpServer>,
    Json(req): Json<SnapshotRequest>,
) -> Result<Json<SnapshotResponse>, ApiError> {
    let store = server.store.read().await;
    store.create_snapshot(&req.name)?;

    Ok(Json(SnapshotResponse {
        success: true,
        path: format!("snapshots/{}", req.name),
    }))
}

async fn list_snapshots(
    State(server): State<VecStoreHttpServer>,
) -> Result<Json<ListSnapshotsResponse>, ApiError> {
    let store = server.store.read().await;
    let snapshots_info = store.list_snapshots()?;

    let snapshots = snapshots_info
        .into_iter()
        .map(|(name, _timestamp, size)| SnapshotInfo {
            name,
            created_at: 0,
            size_bytes: size as i64,
        })
        .collect();

    Ok(Json(ListSnapshotsResponse { snapshots }))
}

async fn restore_snapshot(
    State(server): State<VecStoreHttpServer>,
    Path(name): Path<String>,
) -> Result<Json<RestoreSnapshotResponse>, ApiError> {
    let mut store = server.store.write().await;
    store.restore_snapshot(&name)?;

    Ok(Json(RestoreSnapshotResponse {
        success: true,
        vectors_restored: store.len() as i64,
    }))
}

async fn hybrid_query(
    State(server): State<VecStoreHttpServer>,
    Json(req): Json<HybridQueryRequest>,
) -> Result<Json<QueryResponse>, ApiError> {
    let query = crate::store::HybridQuery {
        vector: req.vector,
        keywords: req.text_query,
        k: req.limit as usize,
        alpha: req.alpha.unwrap_or(0.7),
        filter: req.filter.and_then(|f| crate::store::parse_filter(&f).ok()),
    };

    let store = server.store.read().await;
    let start = std::time::Instant::now();

    let neighbors = store.hybrid_query(query)?;

    let duration_ms = start.elapsed().as_secs_f64() * 1000.0;

    let results = neighbors
        .iter()
        .map(|n| QueryResult {
            id: n.id.clone(),
            score: n.score,
            metadata: n.metadata.fields.clone(),
        })
        .collect();

    let stats = Some(QueryStats {
        total_candidates: neighbors.len() as i32,
        filtered_count: 0,
        duration_ms,
    });

    Ok(Json(QueryResponse { results, stats }))
}

async fn health_check() -> Result<Json<HealthCheckResponse>, ApiError> {
    Ok(Json(HealthCheckResponse {
        status: "healthy".to_string(),
        message: Some("VecStore server is running".to_string()),
    }))
}

async fn ready_check(
    State(server): State<VecStoreHttpServer>,
) -> Result<Json<HealthCheckResponse>, ApiError> {
    // Verify we can access the store
    let _ = server.store.read().await;

    Ok(Json(HealthCheckResponse {
        status: "ready".to_string(),
        message: Some("VecStore server is ready to accept requests".to_string()),
    }))
}

/// Prometheus metrics endpoint
async fn metrics_endpoint(State(server): State<VecStoreHttpServer>) -> Result<String, ApiError> {
    // Update database statistics
    let store = server.store.read().await;
    super::metrics::update_db_stats(
        store.len() + store.deleted_count(),
        store.active_count(),
        store.deleted_count(),
        store.dimension(),
    );
    drop(store);

    // Encode metrics
    super::metrics::encode_metrics()
        .map_err(|e| ApiError(anyhow::anyhow!("Failed to encode metrics: {}", e)))
}

// ============================================================================
// WebSocket streaming
// ============================================================================

/// WebSocket handler for streaming query results
async fn query_stream_ws(
    ws: WebSocketUpgrade,
    State(server): State<VecStoreHttpServer>,
) -> impl IntoResponse {
    ws.on_upgrade(move |socket| handle_query_stream(socket, server))
}

/// Handle WebSocket connection for query streaming
async fn handle_query_stream(mut socket: WebSocket, server: VecStoreHttpServer) {
    while let Some(msg) = socket.recv().await {
        let msg = match msg {
            Ok(msg) => msg,
            Err(e) => {
                tracing::error!("WebSocket error: {}", e);
                break;
            }
        };

        match msg {
            Message::Text(text) => {
                // Parse query request from JSON
                let req: Result<QueryRequest, _> = serde_json::from_str(&text);

                match req {
                    Ok(query_req) => {
                        // Execute query
                        let filter = if let Some(ref filter_str) = query_req.filter {
                            match crate::store::parse_filter(filter_str) {
                                Ok(f) => Some(f),
                                Err(e) => {
                                    let error_msg = serde_json::json!({
                                        "error": format!("Invalid filter: {}", e)
                                    });
                                    if socket
                                        .send(Message::Text(error_msg.to_string()))
                                        .await
                                        .is_err()
                                    {
                                        break;
                                    }
                                    continue;
                                }
                            }
                        } else {
                            None
                        };

                        let query = crate::store::Query {
                            vector: query_req.vector,
                            k: query_req.limit as usize,
                            filter,
                        };

                        let store = server.store.read().await;
                        let start = std::time::Instant::now();

                        match store.query(query) {
                            Ok(neighbors) => {
                                let duration_ms = start.elapsed().as_secs_f64() * 1000.0;
                                let total_results = neighbors.len();

                                // Stream results one by one
                                for neighbor in &neighbors {
                                    let result = QueryResult {
                                        id: neighbor.id.clone(),
                                        score: neighbor.score,
                                        metadata: neighbor.metadata.fields.clone(),
                                    };

                                    let result_json = match serde_json::to_string(&result) {
                                        Ok(json) => json,
                                        Err(e) => {
                                            tracing::error!("Failed to serialize result: {}", e);
                                            break;
                                        }
                                    };

                                    if socket.send(Message::Text(result_json)).await.is_err() {
                                        break;
                                    }
                                }

                                // Send completion message with stats
                                let completion = serde_json::json!({
                                    "complete": true,
                                    "stats": {
                                        "duration_ms": duration_ms,
                                        "total_results": total_results
                                    }
                                });

                                if socket
                                    .send(Message::Text(completion.to_string()))
                                    .await
                                    .is_err()
                                {
                                    break;
                                }
                            }
                            Err(e) => {
                                let error_msg = serde_json::json!({
                                    "error": format!("Query failed: {}", e)
                                });
                                if socket
                                    .send(Message::Text(error_msg.to_string()))
                                    .await
                                    .is_err()
                                {
                                    break;
                                }
                            }
                        }
                    }
                    Err(e) => {
                        let error_msg = serde_json::json!({
                            "error": format!("Invalid query request: {}", e)
                        });
                        if socket
                            .send(Message::Text(error_msg.to_string()))
                            .await
                            .is_err()
                        {
                            break;
                        }
                    }
                }
            }
            Message::Close(_) => {
                break;
            }
            _ => {
                // Ignore other message types (binary, ping, pong)
            }
        }
    }
}