Skip to main content

lean_ctx/proxy/
quality_lab_api.rs

1//! POST /v1/quality-lab — run Quality Lab analysis on a text pair.
2
3use axum::Json;
4use axum::response::{IntoResponse, Response};
5use serde::{Deserialize, Serialize};
6
7use super::admitted::{self, GatewayRefusal, Payload};
8use crate::core::context_admission::egress::{EgressTarget, TrustedDestinationBinding};
9use crate::core::quality_lab::orchestrator::{QualityLabReport, run_quality_lab};
10
11#[derive(Deserialize)]
12pub(crate) struct QualityLabRequest {
13    #[serde(default)]
14    pub original: String,
15    #[serde(default)]
16    pub compressed: String,
17    #[serde(default = "default_ext")]
18    pub ext: String,
19}
20
21fn default_ext() -> String {
22    "rs".to_string()
23}
24
25#[derive(Serialize)]
26pub(crate) struct QualityLabResponse {
27    pub report: QualityLabReport,
28}
29
30/// Destination label of the quality lab in receipts. Like `/v1/compress`, the
31/// reply goes to a caller whose onward destination this proxy cannot see.
32const QUALITY_LAB_DESTINATION: &str = "quality-lab";
33
34/// The report is mostly counts and grades, but it is computed from the
35/// caller's text and echoes the caller's `ext` verbatim
36/// (`context_quality.transformation.source_type`). The pair is therefore
37/// admitted by the gateway before it is analysed, the analysis only sees the
38/// admitted form, and the reply bytes are bound to the receipt.
39pub(crate) async fn handler(Json(req): Json<QualityLabRequest>) -> Response {
40    match admitted_report(&req).await {
41        Ok(response) => response,
42        Err(refusal) => refusal.response("OpenAI"),
43    }
44}
45
46async fn admitted_report(req: &QualityLabRequest) -> Result<Response, GatewayRefusal> {
47    // An array, so no member is taken for protocol structure by its key.
48    let mut document = serde_json::json!([req.original, req.compressed, req.ext]);
49    let original_bytes = document.to_string().len();
50    let target = EgressTarget {
51        provider: QUALITY_LAB_DESTINATION,
52        model: None,
53        upstream_base: "",
54    };
55    let mut admission = admitted::admit(
56        Payload::Document(&document),
57        &target,
58        TrustedDestinationBinding::default(),
59    )?;
60    if admission.is_refused() {
61        return Err(admitted::record_refusal(admission, original_bytes, None).await);
62    }
63    if let Some(admitted_document) = admission.take_rewritten() {
64        document = admitted_document;
65    }
66    let text = |index: usize| document[index].as_str().unwrap_or_default();
67    let report = run_quality_lab(text(0), text(1), text(2));
68    let reply = serde_json::to_vec(&QualityLabResponse { report })
69        .map_err(|_| GatewayRefusal::unavailable("egress.encode_failed"))?;
70    admitted::bind_delivery(admission, &reply, original_bytes).await?;
71    Ok((
72        [(axum::http::header::CONTENT_TYPE, "application/json")],
73        reply,
74    )
75        .into_response())
76}
77
78pub(crate) async fn handler_get() -> Response {
79    let report = run_quality_lab("", "", "");
80    Json(QualityLabResponse { report }).into_response()
81}
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86
87    /// The report echoes the caller's `ext`; a protected value in it — or in
88    /// the analysed pair — must not come back in the reply.
89    #[tokio::test]
90    async fn reply_never_echoes_a_protected_value() {
91        let _data = crate::core::data_dir::isolated_data_dir();
92        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
93        let key = concat!("AK", "IAIOSFODNN7EXAMPLE");
94        let response = handler(Json(QualityLabRequest {
95            original: format!("deploy with {key} today\n").repeat(8),
96            compressed: "deploy today".to_owned(),
97            ext: key.to_owned(),
98        }))
99        .await;
100        assert_eq!(response.status(), axum::http::StatusCode::OK);
101        let reply = axum::body::to_bytes(response.into_body(), usize::MAX)
102            .await
103            .expect("reply body");
104        let reply = String::from_utf8_lossy(&reply);
105        assert!(reply.contains("\"report\""), "{reply}");
106        assert!(!reply.contains(key), "the reply echoes the value: {reply}");
107    }
108}