Skip to main content

kobold_data_shim/
file.rs

1//! Fixed-record container ingest (`KOBOLD.FILE.1`): split a raw byte stream into records of an
2//! explicit, caller-declared length, with stable offsets, named trailing/partial policies, a
3//! file-level audit, and stable exit codes.
4//!
5//! **Doctrine.** KOBOLD.FILE.1 admits only explicit fixed-record container ingest: bytes are split by
6//! a caller-declared record length with stable offsets, policies, manifests, and exit codes, while
7//! GnuCOBOL file I/O, indexed files, line-sequential runtime behavior, auto-resynchronization, and
8//! silent repair remain outside the claim.
9//!
10//! This is **ingest reliability**, not GnuCOBOL file-organization parity. The default is **strict**:
11//! a partial trailing record or an unexpected trailing newline is an error, never silently absorbed.
12
13use crate::sha256::sha256_hex;
14
15/// What to do with a single trailing `\n` (`0x0A`) at the very end of the input.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
17#[non_exhaustive]
18pub enum TrailingNewline {
19    /// A final `\n` is **not** allowed — its presence is an invalid input shape (the strict default).
20    #[default]
21    Reject,
22    /// A single final `\n` is tolerated and removed before splitting (success).
23    AllowFinalLf,
24    /// A single final `\n` is removed before splitting and recorded as stripped in the audit.
25    StripFinalLf,
26}
27
28/// What to do with a trailing partial record (`input_len % record_len != 0`, after newline handling).
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
30#[non_exhaustive]
31pub enum PartialRecord {
32    /// A partial trailing record is an invalid input shape (the strict default).
33    #[default]
34    Reject,
35    /// A partial trailing record is preserved as marked evidence (verdict downgrades to warnings).
36    Evidence,
37}
38
39/// Stable process exit codes (`KOBOLD.FILE.1`). Documented and frozen — operators script against these.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41#[non_exhaustive]
42#[repr(i32)]
43pub enum ExitCode {
44    /// Clean ingest/decode.
45    Success = 0,
46    /// Decoded, but evidence warnings exist (a preserved partial record, or dirty fields).
47    DecodedWithEvidenceWarnings = 1,
48    /// The input shape is invalid (record_len 0, partial record under strict, unexpected trailing LF).
49    InvalidInputShape = 2,
50    /// An unsupported COBOL surface was required.
51    UnsupportedCobolSurface = 3,
52    /// An internal invariant failed (a bug — should never happen).
53    InternalInvariantFailure = 4,
54    /// An I/O or configuration error (missing file, missing required flag, bad encoding).
55    IoOrConfigError = 5,
56}
57
58impl ExitCode {
59    /// The numeric code (for `std::process::exit`).
60    pub fn code(self) -> i32 {
61        self as i32
62    }
63}
64
65/// Why an ingest was rejected, carrying the [`ExitCode`] an operator should see.
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct IngestError {
68    pub message: String,
69    pub exit: ExitCode,
70}
71
72impl core::fmt::Display for IngestError {
73    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
74        write!(f, "{} (exit {})", self.message, self.exit.code())
75    }
76}
77impl std::error::Error for IngestError {}
78
79/// The ingest policy (all explicit — nothing auto-detected).
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub struct IngestPolicy {
82    pub record_len: usize,
83    pub trailing_newline: TrailingNewline,
84    pub partial_record: PartialRecord,
85}
86
87impl IngestPolicy {
88    /// Strict defaults: reject a trailing newline and a partial record.
89    pub fn strict(record_len: usize) -> Self {
90        IngestPolicy {
91            record_len,
92            trailing_newline: TrailingNewline::Reject,
93            partial_record: PartialRecord::Reject,
94        }
95    }
96}
97
98/// One record's position in the original byte stream. `offset` is the **true file offset**.
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub struct RecordSpan {
101    pub index: usize,
102    pub offset: usize,
103    pub len: usize,
104    /// `true` if this is a preserved partial trailing record (shorter than `record_len`).
105    pub partial: bool,
106}
107
108/// The result of ingesting a fixed-record container.
109#[derive(Debug, Clone)]
110pub struct Ingest {
111    pub record_len: usize,
112    pub input_len: usize,
113    pub input_sha256: String,
114    pub spans: Vec<RecordSpan>,
115    pub stripped_final_lf: bool,
116    pub partial_present: bool,
117    pub verdict: ExitCode,
118    pub trailing_policy: TrailingNewline,
119    pub partial_policy: PartialRecord,
120}
121
122impl Ingest {
123    /// The bytes of record `i` (sliced from the caller's original `data`).
124    pub fn record<'a>(&self, data: &'a [u8], i: usize) -> Option<&'a [u8]> {
125        let s = self.spans.get(i)?;
126        data.get(s.offset..s.offset + s.len)
127    }
128
129    /// The canonical-JSON file-level audit manifest (byte-stable for a given input + policy).
130    pub fn file_audit_json(&self) -> String {
131        let policy = |t: TrailingNewline| match t {
132            TrailingNewline::Reject => "reject",
133            TrailingNewline::AllowFinalLf => "allow-final-lf",
134            TrailingNewline::StripFinalLf => "strip-final-lf",
135        };
136        let ppolicy = match self.partial_policy {
137            PartialRecord::Reject => "reject",
138            PartialRecord::Evidence => "evidence",
139        };
140        let (first, last) = match (self.spans.first(), self.spans.last()) {
141            (Some(f), Some(l)) => (f.offset as i64, l.offset as i64),
142            _ => (-1, -1),
143        };
144        format!(
145            "{{\"schema\":\"kobold-file-ingest-v1\",\"file\":{{\"input_sha256\":\"{}\",\"input_len\":{},\
146             \"record_len\":{},\"record_count\":{},\"trailing_policy\":\"{}\",\"partial_record_policy\":\"{}\",\
147             \"stripped_final_lf\":{},\"partial_record_present\":{},\"offsets\":{{\"first\":{},\"last\":{}}},\
148             \"verdict_exit_code\":{}}}}}",
149            self.input_sha256,
150            self.input_len,
151            self.record_len,
152            self.spans.len(),
153            policy(self.trailing_policy),
154            ppolicy,
155            self.stripped_final_lf,
156            self.partial_present,
157            first,
158            last,
159            self.verdict.code(),
160        )
161    }
162}
163
164/// Ingest `data` into fixed-length records under `policy`. Offsets are true file offsets; nothing is
165/// auto-detected or silently repaired.
166pub fn ingest(data: &[u8], policy: &IngestPolicy) -> Result<Ingest, IngestError> {
167    if policy.record_len == 0 {
168        return Err(IngestError {
169            message: "record_len must be > 0".into(),
170            exit: ExitCode::IoOrConfigError,
171        });
172    }
173    let input_len = data.len();
174    let input_sha256 = sha256_hex(data);
175
176    // Trailing-newline handling operates on the *effective* length used for splitting; the recorded
177    // offsets remain true offsets into the original stream (the stripped LF is simply never a record).
178    let mut eff_len = input_len;
179    let mut stripped_final_lf = false;
180    let ends_lf = data.last() == Some(&b'\n');
181    if ends_lf {
182        match policy.trailing_newline {
183            TrailingNewline::Reject => {
184                // Only an error if the LF is what makes the shape wrong is too lenient; strict means a
185                // final LF is simply not allowed.
186                return Err(IngestError {
187                    message: "unexpected trailing newline (policy: reject)".into(),
188                    exit: ExitCode::InvalidInputShape,
189                });
190            }
191            TrailingNewline::AllowFinalLf => {
192                eff_len -= 1;
193            }
194            TrailingNewline::StripFinalLf => {
195                eff_len -= 1;
196                stripped_final_lf = true;
197            }
198        }
199    }
200
201    let rl = policy.record_len;
202    let full = eff_len / rl;
203    let rem = eff_len % rl;
204    let mut spans: Vec<RecordSpan> = (0..full)
205        .map(|i| RecordSpan {
206            index: i,
207            offset: i * rl,
208            len: rl,
209            partial: false,
210        })
211        .collect();
212
213    let mut partial_present = false;
214    let mut verdict = ExitCode::Success;
215    if rem != 0 {
216        match policy.partial_record {
217            PartialRecord::Reject => {
218                return Err(IngestError {
219                    message: format!(
220                        "partial trailing record: {rem} byte(s) beyond {full} full records of {rl} (policy: reject)"
221                    ),
222                    exit: ExitCode::InvalidInputShape,
223                });
224            }
225            PartialRecord::Evidence => {
226                spans.push(RecordSpan {
227                    index: full,
228                    offset: full * rl,
229                    len: rem,
230                    partial: true,
231                });
232                partial_present = true;
233                verdict = ExitCode::DecodedWithEvidenceWarnings;
234            }
235        }
236    }
237
238    Ok(Ingest {
239        record_len: rl,
240        input_len,
241        input_sha256,
242        spans,
243        stripped_final_lf,
244        partial_present,
245        verdict,
246        trailing_policy: policy.trailing_newline,
247        partial_policy: policy.partial_record,
248    })
249}