Skip to main content

kute_adapters/
lib.rs

1//! Modality adapters (FR-001). Each one declares whether it reconstructs the
2//! original bytes exactly; that flag is copied into every vocabulary trained
3//! through it, so a reader can tell lossless pipelines from lossy ones.
4//!
5//! | name           | output  | byte-exact | what it does |
6//! |----------------|---------|------------|--------------|
7//! | `binary`       | bytes   | yes        | passes bytes through |
8//! | `text`         | bytes   | yes        | requires valid UTF-8, passes it through |
9//! | `json`         | bytes   | no         | parses one JSON document and re-serializes it canonically |
10//! | `jsonl`        | bytes   | no         | canonicalizes each non-empty line |
11//! | `jsonl-events` | symbols | no         | takes one field per line as an event symbol |
12//!
13//! The JSON adapters keep every value but not the original spacing or key
14//! order: that is the point of canonicalizing, and it is declared as lossy at
15//! the byte level. To keep a JSON file byte for byte, use `text` or `binary`.
16//!
17//! They are strict: a document in which an object repeats a key, or which
18//! holds a number that would not survive as written (an integer beyond 64
19//! bits, a decimal with more digits than a double keeps), is refused, since
20//! canonicalizing it would silently pick one reading. The adapter option
21//! `strict=false` restores the earlier behaviour: last key wins, numbers are
22//! rounded.
23
24use kute_core::{AdapterCapabilities, ModalityAdapter};
25use kute_types::{AdapterConfig, CanonicalInput, KuteError, Modality, Payload, Result};
26use serde_json::Value;
27
28pub const BINARY: &str = "binary";
29pub const TEXT: &str = "text";
30pub const JSON: &str = "json";
31pub const JSONL: &str = "jsonl";
32pub const JSONL_EVENTS: &str = "jsonl-events";
33
34/// Register this crate's adapters.
35pub fn register(registry: &mut kute_core::Registry) -> kute_types::Result<()> {
36    registry.register_adapter(BINARY, || Box::new(BinaryAdapter))?;
37    registry.register_adapter(TEXT, || Box::new(TextAdapter))?;
38    registry.register_adapter(JSON, || Box::new(JsonAdapter))?;
39    registry.register_adapter(JSONL, || Box::new(JsonlAdapter))?;
40    registry.register_adapter(JSONL_EVENTS, || Box::new(JsonlEventsAdapter))
41}
42
43fn bytes_of(input: &CanonicalInput, adapter: &str) -> Result<Vec<u8>> {
44    match &input.payload {
45        Payload::Bytes(b) => Ok(b.clone()),
46        Payload::Symbols(_) => Err(KuteError::InvalidInput(format!("the {adapter} adapter reconstructs byte payloads, not symbols"))),
47    }
48}
49
50fn caps(name: &str, modality: Modality, lossless: bool, notes: &str) -> AdapterCapabilities {
51    AdapterCapabilities { name: name.to_string(), modality, lossless, notes: notes.to_string() }
52}
53
54/// Canonical JSON: object keys sorted, no insignificant whitespace.
55fn canonical(value: &Value) -> Result<Vec<u8>> {
56    fn sort(value: &Value) -> Value {
57        match value {
58            Value::Object(map) => {
59                let mut keys: Vec<&String> = map.keys().collect();
60                keys.sort();
61                let mut out = serde_json::Map::new();
62                for k in keys {
63                    out.insert(k.clone(), sort(&map[k]));
64                }
65                Value::Object(out)
66            }
67            Value::Array(items) => Value::Array(items.iter().map(sort).collect()),
68            other => other.clone(),
69        }
70    }
71    Ok(serde_json::to_vec(&sort(value))?)
72}
73
74/// One JSON value as the JSON adapters read and write it: parsed, refused
75/// if canonicalizing would change what it says (a repeated key, a number
76/// that does not survive), and written with sorted keys and no spaces.
77/// For code outside the adapters that must agree with them byte for byte.
78pub fn canonical_json(bytes: &[u8], what: &str) -> Result<(Value, Vec<u8>)> {
79    let value = parse(bytes, what, &AdapterConfig::default())?;
80    let text = canonical(&value)?;
81    Ok((value, text))
82}
83
84fn parse(bytes: &[u8], what: &str, config: &AdapterConfig) -> Result<Value> {
85    let value = serde_json::from_slice(bytes).map_err(|e| KuteError::InvalidInput(format!("{what}: {e}")))?;
86    match config.get("strict") {
87        None | Some("true") => strict_check(bytes).map_err(|e| KuteError::InvalidInput(format!("{what}: {e} (the adapter option strict=false accepts it)")))?,
88        Some("false") => {}
89        Some(other) => return Err(KuteError::InvalidInput(format!("{what}: option strict must be true or false, not {other:?}"))),
90    }
91    Ok(value)
92}
93
94/// Refuse what canonicalizing would silently change: repeated keys and
95/// numbers that do not survive. `bytes` has already parsed as JSON, so the
96/// scan only has to find keys and numbers, not validate.
97fn strict_check(bytes: &[u8]) -> std::result::Result<(), String> {
98    // One entry per open container: the keys seen so far if it is an object.
99    let mut open: Vec<Option<std::collections::HashSet<String>>> = Vec::new();
100    let mut i = 0;
101    while i < bytes.len() {
102        match bytes[i] {
103            b'{' => open.push(Some(Default::default())),
104            b'[' => open.push(None),
105            b'}' | b']' => {
106                open.pop();
107            }
108            b'"' => {
109                let start = i;
110                i += 1;
111                while bytes[i] != b'"' {
112                    i += if bytes[i] == b'\\' { 2 } else { 1 };
113                }
114                let mut after = i + 1;
115                while after < bytes.len() && bytes[after].is_ascii_whitespace() {
116                    after += 1;
117                }
118                if bytes.get(after) == Some(&b':') {
119                    if let Some(Some(keys)) = open.last_mut() {
120                        // Compare keys as decoded: "a" and "a" are one key.
121                        let key: String = serde_json::from_slice(&bytes[start..=i]).map_err(|e| e.to_string())?;
122                        if keys.contains(&key) {
123                            return Err(format!("an object repeats the key {key:?}"));
124                        }
125                        keys.insert(key);
126                    }
127                }
128            }
129            b'-' | b'0'..=b'9' => {
130                let start = i;
131                while i < bytes.len() && matches!(bytes[i], b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9') {
132                    i += 1;
133                }
134                // Valid JSON numbers are ASCII.
135                check_number(std::str::from_utf8(&bytes[start..i]).map_err(|e| e.to_string())?)?;
136                continue;
137            }
138            _ => {}
139        }
140        i += 1;
141    }
142    Ok(())
143}
144
145/// A decimal literal as its significant digits and the power of ten of the
146/// last one, so that `2.50`, `25e-1` and `2.5` compare equal.
147fn decimal(literal: &str) -> Option<(String, i64)> {
148    let literal = literal.trim_start_matches('-');
149    let (mantissa, exponent) = match literal.find(['e', 'E']) {
150        Some(at) => (&literal[..at], literal[at + 1..].parse::<i64>().ok()?),
151        None => (literal, 0),
152    };
153    let (whole, fraction) = mantissa.split_once('.').unwrap_or((mantissa, ""));
154    let mut digits = format!("{whole}{fraction}");
155    let mut power = exponent.checked_sub(fraction.len() as i64)?;
156    while digits.ends_with('0') {
157        digits.pop();
158        power = power.checked_add(1)?;
159    }
160    let digits = digits.trim_start_matches('0').to_string();
161    Some(if digits.is_empty() { (digits, 0) } else { (digits, power) })
162}
163
164fn check_number(literal: &str) -> std::result::Result<(), String> {
165    if !literal.contains(['.', 'e', 'E']) {
166        return if literal.parse::<i64>().is_ok() || literal.parse::<u64>().is_ok() {
167            Ok(())
168        } else {
169            Err(format!("the integer {literal} does not fit 64 bits and would be rounded"))
170        };
171    }
172    let rounded = || format!("the number {literal} has more precision than a double keeps and would be rounded");
173    let as_double: f64 = literal.parse().map_err(|_| rounded())?;
174    // What the canonical form will hold, compared digit for digit.
175    let written = serde_json::Number::from_f64(as_double).ok_or_else(rounded)?.to_string();
176    if decimal(literal).is_some() && decimal(literal) == decimal(&written) {
177        Ok(())
178    } else {
179        Err(rounded())
180    }
181}
182
183pub struct BinaryAdapter;
184
185impl ModalityAdapter for BinaryAdapter {
186    fn modality(&self) -> Modality {
187        Modality::Binary
188    }
189    fn ingest(&self, input: &[u8], _: &AdapterConfig) -> Result<CanonicalInput> {
190        Ok(CanonicalInput::bytes(Modality::Binary, input))
191    }
192    fn reconstruct(&self, input: &CanonicalInput, _config: &AdapterConfig) -> Result<Vec<u8>> {
193        bytes_of(input, BINARY)
194    }
195    fn capabilities(&self) -> AdapterCapabilities {
196        caps(BINARY, Modality::Binary, true, "Arbitrary bytes, passed through unchanged.")
197    }
198}
199
200pub struct TextAdapter;
201
202impl ModalityAdapter for TextAdapter {
203    fn modality(&self) -> Modality {
204        Modality::Text
205    }
206    fn ingest(&self, input: &[u8], _: &AdapterConfig) -> Result<CanonicalInput> {
207        std::str::from_utf8(input).map_err(|e| KuteError::InvalidInput(format!("text adapter: not valid UTF-8 ({e}); use the binary adapter")))?;
208        Ok(CanonicalInput::bytes(Modality::Text, input))
209    }
210    fn reconstruct(&self, input: &CanonicalInput, _config: &AdapterConfig) -> Result<Vec<u8>> {
211        bytes_of(input, TEXT)
212    }
213    fn capabilities(&self) -> AdapterCapabilities {
214        caps(TEXT, Modality::Text, true, "Valid UTF-8, passed through unchanged. No normalization.")
215    }
216}
217
218pub struct JsonAdapter;
219
220impl ModalityAdapter for JsonAdapter {
221    fn modality(&self) -> Modality {
222        Modality::Structured
223    }
224    fn ingest(&self, input: &[u8], config: &AdapterConfig) -> Result<CanonicalInput> {
225        Ok(CanonicalInput::bytes(Modality::Structured, canonical(&parse(input, "json adapter", config)?)?))
226    }
227    fn reconstruct(&self, input: &CanonicalInput, _config: &AdapterConfig) -> Result<Vec<u8>> {
228        bytes_of(input, JSON)
229    }
230    fn capabilities(&self) -> AdapterCapabilities {
231        caps(JSON, Modality::Structured, false, "One JSON document, re-serialized with sorted keys and no extra whitespace. Original formatting does not survive. Strict by default: a repeated key, an integer beyond 64 bits or a decimal a double would round is refused. With the option strict=false the last value of a repeated key is kept and such numbers are rounded.")
232    }
233}
234
235pub struct JsonlAdapter;
236
237impl ModalityAdapter for JsonlAdapter {
238    fn modality(&self) -> Modality {
239        Modality::Structured
240    }
241    fn ingest(&self, input: &[u8], config: &AdapterConfig) -> Result<CanonicalInput> {
242        let mut out = Vec::with_capacity(input.len());
243        for (n, line) in input.split(|&b| b == b'\n').enumerate() {
244            let line = trim(line);
245            if line.is_empty() {
246                continue;
247            }
248            out.extend_from_slice(&canonical(&parse(line, &format!("jsonl adapter, line {}", n + 1), config)?)?);
249            out.push(b'\n');
250        }
251        Ok(CanonicalInput::bytes(Modality::Structured, out))
252    }
253    fn reconstruct(&self, input: &CanonicalInput, _config: &AdapterConfig) -> Result<Vec<u8>> {
254        bytes_of(input, JSONL)
255    }
256    fn capabilities(&self) -> AdapterCapabilities {
257        caps(JSONL, Modality::Structured, false, "One JSON value per line, each canonicalized; blank lines dropped. Original formatting does not survive. Strict by default: a repeated key, an integer beyond 64 bits or a decimal a double would round is refused. With the option strict=false the last value of a repeated key is kept and such numbers are rounded.")
258    }
259}
260
261/// Reads one field from each JSONL record as an event symbol.
262///
263/// Options: `field` (default `event`). Reconstruction writes one
264/// `{"<field>": "<symbol>"}` line per symbol, so everything else in the
265/// original records is gone: this adapter is for learning event vocabularies,
266/// not for archiving logs.
267#[derive(Default)]
268pub struct JsonlEventsAdapter;
269
270const DEFAULT_FIELD: &str = "event";
271
272impl ModalityAdapter for JsonlEventsAdapter {
273    fn modality(&self) -> Modality {
274        Modality::Events
275    }
276    fn ingest(&self, input: &[u8], config: &AdapterConfig) -> Result<CanonicalInput> {
277        let field = config.get("field").unwrap_or(DEFAULT_FIELD);
278        let mut symbols = Vec::new();
279        for (n, line) in input.split(|&b| b == b'\n').enumerate() {
280            let line = trim(line);
281            if line.is_empty() {
282                continue;
283            }
284            let what = format!("jsonl-events adapter, line {}", n + 1);
285            let value = parse(line, &what, config)?;
286            let symbol = match value.get(field) {
287                Some(Value::String(s)) if !s.is_empty() => s.clone(),
288                Some(Value::Number(num)) => num.to_string(),
289                Some(Value::Bool(b)) => b.to_string(),
290                Some(_) => return Err(KuteError::InvalidInput(format!("{what}: field {field:?} must be a non-empty string, number or boolean"))),
291                None => return Err(KuteError::InvalidInput(format!("{what}: no field {field:?}"))),
292            };
293            if symbol.len() > kute_types::vocab::MAX_SYMBOL_BYTES {
294                return Err(KuteError::InvalidInput(format!("{what}: symbol longer than 1024 bytes")));
295            }
296            symbols.push(symbol);
297        }
298        Ok(CanonicalInput { modality: Modality::Events, payload: Payload::Symbols(symbols) })
299    }
300    fn reconstruct(&self, input: &CanonicalInput, config: &AdapterConfig) -> Result<Vec<u8>> {
301        let field = config.get("field").unwrap_or(DEFAULT_FIELD);
302        let Payload::Symbols(symbols) = &input.payload else {
303            return Err(KuteError::InvalidInput("the jsonl-events adapter reconstructs symbol payloads".into()));
304        };
305        let mut out = Vec::new();
306        for s in symbols {
307            out.extend_from_slice(&serde_json::to_vec(&serde_json::json!({ field: s }))?);
308            out.push(b'\n');
309        }
310        Ok(out)
311    }
312    fn capabilities(&self) -> AdapterCapabilities {
313        caps(JSONL_EVENTS, Modality::Events, false, "Extracts one field per JSONL record as an event symbol (options: field, default \"event\"; strict, default true, which refuses records with a repeated key or a number that would be rounded). All other fields are dropped.")
314    }
315}
316
317fn trim(mut line: &[u8]) -> &[u8] {
318    while let [first, rest @ ..] = line {
319        if first.is_ascii_whitespace() { line = rest } else { break }
320    }
321    while let [rest @ .., last] = line {
322        if last.is_ascii_whitespace() { line = rest } else { break }
323    }
324    line
325}
326
327#[cfg(test)]
328mod tests {
329    use super::*;
330
331    #[test]
332    fn pass_through_adapters_are_exact() {
333        let cfg = AdapterConfig::default();
334        let data: Vec<u8> = (0u16..=255).map(|b| b as u8).collect();
335        let c = BinaryAdapter.ingest(&data, &cfg).unwrap();
336        assert_eq!(BinaryAdapter.reconstruct(&c, &AdapterConfig::default()).unwrap(), data);
337        assert!(BinaryAdapter.capabilities().lossless);
338        let text = "naïve café — 日本語\r\n";
339        let c = TextAdapter.ingest(text.as_bytes(), &cfg).unwrap();
340        assert_eq!(TextAdapter.reconstruct(&c, &AdapterConfig::default()).unwrap(), text.as_bytes());
341        assert!(TextAdapter.ingest(&[0xff, 0xfe], &cfg).is_err());
342    }
343
344    #[test]
345    fn json_is_canonical_and_declared_lossy() {
346        let cfg = AdapterConfig::default();
347        let a = JsonAdapter.ingest(br#"{ "b": [1, 2.50, {"z":null,"a":true}], "a": "x" }"#, &cfg).unwrap();
348        let b = JsonAdapter.ingest(br#"{"a":"x","b":[1,2.50,{"a":true,"z":null}]}"#, &cfg).unwrap();
349        assert_eq!(a, b);
350        assert_eq!(JsonAdapter.reconstruct(&a, &AdapterConfig::default()).unwrap(), br#"{"a":"x","b":[1,2.5,{"a":true,"z":null}]}"#);
351        assert!(!JsonAdapter.capabilities().lossless);
352        assert!(JsonAdapter.ingest(b"{not json", &cfg).is_err());
353    }
354
355    #[test]
356    fn strict_json_refuses_what_canonicalizing_would_change() {
357        let strict = AdapterConfig::default();
358        let loose = AdapterConfig::default().with("strict", "false");
359        let refused = [
360            (r#"{"a":1,"a":2}"#, "repeats the key"),
361            (r#"{"a":1,"a":2}"#, "repeats the key"),
362            (r#"[{"x":{"k":1,"k":1}}]"#, "repeats the key"),
363            ("18446744073709551616", "does not fit 64 bits"),
364            ("-9223372036854775809", "does not fit 64 bits"),
365            ("0.1000000000000000055", "more precision"),
366            ("[1.00000000000000001]", "more precision"),
367            ("123456789012345678.5", "more precision"),
368            ("1e-400", "more precision"),
369        ];
370        for (text, why) in refused {
371            let err = JsonAdapter.ingest(text.as_bytes(), &strict).unwrap_err().to_string();
372            assert!(err.contains(why) && err.contains("strict=false"), "{text}: {err}");
373            assert!(JsonAdapter.ingest(text.as_bytes(), &loose).is_ok(), "{text}");
374        }
375        let accepted = [
376            r#"{"a":1,"b":{"a":2},"c":[{"a":3},{"a":4}]}"#,
377            r#"{"a:":"a","k":"\"a\":1,\"a\":2","s":"{\\"}"#,
378            "[0, -0, 2.50, 25e-1, 1e2, 1E+2, 0.1, 1.7976931348623157e308, 5e-324, 18446744073709551615, -9223372036854775808]",
379            r#"["1e999", "00012345678901234567890"]"#,
380            "0.30000000000000004",
381        ];
382        for text in accepted {
383            let a = JsonAdapter.ingest(text.as_bytes(), &strict).unwrap_or_else(|e| panic!("{text}: {e}"));
384            assert_eq!(a, JsonAdapter.ingest(text.as_bytes(), &loose).unwrap(), "{text}");
385        }
386        // Line numbers survive, the events adapter is covered, bad option values are named.
387        let err = JsonlAdapter.ingest(b"{\"a\":1}\n{\"a\":1,\"a\":2}\n", &strict).unwrap_err().to_string();
388        assert!(err.contains("line 2") && err.contains("repeats the key"), "{err}");
389        assert!(JsonlEventsAdapter.ingest(b"{\"event\":\"A\",\"event\":\"B\"}\n", &strict).is_err());
390        assert!(JsonlEventsAdapter.ingest(b"{\"event\":\"A\",\"event\":\"B\"}\n", &loose).is_ok());
391        let err = JsonAdapter.ingest(b"1", &AdapterConfig::default().with("strict", "yes")).unwrap_err().to_string();
392        assert!(err.contains("must be true or false"), "{err}");
393    }
394
395    #[test]
396    fn jsonl_canonicalizes_each_line() {
397        let cfg = AdapterConfig::default();
398        let c = JsonlAdapter.ingest(b"{\"b\":1, \"a\":2}\r\n\n  {\"x\": [ ]}\n", &cfg).unwrap();
399        assert_eq!(JsonlAdapter.reconstruct(&c, &AdapterConfig::default()).unwrap(), b"{\"a\":2,\"b\":1}\n{\"x\":[]}\n");
400        let err = JsonlAdapter.ingest(b"{\"ok\":1}\n{broken\n", &cfg).unwrap_err().to_string();
401        assert!(err.contains("line 2"), "{err}");
402    }
403
404    #[test]
405    fn events_extracts_a_field() {
406        let cfg = AdapterConfig::default().with("field", "tag");
407        let c = JsonlEventsAdapter.ingest(b"{\"tag\":\"MOTOR_START\",\"t\":1}\n{\"tag\":\"MOTOR_TRIP\",\"t\":2}\n", &cfg).unwrap();
408        assert_eq!(c.payload, Payload::Symbols(vec!["MOTOR_START".into(), "MOTOR_TRIP".into()]));
409        assert!(JsonlEventsAdapter.ingest(b"{\"other\":1}\n", &cfg).is_err());
410        assert!(!JsonlEventsAdapter.capabilities().lossless);
411    }
412
413    #[test]
414    fn events_come_back_under_the_field_they_were_read_from() {
415        let config = AdapterConfig::default().with("field", "tag");
416        let raw = b"{\"tag\":\"A\",\"other\":1}
417{\"tag\":\"B\"}
418";
419        let c = JsonlEventsAdapter.ingest(raw, &config).unwrap();
420        let out = JsonlEventsAdapter.reconstruct(&c, &config).unwrap();
421        assert_eq!(out, b"{\"tag\":\"A\"}
422{\"tag\":\"B\"}
423");
424        // The adapter can read its own output.
425        assert_eq!(JsonlEventsAdapter.ingest(&out, &config).unwrap(), c);
426    }
427}