velesdb-server 1.13.6

REST API server for VelesDB vector database
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
// Server — triaged pedantic/nursery lints (Sprint 2 Wave 8, A.10).
// Blanket `#![allow(clippy::pedantic)]` removed; each remaining lint is
// justified below.  Axum handler signatures, utoipa derives, and
// OpenAPI-documented error contracts drive most of these.
#![allow(clippy::uninlined_format_args)] // readability in error messages
#![allow(clippy::manual_let_else)] // pattern matching in handlers is clearer
#![allow(clippy::cast_possible_truncation)] // u128→u64 timing casts are bounded
#![allow(clippy::cast_sign_loss)] // Duration→u64 timing casts are non-negative
#![allow(clippy::cast_precision_loss)] // byte-count→f64 display casts are fine
#![allow(clippy::ref_option)] // utoipa-generated code triggers this
#![allow(clippy::match_same_arms)] // explicit arms improve readability in routers
#![allow(clippy::trivially_copy_pass_by_ref)] // Axum extractors require &
#![allow(clippy::map_unwrap_or)] // readability preference
#![allow(clippy::enum_glob_use)] // StatusCode::* in handlers
#![allow(clippy::unused_async)] // Axum requires async signature even for sync handlers
#![allow(clippy::needless_for_each)] // readability in metric recording loops
#![allow(clippy::doc_markdown)] // backtick pedantry — docs use utoipa annotations
#![allow(clippy::missing_errors_doc)] // errors documented in #[utoipa::path] responses
#![allow(clippy::must_use_candidate)] // handlers return impl IntoResponse, not Option
#![allow(clippy::similar_names)] // handler params are intentionally close (name/names)
#![allow(clippy::needless_raw_string_hashes)] // cosmetic, low-value fix
#![allow(clippy::needless_pass_by_value)] // Axum extractors consume by value
#![allow(clippy::redundant_closure_for_method_calls)] // readability in map chains
#![allow(clippy::single_match_else)] // pattern matching in handlers is clearer
#![allow(clippy::assigning_clones)] // minor optimisation, not performance-critical
//! `VelesDB` Server - REST API library for the `VelesDB` vector database.
//!
//! This module provides the HTTP handlers and types for the `VelesDB` REST API.
//!
//! ## OpenAPI Documentation
//!
//! The API is documented using OpenAPI 3.0. Access the interactive documentation at:
//! - Swagger UI: `GET /swagger-ui`
//! - OpenAPI JSON: `GET /api-docs/openapi.json`

pub mod auth;
pub mod config;
mod handlers;
pub mod onboarding;
pub mod rate_limit;
pub mod routes;
mod security_addon;
pub mod tls;
mod types;

use security_addon::SecurityAddon;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use utoipa::OpenApi;
use velesdb_core::guardrails::QueryLimits;
use velesdb_core::metrics::{DurationHistogram, OperationalMetrics, TraversalMetrics};
use velesdb_core::Database;

pub use onboarding::OnboardingMetrics;
pub use types::*;

pub use handlers::{
    aggregate, analyze_collection, batch_search, bulk_delete_points, collection_sanity,
    compact_collection, create_collection, create_index, delete_collection, delete_index,
    delete_point, explain, flush_collection, get_collection, get_collection_config,
    get_collection_stats, get_guardrails, get_point, health_check, hybrid_search, is_empty,
    list_collections, list_indexes, match_query, multi_query_search, query, readiness_check,
    rebuild_index, scroll_points, search, search_ids, stream_insert, stream_upsert_points,
    text_search, update_guardrails, upsert_points, vacuum_collection,
};

pub use handlers::graph::{
    add_edge, get_edge_count, get_edges, get_node_degree, get_node_edges, get_node_payload,
    graph_search, list_nodes, remove_edge, stream_traverse, traverse_graph, traverse_parallel,
    upsert_node_payload, DegreeResponse, EdgeCountResponse, GraphSearchRequest,
    GraphSearchResponse, NodeEdgeQueryParams, NodeListResponse, NodePayloadResponse,
    ParallelTraverseRequest, StreamDoneEvent, StreamNodeEvent, StreamStatsEvent,
    StreamTraverseParams, TraversalResultItem, TraversalStats, TraverseRequest, TraverseResponse,
    UpsertNodePayloadRequest,
};

#[cfg(feature = "prometheus")]
pub use handlers::metrics::{health_metrics, prometheus_metrics};

// ============================================================================
// OpenAPI Documentation

/// VelesDB API Documentation
#[derive(OpenApi)]
#[openapi(
    info(
        title = "VelesDB API",
        version = env!("CARGO_PKG_VERSION"),
        description = "High-performance vector database for AI applications. \
            Supports semantic search, HNSW indexing, and multiple distance metrics. \
            Authentication is optional — when API keys are configured via VELESDB_API_KEYS, \
            all endpoints except /health and /ready require a valid Bearer token.",
        license(name = "VelesDB Core License 1.0", url = "https://github.com/cyberlife-coder/VelesDB/blob/main/LICENSE"),
        contact(name = "VelesDB Team", url = "https://github.com/cyberlife-coder/VelesDB")
    ),
    security(
        ("bearer_auth" = [])
    ),
    modifiers(&SecurityAddon),
    servers(
        (url = "/", description = "Local server")
    ),
    tags(
        (name = "health", description = "Health check endpoints"),
        (name = "collections", description = "Collection management"),
        (name = "points", description = "Vector point operations"),
        (name = "search", description = "Vector similarity search"),
        (name = "query", description = "VelesQL query execution"),
        (name = "indexes", description = "Property index management (EPIC-009)"),
        (name = "graph", description = "Graph traversal and edge operations"),
        (name = "guardrails", description = "Query guard-rails configuration (EPIC-048)")
    ),
    paths(
        handlers::health::health_check,
        handlers::health::readiness_check,
        handlers::collections::list_collections,
        handlers::collections::create_collection,
        handlers::collections::get_collection,
        handlers::collections::delete_collection,
        handlers::collections::collection_sanity,
        handlers::collections::is_empty,
        handlers::collections::flush_collection,
        handlers::admin::analyze_collection,
        handlers::admin::get_collection_stats,
        handlers::admin::get_guardrails,
        handlers::admin::update_guardrails,
        handlers::points::upsert_points,
        handlers::points::stream_upsert_points,
        handlers::points::stream_insert,
        handlers::points::get_point,
        handlers::points::delete_point,
        handlers::points::scroll_points,
        handlers::search::search,
        handlers::search::batch_search,
        handlers::search::multi_query_search,
        handlers::search::text_search,
        handlers::search::hybrid_search,
        handlers::search::search_ids,
        handlers::admin::get_collection_config,
        handlers::query::query,
        handlers::query::aggregate,
        handlers::query::explain,
        handlers::indexes::create_index,
        handlers::indexes::list_indexes,
        handlers::indexes::delete_index,
        handlers::graph::handlers::get_edges,
        handlers::graph::handlers::add_edge,
        handlers::graph::handlers_extended::remove_edge,
        handlers::graph::handlers_extended::get_edge_count,
        handlers::graph::handlers_extended::list_nodes,
        handlers::graph::handlers_extended::get_node_edges,
        handlers::graph::handlers_extended::get_node_payload,
        handlers::graph::handlers_extended::upsert_node_payload,
        handlers::graph::handlers::traverse_graph,
        handlers::graph::handlers_extended::traverse_parallel,
        handlers::graph::handlers::get_node_degree,
        handlers::graph::handlers_extended::graph_search,
        handlers::graph::stream::stream_traverse,
        handlers::match_query::match_query,
        handlers::admin::rebuild_index,
        handlers::admin::vacuum_collection,
        handlers::admin::compact_collection,
        handlers::points::bulk_delete_points
    ),
    components(
        schemas(
            CreateCollectionRequest,
            CollectionResponse,
            UpsertPointsRequest,
            PointRequest,
            StreamInsertRequest,
            SearchRequest,
            BatchSearchRequest,
            TextSearchRequest,
            HybridSearchRequest,
            MultiQuerySearchRequest,
            SearchResponse,
            BatchSearchResponse,
            SearchResultResponse,
            SearchIdsResponse,
            IdScoreResult,
            CollectionConfigResponse,
            ErrorResponse,
            QueryRequest,
            QueryResponse,
            QueryResponseMeta,
            AggregationResponse,
            QueryErrorResponse,
            QueryErrorDetail,
            VelesqlErrorResponse,
            VelesqlErrorDetail,
            ExplainRequest,
            ExplainResponse,
            ExplainStep,
            ExplainCost,
            ExplainFeatures,
            ActualStatsResponse,
            NodeStatsResponse,
            CreateIndexRequest,
            IndexResponse,
            ListIndexesResponse,
            CollectionStatsResponse,
            ColumnStatsResponse,
            IndexStatsResponse,
            ScrollRequest,
            ScrollResponse,
            ScrollPoint,
            GuardRailsConfigRequest,
            GuardRailsConfigResponse,
            handlers::graph::TraverseRequest,
            handlers::graph::TraverseResponse,
            handlers::graph::TraversalResultItem,
            handlers::graph::TraversalStats,
            handlers::graph::DegreeResponse,
            handlers::graph::AddEdgeRequest,
            handlers::graph::EdgesResponse,
            handlers::graph::EdgeResponse,
            handlers::graph::EdgeCountResponse,
            handlers::graph::NodeListResponse,
            handlers::graph::NodePayloadResponse,
            handlers::graph::UpsertNodePayloadRequest,
            handlers::graph::ParallelTraverseRequest,
            handlers::graph::GraphSearchRequest,
            handlers::graph::GraphSearchResponse,
            handlers::graph::GraphSearchResultItem,
            handlers::graph::StreamNodeEvent,
            handlers::graph::StreamStatsEvent,
            handlers::graph::StreamDoneEvent,
            handlers::match_query::MatchQueryRequest,
            handlers::match_query::MatchQueryResponse,
            handlers::match_query::MatchQueryResultItem,
            handlers::match_query::MatchQueryMeta,
            handlers::match_query::MatchQueryError,
            handlers::points::BulkDeleteRequest
        )
    )
)]
pub struct ApiDoc;

// ============================================================================
// Application State

/// Application state shared across handlers.
pub struct AppState {
    /// The `VelesDB` database instance.
    pub db: Database,
    /// New-user onboarding diagnostics counters.
    pub onboarding_metrics: onboarding::OnboardingMetrics,
    /// Query guard-rails configuration (EPIC-048).
    pub query_limits: parking_lot::RwLock<QueryLimits>,
    /// Readiness flag — `true` once the database is fully loaded.
    pub ready: AtomicBool,
    /// Operational metrics: query throughput, connections, doc counts (EPIC-050).
    pub operational_metrics: Arc<OperationalMetrics>,
    /// Graph traversal metrics: nodes visited, depth, edges scanned.
    pub traversal_metrics: Arc<TraversalMetrics>,
    /// Query duration histogram for Prometheus export.
    pub query_duration_histogram: Arc<DurationHistogram>,
}

// ============================================================================
// Tests

#[cfg(test)]
mod tests {
    use super::*;
    use utoipa::OpenApi;

    #[test]
    fn test_openapi_spec_generation() {
        let openapi = ApiDoc::openapi();
        let json = openapi.to_json().expect("Failed to serialize OpenAPI spec");
        assert!(!json.is_empty(), "OpenAPI spec should not be empty");
        assert!(json.contains("VelesDB API"), "Should contain API title");
        assert!(
            json.contains(env!("CARGO_PKG_VERSION")),
            "Should contain version"
        );
    }

    #[test]
    fn test_openapi_has_all_endpoints() {
        let openapi = ApiDoc::openapi();
        let json = openapi.to_json().expect("Failed to serialize OpenAPI spec");
        assert!(json.contains("/health"), "Should document /health");
        assert!(
            json.contains("/collections"),
            "Should document /collections"
        );
        assert!(
            json.contains(r"/collections/{name}"),
            "Should document collections by name"
        );
        assert!(json.contains("/points"), "Should document points endpoint");
        assert!(
            json.contains(r"/collections/{name}/points/stream"),
            "Should document points stream endpoint"
        );
        assert!(json.contains("/search"), "Should document search endpoint");
        assert!(json.contains("/query"), "Should document /query");
        assert!(json.contains("/aggregate"), "Should document /aggregate");
        assert!(
            json.contains("/query/explain"),
            "Should document /query/explain"
        );
    }

    #[test]
    fn test_openapi_has_all_tags() {
        let openapi = ApiDoc::openapi();
        let json = openapi.to_json().expect("Failed to serialize OpenAPI spec");
        assert!(json.contains("\"health\""), "Should have health tag");
        assert!(
            json.contains("\"collections\""),
            "Should have collections tag"
        );
        assert!(json.contains("\"points\""), "Should have points tag");
        assert!(json.contains("\"search\""), "Should have search tag");
        assert!(json.contains("\"query\""), "Should have query tag");
    }

    #[test]
    fn test_openapi_has_schemas() {
        let openapi = ApiDoc::openapi();
        let json = openapi.to_json().expect("Failed to serialize OpenAPI spec");
        assert!(
            json.contains("CreateCollectionRequest"),
            "Should have CreateCollectionRequest schema"
        );
        assert!(
            json.contains("CollectionResponse"),
            "Should have CollectionResponse schema"
        );
        assert!(
            json.contains("SearchRequest"),
            "Should have SearchRequest schema"
        );
        assert!(
            json.contains("SearchResponse"),
            "Should have SearchResponse schema"
        );
        assert!(
            json.contains("ErrorResponse"),
            "Should have ErrorResponse schema"
        );
    }

    #[test]
    fn generate_openapi_spec_files() {
        let openapi = ApiDoc::openapi();
        let json = openapi
            .to_pretty_json()
            .expect("Failed to serialize OpenAPI JSON");
        let yaml = serde_yaml::to_string(&openapi).expect("Failed to serialize OpenAPI YAML");

        // Write to docs/ relative to workspace root
        let docs_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .unwrap()
            .parent()
            .unwrap()
            .join("docs");
        std::fs::create_dir_all(&docs_dir).expect("Failed to create docs dir");

        std::fs::write(docs_dir.join("openapi.json"), &json).expect("Failed to write openapi.json");
        std::fs::write(docs_dir.join("openapi.yaml"), &yaml).expect("Failed to write openapi.yaml");

        // Verify key endpoints are present
        assert!(
            json.contains("sparse"),
            "OpenAPI spec should contain sparse endpoints"
        );
        assert!(
            json.contains("/graph/edges"),
            "Should contain graph edge endpoints"
        );
        assert!(
            json.contains("/graph/traverse"),
            "Should contain graph traverse endpoint"
        );
        assert!(
            json.contains("/stream/insert"),
            "Should contain stream insert endpoint"
        );
        assert!(
            json.contains("/match"),
            "Should contain match query endpoint"
        );
        assert!(
            json.contains("/search/multi"),
            "Should contain multi-query search endpoint"
        );
    }

    #[test]
    fn test_openapi_has_license() {
        let openapi = ApiDoc::openapi();
        let json = openapi.to_json().expect("Failed to serialize OpenAPI spec");
        assert!(
            json.contains("VelesDB Core License 1.0"),
            "Should have VelesDB Core License 1.0"
        );
    }

    #[test]
    fn test_openapi_pretty_json() {
        let openapi = ApiDoc::openapi();
        let pretty_json = openapi
            .to_pretty_json()
            .expect("Failed to serialize pretty JSON");
        assert!(
            pretty_json.contains('\n'),
            "Pretty JSON should have newlines"
        );
        assert!(
            pretty_json.len() > 1000,
            "OpenAPI spec should be substantial"
        );
    }

    #[test]
    fn test_openapi_has_all_metrics_documented() {
        let openapi = ApiDoc::openapi();
        let json = openapi.to_json().expect("Failed to serialize OpenAPI spec");
        assert!(json.contains("cosine"), "Should document cosine metric");
        assert!(
            json.contains("euclidean"),
            "Should document euclidean metric"
        );
        assert!(json.contains("dot"), "Should document dot product metric");
        assert!(json.contains("hamming"), "Should document hamming metric");
        assert!(json.contains("jaccard"), "Should document jaccard metric");
    }

    #[test]
    fn test_openapi_has_storage_mode_documented() {
        let openapi = ApiDoc::openapi();
        let json = openapi.to_json().expect("Failed to serialize OpenAPI spec");
        assert!(
            json.contains("storage_mode"),
            "Should document storage_mode parameter"
        );
    }

    #[test]
    fn test_openapi_has_search_types_documented() {
        let openapi = ApiDoc::openapi();
        let json = openapi.to_json().expect("Failed to serialize OpenAPI spec");
        assert!(json.contains("text_search"), "Should document text search");
        assert!(
            json.contains("hybrid_search"),
            "Should document hybrid search"
        );
        assert!(json.contains("batch"), "Should document batch search");
    }

    #[test]
    fn test_create_collection_request_default_metric() {
        let json = r#"{"name": "test", "dimension": 128}"#;
        let req: CreateCollectionRequest = serde_json::from_str(json).unwrap();
        assert_eq!(req.metric, "cosine");
    }

    #[test]
    fn test_create_collection_request_with_hamming() {
        let json = r#"{"name": "test", "dimension": 128, "metric": "hamming"}"#;
        let req: CreateCollectionRequest = serde_json::from_str(json).unwrap();
        assert_eq!(req.metric, "hamming");
    }

    #[test]
    fn test_create_collection_request_with_jaccard() {
        let json = r#"{"name": "test", "dimension": 128, "metric": "jaccard"}"#;
        let req: CreateCollectionRequest = serde_json::from_str(json).unwrap();
        assert_eq!(req.metric, "jaccard");
    }

    #[test]
    fn test_create_collection_request_with_storage_mode() {
        let json = r#"{"name": "test", "dimension": 128, "storage_mode": "sq8"}"#;
        let req: CreateCollectionRequest = serde_json::from_str(json).unwrap();
        assert_eq!(req.storage_mode, "sq8");
    }

    #[test]
    fn test_search_request_deserialize() {
        let json = r#"{"vector": [0.1, 0.2, 0.3], "top_k": 5}"#;
        let req: SearchRequest = serde_json::from_str(json).unwrap();
        assert_eq!(req.vector, vec![0.1, 0.2, 0.3]);
        assert_eq!(req.top_k, 5);
    }

    #[test]
    fn test_batch_search_request_deserialize() {
        let json = r#"{"searches": [{"vector": [0.1, 0.2], "top_k": 3}]}"#;
        let req: BatchSearchRequest = serde_json::from_str(json).unwrap();
        assert_eq!(req.searches.len(), 1);
        assert_eq!(req.searches[0].top_k, 3);
    }

    #[test]
    fn test_text_search_request_deserialize() {
        let json = r#"{"query": "machine learning", "top_k": 10}"#;
        let req: TextSearchRequest = serde_json::from_str(json).unwrap();
        assert_eq!(req.query, "machine learning");
        assert_eq!(req.top_k, 10);
    }

    #[test]
    fn test_hybrid_search_request_deserialize() {
        let json = r#"{"vector": [0.1, 0.2], "query": "test", "top_k": 5}"#;
        let req: HybridSearchRequest = serde_json::from_str(json).unwrap();
        assert_eq!(req.vector, vec![0.1, 0.2]);
        assert_eq!(req.query, "test");
        assert_eq!(req.top_k, 5);
    }

    #[test]
    fn test_upsert_points_request_deserialize() {
        let json = r#"{"points": [{"id": 1, "vector": [0.1, 0.2]}]}"#;
        let req: UpsertPointsRequest = serde_json::from_str(json).unwrap();
        assert_eq!(req.points.len(), 1);
        assert_eq!(req.points[0].id, 1);
    }

    #[test]
    fn test_collection_response_serialize() {
        let resp = CollectionResponse {
            name: "test".to_string(),
            dimension: 128,
            metric: "cosine".to_string(),
            storage_mode: "full".to_string(),
            point_count: 100,
        };
        let json = serde_json::to_string(&resp).unwrap();
        assert!(json.contains("\"name\":\"test\""));
        assert!(json.contains("\"dimension\":128"));
        assert!(json.contains("\"metric\":\"cosine\""));
        assert!(json.contains("\"storage_mode\":\"full\""));
        assert!(json.contains("\"point_count\":100"));
    }

    #[test]
    fn test_search_response_serialize() {
        let resp = SearchResponse {
            results: vec![SearchResultResponse {
                id: 1,
                score: 0.95,
                payload: None,
            }],
        };
        let json = serde_json::to_string(&resp).unwrap();
        assert!(json.contains("\"results\""));
        // IDs are serialized as strings to prevent JavaScript precision loss (WP-0D).
        assert!(json.contains("\"id\":\"1\""));
    }

    #[test]
    fn test_error_response_serialize() {
        let resp = ErrorResponse {
            error: "Test error".to_string(),
            code: None,
        };
        let json = serde_json::to_string(&resp).unwrap();
        assert!(json.contains("\"error\":\"Test error\""));
        // code: None is omitted from JSON output
        assert!(!json.contains("\"code\""));
    }

    // ========================================================================
    // OpenAPI <-> Router structural conformance
    // ========================================================================

    /// Extracts every `(path_template, HTTP method)` pair declared in the
    /// OpenAPI spec. Returns a sorted `Vec` for deterministic assertions.
    fn extract_openapi_operations() -> Vec<(String, axum::http::Method)> {
        let openapi = ApiDoc::openapi();
        let mut ops = Vec::new();
        for (path, item) in &openapi.paths.paths {
            if item.get.is_some() {
                ops.push((path.clone(), axum::http::Method::GET));
            }
            if item.post.is_some() {
                ops.push((path.clone(), axum::http::Method::POST));
            }
            if item.put.is_some() {
                ops.push((path.clone(), axum::http::Method::PUT));
            }
            if item.delete.is_some() {
                ops.push((path.clone(), axum::http::Method::DELETE));
            }
            if item.patch.is_some() {
                ops.push((path.clone(), axum::http::Method::PATCH));
            }
        }
        ops.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.as_str().cmp(b.1.as_str())));
        ops
    }

    /// Converts an OpenAPI path template into a concrete URI by replacing
    /// each `{param}` placeholder with a safe dummy value.
    fn template_to_uri(template: &str) -> String {
        template
            .replace("{name}", "test_col")
            .replace("{id}", "1")
            .replace("{node_id}", "1")
            .replace("{edge_id}", "1")
            .replace("{label}", "test_label")
            .replace("{property}", "test_prop")
    }

    /// Creates a minimal [`AppState`] backed by an ephemeral directory.
    /// Returns both the state and the `TempDir` guard (must stay alive).
    fn create_conformance_state() -> (std::sync::Arc<AppState>, tempfile::TempDir) {
        let dir = tempfile::TempDir::new().expect("test: create temp dir");
        let db = Database::open(dir.path()).expect("test: open database");
        let state = std::sync::Arc::new(AppState {
            db,
            onboarding_metrics: OnboardingMetrics::default(),
            query_limits: parking_lot::RwLock::new(QueryLimits::default()),
            ready: AtomicBool::new(true),
            operational_metrics: velesdb_core::metrics::OperationalMetrics::new_arc(),
            traversal_metrics: Arc::new(velesdb_core::metrics::TraversalMetrics::new()),
            query_duration_histogram: Arc::new(velesdb_core::metrics::DurationHistogram::new()),
        });
        (state, dir)
    }

    /// Returns `true` when the response is Axum's built-in fallback (route
    /// not found), which is a `404` with an empty body. Handler-generated
    /// 404s always carry a non-empty JSON body.
    async fn is_axum_fallback(resp: axum::http::Response<axum::body::Body>) -> bool {
        if resp.status() != axum::http::StatusCode::NOT_FOUND {
            return false;
        }
        let body = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
            .await
            .expect("test: read response body");
        body.is_empty()
    }

    /// Structural conformance: every `(path, method)` declared in the OpenAPI
    /// spec must be reachable through the Axum router (must NOT hit Axum's
    /// built-in fallback 404).
    #[tokio::test]
    async fn test_openapi_routes_match_router() {
        let operations = extract_openapi_operations();
        assert!(
            !operations.is_empty(),
            "OpenAPI spec should declare at least one operation"
        );

        let (state, _dir) = create_conformance_state();
        let router = crate::routes::api_routes().with_state(state);

        let mut failures: Vec<String> = Vec::new();
        for (template, method) in &operations {
            let uri = template_to_uri(template);
            let req = axum::http::Request::builder()
                .method(method)
                .uri(&uri)
                .header("content-type", "application/json")
                .body(axum::body::Body::from("{}"))
                .expect("test: build request");

            let resp = tower::ServiceExt::oneshot(router.clone(), req)
                .await
                .expect("test: send request");

            if is_axum_fallback(resp).await {
                failures.push(format!("{method} {template}"));
            }
        }

        assert!(
            failures.is_empty(),
            "OpenAPI operations with no matching router route:\n  {}",
            failures.join("\n  ")
        );
    }
}