Skip to main content

meta_language/grammar/feature_runtime/
mapped_tree_validation.rs

1//! Inspectable ordinary-data adapter for generated source-mapping decisions.
2//! Generic Links decoding alone does not authenticate mapping or grammar CSTs.
3
4use std::cell::Cell;
5use std::collections::HashMap;
6use std::rc::Rc;
7
8use serde_json::Value;
9
10#[path = "mapped_tree_validation/field_ranges.rs"]
11mod field_ranges;
12
13use super::field_range_source::read_field_range_view;
14use super::operations::Abort;
15use super::selection_source_mapping::{MappedSource, MappingBudget, SourceRegistry, numeric};
16use super::{DEFAULT_MAX_DEPTH, DEFAULT_MEMORY_LIMIT, FeatureParseOptions, GrammarRuntimeError};
17use crate::translation::frontend_rules::ml_array::number_index;
18use crate::translation::grammar_selection_field_range_rules::accept_grammar_selection_field_range_mapping;
19use crate::translation::grammar_selection_included_range_rules::{
20    accept_grammar_selection_included_range_agreement,
21    accept_grammar_selection_included_range_derivation,
22    accept_grammar_selection_included_range_descriptor,
23    accept_grammar_selection_included_range_mapping,
24    accept_grammar_selection_included_range_profile,
25    accept_grammar_selection_included_range_source_range,
26    read_grammar_selection_included_range_field_order,
27};
28use crate::translation::grammar_selection_mapping_rules::{
29    accept_grammar_selection_mapping_descriptor, accept_grammar_selection_mapping_occurrence,
30    accept_grammar_selection_mapping_profile, accept_grammar_selection_mapping_reference,
31    accept_grammar_selection_physical_span, accept_grammar_selection_source_definition,
32    accept_grammar_selection_source_derivation, accept_grammar_selection_source_interval,
33    accept_grammar_selection_source_root, read_grammar_selection_mapping_field_order,
34    read_grammar_selection_tree_children,
35};
36use field_ranges::{
37    accept_field_range_keys, field_facts_agree, field_selector, field_view_agrees, same_bytes,
38    same_field_witness,
39};
40
41fn invalid(detail: &str) -> GrammarRuntimeError {
42    GrammarRuntimeError {
43        reason: "selection",
44        message: format!("mapped grammar CST: {detail}"),
45    }
46}
47
48fn aborted(abort: Abort) -> GrammarRuntimeError {
49    let reason = match abort {
50        Abort::StepLimit => "stepLimit",
51        Abort::MemoryBudget => "memoryBudget",
52        Abort::NestingTooDeep => "nestingDepth",
53        Abort::Operation => "operation",
54    };
55    GrammarRuntimeError {
56        reason,
57        message: format!("mapped grammar CST: {reason} resource refusal"),
58    }
59}
60
61fn number(value: &Value) -> f64 {
62    value.as_f64().unwrap_or(f64::NAN)
63}
64fn offset(value: &Value) -> Option<usize> {
65    number_index(number(value))
66}
67
68struct ValidationBudget {
69    steps: Cell<usize>,
70    cells: Cell<usize>,
71    step_limit: usize,
72    memory_limit: usize,
73    max_depth: usize,
74}
75
76impl MappingBudget for ValidationBudget {
77    fn mapping_step(&self) -> Result<(), Abort> {
78        let steps = self.steps.get().checked_add(1).ok_or(Abort::StepLimit)?;
79        self.steps.set(steps);
80        if steps > self.step_limit {
81            Err(Abort::StepLimit)
82        } else {
83            Ok(())
84        }
85    }
86    fn mapping_retain(&self, count: usize) -> Result<(), Abort> {
87        let cells = self
88            .cells
89            .get()
90            .checked_add(count)
91            .ok_or(Abort::MemoryBudget)?;
92        self.cells.set(cells);
93        if cells > self.memory_limit {
94            Err(Abort::MemoryBudget)
95        } else {
96            Ok(())
97        }
98    }
99}
100
101impl ValidationBudget {
102    fn depth(&self, depth: usize) -> Result<(), GrammarRuntimeError> {
103        self.mapping_step().map_err(aborted)?;
104        if depth > self.max_depth {
105            Err(aborted(Abort::NestingTooDeep))
106        } else {
107            Ok(())
108        }
109    }
110    fn retain(&self, count: usize) -> Result<(), GrammarRuntimeError> {
111        self.mapping_retain(count).map_err(aborted)
112    }
113    fn step(&self) -> Result<(), GrammarRuntimeError> {
114        self.mapping_step().map_err(aborted)
115    }
116    fn plain(&self, value: &Value, depth: usize) -> Result<(), GrammarRuntimeError> {
117        self.depth(depth)?;
118        match value {
119            Value::Array(items) => {
120                self.retain(items.len() + 2)?;
121                for item in items {
122                    self.step()?;
123                    self.plain(item, depth + 1)?;
124                }
125                // The JS ordinary-data snapshot visits the own length
126                // descriptor after its dense array elements.
127                self.step()?;
128            }
129            Value::Object(fields) => {
130                self.retain(fields.len() + 1)?;
131                for item in fields.values() {
132                    self.step()?;
133                    self.plain(item, depth + 1)?;
134                }
135            }
136            _ => {}
137        }
138        Ok(())
139    }
140}
141
142fn exact_keys(value: &Value, role: &str) -> bool {
143    let Some(fields) = value.as_object() else {
144        return false;
145    };
146    let plan = read_grammar_selection_mapping_field_order(role);
147    fields.keys().map(String::as_str).eq(plan.split('|'))
148}
149
150fn accept_included_range_keys(value: &Value, role: &str) -> bool {
151    let Some(fields) = value.as_object() else {
152        return false;
153    };
154    let plan = read_grammar_selection_included_range_field_order(role);
155    fields.keys().map(String::as_str).eq(plan.split('|'))
156}
157
158fn read_included_range_columns(
159    value: &Value,
160    budget: &ValidationBudget,
161) -> Result<Vec<f64>, GrammarRuntimeError> {
162    let ranges = value
163        .as_array()
164        .ok_or_else(|| invalid("invalid included source ranges"))?;
165    let cells = ranges
166        .len()
167        .checked_mul(2)
168        .and_then(|count| count.checked_add(1))
169        .ok_or_else(|| aborted(Abort::MemoryBudget))?;
170    budget.retain(cells)?;
171    let mut columns = Vec::new();
172    for range in ranges {
173        budget.step()?;
174        let row = range
175            .as_array()
176            .filter(|row| row.len() == 2)
177            .ok_or_else(|| invalid("invalid included source ranges"))?;
178        if !accept_grammar_selection_included_range_source_range(
179            "source-range",
180            number(&row[0]),
181            number(&row[1]),
182        ) {
183            return Err(invalid("invalid included source ranges"));
184        }
185        columns.extend([number(&row[0]), number(&row[1])]);
186    }
187    Ok(columns)
188}
189
190fn physical(
191    nodes: &[Value],
192    begin: usize,
193    end: usize,
194    depth: usize,
195    budget: &ValidationBudget,
196) -> Result<Vec<u8>, GrammarRuntimeError> {
197    let mut bytes = Vec::new();
198    let mut cursor = begin;
199    for node in nodes {
200        physical_node(node, &mut cursor, &mut bytes, depth, budget)?;
201    }
202    if cursor != end {
203        return Err(invalid("incomplete physical source plane"));
204    }
205    Ok(bytes)
206}
207
208fn physical_node(
209    node: &Value,
210    cursor: &mut usize,
211    bytes: &mut Vec<u8>,
212    depth: usize,
213    budget: &ValidationBudget,
214) -> Result<(), GrammarRuntimeError> {
215    budget.depth(depth)?;
216    budget.retain(1)?;
217    if !node.is_object() {
218        return Err(invalid("invalid physical tree"));
219    }
220    let begin = *cursor;
221    let role = read_grammar_selection_tree_children(
222        node["type"].as_str().unwrap_or_default(),
223        node.get("sourceChildren").is_some(),
224    );
225    match role.as_str() {
226        "leaf" => {
227            let count = if let Some(text) = node["text"].as_str() {
228                text.len()
229            } else if node.get("text").is_some_and(Value::is_null) {
230                let Some(hex) = node["hex"].as_str().filter(|hex| {
231                    hex.len().is_multiple_of(2)
232                        && hex
233                            .bytes()
234                            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
235                }) else {
236                    return Err(invalid("invalid physical leaf bytes"));
237                };
238                hex.len() / 2
239            } else {
240                return Err(invalid("invalid physical leaf bytes"));
241            };
242            if !accept_grammar_selection_physical_span(
243                number(&node["start"]),
244                number(&node["end"]),
245                numeric(*cursor),
246                numeric(count),
247                false,
248            ) {
249                return Err(invalid("physical leaf span differs"));
250            }
251            budget.retain(count + 1)?;
252            if let Some(text) = node["text"].as_str() {
253                for byte in text.as_bytes() {
254                    budget.step()?;
255                    bytes.push(*byte);
256                }
257            } else {
258                let hex = node["hex"]
259                    .as_str()
260                    .ok_or_else(|| invalid("invalid physical leaf bytes"))?;
261                for word in hex.as_bytes().as_chunks::<2>().0 {
262                    budget.step()?;
263                    let word = std::str::from_utf8(word)
264                        .map_err(|_| invalid("invalid physical leaf bytes"))?;
265                    bytes.push(
266                        u8::from_str_radix(word, 16)
267                            .map_err(|_| invalid("invalid physical leaf bytes"))?,
268                    );
269                }
270            }
271            *cursor = offset(&node["end"]).ok_or_else(|| invalid("physical leaf span differs"))?;
272        }
273        "missing" => {
274            if !accept_grammar_selection_physical_span(
275                number(&node["start"]),
276                number(&node["end"]),
277                numeric(*cursor),
278                0.0,
279                true,
280            ) {
281                return Err(invalid("invalid missing span"));
282            }
283        }
284        "children" | "sourceChildren" => {
285            let field = if role == "children" {
286                "children"
287            } else {
288                "sourceChildren"
289            };
290            let children = node[field]
291                .as_array()
292                .ok_or_else(|| invalid("missing concrete children"))?;
293            for child in children {
294                physical_node(child, cursor, bytes, depth + 1, budget)?;
295            }
296        }
297        "root" => physical_node(&node["root"], cursor, bytes, depth + 1, budget)?,
298        _ => return Err(invalid("unknown concrete node kind")),
299    }
300    if role != "leaf"
301        && role != "missing"
302        && !accept_grammar_selection_physical_span(
303            number(&node["start"]),
304            number(&node["end"]),
305            numeric(begin),
306            numeric(*cursor - begin),
307            false,
308        )
309    {
310        return Err(invalid("physical container span differs"));
311    }
312    Ok(())
313}
314
315struct Validator<'a> {
316    definitions: &'a [Value],
317    planes: Vec<Rc<[u8]>>,
318    field_sources: HashMap<usize, MappedSource>,
319    registry: SourceRegistry,
320    budget: ValidationBudget,
321}
322
323impl Validator<'_> {
324    fn walk(
325        &mut self,
326        node: &Value,
327        plane: usize,
328        depth: usize,
329    ) -> Result<(), GrammarRuntimeError> {
330        self.budget.depth(depth)?;
331        if node["type"] == "node" {
332            let children = node["children"]
333                .as_array()
334                .ok_or_else(|| invalid("missing concrete children"))?;
335            for child in children {
336                self.walk(child, plane, depth + 1)?;
337            }
338            return Ok(());
339        }
340        if node["type"] != "embed" {
341            return Ok(());
342        }
343        let selection = &node["selection"];
344        let profile = match selection.get("mapping") {
345            None | Some(Value::Null) => "identity",
346            Some(Value::String(profile)) => profile,
347            _ => return Err(invalid("unknown mapping profile")),
348        };
349        let field = accept_grammar_selection_field_range_mapping(profile);
350        let included = accept_grammar_selection_included_range_mapping(profile);
351        let accepted_profile = if field || included {
352            accept_grammar_selection_included_range_profile(
353                if field { "included-ranges" } else { profile },
354                node.get("sourceChildren").is_some(),
355                selection.get("sourceMapping").is_some(),
356            )
357        } else {
358            accept_grammar_selection_mapping_profile(
359                profile,
360                node.get("sourceChildren").is_some(),
361                selection.get("sourceMapping").is_some(),
362            )
363        };
364        if !accepted_profile {
365            return Err(invalid("unknown mapping profile"));
366        }
367        let alternatives = selection["alternatives"].as_array();
368        if profile != "json-string" && !included && !field {
369            self.walk(&node["root"], plane, depth + 1)?;
370            if let Some(alternatives) = alternatives {
371                for alternative in alternatives {
372                    self.walk(&alternative["root"], plane, depth + 1)?;
373                }
374            }
375            return Ok(());
376        }
377        let mapping = &selection["sourceMapping"];
378        let (ordered_fields, descriptor) = if field {
379            (
380                accept_field_range_keys(mapping, "mapping"),
381                accept_grammar_selection_included_range_descriptor(
382                    mapping["kind"].as_str().unwrap_or_default(),
383                    "included-ranges",
384                ) && accept_grammar_selection_field_range_mapping(
385                    mapping["operation"].as_str().unwrap_or_default(),
386                ),
387            )
388        } else if included {
389            (
390                accept_included_range_keys(mapping, "mapping"),
391                accept_grammar_selection_included_range_descriptor(
392                    mapping["kind"].as_str().unwrap_or_default(),
393                    mapping["operation"].as_str().unwrap_or_default(),
394                ),
395            )
396        } else {
397            (
398                exact_keys(mapping, "mapping"),
399                accept_grammar_selection_mapping_descriptor(
400                    mapping["kind"].as_str().unwrap_or_default(),
401                    mapping["operation"].as_str().unwrap_or_default(),
402                ),
403            )
404        };
405        if !ordered_fields
406            || !descriptor
407            || !node["sourceChildren"].is_array()
408            || mapping["input"] == mapping["output"]
409            || !accept_grammar_selection_mapping_occurrence(
410                number(&mapping["input"]),
411                numeric(plane),
412                number(&selection["start"]),
413                number(&node["start"]),
414                number(&selection["end"]),
415                number(&node["end"]),
416            )
417        {
418            return Err(invalid("invalid mapped boundary"));
419        }
420        if !accept_grammar_selection_mapping_reference(
421            number(&mapping["input"]),
422            numeric(plane),
423            number(&mapping["output"]),
424            numeric(self.planes.len()),
425        ) {
426            return Err(invalid("unowned source-plane reference"));
427        }
428        let output =
429            offset(&mapping["output"]).ok_or_else(|| invalid("unowned source-plane reference"))?;
430        let origin = &self.definitions[output]["derivation"];
431        if !accept_grammar_selection_mapping_occurrence(
432            number(&origin["input"]),
433            number(&mapping["input"]),
434            number(&origin["start"]),
435            number(&node["start"]),
436            number(&origin["end"]),
437            number(&node["end"]),
438        ) {
439            return Err(invalid("mapping belongs to another source occurrence"));
440        }
441        if field
442            && !accept_grammar_selection_field_range_mapping(
443                origin["operation"].as_str().unwrap_or_default(),
444            )
445        {
446            return Err(invalid("source field operation differs"));
447        }
448        let ranges = if included {
449            let actual = read_included_range_columns(&mapping["ranges"], &self.budget)?;
450            let expected = read_included_range_columns(&origin["ranges"], &self.budget)?;
451            if !accept_grammar_selection_included_range_agreement(&actual, &expected) {
452                return Err(invalid("ordered included source ranges differ"));
453            }
454            Some(expected.as_chunks::<2>().0.to_vec())
455        } else {
456            None
457        };
458        let start = offset(&node["start"]).ok_or_else(|| invalid("invalid mapped boundary"))?;
459        let end = offset(&node["end"]).ok_or_else(|| invalid("invalid mapped boundary"))?;
460        let repeated;
461        let derived = if field {
462            field_facts_agree(mapping, origin, &self.budget)?;
463            let view = read_field_range_view(
464                &self.planes[plane],
465                start,
466                end,
467                &mapping["selector"],
468                &node["sourceChildren"],
469                &self.budget,
470                self.budget.max_depth.saturating_sub(depth),
471            )
472            .map_err(aborted)?
473            .map_err(|failed| invalid(failed.reason))?;
474            field_view_agrees(&view, origin, &self.budget)?;
475            if !same_field_witness(&view.witness, &origin["witness"], 0, &self.budget)? {
476                return Err(invalid(
477                    "physical source witness differs from the accepted source view",
478                ));
479            }
480            self.field_sources
481                .get(&output)
482                .ok_or_else(|| invalid("source field definition was not verified"))?
483        } else {
484            repeated = if let Some(ranges) = &ranges {
485                self.registry
486                    .map_included(&self.planes[plane], start, end, ranges, &self.budget)
487            } else {
488                self.registry
489                    .map(&self.planes[plane], start, end, &self.budget)
490            }
491            .map_err(aborted)?
492            .map_err(|failed| invalid(failed.reason))?;
493            &repeated
494        };
495        let actual = mapping["intervals"]
496            .as_array()
497            .ok_or_else(|| invalid("ordered source intervals differ"))?;
498        let expected = derived.mapping["intervals"]
499            .as_array()
500            .ok_or_else(|| invalid("ordered source intervals differ"))?;
501        if actual.len() != expected.len() {
502            return Err(invalid("ordered source intervals differ"));
503        }
504        for (row, expected) in actual.iter().zip(expected) {
505            let Some(row) = row.as_array() else {
506                return Err(invalid("ordered source intervals differ"));
507            };
508            let Some(expected) = expected.as_array() else {
509                return Err(invalid("ordered source intervals differ"));
510            };
511            let row = row.iter().map(number).collect::<Vec<_>>();
512            let expected = expected.iter().map(number).collect::<Vec<_>>();
513            if !accept_grammar_selection_source_interval(&row, &expected) {
514                return Err(invalid("ordered source intervals differ"));
515            }
516        }
517        if offset(&derived.mapping["output"]) != offset(&mapping["output"]) {
518            return Err(invalid(
519                "source reference differs from its actual derivation",
520            ));
521        }
522        let derived_bytes = derived.bytes.clone();
523        for child in node["sourceChildren"]
524            .as_array()
525            .ok_or_else(|| invalid("invalid physical source children"))?
526        {
527            self.walk(child, plane, depth + 1)?;
528        }
529        let alternatives = alternatives.ok_or_else(|| invalid("invalid selection witnesses"))?;
530        for root in std::iter::once(&node["root"])
531            .chain(alternatives.iter().map(|alternative| &alternative["root"]))
532        {
533            let stored = physical(
534                std::slice::from_ref(root),
535                0,
536                derived_bytes.len(),
537                depth + 1,
538                &self.budget,
539            )?;
540            if stored.as_slice() != &*derived_bytes {
541                return Err(invalid("decoded tree bytes differ"));
542            }
543            self.walk(root, output, depth + 1)?;
544        }
545        Ok(())
546    }
547}
548
549/// Validate source correspondence in a complete mapped CST plain-data bundle.
550///
551/// Returns the same borrowed value; grammar membership still requires parsing
552/// with its actual grammar. No generic decoding or numeric ID proves ownership.
553///
554/// # Errors
555/// Returns a selection error for malformed maps, source definitions or CST
556/// bytes, and the unchanged resource reason when the shared bounds are reached.
557pub fn check_grammar_selection_mapped_tree<'a>(
558    bundle: &'a Value,
559    options: &FeatureParseOptions,
560) -> Result<&'a Value, GrammarRuntimeError> {
561    let tree = bundle
562        .get("tree")
563        .filter(|tree| tree.is_object())
564        .ok_or_else(|| invalid("a complete physical root CST is required"))?;
565    let end = offset(&tree["end"])
566        .filter(|end| u32::try_from(*end).is_ok())
567        .ok_or_else(|| invalid("a complete physical root CST is required"))?;
568    let budget = ValidationBudget {
569        steps: Cell::new(0),
570        cells: Cell::new(0),
571        step_limit: options.step_limit.unwrap_or_else(|| {
572            (100_000 + 1000 * end)
573                * if options.error_recovery == Some(true) {
574                    2
575                } else {
576                    1
577                }
578        }),
579        memory_limit: options.memory_limit.unwrap_or(DEFAULT_MEMORY_LIMIT),
580        max_depth: options.max_depth.unwrap_or(DEFAULT_MAX_DEPTH),
581    };
582    budget.plain(bundle, 0)?;
583    let definitions = bundle["sourcePlanes"]
584        .as_array()
585        .filter(|rows| !rows.is_empty())
586        .ok_or_else(|| invalid("the source-plane table is required"))?;
587    let bytes = physical(std::slice::from_ref(tree), 0, end, 0, &budget)?;
588    let mut position = 0;
589    while position < bytes.len() {
590        budget.step()?;
591        let (scalar, width) = super::text::decode_at(&bytes, position, bytes.len());
592        if scalar.is_none() {
593            return Err(invalid("the root source plane is not UTF-8"));
594        }
595        position += width;
596    }
597    let mut validator = Validator {
598        definitions,
599        planes: Vec::new(),
600        field_sources: HashMap::new(),
601        registry: SourceRegistry::default(),
602        budget,
603    };
604    let root: Rc<[u8]> = Rc::from(bytes);
605    for (identity, definition) in definitions.iter().enumerate() {
606        validator.budget.step()?;
607        validator.budget.retain(1)?;
608        if !exact_keys(definition, "source") {
609            return Err(invalid("invalid ordered source definition"));
610        }
611        if !accept_grammar_selection_source_root(
612            numeric(identity),
613            definition["derivation"].is_null(),
614        ) {
615            return Err(invalid("invalid source derivation presence"));
616        }
617        let mut field_source = None;
618        let bytes = if identity == 0 {
619            root.clone()
620        } else {
621            let origin = &definition["derivation"];
622            let field = accept_grammar_selection_field_range_mapping(
623                origin["operation"].as_str().unwrap_or_default(),
624            );
625            let included = accept_grammar_selection_included_range_mapping(
626                origin["operation"].as_str().unwrap_or_default(),
627            );
628            let ordered = if field {
629                accept_field_range_keys(origin, "derivation")
630            } else if included {
631                accept_included_range_keys(origin, "derivation")
632            } else {
633                exact_keys(origin, "derivation")
634            };
635            if !ordered {
636                return Err(invalid("unowned source derivation"));
637            }
638            let input = offset(&origin["input"])
639                .and_then(|index| validator.planes.get(index))
640                .ok_or_else(|| invalid("unowned source derivation"))?;
641            // The separately admitted field operation uses the existing byte
642            // contraction protocol's coordinate invariant, just as JS does.
643            let accepted = if field || included {
644                accept_grammar_selection_included_range_derivation(
645                    if field {
646                        "included-ranges"
647                    } else {
648                        origin["operation"].as_str().unwrap_or_default()
649                    },
650                    number(&origin["input"]),
651                    numeric(identity),
652                    number(&origin["start"]),
653                    number(&origin["end"]),
654                    numeric(input.len()),
655                )
656            } else {
657                accept_grammar_selection_source_derivation(
658                    origin["operation"].as_str().unwrap_or_default(),
659                    number(&origin["input"]),
660                    numeric(identity),
661                    number(&origin["start"]),
662                    number(&origin["end"]),
663                    numeric(input.len()),
664                )
665            };
666            if !accepted {
667                return Err(invalid("unowned source derivation"));
668            }
669            let start =
670                offset(&origin["start"]).ok_or_else(|| invalid("unowned source derivation"))?;
671            let end = offset(&origin["end"]).ok_or_else(|| invalid("unowned source derivation"))?;
672            let derived = if field {
673                read_included_range_columns(&origin["ranges"], &validator.budget)?;
674                field_selector(&origin["selector"], &validator.budget)?;
675                let witness = &origin["witness"];
676                let ordered_witness = witness.as_object().is_some_and(|fields| {
677                    fields
678                        .keys()
679                        .map(String::as_str)
680                        .eq(["start", "end", "children"])
681                });
682                let children = witness["children"]
683                    .as_array()
684                    .filter(|_| {
685                        ordered_witness
686                            && offset(&witness["start"]) == Some(start)
687                            && offset(&witness["end"]) == Some(end)
688                    })
689                    .ok_or_else(|| invalid("invalid physical source witness"))?;
690                let stored = physical(children, start, end, 0, &validator.budget)?;
691                if stored.len() != end - start
692                    || !same_bytes(&stored, input, start, &validator.budget)?
693                {
694                    return Err(invalid("physical source witness bytes differ"));
695                }
696                // A fresh replay owner for each actual definition replaces
697                // JS's fresh private children array. No archive pointer or
698                // structural deduplication can establish this owner identity.
699                validator.budget.retain(children.len() + 1)?;
700                for _ in children {
701                    validator.budget.step()?;
702                }
703                validator.registry.map_field_value(
704                    input,
705                    (start, end),
706                    &origin["selector"],
707                    (identity, &witness["children"]),
708                    &validator.budget,
709                    validator.budget.max_depth,
710                )
711            } else if included {
712                let ranges = read_included_range_columns(&origin["ranges"], &validator.budget)?
713                    .as_chunks::<2>()
714                    .0
715                    .to_vec();
716                validator
717                    .registry
718                    .map_included(input, start, end, &ranges, &validator.budget)
719            } else {
720                validator.registry.map(input, start, end, &validator.budget)
721            }
722            .map_err(aborted)?
723            .map_err(|_| invalid("invalid source derivation"))?;
724            if field {
725                field_facts_agree(origin, &derived.mapping, &validator.budget)?;
726                let canonical = validator
727                    .registry
728                    .definition(
729                        offset(&derived.mapping["output"])
730                            .ok_or_else(|| invalid("invalid source derivation"))?,
731                    )
732                    .ok_or_else(|| invalid("invalid source derivation"))?;
733                if !same_field_witness(
734                    &origin["witness"],
735                    &canonical["derivation"]["witness"],
736                    0,
737                    &validator.budget,
738                )? {
739                    return Err(invalid(
740                        "physical source witness metadata differs from its replay",
741                    ));
742                }
743            }
744            if offset(&derived.mapping["output"]) != Some(identity) {
745                return Err(invalid("invalid source derivation"));
746            }
747            if field {
748                let bytes = derived.bytes.clone();
749                field_source = Some(derived);
750                bytes
751            } else {
752                derived.bytes
753            }
754        };
755        if !accept_grammar_selection_source_definition(
756            definition["kind"].as_str().unwrap_or_default(),
757            number(&definition["identity"]),
758            numeric(identity),
759            definition["encoding"].as_str().unwrap_or_default(),
760            number(&definition["byteLength"]),
761            numeric(bytes.len()),
762        ) {
763            return Err(invalid("invalid source definition"));
764        }
765        if let Some(derived) = field_source {
766            validator.field_sources.insert(identity, derived);
767        }
768        validator.planes.push(bytes);
769    }
770    validator.walk(tree, 0, 0)?;
771    Ok(bundle)
772}