Skip to main content

reddb_server/runtime/ai/
pg_wire_ask_row_encoder.rs

1//! `PgWireAskRowEncoder` — pure encoder that turns an
2//! [`AskResult`](super::ask_response_envelope::AskResult) into the
3//! single-row Postgres-wire result set that #408 exposes to psycopg /
4//! pgx / JDBC.
5//!
6//! Deep module: no I/O, no transport, no clock. Mirrors the slice-1
7//! pattern used by #395, #396, #398, #400, #401, #402, #403, #405,
8//! #406, #409, #411 — the contract is pinned in tests so the wiring
9//! slice (extended-query handler in `wire::postgres`) cannot drop or
10//! rename a column.
11//!
12//! ## Why a separate module
13//!
14//! The acceptance criteria for #408 demand that ASK over PG-wire
15//! returns a single-row result set with stable columns and stable
16//! OIDs across every PG client. Three different drivers (psycopg, pgx,
17//! JDBC) read columns by index after a `RowDescription`; renaming or
18//! reordering a column silently breaks every integration test in this
19//! issue's blocker chain. Building the row in a tested deep module
20//! keeps the wiring slice focused on "where do I hand these bytes to
21//! the PG codec" and the contract here on "are the bytes right".
22//!
23//! ## Shape pinned by tests
24//!
25//! Twelve columns, alphabetised — exact same order as the JSON keys
26//! [`AskResponseEnvelope::build`](super::ask_response_envelope::build)
27//! emits. Sharing the order means a bridge that takes the envelope
28//! JSON object and projects it column-wise stays index-aligned without
29//! re-shuffling.
30//!
31//! | # | Name              | OID                  | Format                                      |
32//! |---|-------------------|----------------------|---------------------------------------------|
33//! | 0 | `answer`          | `text` (25)          | UTF-8                                       |
34//! | 1 | `cache_hit`       | `bool` (16)          | `"t"` / `"f"`                               |
35//! | 2 | `citations`       | `jsonb` (3802)       | compact JSON, marker-ascending              |
36//! | 3 | `completion_tokens` | `int8` (20)        | decimal                                     |
37//! | 4 | `cost_usd`        | `numeric` (1700)     | decimal, `f64::to_string` form              |
38//! | 5 | `mode`            | `text` (25)          | `"strict"` / `"lenient"`                    |
39//! | 6 | `model`           | `text` (25)          | UTF-8                                       |
40//! | 7 | `prompt_tokens`   | `int8` (20)          | decimal                                     |
41//! | 8 | `provider`        | `text` (25)          | UTF-8                                       |
42//! | 9 | `retry_count`     | `int8` (20)          | decimal (0 or 1 per #395)                   |
43//! |10 | `sources_flat`    | `jsonb` (3802)       | compact JSON, RRF order preserved           |
44//! |11 | `validation`      | `jsonb` (3802)       | compact JSON `{errors, ok, warnings}`       |
45//!
46//! ## Why text format
47//!
48//! Binary format is opt-in via `Bind`'s result-column format codes.
49//! The existing PG-wire surface (`wire::postgres::types`) only emits
50//! text — see `value_to_pg_wire_bytes`. ASK rides the same codec, so
51//! every cell here is a UTF-8 byte buffer.
52//!
53//! ## Why numeric for cost_usd
54//!
55//! PG `numeric` is the only PG type with arbitrary precision and no
56//! representation loss across the wire. `float8` would round
57//! `0.0000001` to scientific form and trip JDBC `BigDecimal` parsing.
58//! `f64::to_string()` produces the canonical Rust form which PG's
59//! `numeric` parser accepts verbatim.
60//!
61//! ## Why jsonb (not json)
62//!
63//! psycopg ≥ 3 maps `jsonb` to native dicts; pgx exposes a
64//! `pgtype.JSONB` decoder; JDBC's PG driver routes `jsonb` to
65//! `PGobject` with `getType() == "jsonb"`. Returning `jsonb` lets
66//! every supported driver decode the column without an explicit cast.
67
68use crate::runtime::ai::ask_response_envelope::{
69    self, AskResult, Citation, SourceRow, Validation, ValidationError, ValidationWarning,
70};
71use crate::serde_json::{Map, Value};
72use crate::wire::postgres::types::PgOid;
73
74/// One column in the ASK PG-wire result set.
75///
76/// `name` is always a `&'static str` — the column set is fixed at
77/// compile time and no user-supplied string ever appears here.
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub struct ColumnDesc {
80    pub name: &'static str,
81    pub oid: PgOid,
82}
83
84/// The single-row ASK PG-wire result set. The wiring slice hands
85/// `columns` to the `RowDescription` codec and `cells` to the
86/// `DataRow` codec (one row, then `CommandComplete`).
87#[derive(Debug, Clone)]
88pub struct AskRow {
89    pub columns: Vec<ColumnDesc>,
90    pub cells: Vec<Option<Vec<u8>>>,
91}
92
93/// Canonical column list, in wire order. Kept private so callers can't
94/// pull out a stale copy and drift from `encode()`.
95const COLUMNS: &[ColumnDesc] = &[
96    ColumnDesc {
97        name: "answer",
98        oid: PgOid::Text,
99    },
100    ColumnDesc {
101        name: "cache_hit",
102        oid: PgOid::Bool,
103    },
104    ColumnDesc {
105        name: "citations",
106        oid: PgOid::Jsonb,
107    },
108    ColumnDesc {
109        name: "completion_tokens",
110        oid: PgOid::Int8,
111    },
112    ColumnDesc {
113        name: "cost_usd",
114        oid: PgOid::Numeric,
115    },
116    ColumnDesc {
117        name: "mode",
118        oid: PgOid::Text,
119    },
120    ColumnDesc {
121        name: "model",
122        oid: PgOid::Text,
123    },
124    ColumnDesc {
125        name: "prompt_tokens",
126        oid: PgOid::Int8,
127    },
128    ColumnDesc {
129        name: "provider",
130        oid: PgOid::Text,
131    },
132    ColumnDesc {
133        name: "retry_count",
134        oid: PgOid::Int8,
135    },
136    ColumnDesc {
137        name: "sources_flat",
138        oid: PgOid::Jsonb,
139    },
140    ColumnDesc {
141        name: "validation",
142        oid: PgOid::Jsonb,
143    },
144];
145
146/// Encode an [`AskResult`] as the single-row PG-wire result set.
147///
148/// Deterministic: re-running on byte-equal input is byte-equal output
149/// (pinned by `encode_is_deterministic_across_calls`). Required by the
150/// ASK determinism contract (#400) and by the cache-hit path (#403)
151/// where the cached PG row must equal the freshly-encoded one.
152pub fn encode(result: &AskResult) -> AskRow {
153    let cells = vec![
154        Some(result.answer.as_bytes().to_vec()),
155        Some(bool_cell(result.cache_hit)),
156        Some(citations_jsonb(&result.citations)),
157        Some(result.completion_tokens.to_string().into_bytes()),
158        Some(numeric_cell(result.cost_usd)),
159        Some(mode_cell(result.effective_mode)),
160        Some(result.model.as_bytes().to_vec()),
161        Some(result.prompt_tokens.to_string().into_bytes()),
162        Some(result.provider.as_bytes().to_vec()),
163        Some(result.retry_count.to_string().into_bytes()),
164        Some(sources_jsonb(&result.sources_flat)),
165        Some(validation_jsonb(&result.validation)),
166    ];
167    AskRow {
168        columns: COLUMNS.to_vec(),
169        cells,
170    }
171}
172
173/// Column descriptors only — the wiring slice needs these before it
174/// knows the result body (PG protocol: `RowDescription` is sent before
175/// `Execute` finishes). Exposed so the `Parse`/`Describe` codepath can
176/// answer without running the query.
177pub fn columns() -> Vec<ColumnDesc> {
178    COLUMNS.to_vec()
179}
180
181fn bool_cell(b: bool) -> Vec<u8> {
182    if b {
183        b"t".to_vec()
184    } else {
185        b"f".to_vec()
186    }
187}
188
189fn mode_cell(m: ask_response_envelope::Mode) -> Vec<u8> {
190    match m {
191        ask_response_envelope::Mode::Strict => b"strict".to_vec(),
192        ask_response_envelope::Mode::Lenient => b"lenient".to_vec(),
193    }
194}
195
196fn numeric_cell(v: f64) -> Vec<u8> {
197    // PG `numeric` text input accepts the same forms Rust's
198    // `f64::to_string` emits, including `0`, `0.0000321`, and
199    // scientific notation for very large values. Non-finite values
200    // (`NaN`, `Inf`) cannot appear here — cost is always a
201    // non-negative finite number per the cost-counter contract
202    // (#401). If one does sneak through, PG will reject the row with
203    // a parse error at the codec layer, which is the correct loud
204    // failure mode.
205    v.to_string().into_bytes()
206}
207
208fn citations_jsonb(cites: &[Citation]) -> Vec<u8> {
209    // Marker-ascending order is the contract — same as
210    // ask_response_envelope::citations_value. Re-implemented here
211    // rather than reused so the JSON-shape tests in the envelope
212    // module and the column-shape tests here can fail
213    // independently: a wire shape regression points at one module,
214    // not the seam between two.
215    let mut sorted: Vec<Citation> = cites.to_vec();
216    sorted.sort_by_key(|c| c.marker);
217    let arr: Vec<Value> = sorted
218        .iter()
219        .map(|c| {
220            let mut o = Map::new();
221            o.insert("marker".into(), Value::Number(c.marker as f64));
222            o.insert("urn".into(), Value::String(c.urn.clone()));
223            Value::Object(o)
224        })
225        .collect();
226    Value::Array(arr).to_string_compact().into_bytes()
227}
228
229fn sources_jsonb(rows: &[SourceRow]) -> Vec<u8> {
230    let arr: Vec<Value> = rows
231        .iter()
232        .map(|r| {
233            let mut o = Map::new();
234            o.insert("payload".into(), Value::String(r.payload.clone()));
235            o.insert("urn".into(), Value::String(r.urn.clone()));
236            Value::Object(o)
237        })
238        .collect();
239    Value::Array(arr).to_string_compact().into_bytes()
240}
241
242fn validation_jsonb(v: &Validation) -> Vec<u8> {
243    let mut o = Map::new();
244    o.insert(
245        "errors".into(),
246        Value::Array(v.errors.iter().map(error_value).collect()),
247    );
248    o.insert("ok".into(), Value::Bool(v.ok));
249    o.insert(
250        "warnings".into(),
251        Value::Array(v.warnings.iter().map(warning_value).collect()),
252    );
253    Value::Object(o).to_string_compact().into_bytes()
254}
255
256fn warning_value(w: &ValidationWarning) -> Value {
257    let mut o = Map::new();
258    o.insert("detail".into(), Value::String(w.detail.clone()));
259    o.insert("kind".into(), Value::String(w.kind.clone()));
260    Value::Object(o)
261}
262
263fn error_value(e: &ValidationError) -> Value {
264    let mut o = Map::new();
265    o.insert("detail".into(), Value::String(e.detail.clone()));
266    o.insert("kind".into(), Value::String(e.kind.clone()));
267    Value::Object(o)
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273    use crate::runtime::ai::ask_response_envelope::{
274        AskResult, Citation, Mode, SourceRow, Validation, ValidationError, ValidationWarning,
275    };
276
277    fn fixture() -> AskResult {
278        AskResult {
279            answer: "X is 42 [^1].".into(),
280            reasoning: crate::json::Value::Null,
281            exploratory_queries: crate::json::Value::Array(Vec::new()),
282            final_query: None,
283            final_query_params: crate::json::Value::Array(Vec::new()),
284            sources_flat: vec![SourceRow {
285                urn: "urn:reddb:row:1".into(),
286                payload: "{\"k\":\"v\"}".into(),
287            }],
288            citations: vec![Citation {
289                marker: 1,
290                urn: "urn:reddb:row:1".into(),
291            }],
292            validation: Validation {
293                ok: true,
294                warnings: vec![],
295                errors: vec![],
296            },
297            cache_hit: false,
298            provider: "openai".into(),
299            model: "gpt-4o-mini".into(),
300            prompt_tokens: 123,
301            completion_tokens: 45,
302            cost_usd: 0.000_321,
303            effective_mode: Mode::Strict,
304            retry_count: 0,
305        }
306    }
307
308    fn cell_str(row: &AskRow, idx: usize) -> &str {
309        std::str::from_utf8(row.cells[idx].as_ref().unwrap()).unwrap()
310    }
311
312    #[test]
313    fn emits_exactly_twelve_columns() {
314        let row = encode(&fixture());
315        assert_eq!(row.columns.len(), 12);
316        assert_eq!(row.cells.len(), 12);
317    }
318
319    #[test]
320    fn column_order_matches_envelope_alphabetical_order() {
321        let row = encode(&fixture());
322        let names: Vec<&str> = row.columns.iter().map(|c| c.name).collect();
323        assert_eq!(
324            names,
325            vec![
326                "answer",
327                "cache_hit",
328                "citations",
329                "completion_tokens",
330                "cost_usd",
331                "mode",
332                "model",
333                "prompt_tokens",
334                "provider",
335                "retry_count",
336                "sources_flat",
337                "validation",
338            ]
339        );
340    }
341
342    #[test]
343    fn columns_helper_returns_same_descriptors_as_encode() {
344        let row = encode(&fixture());
345        assert_eq!(columns(), row.columns);
346    }
347
348    #[test]
349    fn oids_match_pg_type_d_h_canonical_values() {
350        let row = encode(&fixture());
351        let by_name: std::collections::BTreeMap<&str, PgOid> =
352            row.columns.iter().map(|c| (c.name, c.oid)).collect();
353        assert_eq!(by_name["answer"], PgOid::Text);
354        assert_eq!(by_name["cache_hit"], PgOid::Bool);
355        assert_eq!(by_name["citations"], PgOid::Jsonb);
356        assert_eq!(by_name["completion_tokens"], PgOid::Int8);
357        assert_eq!(by_name["cost_usd"], PgOid::Numeric);
358        assert_eq!(by_name["mode"], PgOid::Text);
359        assert_eq!(by_name["model"], PgOid::Text);
360        assert_eq!(by_name["prompt_tokens"], PgOid::Int8);
361        assert_eq!(by_name["provider"], PgOid::Text);
362        assert_eq!(by_name["retry_count"], PgOid::Int8);
363        assert_eq!(by_name["sources_flat"], PgOid::Jsonb);
364        assert_eq!(by_name["validation"], PgOid::Jsonb);
365    }
366
367    #[test]
368    fn answer_text_preserved_with_inline_markers() {
369        let row = encode(&fixture());
370        assert_eq!(cell_str(&row, 0), "X is 42 [^1].");
371    }
372
373    #[test]
374    fn cache_hit_serializes_as_pg_bool_text() {
375        let mut r = fixture();
376        r.cache_hit = false;
377        assert_eq!(cell_str(&encode(&r), 1), "f");
378        r.cache_hit = true;
379        assert_eq!(cell_str(&encode(&r), 1), "t");
380    }
381
382    #[test]
383    fn citations_jsonb_is_marker_ascending() {
384        let mut r = fixture();
385        r.citations = vec![
386            Citation {
387                marker: 3,
388                urn: "urn:c".into(),
389            },
390            Citation {
391                marker: 1,
392                urn: "urn:a".into(),
393            },
394            Citation {
395                marker: 2,
396                urn: "urn:b".into(),
397            },
398        ];
399        let row = encode(&r);
400        let s = cell_str(&row, 2);
401        // Markers appear in ascending order within the JSON array.
402        let p1 = s.find("\"marker\":1").unwrap();
403        let p2 = s.find("\"marker\":2").unwrap();
404        let p3 = s.find("\"marker\":3").unwrap();
405        assert!(p1 < p2 && p2 < p3, "order: {s}");
406    }
407
408    #[test]
409    fn empty_citations_serialize_as_empty_array_not_null() {
410        let mut r = fixture();
411        r.citations = vec![];
412        assert_eq!(cell_str(&encode(&r), 2), "[]");
413    }
414
415    #[test]
416    fn completion_tokens_is_decimal_text() {
417        let mut r = fixture();
418        r.completion_tokens = 0;
419        assert_eq!(cell_str(&encode(&r), 3), "0");
420        r.completion_tokens = 1_000_000;
421        assert_eq!(cell_str(&encode(&r), 3), "1000000");
422    }
423
424    #[test]
425    fn cost_usd_uses_canonical_rust_f64_form() {
426        let mut r = fixture();
427        r.cost_usd = 0.0;
428        assert_eq!(cell_str(&encode(&r), 4), "0");
429        r.cost_usd = 0.000_321;
430        // f64::to_string preserves a representation PG `numeric`
431        // accepts directly — no precision loss across the wire.
432        assert_eq!(cell_str(&encode(&r), 4), "0.000321");
433        r.cost_usd = 1.5;
434        assert_eq!(cell_str(&encode(&r), 4), "1.5");
435    }
436
437    #[test]
438    fn mode_serialises_as_strict_or_lenient_text() {
439        let mut r = fixture();
440        r.effective_mode = Mode::Strict;
441        assert_eq!(cell_str(&encode(&r), 5), "strict");
442        r.effective_mode = Mode::Lenient;
443        assert_eq!(cell_str(&encode(&r), 5), "lenient");
444    }
445
446    #[test]
447    fn model_and_provider_are_utf8_text() {
448        let mut r = fixture();
449        r.model = "claude-sonnet-4-6".into();
450        r.provider = "anthropic".into();
451        let row = encode(&r);
452        assert_eq!(cell_str(&row, 6), "claude-sonnet-4-6");
453        assert_eq!(cell_str(&row, 8), "anthropic");
454    }
455
456    #[test]
457    fn prompt_tokens_is_decimal_text() {
458        let mut r = fixture();
459        r.prompt_tokens = 4096;
460        assert_eq!(cell_str(&encode(&r), 7), "4096");
461    }
462
463    #[test]
464    fn retry_count_is_zero_or_one() {
465        // #395 caps retry budget at one. We don't enforce here (the
466        // validator does) but the column must round-trip both values.
467        let mut r = fixture();
468        r.retry_count = 0;
469        assert_eq!(cell_str(&encode(&r), 9), "0");
470        r.retry_count = 1;
471        assert_eq!(cell_str(&encode(&r), 9), "1");
472    }
473
474    #[test]
475    fn sources_flat_preserves_input_order() {
476        // Post-RRF order is the contract — `[^N]` indexes into this
477        // array, so reordering would silently break grounding.
478        let mut r = fixture();
479        r.sources_flat = vec![
480            SourceRow {
481                urn: "urn:z".into(),
482                payload: "{}".into(),
483            },
484            SourceRow {
485                urn: "urn:a".into(),
486                payload: "{}".into(),
487            },
488        ];
489        let row = encode(&r);
490        let s = cell_str(&row, 10);
491        let pz = s.find("urn:z").unwrap();
492        let pa = s.find("urn:a").unwrap();
493        assert!(pz < pa, "order: {s}");
494    }
495
496    #[test]
497    fn empty_sources_flat_serializes_as_empty_array() {
498        let mut r = fixture();
499        r.sources_flat = vec![];
500        assert_eq!(cell_str(&encode(&r), 10), "[]");
501    }
502
503    #[test]
504    fn validation_jsonb_carries_ok_false_with_errors() {
505        let mut r = fixture();
506        r.validation = Validation {
507            ok: false,
508            warnings: vec![],
509            errors: vec![ValidationError {
510                kind: "out_of_range".into(),
511                detail: "marker 5 > sources_count 2".into(),
512            }],
513        };
514        let encoded = encode(&r);
515        let s = cell_str(&encoded, 11);
516        assert!(s.contains("\"ok\":false"), "got {s}");
517        assert!(s.contains("\"kind\":\"out_of_range\""), "got {s}");
518        assert!(s.contains("marker 5 > sources_count 2"), "got {s}");
519    }
520
521    #[test]
522    fn validation_jsonb_with_warnings_only_keeps_ok_true() {
523        let mut r = fixture();
524        r.validation = Validation {
525            ok: true,
526            warnings: vec![ValidationWarning {
527                kind: "mode_fallback".into(),
528                detail: "provider does not support citations".into(),
529            }],
530            errors: vec![],
531        };
532        let encoded = encode(&r);
533        let s = cell_str(&encoded, 11);
534        assert!(s.contains("\"ok\":true"), "got {s}");
535        assert!(s.contains("\"kind\":\"mode_fallback\""), "got {s}");
536    }
537
538    #[test]
539    fn validation_empty_arrays_are_present_not_null() {
540        let row = encode(&fixture());
541        let s = cell_str(&row, 11);
542        assert!(s.contains("\"errors\":[]"), "got {s}");
543        assert!(s.contains("\"warnings\":[]"), "got {s}");
544    }
545
546    #[test]
547    fn every_cell_is_some_no_nulls() {
548        // PG-wire `DataRow` distinguishes NULL (length -1) from empty
549        // string (length 0). The ASK row never emits NULL — empty
550        // arrays serialize as `[]`, empty strings as `""`. The wiring
551        // slice can rely on this invariant when streaming cells.
552        let row = encode(&fixture());
553        assert!(row.cells.iter().all(|c| c.is_some()));
554    }
555
556    #[test]
557    fn encode_is_deterministic_across_calls() {
558        let r = fixture();
559        let a = encode(&r);
560        let b = encode(&r);
561        assert_eq!(a.columns, b.columns);
562        assert_eq!(a.cells, b.cells);
563    }
564
565    #[test]
566    fn cells_index_aligns_with_columns_index() {
567        // The wiring slice will iterate `columns` and `cells` in
568        // lock-step. Pin the invariant so reordering one without the
569        // other trips here first.
570        let row = encode(&fixture());
571        for (i, col) in row.columns.iter().enumerate() {
572            let cell = row.cells[i].as_ref().expect("no nulls");
573            match col.name {
574                "answer" => assert_eq!(cell.as_slice(), b"X is 42 [^1]."),
575                "cache_hit" => assert_eq!(cell.as_slice(), b"f"),
576                "citations" => assert!(cell.starts_with(b"[")),
577                "completion_tokens" => assert_eq!(cell.as_slice(), b"45"),
578                "cost_usd" => assert_eq!(cell.as_slice(), b"0.000321"),
579                "mode" => assert_eq!(cell.as_slice(), b"strict"),
580                "model" => assert_eq!(cell.as_slice(), b"gpt-4o-mini"),
581                "prompt_tokens" => assert_eq!(cell.as_slice(), b"123"),
582                "provider" => assert_eq!(cell.as_slice(), b"openai"),
583                "retry_count" => assert_eq!(cell.as_slice(), b"0"),
584                "sources_flat" => assert!(cell.starts_with(b"[")),
585                "validation" => assert!(cell.starts_with(b"{")),
586                other => panic!("unexpected column {other}"),
587            }
588        }
589    }
590
591    #[test]
592    fn answer_with_multibyte_utf8_round_trips_byte_for_byte() {
593        let mut r = fixture();
594        r.answer = "Café — résumé 中文 [^1]".into();
595        let row = encode(&r);
596        assert_eq!(
597            row.cells[0].as_ref().unwrap().as_slice(),
598            "Café — résumé 中文 [^1]".as_bytes()
599        );
600    }
601
602    #[test]
603    fn jsonb_outputs_are_compact_not_pretty() {
604        // PG drivers route `jsonb` through their own parser; whitespace
605        // is irrelevant for correctness but matters for wire-size
606        // budgets and audit-row equality (#402). Pin compact form.
607        let row = encode(&fixture());
608        for idx in [2usize, 10, 11] {
609            let s = cell_str(&row, idx);
610            assert!(!s.contains("\n"), "col {idx} not compact: {s}");
611            assert!(!s.contains(": "), "col {idx} pretty-spaced: {s}");
612        }
613    }
614
615    #[test]
616    fn columns_helper_is_callable_before_query_runs() {
617        // The PG `Describe` codepath needs column descriptors before
618        // the query executes — pin that `columns()` does not require
619        // an `AskResult` instance.
620        let cols = columns();
621        assert_eq!(cols.len(), 12);
622        assert_eq!(cols[0].name, "answer");
623    }
624}