type-bridge-server 2.3.2

Query-intercepting proxy server for TypeDB with validation and audit logging
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
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
#![allow(deprecated)] // Legacy node bridges are removed in 3.0.
use std::sync::Arc;

use axum::extract::State;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use axum::{Json, Router};
use serde::Serialize;
use type_bridge_core_lib::query_parser::parse_typeql_query;

use crate::error::PipelineError;
use crate::pipeline::{QueryInput, QueryPipeline, ValidateInput};
use crate::transport::types::*;

/// The final released V1 HTTP identity.
///
/// `/health` is part of the released V1 wire contract, so its body cannot
/// follow the containing package version without changing bytes in V2.
const RELEASED_V1_HTTP_VERSION: &str = "1.5.11";

// --- Axum-specific error response types ---

#[derive(Debug, Serialize)]
struct ErrorResponse {
    pub status: String,
    pub error: ErrorDetail,
}

#[derive(Debug, Serialize)]
struct ErrorDetail {
    pub code: String,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<serde_json::Value>,
}

impl IntoResponse for PipelineError {
    fn into_response(self) -> Response {
        let failure = self.failure();
        failure_response(self, failure)
    }
}

#[cfg(feature = "typedb")]
impl IntoResponse for crate::typedb::ExecuteError {
    fn into_response(self) -> Response {
        let failure = self.failure();
        failure_response(self.into(), failure)
    }
}

fn failure_response(
    error: PipelineError,
    failure: Option<type_bridge_contract::failure::Failure>,
) -> Response {
    let (status, code) = match &error {
        PipelineError::Config(_) => (StatusCode::INTERNAL_SERVER_ERROR, "CONFIG_ERROR"),
        PipelineError::Connection(_) => (StatusCode::SERVICE_UNAVAILABLE, "CONNECTION_ERROR"),
        PipelineError::UnsupportedVersion(_) => {
            (StatusCode::SERVICE_UNAVAILABLE, "UNSUPPORTED_VERSION")
        }
        PipelineError::QueryExecution(_) => (StatusCode::BAD_REQUEST, "QUERY_EXECUTION_ERROR"),
        PipelineError::Validation(_) => (StatusCode::BAD_REQUEST, "VALIDATION_FAILED"),
        PipelineError::Parse(_) => (StatusCode::BAD_REQUEST, "PARSE_ERROR"),
        PipelineError::Schema(_) => (StatusCode::INTERNAL_SERVER_ERROR, "SCHEMA_ERROR"),
        PipelineError::Interceptor(_) => (StatusCode::FORBIDDEN, "INTERCEPTOR_ERROR"),
        PipelineError::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "INTERNAL_ERROR"),
    };

    let body = ErrorResponse {
        status: "error".to_string(),
        error: ErrorDetail {
            code: code.to_string(),
            message: error.to_string(),
            details: failure.map(|failure| failure.host_json()),
        },
    };

    (status, axum::Json(body)).into_response()
}

// --- Router ---

/// Build the released V1 HTTP router around a shared query pipeline.
pub fn create_router(pipeline: Arc<QueryPipeline>) -> Router {
    Router::new()
        .route("/query", post(handle_query))
        .route("/query/raw", post(handle_raw_query))
        .route("/query/validate", post(handle_validate))
        .route("/health", get(handle_health))
        .route("/schema", get(handle_schema))
        .with_state(pipeline)
}

// --- Handlers ---

async fn handle_query(
    State(pipeline): State<Arc<QueryPipeline>>,
    Json(req): Json<QueryRequest>,
) -> Result<Json<QueryResponse>, PipelineError> {
    let output = pipeline
        .execute_query(QueryInput {
            database: req.database,
            transaction_type: req.transaction_type,
            clauses: req.clauses,
            metadata: req.metadata,
        })
        .await?;

    Ok(Json(QueryResponse {
        status: "ok".to_string(),
        results: output.results,
        metadata: ResponseMetadata {
            request_id: output.request_id,
            execution_time_ms: output.execution_time_ms,
            interceptors_applied: output.interceptors_applied,
        },
    }))
}

async fn handle_raw_query(
    State(pipeline): State<Arc<QueryPipeline>>,
    Json(req): Json<RawQueryRequest>,
) -> Result<Json<QueryResponse>, PipelineError> {
    let clauses =
        parse_typeql_query(&req.query).map_err(|e| PipelineError::Parse(e.to_string()))?;

    let output = pipeline
        .execute_query(QueryInput {
            database: req.database,
            transaction_type: req.transaction_type,
            clauses,
            metadata: req.metadata,
        })
        .await?;

    Ok(Json(QueryResponse {
        status: "ok".to_string(),
        results: output.results,
        metadata: ResponseMetadata {
            request_id: output.request_id,
            execution_time_ms: output.execution_time_ms,
            interceptors_applied: output.interceptors_applied,
        },
    }))
}

async fn handle_validate(
    State(pipeline): State<Arc<QueryPipeline>>,
    Json(req): Json<ValidateRequest>,
) -> Result<Json<ValidateResponse>, PipelineError> {
    let output = pipeline.validate(&ValidateInput {
        clauses: req.clauses,
    })?;

    let errors: Vec<serde_json::Value> = output
        .errors
        .iter()
        .map(|e| {
            serde_json::json!({
                "code": e.code,
                "message": e.message,
                "path": e.path,
            })
        })
        .collect();

    Ok(Json(ValidateResponse {
        status: "ok".to_string(),
        is_valid: output.is_valid,
        errors,
    }))
}

async fn handle_health(State(pipeline): State<Arc<QueryPipeline>>) -> Json<HealthResponse> {
    Json(HealthResponse {
        status: "ok".to_string(),
        version: RELEASED_V1_HTTP_VERSION.to_string(),
        typedb_connected: pipeline.is_connected(),
    })
}

#[cfg_attr(coverage_nightly, coverage(off))]
fn to_schema_error(e: impl std::fmt::Display) -> PipelineError {
    PipelineError::Schema(e.to_string())
}

#[cfg_attr(coverage_nightly, coverage(off))]
fn to_internal_error(e: impl std::fmt::Display) -> PipelineError {
    PipelineError::Internal(e.to_string())
}

async fn handle_schema(
    State(pipeline): State<Arc<QueryPipeline>>,
) -> Result<Json<serde_json::Value>, PipelineError> {
    let schema = pipeline
        .schema()
        .ok_or_else(|| PipelineError::Schema("No schema loaded".to_string()))?;

    schema_to_json(schema)
}

#[cfg_attr(coverage_nightly, coverage(off))]
fn schema_to_json(
    schema: &type_bridge_core_lib::_schema::TypeSchema,
) -> Result<Json<serde_json::Value>, PipelineError> {
    let json = schema.to_json().map_err(to_schema_error)?;

    let value: serde_json::Value = serde_json::from_str(&json).map_err(to_internal_error)?;

    Ok(Json(value))
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use axum::body::Body;
    use axum::http::{self, Request};
    use http_body_util::BodyExt;
    use tower::ServiceExt;

    use type_bridge_core_lib::ast::{Clause, Constraint, LiteralValue, Pattern, Value};

    use super::*;
    use crate::test_helpers::{MockExecutor, make_pipeline, make_simple_clauses};

    /// Build an invalid clause (references nonexistent attr) as a serde_json::Value.
    fn invalid_clause_json() -> serde_json::Value {
        let clauses = vec![Clause::Match(vec![Pattern::Entity {
            variable: "p".to_string(),
            type_name: "person".to_string(),
            constraints: vec![Constraint::Has {
                attr_name: "nonexistent".to_string(),
                value: Value::Literal(LiteralValue {
                    value: serde_json::json!("val"),
                    value_type: "string".to_string(),
                }),
            }],
            is_strict: false,
        }])];
        serde_json::to_value(&clauses).unwrap()
    }

    fn app(executor: MockExecutor, with_schema: bool) -> Router {
        let pipeline = Arc::new(make_pipeline(executor, with_schema));
        create_router(pipeline)
    }

    async fn body_json(response: Response) -> serde_json::Value {
        let bytes = response.into_body().collect().await.unwrap().to_bytes();
        serde_json::from_slice(&bytes).unwrap()
    }

    fn json_request(method: &str, uri: &str, body: serde_json::Value) -> Request<Body> {
        Request::builder()
            .method(method)
            .uri(uri)
            .header(http::header::CONTENT_TYPE, "application/json")
            .body(Body::from(serde_json::to_vec(&body).unwrap()))
            .unwrap()
    }

    // =============================================
    // PipelineError IntoResponse tests
    // =============================================

    #[test]
    fn into_response_config_error() {
        let resp = PipelineError::Config("bad".into()).into_response();
        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[test]
    fn into_response_connection_error() {
        let resp = PipelineError::Connection("down".into()).into_response();
        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
    }

    #[test]
    fn into_response_query_execution_error() {
        let resp = PipelineError::QueryExecution("fail".into()).into_response();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn into_response_validation_error() {
        let resp = PipelineError::Validation("invalid".into()).into_response();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn into_response_parse_error() {
        let resp = PipelineError::Parse("syntax".into()).into_response();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn into_response_schema_error() {
        let resp = PipelineError::Schema("missing".into()).into_response();
        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[test]
    fn into_response_interceptor_error() {
        let resp = PipelineError::Interceptor("denied".into()).into_response();
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
    }

    #[test]
    fn into_response_internal_error() {
        let resp = PipelineError::Internal("oops".into()).into_response();
        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[tokio::test]
    async fn commit_failure_body_pins_released_v1_bytes() {
        // Golden merge-base contract: a commit rejection surfaces as HTTP 400
        // with exactly this body. Released 1.5.x clients match on these bytes;
        // the runtime-to-pipeline conversion producing this message is pinned
        // in typedb::real_driver's tests.
        let error = PipelineError::QueryExecution("Commit failed: constraint violated".into());
        let resp = error.into_response();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(
            bytes.as_ref(),
            br#"{"status":"error","error":{"code":"QUERY_EXECUTION_ERROR","message":"Query execution error: Commit failed: constraint violated"}}"#
        );
    }

    #[cfg(feature = "typedb")]
    #[tokio::test]
    async fn unclassified_commit_errors_keep_released_v1_body_bytes() {
        use crate::typedb::{CommitCertainty, CommitFailure, ExecuteError};
        for certainty in [CommitCertainty::Rejected, CommitCertainty::Indeterminate] {
            let error = ExecuteError::Commit(CommitFailure {
                failure: None,
                certainty,
                message: "constraint violated".into(),
            });
            let response = PipelineError::from(error).into_response();
            assert_eq!(response.status(), StatusCode::BAD_REQUEST);
            let bytes = response.into_body().collect().await.unwrap().to_bytes();
            assert_eq!(bytes.as_ref(), br#"{"status":"error","error":{"code":"QUERY_EXECUTION_ERROR","message":"Query execution error: Commit failed: constraint violated"}}"#);
        }
    }

    #[cfg(feature = "typedb")]
    #[tokio::test]
    async fn typed_failure_http_details_preserve_structural_commit_outcome() {
        use type_bridge_typedb_runtime::failure::{classify_commit, redacted_failure};
        let failure = classify_commit(
            "STC2",
            "[STC2] Commit in database 'db' failed with isolation conflict: \
             Transaction uses a lock held by a concurrent commit.",
            true,
        );
        let error = crate::typedb::ExecuteError::Commit(crate::typedb::CommitFailure {
            certainty: crate::typedb::CommitCertainty::Rejected,
            message: redacted_failure(&failure),
            failure: Some(failure.clone()),
        });
        let response = error.into_response();
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        let body = body_json(response).await;
        assert_eq!(body["error"]["code"], "QUERY_EXECUTION_ERROR");
        assert_eq!(
            body,
            serde_json::json!({
                "status":"error", "error": {
                    "code":"QUERY_EXECUTION_ERROR",
                    "message":"Query execution error: Commit failed: [STC2] TypeDB commit rejected: exclusive lock conflict",
                    "details":failure.host_json(),
                }
            })
        );
        let query =
            PipelineError::QueryExecution("[CNT9] TypeDB query rejected: unique constraint".into());
        let body = body_json(query.into_response()).await;
        assert_eq!(body["error"]["details"]["reason"], "unique");
        assert!(body["error"]["details"]["op_index"].is_null());
    }
    #[tokio::test]
    async fn into_response_body_structure() {
        let resp = PipelineError::Config("bad config".into()).into_response();
        let json = body_json(resp).await;
        assert_eq!(json["status"], "error");
        assert_eq!(json["error"]["code"], "CONFIG_ERROR");
        assert!(
            json["error"]["message"]
                .as_str()
                .unwrap()
                .contains("bad config")
        );
    }

    // =============================================
    // handle_health tests
    // =============================================

    #[tokio::test]
    async fn health_returns_200_with_status() {
        let router = app(MockExecutor::new(), false);
        let req = Request::builder()
            .uri("/health")
            .body(Body::empty())
            .unwrap();
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let json = body_json(resp).await;
        assert_eq!(json["status"], "ok");
        assert!(!json["version"].as_str().unwrap().is_empty());
    }

    #[tokio::test]
    async fn health_reflects_connection_status() {
        let executor = MockExecutor::new();
        *executor.connected.lock().unwrap() = false;
        let router = app(executor, false);
        let req = Request::builder()
            .uri("/health")
            .body(Body::empty())
            .unwrap();
        let resp = router.oneshot(req).await.unwrap();
        let json = body_json(resp).await;
        assert_eq!(json["typedb_connected"], false);
    }

    #[tokio::test]
    async fn health_connected_true() {
        let router = app(MockExecutor::new(), false);
        let req = Request::builder()
            .uri("/health")
            .body(Body::empty())
            .unwrap();
        let resp = router.oneshot(req).await.unwrap();
        let json = body_json(resp).await;
        assert_eq!(json["typedb_connected"], true);
    }

    // =============================================
    // handle_schema tests
    // =============================================

    #[tokio::test]
    async fn schema_no_schema_returns_500() {
        let router = app(MockExecutor::new(), false);
        let req = Request::builder()
            .uri("/schema")
            .body(Body::empty())
            .unwrap();
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[tokio::test]
    async fn schema_with_schema_returns_200() {
        let router = app(MockExecutor::new(), true);
        let req = Request::builder()
            .uri("/schema")
            .body(Body::empty())
            .unwrap();
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let json = body_json(resp).await;
        assert!(json["entities"].is_object());
    }

    #[tokio::test]
    async fn schema_post_not_allowed() {
        let router = app(MockExecutor::new(), false);
        let req = Request::builder()
            .method("POST")
            .uri("/schema")
            .body(Body::empty())
            .unwrap();
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
    }

    // =============================================
    // handle_query tests
    // =============================================

    #[tokio::test]
    async fn query_success() {
        let router = app(MockExecutor::new(), false);
        let body = serde_json::json!({
            "transaction_type": "read",
            "clauses": []
        });
        let req = json_request("POST", "/query", body);
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let json = body_json(resp).await;
        assert_eq!(json["status"], "ok");
        assert!(!json["metadata"]["request_id"].as_str().unwrap().is_empty());
    }

    #[tokio::test]
    async fn raw_query_success() {
        let router = app(MockExecutor::new(), false);
        let body = serde_json::json!({
            "transaction_type": "read",
            "query": "match $p isa person; fetch { \"person\": { $p.* } };"
        });
        let req = json_request("POST", "/query/raw", body);
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let json = body_json(resp).await;
        assert_eq!(json["status"], "ok");
        assert!(!json["metadata"]["request_id"].as_str().unwrap().is_empty());
    }

    #[tokio::test]
    async fn raw_query_parse_error() {
        let router = app(MockExecutor::new(), false);
        let body = serde_json::json!({
            "transaction_type": "read",
            "query": "this is not valid typeql!!!"
        });
        let req = json_request("POST", "/query/raw", body);
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);

        let json = body_json(resp).await;
        assert_eq!(json["error"]["code"], "PARSE_ERROR");
    }

    #[tokio::test]
    async fn query_executor_failure() {
        let router = app(MockExecutor::failing("db error"), false);
        let body = serde_json::json!({
            "transaction_type": "read",
            "clauses": []
        });
        let req = json_request("POST", "/query", body);
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);

        let json = body_json(resp).await;
        assert_eq!(json["error"]["code"], "QUERY_EXECUTION_ERROR");
    }

    #[tokio::test]
    async fn query_bad_json() {
        let router = app(MockExecutor::new(), false);
        let req = Request::builder()
            .method("POST")
            .uri("/query")
            .header(http::header::CONTENT_TYPE, "application/json")
            .body(Body::from("not json"))
            .unwrap();
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn query_database_override() {
        let executor = MockExecutor::new();
        let calls = executor.calls.clone();
        let pipeline = Arc::new(make_pipeline(executor, false));
        let router = create_router(pipeline);

        let body = serde_json::json!({
            "database": "custom_db",
            "transaction_type": "read",
            "clauses": []
        });
        let req = json_request("POST", "/query", body);
        router.oneshot(req).await.unwrap();

        let recorded = calls.lock().unwrap();
        assert_eq!(recorded[0].0, "custom_db");
    }

    #[tokio::test]
    async fn query_response_metadata_fields() {
        let router = app(MockExecutor::new(), false);
        let body = serde_json::json!({
            "transaction_type": "read",
            "clauses": []
        });
        let req = json_request("POST", "/query", body);
        let resp = router.oneshot(req).await.unwrap();
        let json = body_json(resp).await;

        assert!(json["metadata"]["request_id"].is_string());
        assert!(json["metadata"]["execution_time_ms"].is_number());
        assert!(json["metadata"]["interceptors_applied"].is_array());
    }

    #[tokio::test]
    async fn query_validation_failure() {
        let router = app(MockExecutor::new(), true);
        let body = serde_json::json!({
            "transaction_type": "read",
            "clauses": invalid_clause_json()
        });
        let req = json_request("POST", "/query", body);
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);

        let json = body_json(resp).await;
        assert_eq!(json["error"]["code"], "VALIDATION_FAILED");
    }

    // =============================================
    // handle_validate tests
    // =============================================

    #[tokio::test]
    async fn validate_valid_query() {
        let router = app(MockExecutor::new(), true);
        let clauses = serde_json::to_value(make_simple_clauses()).unwrap();
        let body = serde_json::json!({
            "clauses": clauses
        });
        let req = json_request("POST", "/query/validate", body);
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let json = body_json(resp).await;
        assert_eq!(json["is_valid"], true);
        assert!(json["errors"].as_array().unwrap().is_empty());
    }

    #[tokio::test]
    async fn validate_invalid_query() {
        let router = app(MockExecutor::new(), true);
        let body = serde_json::json!({ "clauses": invalid_clause_json() });
        let req = json_request("POST", "/query/validate", body);
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let json = body_json(resp).await;
        assert_eq!(json["is_valid"], false);
        assert!(!json["errors"].as_array().unwrap().is_empty());
    }

    #[tokio::test]
    async fn validate_no_schema() {
        let router = app(MockExecutor::new(), false);
        let body = serde_json::json!({ "clauses": [] });
        let req = json_request("POST", "/query/validate", body);
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);

        let json = body_json(resp).await;
        assert_eq!(json["error"]["code"], "SCHEMA_ERROR");
    }

    #[tokio::test]
    async fn validate_error_structure() {
        let router = app(MockExecutor::new(), true);
        let body = serde_json::json!({ "clauses": invalid_clause_json() });
        let req = json_request("POST", "/query/validate", body);
        let resp = router.oneshot(req).await.unwrap();
        let json = body_json(resp).await;

        let error = &json["errors"][0];
        assert!(error["code"].is_string());
        assert!(error["message"].is_string());
        assert!(error["path"].is_string());
    }

    #[tokio::test]
    async fn validate_bad_json() {
        let router = app(MockExecutor::new(), true);
        let req = Request::builder()
            .method("POST")
            .uri("/query/validate")
            .header(http::header::CONTENT_TYPE, "application/json")
            .body(Body::from("not json"))
            .unwrap();
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn validate_empty_clauses() {
        let router = app(MockExecutor::new(), true);
        let body = serde_json::json!({ "clauses": [] });
        let req = json_request("POST", "/query/validate", body);
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let json = body_json(resp).await;
        assert_eq!(json["is_valid"], true);
    }

    // =============================================
    // Router integration tests
    // =============================================

    #[tokio::test]
    async fn router_health_route_exists() {
        let router = app(MockExecutor::new(), false);
        let req = Request::builder()
            .uri("/health")
            .body(Body::empty())
            .unwrap();
        let resp = router.oneshot(req).await.unwrap();
        assert_ne!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn router_schema_route_exists() {
        let router = app(MockExecutor::new(), false);
        let req = Request::builder()
            .uri("/schema")
            .body(Body::empty())
            .unwrap();
        let resp = router.oneshot(req).await.unwrap();
        assert_ne!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn router_query_route_exists() {
        let router = app(MockExecutor::new(), false);
        let body = serde_json::json!({
            "transaction_type": "read",
            "clauses": []
        });
        let req = json_request("POST", "/query", body);
        let resp = router.oneshot(req).await.unwrap();
        assert_ne!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn router_validate_route_exists() {
        let router = app(MockExecutor::new(), true);
        let body = serde_json::json!({ "clauses": [] });
        let req = json_request("POST", "/query/validate", body);
        let resp = router.oneshot(req).await.unwrap();
        assert_ne!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn router_unknown_route_returns_404() {
        let router = app(MockExecutor::new(), false);
        let req = Request::builder()
            .uri("/nonexistent")
            .body(Body::empty())
            .unwrap();
        let resp = router.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    // =============================================
    // Content-type tests
    // =============================================

    #[tokio::test]
    async fn health_response_is_json() {
        let router = app(MockExecutor::new(), false);
        let req = Request::builder()
            .uri("/health")
            .body(Body::empty())
            .unwrap();
        let resp = router.oneshot(req).await.unwrap();
        let content_type = resp.headers().get(http::header::CONTENT_TYPE).unwrap();
        assert!(content_type.to_str().unwrap().contains("application/json"));
    }

    #[tokio::test]
    async fn error_response_is_json() {
        let router = app(MockExecutor::failing("fail"), false);
        let body = serde_json::json!({
            "transaction_type": "read",
            "clauses": []
        });
        let req = json_request("POST", "/query", body);
        let resp = router.oneshot(req).await.unwrap();
        let content_type = resp.headers().get(http::header::CONTENT_TYPE).unwrap();
        assert!(content_type.to_str().unwrap().contains("application/json"));
    }

    #[tokio::test]
    async fn query_response_is_json() {
        let router = app(MockExecutor::new(), false);
        let body = serde_json::json!({
            "transaction_type": "read",
            "clauses": []
        });
        let req = json_request("POST", "/query", body);
        let resp = router.oneshot(req).await.unwrap();
        let content_type = resp.headers().get(http::header::CONTENT_TYPE).unwrap();
        assert!(content_type.to_str().unwrap().contains("application/json"));
    }

    #[tokio::test]
    async fn validate_response_is_json() {
        let router = app(MockExecutor::new(), true);
        let body = serde_json::json!({ "clauses": [] });
        let req = json_request("POST", "/query/validate", body);
        let resp = router.oneshot(req).await.unwrap();
        let content_type = resp.headers().get(http::header::CONTENT_TYPE).unwrap();
        assert!(content_type.to_str().unwrap().contains("application/json"));
    }
}

#[cfg(all(test, feature = "typedb"))]
#[path = "../../../../../tests/support/typed_failure_live.rs"]
mod typed_failure_live;
#[cfg(all(test, feature = "typedb"))]
#[tokio::test]
#[ignore = "requires an owned TypeDB 3.13.6 container and failure-smoke environment"]
async fn live_provider_failures_reach_http_details() {
    use http_body_util::BodyExt;
    for (case, error) in typed_failure_live::observations("tb_failure_http").await {
        let error = crate::typedb::ExecuteError::from(error);
        let failure = error.failure().expect("classification retained");
        let response = error.into_response();
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        let bytes = response.into_body().collect().await.unwrap().to_bytes();
        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(body["error"]["code"], "QUERY_EXECUTION_ERROR");
        assert_eq!(body["error"]["details"], failure.host_json());
        assert_eq!(failure.retry_safe(), case != "paused");
        assert!(
            !std::str::from_utf8(&bytes)
                .unwrap()
                .contains("SECRET_SENTINEL")
        );
        println!("{case}: {}", body["error"]["details"]);
    }
}

#[cfg(all(test, feature = "typedb"))]
#[tokio::test]
#[ignore = "requires an isolated TypeDB 3.13.6 server and failure-smoke environment"]
async fn live_http_requests_report_typed_failures() {
    use http_body_util::BodyExt;
    use tower::ServiceExt;
    let fixture: serde_json::Value = serde_json::from_str(include_str!(
        "../../../../../tests/contracts/typed-failure-scenarios.json"
    ))
    .unwrap();
    let name = format!("tb_failure_http_request_{}", std::process::id());
    let config = crate::config::TypeDBSection {
        address: std::env::var("TYPEDB_ADDRESS").unwrap(),
        database: name.clone(),
        username: "admin".into(),
        password: "password".into(),
        http_port: std::env::var("TYPEDB_HTTP_PORT").unwrap().parse().unwrap(),
        server_version: None,
    };
    let admin = crate::typedb::TypeDBClient::connect(&config).await.unwrap();
    admin.create_database(&name).await.unwrap();
    admin
        .execute(&name, fixture["schema"].as_str().unwrap(), "schema")
        .await
        .unwrap();
    admin
        .execute(&name, fixture["seed"].as_str().unwrap(), "write")
        .await
        .unwrap();
    let executor = crate::typedb::TypeDBClient::connect(&config).await.unwrap();
    let pipeline = crate::pipeline::PipelineBuilder::new(executor)
        .with_default_database(&name)
        .build()
        .unwrap();
    let app = create_router(Arc::new(pipeline));
    let request = |query: &str| {
        use type_bridge_core_lib::ast::{Clause, Pattern, Statement};
        let (matched, inserted) = query
            .strip_prefix("match ")
            .unwrap()
            .split_once("insert ")
            .unwrap();
        let clauses = vec![
            Clause::Match(vec![Pattern::Raw(
                matched.trim().trim_end_matches(';').to_owned(),
            )]),
            Clause::Insert(vec![Statement::Raw(
                inserted.trim().trim_end_matches(';').to_owned(),
            )]),
        ];
        axum::http::Request::builder()
            .method("POST")
            .uri("/query")
            .header("content-type", "application/json")
            .body(axum::body::Body::from(
                serde_json::to_vec(&serde_json::json!({
                    "database":name,"transaction_type":"write","clauses":clauses,
                }))
                .unwrap(),
            ))
            .unwrap()
    };
    for (case, reason) in [("cnt5", "cardinality"), ("cnt9", "unique")] {
        let response = app
            .clone()
            .oneshot(request(fixture[case].as_str().unwrap()))
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        let bytes = response.into_body().collect().await.unwrap().to_bytes();
        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(body["error"]["details"]["reason"], reason, "{body}");
        assert_eq!(body["error"]["details"]["retry_safe"], true);
        assert!(
            !std::str::from_utf8(&bytes)
                .unwrap()
                .contains("SECRET_SENTINEL")
        );
        println!("HTTP {case}: {}", body["error"]["details"]);
    }
    enum Fault {
        Race(tokio::sync::Barrier),
        Pause,
    }
    struct ControlledExecutor {
        database: type_bridge_orm::Database,
        fault: Fault,
    }
    impl crate::executor::QueryExecutor for ControlledExecutor {
        fn execute<'a>(
            &'a self,
            _database: &'a str,
            typeql: &'a str,
            _kind: &'a str,
        ) -> std::pin::Pin<
            Box<
                dyn std::future::Future<Output = Result<serde_json::Value, PipelineError>>
                    + Send
                    + 'a,
            >,
        > {
            Box::pin(async move {
                let tx = self
                    .database
                    .transaction_context(type_bridge_orm::session::backend::TxType::Write)
                    .await
                    .map_err(PipelineError::from)?;
                if let Fault::Race(barrier) = &self.fault {
                    barrier.wait().await;
                }
                tx.query(typeql).await.map_err(PipelineError::from)?;
                let unpause = if matches!(self.fault, Fault::Pause) {
                    Some(typed_failure_live::pause_owned_server())
                } else {
                    None
                };
                let result = tokio::time::timeout(
                    std::time::Duration::from_secs(60),
                    tx.commit_classified(),
                )
                .await
                .expect("driver must return an actual commit failure");
                drop(unpause);
                tx.close().await.map_err(PipelineError::from)?;
                result.map_err(|error| {
                    PipelineError::from(crate::typedb::ExecuteError::from(error))
                })?;
                Ok(serde_json::json!({"ok":true}))
            })
        }
        fn is_connected(&self) -> bool {
            true
        }
    }
    let options = type_bridge_orm::ConnectOptions {
        http_port: config.http_port,
        ..Default::default()
    };
    let database = type_bridge_orm::Database::connect_with_options(
        &config.address,
        &name,
        "admin",
        "password",
        options,
    )
    .await
    .unwrap();
    let race_app = create_router(Arc::new(
        crate::pipeline::PipelineBuilder::new(ControlledExecutor {
            database,
            fault: Fault::Race(tokio::sync::Barrier::new(2)),
        })
        .with_default_database(&name)
        .build()
        .unwrap(),
    ));
    let (a, b) = tokio::join!(
        race_app
            .clone()
            .oneshot(request(fixture["purchase"].as_str().unwrap())),
        race_app
            .clone()
            .oneshot(request(fixture["purchase"].as_str().unwrap()))
    );
    let responses = [a.unwrap(), b.unwrap()];
    assert_eq!(
        responses
            .iter()
            .filter(|response| response.status() == StatusCode::OK)
            .count(),
        1
    );
    for response in responses {
        if response.status() != StatusCode::OK {
            assert_eq!(response.status(), StatusCode::BAD_REQUEST);
            let bytes = response.into_body().collect().await.unwrap().to_bytes();
            let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
            assert_eq!(body["error"]["details"]["code"], "STC2", "{body}");
            assert_eq!(body["error"]["details"]["lock_kind"], "exclusive");
            assert_eq!(body["error"]["details"]["retry_safe"], true);
            println!("HTTP stc2: {}", body["error"]["details"]);
        }
    }
    drop(race_app);
    let database = type_bridge_orm::Database::connect_with_options(
        &config.address,
        &name,
        "admin",
        "password",
        options,
    )
    .await
    .unwrap();
    let paused_app = create_router(Arc::new(
        crate::pipeline::PipelineBuilder::new(ControlledExecutor {
            database,
            fault: Fault::Pause,
        })
        .with_default_database(&name)
        .build()
        .unwrap(),
    ));
    let response = paused_app
        .oneshot(request(fixture["paused"].as_str().unwrap()))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(body["error"]["details"]["retry_safe"], false, "{body}");
    assert_eq!(body["error"]["details"]["reason"], serde_json::Value::Null);
    println!("HTTP paused: {}", body["error"]["details"]);
    drop(app);
    admin.delete_database(&name).await.unwrap();
}