Skip to main content

risingwave_expr_impl/scalar/
ai_decide.rs

1// Copyright 2026 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::sync::LazyLock;
16use std::time::Duration;
17
18use futures::StreamExt;
19use futures::stream::FuturesUnordered;
20use reqwest::Client;
21use risingwave_common::array::{ArrayRef, DataChunk};
22use risingwave_common::log::LogSuppressor;
23use risingwave_common::row::OwnedRow;
24use risingwave_common::types::{
25    DataType, Datum, DatumRef, F64, JsonbRef, JsonbVal, ListValue, MapValue, Scalar, ScalarImpl,
26    StructValue, ToDatumRef,
27};
28use risingwave_expr::expr::{
29    AsyncExpression, AsyncExpressionBoxExt, BoxedExpression, ExpressionInfo, ValueImpl,
30};
31use risingwave_expr::scalar::ai_decide::{QuestionKind, QuestionSchema};
32use risingwave_expr::{ExprError, Result, build_function};
33use serde::Serialize;
34use thiserror_ext::AsReport;
35
36const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
37const RETRY_DELAY: Duration = Duration::from_millis(100);
38const MAX_RETRY_DELAY: Duration = Duration::from_secs(10);
39const MAX_RETRY_AFTER: Duration = Duration::from_secs(5);
40const MAX_RESPONSE_BYTES: usize = 16 * 1024 * 1024;
41
42/// One state is one request. An array in `state` is context, not an HTTP batch.
43#[derive(Serialize)]
44struct Request<'a> {
45    model: &'a str,
46    state: jsonbb::ValueRef<'a>,
47    questions: jsonbb::ValueRef<'a>,
48}
49
50struct AiDecide {
51    children: [BoxedExpression; 4],
52    questions: JsonbVal,
53    return_type: DataType,
54    schema: QuestionSchema,
55    client: Client,
56}
57
58impl std::fmt::Debug for AiDecide {
59    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60        // Arguments may contain credentials or customer state.
61        f.debug_struct("AiDecide").finish_non_exhaustive()
62    }
63}
64
65#[build_function(
66    "ai_decide(jsonb, varchar, varchar, jsonb, varchar) -> struct",
67    volatile,
68    async,
69    type_infer = "unreachable"
70)]
71fn build(return_type: DataType, children: Vec<BoxedExpression>) -> Result<BoxedExpression> {
72    let children: [BoxedExpression; 5] =
73        children.try_into().map_err(|_| ExprError::InvalidParam {
74            name: "ai_decide",
75            reason: "expected exactly five arguments".into(),
76        })?;
77    let Some(ScalarImpl::Jsonb(questions)) = children[3].eval_const()? else {
78        return Err(ExprError::InvalidParam {
79            name: "ai_decide questions",
80            reason: "must be constant non-null JSONB".into(),
81        });
82    };
83    let schema = QuestionSchema::parse(&questions)?;
84    if return_type != schema.return_type() {
85        return Err(ExprError::InvalidParam {
86            name: "ai_decide",
87            reason: "return type does not match fixed questions".into(),
88        });
89    }
90    let client = Client::builder()
91        .timeout(REQUEST_TIMEOUT)
92        .redirect(reqwest::redirect::Policy::none())
93        .build()
94        .map_err(|_| request_error("could not initialize HTTP client"))?;
95    let [state, url, model, _, api_key] = children;
96    Ok(AiDecide {
97        children: [state, url, model, api_key],
98        questions,
99        return_type,
100        schema,
101        client,
102    }
103    .boxed())
104}
105
106fn request_error(message: impl std::fmt::Display) -> ExprError {
107    // Do not attach the request, response body, URL, or function arguments to errors.
108    ExprError::Custom(format!("ai_decide: {message}"))
109}
110
111/// Decode strictly before the result can be persisted. Invalid responses are retried
112/// inside the request loop, without reaching non-strict expression wrappers.
113/// An explicit provider refusal is a valid unanswered question, represented by SQL NULL.
114fn decode_response(response: JsonbVal, schema: &QuestionSchema) -> Result<StructValue> {
115    let response = response.take();
116    let answers = response
117        .get("answers")
118        .and_then(serde_json::Value::as_object)
119        .ok_or_else(|| request_error("response must contain an answers object"))?;
120    let mut fields = Vec::with_capacity(schema.0.len());
121    for question in &schema.0 {
122        let error = |field: &str| {
123            request_error(format!(
124                "invalid response for question {:?}: {field}",
125                question.id
126            ))
127        };
128        let answer = answers
129            .get(&question.id)
130            .and_then(serde_json::Value::as_object)
131            .ok_or_else(|| error("missing answer object"))?;
132        if answer.get("type").and_then(serde_json::Value::as_str) == Some("refusal") {
133            fields.push(None);
134            continue;
135        }
136        let expected = match &question.kind {
137            QuestionKind::Noul => "noul",
138            QuestionKind::Choice(_) => "choice",
139            QuestionKind::Score(_) => "score",
140        };
141        if answer.get("type").and_then(serde_json::Value::as_str) != Some(expected) {
142            return Err(error("answer type does not match the question"));
143        }
144        let number = |field: &str, maximum: f64| -> Result<F64> {
145            answer
146                .get(field)
147                .and_then(serde_json::Value::as_f64)
148                .filter(|v| v.is_finite() && (0.0..=maximum).contains(v))
149                .map(F64::from)
150                .ok_or_else(|| error(field))
151        };
152        let value = if let QuestionKind::Noul = &question.kind {
153            ScalarImpl::Float64(number("noul", 1.0)?)
154        } else {
155            let confidence = number("confidence", 1.0)?;
156            let probabilities = answer
157                .get("probabilities")
158                .and_then(serde_json::Value::as_object)
159                .ok_or_else(|| error("missing probabilities object"))?;
160            let keys = match &question.kind {
161                QuestionKind::Choice(labels) => labels.clone(),
162                QuestionKind::Score(count) => (0..*count).map(|i| i.to_string()).collect(),
163                QuestionKind::Noul => unreachable!(),
164            };
165            if probabilities.len() != keys.len() {
166                return Err(error(
167                    "probabilities must contain exactly the declared options",
168                ));
169            }
170            let distribution = keys
171                .iter()
172                .map(|key| {
173                    probabilities
174                        .get(key)
175                        .and_then(serde_json::Value::as_f64)
176                        .filter(|v| v.is_finite() && (0.0..=1.0).contains(v))
177                        .ok_or_else(|| error("missing or invalid probability"))
178                })
179                .collect::<Result<Vec<_>>>()?;
180            // Services may round each probability independently. Preserve their values
181            // rather than imposing a precision or silently renormalizing the answer.
182            let distribution = ListValue::from_iter(distribution.into_iter().map(F64::from));
183            let (value, probabilities) = match &question.kind {
184                QuestionKind::Choice(labels) => {
185                    let choice = answer
186                        .get("choice")
187                        .and_then(serde_json::Value::as_str)
188                        .filter(|s| labels.iter().any(|label| label == s))
189                        .ok_or_else(|| error("choice must be a declared option"))?;
190                    let probabilities = MapValue::try_from_kv(
191                        ListValue::from_iter(labels.iter().map(String::as_str)),
192                        distribution,
193                    )
194                    .map_err(|_| error("invalid probability map"))?;
195                    (
196                        ScalarImpl::Utf8(choice.into()),
197                        ScalarImpl::Map(probabilities),
198                    )
199                }
200                QuestionKind::Score(count) => (
201                    ScalarImpl::Float64(number("score", (count - 1) as f64)?),
202                    ScalarImpl::List(distribution),
203                ),
204                QuestionKind::Noul => unreachable!(),
205            };
206            ScalarImpl::Struct(StructValue::new(vec![
207                Some(value),
208                Some(confidence.into()),
209                Some(probabilities),
210            ]))
211        };
212        fields.push(Some(value));
213    }
214    Ok(StructValue::new(fields))
215}
216
217impl AiDecide {
218    async fn request(
219        &self,
220        state: JsonbRef<'_>,
221        url: &str,
222        model: &str,
223        api_key: &str,
224    ) -> Result<StructValue> {
225        let url = reqwest::Url::parse(url).map_err(|_| request_error("invalid model_url"))?;
226        if !matches!(url.scheme(), "http" | "https")
227            || !url.username().is_empty()
228            || url.password().is_some()
229        {
230            return Err(request_error(
231                "model_url must be an HTTP(S) URL without embedded credentials",
232            ));
233        }
234        let request = self
235            .client
236            .post(url)
237            .bearer_auth(api_key)
238            .json(&Request {
239                model,
240                state: state.into(),
241                questions: self.questions.as_scalar_ref().into(),
242            })
243            .build()
244            .map_err(|_| request_error("could not build HTTP request"))?;
245        let mut backoff = RETRY_DELAY;
246        loop {
247            let mut delay = backoff;
248            // Drop the response and its bytes before sleeping. Retry the same serialized
249            // request for every remote failure, including invalid success responses.
250            let result = async {
251                let mut response = self
252                    .client
253                    .execute(request.try_clone().expect("JSON body is cloneable"))
254                    .await
255                    .map_err(|err| {
256                        request_error(if err.is_timeout() {
257                            "HTTP request timed out"
258                        } else {
259                            "HTTP transport failed"
260                        })
261                    })?;
262                let status = response.status();
263                if !status.is_success() {
264                    if let Some(seconds) = response
265                        .headers()
266                        .get(reqwest::header::RETRY_AFTER)
267                        .and_then(|value| value.to_str().ok())
268                        .and_then(|value| value.parse::<u64>().ok())
269                    {
270                        delay = Duration::from_secs(seconds).min(MAX_RETRY_AFTER);
271                    }
272                    return Err(request_error(format!("HTTP {status}")));
273                }
274                let too_large =
275                    || request_error(format!("response exceeds {} bytes", MAX_RESPONSE_BYTES));
276                if response
277                    .content_length()
278                    .is_some_and(|len| len > MAX_RESPONSE_BYTES as u64)
279                {
280                    return Err(too_large());
281                }
282                let mut bytes = Vec::new();
283                while let Some(chunk) = response
284                    .chunk()
285                    .await
286                    .map_err(|_| request_error("HTTP response body read failed"))?
287                {
288                    if chunk.len() > MAX_RESPONSE_BYTES.saturating_sub(bytes.len()) {
289                        return Err(too_large());
290                    }
291                    bytes.extend_from_slice(&chunk);
292                }
293                let json = jsonbb::Value::from_text(&bytes)
294                    .map(JsonbVal::from)
295                    .map_err(|_| request_error("successful response is not valid JSON"))?;
296                decode_response(json, &self.schema)
297            }
298            .await;
299            match result {
300                Ok(value) => return Ok(value),
301                Err(error) => {
302                    static LOG_SUPPRESSOR: LazyLock<LogSuppressor> =
303                        LazyLock::new(LogSuppressor::default);
304                    if let Ok(suppressed_count) = LOG_SUPPRESSOR.check() {
305                        // Only sanitized errors: never log credentials, URL or payloads.
306                        tracing::error!(error = %error.as_report(), ?delay, suppressed_count, "AI_DECIDE request failed, retrying");
307                    }
308                }
309            }
310            // Dropping evaluation also cancels the backoff sleep.
311            tokio::time::sleep(delay).await;
312            backoff = backoff.saturating_mul(2).min(MAX_RETRY_DELAY);
313        }
314    }
315
316    async fn evaluate(&self, args: [DatumRef<'_>; 4]) -> Result<Option<StructValue>> {
317        let [Some(state), Some(url), Some(model), Some(api_key)] = args else {
318            return Ok(None);
319        };
320        self.request(
321            state.into_jsonb(),
322            url.into_utf8(),
323            model.into_utf8(),
324            api_key.into_utf8(),
325        )
326        .await
327        .map(Some)
328    }
329}
330
331impl ExpressionInfo for AiDecide {
332    fn return_type(&self) -> DataType {
333        self.return_type.clone()
334    }
335}
336
337impl AsyncExpression for AiDecide {
338    async fn eval(&self, input: &DataChunk) -> Result<ArrayRef> {
339        let mut values = Vec::with_capacity(4);
340        for child in &self.children {
341            values.push(child.eval_v2(input).await?);
342        }
343        let mut results = (0..input.capacity())
344            .map(|index| {
345                let values = &values;
346                async move {
347                    if !input.visibility().is_set(index) {
348                        return (index, Ok(None));
349                    }
350                    let value = self
351                        .evaluate(std::array::from_fn(|i| match &values[i] {
352                            ValueImpl::Array(array) => array.value_at(index),
353                            ValueImpl::Scalar { value, .. } => value.to_datum_ref(),
354                        }))
355                        .await;
356                    (index, value)
357                }
358            })
359            .collect::<FuturesUnordered<_>>();
360        // Preserve successful rows when another row cannot construct its request.
361        // NonStrict uses the partial array in Multiple; strict wrappers still report an error.
362        let mut ordered_results = vec![None; input.capacity()];
363        let mut errors = Vec::new();
364        while let Some((index, result)) = results.next().await {
365            match result {
366                Ok(value) => ordered_results[index] = value,
367                Err(error) => errors.push(error),
368            }
369        }
370        let mut builder = self.return_type().create_array_builder(input.capacity());
371        for result in ordered_results {
372            builder.append(result.map(ScalarImpl::Struct));
373        }
374        let array = builder.finish().into_ref();
375        if errors.is_empty() {
376            Ok(array)
377        } else {
378            Err(ExprError::Multiple(array, errors.into()))
379        }
380    }
381
382    async fn eval_row(&self, input: &OwnedRow) -> Result<Datum> {
383        let mut args = Vec::with_capacity(4);
384        for child in &self.children {
385            args.push(child.eval_row(input).await?);
386        }
387        self.evaluate(std::array::from_fn(|i| {
388            args[i].as_ref().map(ScalarImpl::as_scalar_ref_impl)
389        }))
390        .await
391        .map(|value| value.map(ScalarImpl::Struct))
392    }
393}
394
395#[cfg(all(test, not(madsim)))]
396mod tests {
397    use std::sync::Arc;
398    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
399
400    use axum::http::{HeaderMap, StatusCode};
401    use axum::response::IntoResponse;
402    use axum::routing::post;
403    use axum::{Json, Router};
404    use risingwave_common::array::{Array, ArrayBuilder, JsonbArrayBuilder, Utf8Array};
405    use risingwave_expr::expr::{
406        InputRefExpression, LiteralExpression, LogReport, NonStrictExpression,
407        SyncExpressionBoxExt, build_func,
408    };
409    use risingwave_pb::expr::expr_node::Type as ExprType;
410    use serde_json::{Value, json};
411    use tokio::io::{AsyncReadExt, AsyncWriteExt};
412    use tokio::sync::{Barrier, Semaphore};
413
414    use super::*;
415
416    struct Server {
417        url: String,
418        task: tokio::task::JoinHandle<()>,
419    }
420
421    impl Drop for Server {
422        fn drop(&mut self) {
423            self.task.abort();
424        }
425    }
426
427    async fn server(router: Router) -> Server {
428        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
429        let url = format!("http://{}/evaluate", listener.local_addr().unwrap());
430        let task = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
431        Server { url, task }
432    }
433
434    fn expression(timeout: Duration) -> AiDecide {
435        AiDecide {
436            schema: test_schema(),
437            questions: test_questions(),
438            return_type: test_schema().return_type(),
439            children: [0, 1, 2, 4].map(|i| {
440                let ty = if i == 0 {
441                    DataType::Jsonb
442                } else {
443                    DataType::Varchar
444                };
445                InputRefExpression::new(ty, i).boxed()
446            }),
447            client: Client::builder()
448                .timeout(timeout)
449                .no_proxy()
450                .redirect(reqwest::redirect::Policy::none())
451                .build()
452                .unwrap(),
453        }
454    }
455
456    fn test_questions() -> JsonbVal {
457        JsonbVal::from(json!({"q": {"type": "noul", "instructions": "Test probability?"}}))
458    }
459
460    fn test_schema() -> QuestionSchema {
461        QuestionSchema::parse(&test_questions()).unwrap()
462    }
463
464    fn score_at(array: &ArrayRef, index: usize) -> Option<f64> {
465        array
466            .as_struct()
467            .value_at(index)
468            .map(|value| value.field_at(0).unwrap().into_float64().0)
469    }
470
471    #[test]
472    fn decodes_mixed_answers_without_losing_distributions() {
473        let schema = QuestionSchema::parse(&JsonbVal::from(json!({
474            "refund":{"type":"noul","instructions":"Refund?"},
475            "team":{"type":"choice","instructions":"Team?","criteria":{"billing":"Payments","tech":"Bugs"}},
476            "urgency":{"type":"score","instructions":"Urgent?","criteria":["Routine","Soon","Blocking"]}
477        }))).unwrap();
478        let response = json!({"answers":{
479            "refund":{"type":"noul","noul":0.8},
480            "team":{"type":"choice","choice":"billing","confidence":0.6,"probabilities":{"tech":0.2,"billing":0.8}},
481            "urgency":{"type":"score","score":1.25,"confidence":0.4,"probabilities":{"2":0.5,"0":0.25,"1":0.25}}
482        },"unknown_metadata":true});
483        let result = decode_response(JsonbVal::from(response.clone()), &schema).unwrap();
484        assert_eq!(result.fields()[0], Some(ScalarImpl::Float64(0.8.into())));
485        let team = result.fields()[1].as_ref().unwrap().as_struct();
486        assert_eq!(team.fields()[0], Some(ScalarImpl::Utf8("billing".into())));
487        assert_eq!(team.fields()[1], Some(ScalarImpl::Float64(0.6.into())));
488        let expected_map = MapValue::try_from_kv(
489            ListValue::from_iter(["billing", "tech"]),
490            ListValue::from_iter([F64::from(0.8), F64::from(0.2)]),
491        )
492        .unwrap();
493        assert_eq!(team.fields()[2], Some(ScalarImpl::Map(expected_map)));
494        let urgency = result.fields()[2].as_ref().unwrap().as_struct();
495        assert_eq!(urgency.fields()[0], Some(ScalarImpl::Float64(1.25.into())));
496        assert_eq!(
497            urgency.fields()[2],
498            Some(ScalarImpl::List(ListValue::from_iter([
499                F64::from(0.25),
500                F64::from(0.25),
501                F64::from(0.5)
502            ])))
503        );
504
505        // Refusals are valid for every question kind and preserve successful siblings.
506        for refused in [
507            vec!["refund"],
508            vec!["team"],
509            vec!["urgency"],
510            vec!["refund", "team", "urgency"],
511        ] {
512            let mut mixed = response.clone();
513            let mut expected = result.fields().to_vec();
514            for id in refused {
515                mixed["answers"][id] = json!({"type": "refusal"});
516                let index = schema
517                    .0
518                    .iter()
519                    .position(|question| question.id == id)
520                    .unwrap();
521                expected[index] = None;
522            }
523            assert_eq!(
524                decode_response(JsonbVal::from(mixed), &schema).unwrap(),
525                StructValue::new(expected)
526            );
527        }
528
529        let mut rounded = response.clone();
530        rounded["answers"]["urgency"]["probabilities"] =
531            json!({"0": 0.3333, "1": 0.3333, "2": 0.3333});
532        let rounded = decode_response(JsonbVal::from(rounded), &schema).unwrap();
533        assert_eq!(
534            rounded.fields()[2].as_ref().unwrap().as_struct().fields()[2],
535            Some(ScalarImpl::List(ListValue::from_iter(
536                [F64::from(0.3333); 3]
537            )))
538        );
539
540        for (pointer, value) in [
541            ("/answers/refund", Value::Null),
542            ("/answers/refund", json!({})),
543            ("/answers/refund/type", Value::Null),
544            ("/answers/refund/type", json!("unknown")),
545            ("/answers/refund/noul", json!(1.1)),
546            ("/answers/refund/noul", json!("test-only-key")),
547            ("/answers/team/type", json!("score")),
548            ("/answers/team/choice", json!("undeclared")),
549            ("/answers/team/confidence", Value::Null),
550            ("/answers/team/probabilities", json!({"billing":0.8})),
551            (
552                "/answers/team/probabilities",
553                json!({"billing":0.8,"other":0.2}),
554            ),
555            ("/answers/team/probabilities/tech", json!(1.2)),
556            ("/answers/team/probabilities/tech", json!(-0.2)),
557            ("/answers/urgency/score", json!(3.0)),
558            ("/answers/urgency/probabilities", json!([0.25, 0.25, 0.5])),
559        ] {
560            let mut malformed = response.clone();
561            *malformed.pointer_mut(pointer).unwrap() = value;
562            let error = decode_response(JsonbVal::from(malformed), &schema).unwrap_err();
563            assert!(matches!(error, ExprError::Custom(_)), "{pointer}");
564            assert!(!error.to_string().contains("test-only-key"));
565        }
566    }
567
568    async fn call(expr: &AiDecide, url: &str) -> Result<StructValue> {
569        expr.request(
570            JsonbVal::from(json!({"messages": ["I received the refund."]})).as_scalar_ref(),
571            url,
572            "test-model",
573            "test-only-key",
574        )
575        .await
576    }
577
578    #[tokio::test]
579    async fn scalar_arguments_and_request_contract() {
580        let server = server(Router::new().route("/evaluate", post(|headers: HeaderMap, Json(body): Json<Value>| async move {
581            assert_eq!(headers["authorization"], "Bearer test-only-key");
582            assert_eq!(body["model"], "test-model");
583            assert_eq!(body["state"]["messages"][0], "I received the refund.");
584            assert_eq!(body["questions"]["q"]["instructions"], "Resolved?");
585            Json(json!({"answers": {"q": {"type": "noul", "noul": 0.99}}, "unknown_metadata": [1, null, true]}))
586        }))).await;
587        let mut expr = expression(REQUEST_TIMEOUT);
588        expr.questions =
589            JsonbVal::from(json!({"q": {"type": "noul", "instructions": "Resolved?"}}));
590        expr.children = [
591            LiteralExpression::new(
592                DataType::Jsonb,
593                Some(JsonbVal::from(json!({"messages": ["I received the refund."]})).into()),
594            )
595            .boxed(),
596            LiteralExpression::new(DataType::Varchar, Some(server.url.clone().into())).boxed(),
597            LiteralExpression::new(DataType::Varchar, Some("test-model".into())).boxed(),
598            LiteralExpression::new(DataType::Varchar, Some("test-only-key".into())).boxed(),
599        ];
600        // The credential is actually present in a child, so formatting the children
601        // would make this assertion fail.
602        assert!(format!("{:?}", expr.children[3]).contains("test-only-key"));
603        assert!(!format!("{expr:?}").contains("test-only-key"));
604        let output = expr.eval(&DataChunk::new_dummy(3)).await.unwrap();
605        for i in 0..3 {
606            assert_eq!(score_at(&output, i), Some(0.99));
607        }
608        assert_eq!(
609            expr.eval_row(&OwnedRow::empty()).await.unwrap(),
610            output.datum_at(0)
611        );
612    }
613
614    // Raw HTTP permits deliberately truncated and chunked responses that an HTTP
615    // framework would repair or reject before sending.
616    async fn raw_server(responses: Vec<Vec<u8>>, attempts: Arc<AtomicUsize>) -> Server {
617        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
618        let url = format!("http://{}/evaluate", listener.local_addr().unwrap());
619        let task = tokio::spawn(async move {
620            let mut first_body = None;
621            loop {
622                let (mut socket, _) = listener.accept().await.unwrap();
623                let mut request = Vec::new();
624                let header_end = loop {
625                    let byte = socket.read_u8().await.unwrap();
626                    request.push(byte);
627                    if request.ends_with(b"\r\n\r\n") {
628                        break request.len();
629                    }
630                };
631                let headers = String::from_utf8_lossy(&request).to_ascii_lowercase();
632                let length: usize = headers
633                    .lines()
634                    .find_map(|line| line.strip_prefix("content-length: "))
635                    .unwrap()
636                    .parse()
637                    .unwrap();
638                request.resize(header_end + length, 0);
639                socket.read_exact(&mut request[header_end..]).await.unwrap();
640                let body = request[header_end..].to_vec();
641                if let Some(first) = &first_body {
642                    assert_eq!(&body, first, "retries must preserve the request body");
643                } else {
644                    first_body = Some(body);
645                }
646                let index = attempts.fetch_add(1, Ordering::SeqCst);
647                let response = &responses[index.min(responses.len() - 1)];
648                // A size-limit rejection may close the socket before all bytes are sent.
649                let _ = socket.write_all(response).await;
650                let _ = socket.shutdown().await;
651            }
652        });
653        Server { url, task }
654    }
655
656    fn complete_response(body: &str) -> Vec<u8> {
657        format!(
658            "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
659            body.len()
660        )
661        .into_bytes()
662    }
663
664    #[tokio::test]
665    async fn retries_all_remote_errors_until_a_valid_answer() {
666        let good = r#"{"answers":{"q":{"type":"noul","noul":0.5}}}"#;
667        let oversized = " ".repeat(MAX_RESPONSE_BYTES + 1);
668        let mut responses = vec![
669            complete_response("test-only-key is not JSON"),
670            complete_response(r#"{"answers":{"q":{"type":"noul","noul":2}}}"#),
671            b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\nConnection: close\r\n\r\n{\"answers\":".to_vec(),
672            format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", MAX_RESPONSE_BYTES + 1).into_bytes(),
673            format!("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n{:x}\r\n{}\r\n0\r\n\r\n", oversized.len(), oversized).into_bytes(),
674        ];
675        responses.extend([429, 503, 401, 400, 307].into_iter().map(|status| {
676            // Exercise the fixed Retry-After cap once; other statuses need no delay.
677            let retry_after = if status == 429 { 100 } else { 0 };
678            format!("HTTP/1.1 {status} Test\r\nContent-Length: 0\r\nRetry-After: {retry_after}\r\nLocation: /wrong\r\nConnection: close\r\n\r\n").into_bytes()
679        }));
680        responses.push(complete_response(good));
681        let expected = responses.len();
682        let attempts = Arc::new(AtomicUsize::new(0));
683        let server = raw_server(responses, attempts.clone()).await;
684        let expr = expression(REQUEST_TIMEOUT);
685        let value = tokio::time::timeout(Duration::from_secs(20), call(&expr, &server.url))
686            .await
687            .unwrap()
688            .unwrap();
689        assert_eq!(value.fields()[0], Some(ScalarImpl::Float64(0.5.into())));
690        assert_eq!(attempts.load(Ordering::SeqCst), expected);
691    }
692
693    #[tokio::test]
694    async fn retries_timeouts_until_success() {
695        let attempts = Arc::new(AtomicUsize::new(0));
696        let seen = attempts.clone();
697        let server = server(Router::new().route(
698            "/evaluate",
699            post(move || {
700                let attempt = seen.fetch_add(1, Ordering::SeqCst);
701                async move {
702                    if attempt < 4 {
703                        tokio::time::sleep(Duration::from_millis(200)).await;
704                    }
705                    Json(json!({"answers":{"q":{"type":"noul","noul":0.5}}}))
706                }
707            }),
708        ))
709        .await;
710        let expr = expression(Duration::from_millis(50));
711        let value = tokio::time::timeout(Duration::from_secs(5), call(&expr, &server.url))
712            .await
713            .unwrap()
714            .unwrap();
715        assert_eq!(value.fields()[0], Some(ScalarImpl::Float64(0.5.into())));
716        assert_eq!(attempts.load(Ordering::SeqCst), 5);
717    }
718
719    fn chunk(url: &str, count: usize) -> DataChunk {
720        let mut states = JsonbArrayBuilder::new(count);
721        let mut questions = JsonbArrayBuilder::new(count);
722        for i in 0..count {
723            states.append_owned((i != 1).then(|| JsonbVal::from(json!({"index": i}))));
724            questions.append_owned(Some(JsonbVal::from(json!({"q": {"type": "noul"}}))));
725        }
726        DataChunk::new(
727            vec![
728                states.finish().into_ref(),
729                Utf8Array::from_iter(std::iter::repeat_n(Some(url), count)).into_ref(),
730                Utf8Array::from_iter(std::iter::repeat_n(Some("test-model"), count)).into_ref(),
731                questions.finish().into_ref(),
732                Utf8Array::from_iter(std::iter::repeat_n(Some("test-only-key"), count)).into_ref(),
733            ],
734            (0..count)
735                .map(|i| i != 2)
736                .collect::<risingwave_common::bitmap::Bitmap>(),
737        )
738    }
739
740    #[tokio::test]
741    async fn request_construction_errors_preserve_other_rows() {
742        let requests = Arc::new(AtomicUsize::new(0));
743        let seen = requests.clone();
744        let server = server(Router::new().route(
745            "/evaluate",
746            post(move |Json(body): Json<Value>| {
747                seen.fetch_add(1, Ordering::SeqCst);
748                async move {
749                    let index = body["state"]["index"].as_u64().unwrap();
750                    Json(json!({"answers":{"q":{"type":"noul","noul":index as f64 / 10.0}}}))
751                }
752            }),
753        ))
754        .await;
755        let (mut columns, visibility) = chunk(&server.url, 8).into_parts();
756        columns[1] = Utf8Array::from_iter([
757            Some(server.url.as_str()),
758            Some("invalid"), // NULL state: no request or error.
759            Some("invalid"), // Invisible row: no request or error.
760            Some("invalid"),
761            Some(server.url.as_str()),
762            Some("ftp://example.com"),
763            Some(server.url.as_str()),
764            Some(server.url.as_str()),
765        ])
766        .into_ref();
767        columns[4] = Utf8Array::from_iter(
768            (0..8).map(|i| Some(if i == 6 { "secret\nkey" } else { "test-key" })),
769        )
770        .into_ref();
771        let input = DataChunk::new(columns, visibility);
772        let expr = expression(REQUEST_TIMEOUT);
773        let Err(ExprError::Multiple(partial, errors)) = expr.eval(&input).await else {
774            panic!("row errors must carry the successful results");
775        };
776        let errors: Vec<_> = errors.into_iter().collect();
777        assert_eq!(errors.len(), 3);
778        assert!(
779            errors
780                .iter()
781                .all(|error| !error.to_string().contains("secret"))
782        );
783        let expr = NonStrictExpression::new_topmost(expr.boxed(), LogReport);
784        let output = expr.eval_infallible(&input).await;
785        for array in [&partial, &output] {
786            for i in 0..8 {
787                assert_eq!(
788                    score_at(array, i),
789                    [0, 4, 7].contains(&i).then_some(i as f64 / 10.0)
790                );
791            }
792        }
793        assert_eq!(requests.load(Ordering::SeqCst), 6);
794    }
795
796    #[tokio::test]
797    async fn registered_expression_evaluates_all_visible_rows_across_chunks() {
798        // Each chunk has 20 rows, minus one NULL and one invisible row. Hold every request
799        // until all 36 have arrived: neither a per-chunk nor a shared limit may block them.
800        let ready = Arc::new(Barrier::new(36));
801        let requests = Arc::new(AtomicUsize::new(0));
802        let seen = requests.clone();
803        let server = server(Router::new().route(
804            "/evaluate",
805            post(move |Json(body): Json<Value>| {
806                let (ready, seen) = (ready.clone(), seen.clone());
807                async move {
808                    seen.fetch_add(1, Ordering::SeqCst);
809                    ready.wait().await;
810                    let index = body["state"]["index"].as_u64().unwrap();
811                    Json(json!({"answers": {"q": {"type": "noul", "noul": index as f64 / 100.0}}}))
812                }
813            }),
814        ))
815        .await;
816        let mut children: Vec<_> = expression(REQUEST_TIMEOUT).children.into_iter().collect();
817        children.insert(
818            3,
819            LiteralExpression::new(DataType::Jsonb, Some(test_questions().into())).boxed(),
820        );
821        let expr = build_func(ExprType::AiDecide, test_schema().return_type(), children).unwrap();
822        let input = chunk(&server.url, 20);
823        let (left, right) = tokio::time::timeout(Duration::from_secs(5), async {
824            tokio::join!(expr.eval(&input), expr.eval(&input))
825        })
826        .await
827        .expect("all eligible rows in both chunks must start without an internal limit");
828        for output in [left.unwrap(), right.unwrap()] {
829            for i in 0..20 {
830                assert_eq!(
831                    score_at(&output, i),
832                    (![1, 2].contains(&i)).then_some(i as f64 / 100.0)
833                );
834            }
835        }
836        assert_eq!(requests.load(Ordering::SeqCst), 36);
837
838        let empty = expr.eval(&chunk(&server.url, 0)).await.unwrap();
839        assert_eq!(empty.len(), 0);
840        assert_eq!(requests.load(Ordering::SeqCst), 36);
841    }
842
843    #[tokio::test]
844    async fn persistent_failure_retries_until_cancelled() {
845        let healthy = Arc::new(AtomicBool::new(false));
846        let service_healthy = healthy.clone();
847        let (started, mut attempts) = tokio::sync::mpsc::unbounded_channel();
848        let server = server(Router::new().route(
849            "/evaluate",
850            post(move || {
851                let healthy = service_healthy.load(Ordering::SeqCst);
852                started.send(()).unwrap();
853                async move {
854                    if healthy {
855                        Json(json!({"answers":{"q":{"type":"noul","noul":0.5}}})).into_response()
856                    } else {
857                        StatusCode::UNAUTHORIZED.into_response()
858                    }
859                }
860            }),
861        ))
862        .await;
863        let expr = Arc::new(expression(REQUEST_TIMEOUT));
864        let input = chunk(&server.url, 1);
865        let task = {
866            let expr = expr.clone();
867            let input = input.clone();
868            tokio::spawn(async move { expr.eval(&input).await })
869        };
870        for _ in 0..6 {
871            tokio::time::timeout(Duration::from_secs(5), attempts.recv())
872                .await
873                .unwrap()
874                .unwrap();
875        }
876        assert!(
877            !task.is_finished(),
878            "permanent HTTP failures must stay inside the retry loop"
879        );
880        task.abort();
881        assert!(task.await.unwrap_err().is_cancelled());
882        healthy.store(true, Ordering::SeqCst);
883        let result = tokio::time::timeout(Duration::from_secs(5), expr.eval(&input))
884            .await
885            .unwrap()
886            .unwrap();
887        assert_eq!(score_at(&result, 0), Some(0.5));
888    }
889
890    #[tokio::test]
891    async fn any_null_argument_skips_request() {
892        let expr = expression(REQUEST_TIMEOUT);
893        for null_index in [0, 1, 2, 4] {
894            let mut args = vec![
895                Some(ScalarImpl::Jsonb(JsonbVal::empty_object())),
896                Some(ScalarImpl::Utf8("invalid URL".into())),
897                Some(ScalarImpl::Utf8("model".into())),
898                Some(ScalarImpl::Jsonb(JsonbVal::empty_object())),
899                Some(ScalarImpl::Utf8("key".into())),
900            ];
901            args[null_index] = None;
902            assert!(expr.eval_row(&OwnedRow::new(args)).await.unwrap().is_none());
903        }
904    }
905
906    #[tokio::test]
907    async fn completes_later_rows_while_first_is_blocked_and_restores_order() {
908        let first = Arc::new(Semaphore::new(0));
909        let gate = first.clone();
910        let completed = Arc::new(AtomicUsize::new(0));
911        let seen = completed.clone();
912        let server = server(Router::new().route(
913            "/evaluate",
914            post(move |Json(body): Json<Value>| {
915                let gate = gate.clone();
916                let seen = seen.clone();
917                async move {
918                    let index = body["state"]["index"].as_u64().unwrap();
919                    if index == 0 {
920                        gate.acquire().await.unwrap().forget();
921                    }
922                    seen.fetch_add(1, Ordering::SeqCst);
923                    Json(json!({"answers": {"q": {"type": "noul", "noul": index as f64 / 100.0}}}))
924                }
925            }),
926        ))
927        .await;
928        let expr = expression(REQUEST_TIMEOUT);
929        let input = chunk(&server.url, 30);
930        let evaluation = expr.eval(&input);
931        futures::pin_mut!(evaluation);
932        tokio::select! {
933            result = &mut evaluation => panic!("first row was not released: {result:?}"),
934            _ = async {
935                tokio::time::timeout(Duration::from_secs(5), async {
936                    // 30 rows minus SQL NULL, invisible row and the blocked first row.
937                    while completed.load(Ordering::SeqCst) != 27 {
938                        tokio::time::sleep(Duration::from_millis(1)).await;
939                    }
940                }).await.expect("later rows must complete independently of the first row");
941            } => {}
942        }
943        first.add_permits(1);
944        let output = evaluation.await.unwrap();
945        for i in 0..30 {
946            assert_eq!(
947                score_at(&output, i),
948                (![1, 2].contains(&i)).then_some(i as f64 / 100.0)
949            );
950        }
951    }
952}