Skip to main content

rustev_core/
extraction_fallback.rs

1//! Pure fallback extraction (spec 038, 3.7), without runtime or compiler wiring.
2use std::collections::{BTreeMap, BTreeSet};
3
4use rustev_contract::{
5    Document,
6    definition::{InputDecl, ProvenanceClass, TypeDecl},
7    extraction::{
8        AbsenceReason as Reason, Distributions, Extract, ExtractionSchema, ExtractionType, Fill,
9    },
10    extraction_documents::{
11        DateFormat, ExtractRules, ExtractionCondition as Condition, ExtractionValue as Expr, Scalar,
12    },
13    extraction_results::{ExtractionFieldEvidence, ExtractionOrigin},
14    judgment::Derivation,
15    output::RawOutput,
16};
17use serde_json::Value as Json;
18
19use crate::extraction_validate::{self, ValidatedField, fallback_derivation};
20
21/// Screening for exact steps has already been applied by the caller. A source
22/// withheld only from model steps belongs in `Readable`, not `Unavailable`.
23#[derive(Debug, Clone, Copy)]
24pub enum Source<'a> {
25    Readable {
26        bytes: &'a [u8],
27        derivation: Derivation,
28    },
29    /// An `integer`, `bool` or `enum` input value, which only an `equals` or
30    /// `one_of` condition reads (spec 070, 3.4). An enum is its option text.
31    Exact {
32        value: &'a Scalar,
33        derivation: Derivation,
34    },
35    Unavailable,
36}
37
38/// A validated field plus sorted, unique input references actually read while
39/// evaluating it, including reads by rules that did not produce its value.
40#[derive(Debug, Clone, PartialEq)]
41pub struct FallbackField {
42    pub field: ValidatedField,
43    pub sources_read: Vec<String>,
44}
45
46/// Only `bind` constructs this, checking document bounds and step compatibility.
47#[derive(Debug, Clone)]
48pub struct BoundProgram {
49    program: ExtractRules,
50    schema: ExtractionSchema,
51}
52
53/// Check spec 038, 3.7.2 and 3.7.3. Errors are for the compiler to map to
54/// `invalid_extraction`. Literal bounds and vocabulary membership are evaluated
55/// later by the shared field validator, against resolved vocabularies.
56pub fn bind(program: &ExtractRules, step: &Extract) -> Result<BoundProgram, String> {
57    bind_in(program, step, &[])
58}
59
60/// [`bind`], with the definition's inputs, which spec 070's binding checks
61/// read (3.5): a source a version 2 extractor reads is a declared `text`
62/// input or record field. Without them no such source binds.
63pub fn bind_in(
64    program: &ExtractRules,
65    step: &Extract,
66    inputs: &[InputDecl],
67) -> Result<BoundProgram, String> {
68    // Reuse document-local checks even for directly constructed Rust values.
69    let bytes = serde_json::to_vec(program).map_err(|e| e.to_string())?;
70    let program = ExtractRules::parse(&bytes).map_err(|e| e.to_string())?;
71    // Spec 070, 3.4.2: a source read only by exact-value conditions need
72    // not be projected, because only the core reads it.
73    let mut text_read = BTreeSet::new();
74    let mut exact_read = BTreeSet::new();
75    for r in program.fields.iter().flat_map(|f| &f.rules) {
76        condition_reads(&r.when, &mut text_read, &mut exact_read);
77        value_sources(&r.then, &mut text_read);
78    }
79    let mut names = BTreeSet::new();
80    for s in &program.sources {
81        let core_only =
82            exact_read.contains(s.name.as_str()) && !text_read.contains(s.name.as_str());
83        if (!core_only && !step.projection.contains(&s.reference))
84            || !s.reference.starts_with("input:")
85        {
86            return Err(format!("source {} is not in the input projection", s.name));
87        }
88        if !names.insert(s.name.as_str()) {
89            return Err(format!("duplicate source {}", s.name));
90        }
91    }
92    let mut fields = BTreeSet::new();
93    for f in &program.fields {
94        if !fields.insert(&f.field) {
95            return Err(format!("duplicate field {}", f.field));
96        }
97        let declared = step
98            .output
99            .fields
100            .iter()
101            .find(|d| d.name == f.field)
102            .ok_or_else(|| format!("undeclared field {}", f.field))?;
103        let mut literals = Vec::new();
104        for rule in &f.rules {
105            let mut used = BTreeSet::new();
106            condition_sources(&rule.when, &mut used);
107            value_sources(&rule.then, &mut used);
108            if let Some(s) = used.iter().find(|s| !names.contains(**s)) {
109                return Err(format!("undeclared source {s}"));
110            }
111            extractors_v2(&program, &rule.then, inputs)?;
112            exact_conditions(&program, &rule.when, inputs)?;
113            vocabulary_values(&rule.then, &declared.ty, step)?;
114            if let ExtractionType::List { item, .. } = &declared.ty {
115                let Expr::Literal(v) = &rule.then else {
116                    return Err(format!("list field {} requires literal items", f.field));
117                };
118                if !literal_type(v, item) {
119                    return Err(format!("wrong list item type for {}", f.field));
120                }
121                if literals.contains(&v) {
122                    return Err(format!("duplicate literal item for {}", f.field));
123                }
124                literals.push(v);
125            } else if !value_type(&rule.then, &declared.ty) {
126                return Err(format!("incompatible value for {}", f.field));
127            }
128        }
129    }
130    Ok(BoundProgram {
131        program,
132        schema: step.output.clone(),
133    })
134}
135
136fn literal_type(v: &Json, ty: &ExtractionType) -> bool {
137    match ty {
138        ExtractionType::Bool {} => v.is_boolean(),
139        ExtractionType::Integer { .. } => v.is_i64() || v.is_u64(),
140        ExtractionType::Decimal(_)
141        | ExtractionType::Text { .. }
142        | ExtractionType::Date {}
143        | ExtractionType::Enum { .. } => v.is_string(),
144        ExtractionType::Record { fields } => v.as_object().is_some_and(|obj| {
145            obj.iter().all(|(name, value)| {
146                fields
147                    .iter()
148                    .any(|f| f.name == *name && literal_type(value, &f.ty))
149            })
150        }),
151        ExtractionType::List { .. } => false,
152    }
153}
154
155fn value_type(v: &Expr, ty: &ExtractionType) -> bool {
156    match (v, ty) {
157        (Expr::Literal(v), ty) => literal_type(v, ty),
158        (Expr::IntegerAfter { .. }, ExtractionType::Integer { .. })
159        | (Expr::DateIso { .. }, ExtractionType::Date {})
160        | (Expr::TokenAfter { .. } | Expr::TokenMatching { .. }, ExtractionType::Text { .. })
161        | (Expr::Date { .. }, ExtractionType::Date {})
162        | (Expr::VocabularyAfter { .. }, ExtractionType::Text { .. }) => true,
163        (Expr::VocabularyAfter { vocabulary, .. }, ExtractionType::Enum { vocabulary: v }) => {
164            vocabulary == v
165        }
166        (Expr::Record(values), ExtractionType::Record { fields }) => values
167            .iter()
168            .all(|(n, v)| fields.iter().any(|f| f.name == *n && value_type(v, &f.ty))),
169        _ => false,
170    }
171}
172
173/// The declared type of an input reference `input:<name>` or
174/// `input:<name>/<field>`.
175fn input_type<'a>(inputs: &'a [InputDecl], reference: &str) -> Option<&'a TypeDecl> {
176    let path = reference.strip_prefix("input:")?;
177    let (name, field) = match path.split_once('/') {
178        Some((name, field)) => (name, Some(field)),
179        None => (path, None),
180    };
181    let ty = &inputs.iter().find(|i| i.name == name)?.ty;
182    match (ty, field) {
183        (ty, None) => Some(ty),
184        (TypeDecl::Record { fields, .. }, Some(field)) => {
185            fields.iter().find(|f| f.name == field).map(|f| &f.ty)
186        }
187        _ => None,
188    }
189}
190
191/// Spec 070, 3.5.1 and 3.5.4: a version 2 extractor reads a projected
192/// `text` source, and a date names a declared month table exactly when its
193/// format has month names.
194fn extractors_v2(program: &ExtractRules, v: &Expr, inputs: &[InputDecl]) -> Result<(), String> {
195    let source = match v {
196        Expr::Record(vs) => {
197            return vs
198                .values()
199                .try_for_each(|v| extractors_v2(program, v, inputs));
200        }
201        Expr::Literal(_) | Expr::IntegerAfter { .. } | Expr::DateIso { .. } => return Ok(()),
202        Expr::Date {
203            source,
204            format,
205            months,
206            ..
207        } => {
208            let named = matches!(format, DateFormat::DmyName | DateFormat::MdyName);
209            match months {
210                None if named => return Err(format!("date format {format:?} requires months")),
211                Some(_) if !named => {
212                    return Err(format!("date format {format:?} takes no months"));
213                }
214                Some(t)
215                    if !program
216                        .month_tables
217                        .as_ref()
218                        .is_some_and(|tables| tables.contains_key(t)) =>
219                {
220                    return Err(format!("undeclared month table {t}"));
221                }
222                _ => {}
223            }
224            source
225        }
226        Expr::TokenAfter { source, .. }
227        | Expr::TokenMatching { source, .. }
228        | Expr::VocabularyAfter { source, .. } => source,
229    };
230    let reference = program
231        .sources
232        .iter()
233        .find(|s| s.name == *source)
234        .map(|s| s.reference.as_str())
235        .unwrap_or_default();
236    if !matches!(input_type(inputs, reference), Some(TypeDecl::Text { .. })) {
237        return Err(format!(
238            "source {source} of a version 2 extractor is not text"
239        ));
240    }
241    Ok(())
242}
243
244fn condition_sources<'a>(c: &'a Condition, out: &mut BTreeSet<&'a str>) {
245    let mut exact = BTreeSet::new();
246    condition_reads(c, out, &mut exact);
247    out.extend(exact);
248}
249
250/// The sources text conditions read, and those exact-value conditions read.
251fn condition_reads<'a>(
252    c: &'a Condition,
253    text: &mut BTreeSet<&'a str>,
254    exact: &mut BTreeSet<&'a str>,
255) {
256    match c {
257        Condition::Always => {}
258        Condition::ContainsAny { source, .. } | Condition::ContainsAll { source, .. } => {
259            text.insert(source);
260        }
261        Condition::Equals { source, .. } | Condition::OneOf { source, .. } => {
262            exact.insert(source);
263        }
264        Condition::All(cs) | Condition::Any(cs) => {
265            for c in cs {
266                condition_reads(c, text, exact);
267            }
268        }
269        Condition::Not(c) => condition_reads(c, text, exact),
270    }
271}
272
273/// Spec 070, 3.4.2 and 3.5.2: an exact-value condition reads a non-nullable
274/// `text`, `integer`, `bool` or `enum` input or record field whose accepted
275/// provenance excludes `model-derived`, and every value is of its type (an
276/// enum value one of its options).
277fn exact_conditions(
278    program: &ExtractRules,
279    c: &Condition,
280    inputs: &[InputDecl],
281) -> Result<(), String> {
282    let (source, values) = match c {
283        Condition::Always | Condition::ContainsAny { .. } | Condition::ContainsAll { .. } => {
284            return Ok(());
285        }
286        Condition::All(cs) | Condition::Any(cs) => {
287            return cs
288                .iter()
289                .try_for_each(|c| exact_conditions(program, c, inputs));
290        }
291        Condition::Not(c) => return exact_conditions(program, c, inputs),
292        Condition::Equals { source, value } => (source, std::slice::from_ref(value)),
293        Condition::OneOf { source, values } => (source, values.as_slice()),
294    };
295    let reference = program
296        .sources
297        .iter()
298        .find(|s| s.name == *source)
299        .map(|s| s.reference.as_str())
300        .unwrap_or_default();
301    let input = reference
302        .strip_prefix("input:")
303        .map(|p| p.split('/').next().unwrap_or(p))
304        .and_then(|name| inputs.iter().find(|i| i.name == name));
305    if input.is_none_or(|i| i.provenance.contains(&ProvenanceClass::ModelDerived)) {
306        return Err(format!(
307            "condition source {source} is not an input that excludes model-derived"
308        ));
309    }
310    let fits = |v: &Scalar| match (input_type(inputs, reference), v) {
311        (Some(TypeDecl::Text { .. }), Scalar::Text(_))
312        | (Some(TypeDecl::Integer), Scalar::Integer(_))
313        | (Some(TypeDecl::Bool), Scalar::Bool(_)) => true,
314        (Some(TypeDecl::Enum { options }), Scalar::Text(t)) => options.contains(t),
315        _ => false,
316    };
317    if let Some(v) = values.iter().find(|v| !fits(v)) {
318        return Err(format!(
319            "condition value {v:?} does not fit the type of source {source}"
320        ));
321    }
322    Ok(())
323}
324
325/// Spec 070, 3.5.5: `vocabulary_after` names a vocabulary the step declares;
326/// its field type is checked with the other values.
327fn vocabulary_values(v: &Expr, ty: &ExtractionType, step: &Extract) -> Result<(), String> {
328    match (v, ty) {
329        (Expr::VocabularyAfter { vocabulary, .. }, _) => {
330            if !step.vocabularies.contains_key(vocabulary) {
331                return Err(format!("undeclared vocabulary {vocabulary}"));
332            }
333            Ok(())
334        }
335        (Expr::Record(vs), ExtractionType::Record { fields }) => {
336            vs.iter()
337                .try_for_each(|(n, v)| match fields.iter().find(|f| f.name == *n) {
338                    Some(f) => vocabulary_values(v, &f.ty, step),
339                    None => Ok(()),
340                })
341        }
342        _ => Ok(()),
343    }
344}
345
346/// The paths of the extract fields a `vocabulary_after` rule can fill, as
347/// `(field, subfield)`: their values are graded `hint` (spec 070, 3.8.2).
348pub fn hint_paths(program: &ExtractRules) -> BTreeSet<(String, Option<String>)> {
349    let mut out = BTreeSet::new();
350    for f in &program.fields {
351        for r in &f.rules {
352            match &r.then {
353                Expr::VocabularyAfter { .. } => {
354                    out.insert((f.field.clone(), None));
355                }
356                Expr::Record(vs) => {
357                    for (n, v) in vs {
358                        if matches!(v, Expr::VocabularyAfter { .. }) {
359                            out.insert((f.field.clone(), Some(n.clone())));
360                        }
361                    }
362                }
363                _ => {}
364            }
365        }
366    }
367    out
368}
369
370fn value_sources<'a>(v: &'a Expr, out: &mut BTreeSet<&'a str>) {
371    match v {
372        Expr::Literal(_) => {}
373        Expr::IntegerAfter { source, .. }
374        | Expr::DateIso { source, .. }
375        | Expr::TokenAfter { source, .. }
376        | Expr::TokenMatching { source, .. }
377        | Expr::Date { source, .. }
378        | Expr::VocabularyAfter { source, .. } => {
379            out.insert(source);
380        }
381        Expr::Record(vs) => {
382            for v in vs.values() {
383                value_sources(v, out);
384            }
385        }
386    }
387}
388
389struct Reads<'a> {
390    months: &'a BTreeMap<String, Vec<Vec<String>>>,
391    vocabularies: &'a BTreeMap<String, Vec<String>>,
392    /// A `vocabulary_after` rule was skipped because its vocabulary was
393    /// unavailable (spec 070, 3.3.5).
394    vocabulary_unavailable: bool,
395    sources: &'a BTreeMap<String, Source<'a>>,
396    references: &'a BTreeMap<&'a str, &'a str>,
397    max_bytes: u64,
398    read: BTreeMap<String, Derivation>,
399}
400impl<'a> Reads<'a> {
401    fn get(&mut self, source: &str) -> Result<&'a [u8], Reason> {
402        let reference = self
403            .references
404            .get(source)
405            .ok_or(Reason::SourceUnavailable)?;
406        match self.sources.get(*reference) {
407            Some(Source::Readable { bytes, derivation })
408                if bytes.len() as u64 <= self.max_bytes =>
409            {
410                self.read.insert((*reference).into(), *derivation);
411                Ok(bytes)
412            }
413            _ => Err(Reason::SourceUnavailable),
414        }
415    }
416
417    /// An exact-value condition's read: the text bytes or the scalar value.
418    fn exact(&mut self, source: &str) -> Result<Exact<'a>, Reason> {
419        let reference = self
420            .references
421            .get(source)
422            .ok_or(Reason::SourceUnavailable)?;
423        match self.sources.get(*reference) {
424            Some(Source::Exact { value, derivation }) => {
425                self.read.insert((*reference).into(), *derivation);
426                Ok(Exact::Value(value))
427            }
428            Some(Source::Readable { .. }) => self.get(source).map(Exact::Text),
429            _ => Err(Reason::SourceUnavailable),
430        }
431    }
432}
433
434enum Exact<'a> {
435    Text(&'a [u8]),
436    Value(&'a Scalar),
437}
438
439/// Spec 070, 3.4.3: bytes with no folding, integers and booleans by value.
440fn equal(read: &Exact<'_>, v: &Scalar) -> bool {
441    match (read, v) {
442        (Exact::Text(bytes), Scalar::Text(t)) => *bytes == t.as_bytes(),
443        (Exact::Value(value), v) => *value == v,
444        _ => false,
445    }
446}
447
448// Spec 005, 3.4.4: the backend uses to_ascii_lowercase; its private
449// implementation cannot be imported into core. Other bytes remain unchanged.
450fn occurrence(text: &[u8], term: &str) -> Option<usize> {
451    text.windows(term.len())
452        .position(|w| w.eq_ignore_ascii_case(term.as_bytes()))
453}
454fn condition(c: &Condition, reads: &mut Reads<'_>) -> Result<bool, Reason> {
455    Ok(match c {
456        Condition::Always => true,
457        Condition::ContainsAny { source, terms } => {
458            let text = reads.get(source)?;
459            terms.iter().any(|t| occurrence(text, t).is_some())
460        }
461        Condition::ContainsAll { source, terms } => {
462            let text = reads.get(source)?;
463            terms.iter().all(|t| occurrence(text, t).is_some())
464        }
465        Condition::All(cs) => {
466            for c in cs {
467                if !condition(c, reads)? {
468                    return Ok(false);
469                }
470            }
471            true
472        }
473        Condition::Any(cs) => {
474            for c in cs {
475                if condition(c, reads)? {
476                    return Ok(true);
477                }
478            }
479            false
480        }
481        Condition::Not(c) => !condition(c, reads)?,
482        // An unreadable source ends the field's evaluation: never false
483        // (spec 070, 3.4.5).
484        Condition::Equals { source, value } => equal(&reads.exact(source)?, value),
485        Condition::OneOf { source, values } => {
486            let read = reads.exact(source)?;
487            values.iter().any(|v| equal(&read, v))
488        }
489    })
490}
491fn value(v: &Expr, reads: &mut Reads<'_>) -> Result<Option<Json>, Reason> {
492    Ok(match v {
493        Expr::Literal(v) => Some(v.clone()),
494        Expr::IntegerAfter {
495            source,
496            terms,
497            max_digits,
498        } => {
499            let text = reads.get(source)?;
500            // Earliest byte offset wins; equal offsets keep declared term order.
501            let Some((i, len)) = crate::extraction_match::first_term(text, terms) else {
502                return Ok(None);
503            };
504            let tail = &text[i + len..];
505            let spaces = tail.iter().take_while(|b| **b == b' ').count();
506            let digits = &tail[spaces..];
507            let n = digits.iter().take_while(|b| b.is_ascii_digit()).count();
508            if n == 0 || n > usize::from(*max_digits) {
509                return Ok(None);
510            }
511            Some(Json::from(
512                digits[..n]
513                    .iter()
514                    .fold(0i64, |v, b| v * 10 + i64::from(b - b'0')),
515            ))
516        }
517        Expr::DateIso { source, occurrence } => {
518            let text = reads.get(source)?;
519            text.windows(10)
520                .filter(|w| {
521                    w.iter().enumerate().all(|(i, b)| {
522                        if i == 4 || i == 7 {
523                            *b == b'-'
524                        } else {
525                            b.is_ascii_digit()
526                        }
527                    })
528                })
529                .nth(usize::from(*occurrence) - 1)
530                .map(|w| Json::String(w.iter().map(|b| char::from(*b)).collect()))
531        }
532        Expr::Record(fields) => {
533            let mut obj = serde_json::Map::new();
534            for (name, v) in fields {
535                let Some(v) = value(v, reads)? else {
536                    return Ok(None);
537                };
538                obj.insert(name.clone(), v);
539            }
540            Some(Json::Object(obj))
541        }
542        Expr::TokenAfter {
543            source,
544            terms,
545            charset,
546            min_len,
547            max_len,
548        } => crate::extraction_match::token_after(
549            reads.get(source)?,
550            terms,
551            charset,
552            *min_len,
553            *max_len,
554        )
555        .map(Json::String),
556        Expr::TokenMatching {
557            source,
558            shape,
559            occurrence,
560        } => crate::extraction_match::token_matching(
561            reads.get(source)?,
562            shape,
563            occurrence.unwrap_or(1),
564        )
565        .map(Json::String),
566        Expr::Date {
567            source,
568            format,
569            months,
570            occurrence,
571        } => {
572            let text = reads.get(source)?;
573            let table = months
574                .as_ref()
575                .and_then(|t| reads.months.get(t))
576                .map_or(&[][..], Vec::as_slice);
577            crate::extraction_match::date(text, *format, table, *occurrence).map(Json::String)
578        }
579        Expr::VocabularyAfter {
580            source,
581            terms,
582            vocabulary,
583        } => {
584            let text = reads.get(source)?;
585            let Some(options) = reads.vocabularies.get(vocabulary) else {
586                reads.vocabulary_unavailable = true;
587                return Ok(None);
588            };
589            crate::extraction_match::word_after(text, terms)
590                .filter(|w| options.iter().any(|o| o == w))
591                .map(Json::String)
592        }
593    })
594}
595
596impl BoundProgram {
597    /// Sources are keyed by input reference, vocabularies by declared name.
598    /// Boolean conditions short-circuit in declared order; only reached reads
599    /// contribute lineage. An unavailable reached source stops that field.
600    pub fn evaluate(
601        &self,
602        sources: &BTreeMap<String, Source<'_>>,
603        vocabularies: &BTreeMap<String, Vec<String>>,
604        max_projection_bytes: u64,
605    ) -> Vec<FallbackField> {
606        let months = self.program.month_tables.clone().unwrap_or_default();
607        let references = self
608            .program
609            .sources
610            .iter()
611            .map(|s| (s.name.as_str(), s.reference.as_str()))
612            .collect();
613        self.schema
614            .fields
615            .iter()
616            .map(|field| {
617                let mut reads = Reads {
618                    months: &months,
619                    vocabularies,
620                    vocabulary_unavailable: false,
621                    sources,
622                    references: &references,
623                    max_bytes: max_projection_bytes,
624                    read: BTreeMap::new(),
625                };
626                let result = (|| {
627                    let mut items = Vec::new();
628                    if let Some(f) = self.program.fields.iter().find(|f| f.field == field.name) {
629                        for rule in &f.rules {
630                            if condition(&rule.when, &mut reads)?
631                                && let Some(v) = value(&rule.then, &mut reads)?
632                            {
633                                if matches!(field.ty, ExtractionType::List { .. }) {
634                                    items.push(v);
635                                } else {
636                                    return Ok(v);
637                                }
638                            }
639                        }
640                    }
641                    if items.is_empty() {
642                        Err(if reads.vocabulary_unavailable {
643                            Reason::VocabularyUnavailable
644                        } else {
645                            Reason::FallbackNoMatch
646                        })
647                    } else {
648                        Ok(Json::Array(items))
649                    }
650                })();
651                let validated = result
652                    .and_then(|v| {
653                        let schema = ExtractionSchema {
654                            fields: vec![field.clone()],
655                        };
656                        let raw = RawOutput::TypedRecord {
657                            fields: BTreeMap::from([(field.name.clone(), v)]),
658                            logprobs: vec![],
659                            provider_reported: BTreeMap::new(),
660                        };
661                        let mut validated = extraction_validate::validate(
662                            &schema,
663                            vocabularies,
664                            &raw,
665                            Distributions::None,
666                            false,
667                        )
668                        .map_err(|_| Reason::FallbackInvalid)?
669                        .remove(0);
670                        // A failing fallback item invalidates the fallback field; never
671                        // silently salvage a partially invalid deterministic result.
672                        if validated.value.is_none() || !validated.evidence.rejected.is_empty() {
673                            return Err(Reason::FallbackInvalid);
674                        }
675                        validated.evidence.origin = ExtractionOrigin::Fallback;
676                        validated.evidence.derivation =
677                            Some(fallback_derivation(reads.read.values().copied()));
678                        Ok(validated)
679                    })
680                    .unwrap_or_else(|reason| ValidatedField {
681                        value: None,
682                        evidence: ExtractionFieldEvidence::new(
683                            field.name.clone(),
684                            &field.ty,
685                            ExtractionOrigin::Absent { reason },
686                            None,
687                            None,
688                            None,
689                            vec![],
690                        ),
691                    });
692                FallbackField {
693                    field: validated,
694                    sources_read: reads.read.into_keys().collect(),
695                }
696            })
697            .collect()
698    }
699}
700
701/// Merge by field name, preserving model order and every present model field.
702/// `request_produced_output` distinguishes an accepted record with absent fields
703/// from a request failure. The caller supplies model entries for the full schema.
704/// Returns source lineage only for fallback entries actually selected by the fill.
705pub fn merge(
706    model: &mut [ValidatedField],
707    fallback: &[FallbackField],
708    fill: Fill,
709    request_produced_output: bool,
710) -> BTreeMap<String, Vec<String>> {
711    let mut reads = BTreeMap::new();
712    if fill == Fill::RequestFailure && request_produced_output {
713        return reads;
714    }
715    for field in model {
716        if field.value.is_none()
717            && let Some(f) = fallback
718                .iter()
719                .find(|f| f.field.evidence.name == field.evidence.name)
720        {
721            *field = f.field.clone();
722            reads.insert(field.evidence.name.clone(), f.sources_read.clone());
723        }
724    }
725    reads
726}