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