grippo 0.1.3

Parse, match and scrub data at scale.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
// Project:   grippo
// File:      src/parse/driver.rs
// Purpose:   The chain driver: a source's compiled parse plan and its run
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A [`ParsePlan`] is compiled once per source from its [`ParseConfig`]. A
//! record enters at the first hop. Every parser that takes its input runs the
//! rest of the chain on what it produced: its body, one of its values, or
//! each of them. What a record parses to depends on that record and the plan
//! alone, never on the records before it.

use std::borrow::Cow;
use std::cmp::Reverse;
use std::ops::Range;
use std::sync::Arc;
use std::time::Instant;

use thiserror::Error;

use super::capture::{Budget, Capture, Captured, Promote, Want};
use super::chain::ChainError;
use super::config::{FallbackConfig, FormatChoice, HopConfig, ParseConfig, Settings};
use super::frame::{Frame, FrameState, FramingConfig};
use super::sink::{FieldSink, SinkMark};
use super::trace::{Event, Failure, Input, Step, Trace};
use super::{ParseError, Parsed, Parser, Resolve, ResolveError};
use crate::path::canonical;
use crate::strmatch::{SignatureError, SignatureScratch, SignatureSet};

/// The least the byte budget is, so a short record isn't cut for its size.
const BUDGET_FLOOR: usize = 64 * 1024;

/// What a branch may spend per level, in record lengths: a scan and a parse
/// of its body, a scan and a parse of its values, a copy of the values its
/// parser rewrote, and the keeping of two-byte values end to end.
const PASSES_PER_LEVEL: usize = 8;

/// Why a config did not compile into a plan.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum CompileError {
    /// The chain string isn't a chain.
    #[error(transparent)]
    Chain(#[from] ChainError),
    /// A named parser could not be resolved.
    #[error(transparent)]
    Resolve(#[from] ResolveError),
    /// The candidates' signatures did not build into a set.
    #[error(transparent)]
    Signature(#[from] SignatureError),
    /// Settings keyed by a parser the chain never runs.
    #[error("settings under {key:?} belong to no parser the chain names")]
    StraySettings {
        /// The settings key.
        key: String,
    },
    /// A chain with no hop.
    #[error("the chain is empty: name a format, or write auto")]
    EmptyChain,
    /// A format list with no names.
    #[error("hop {hop}: the format list is empty")]
    EmptyList {
        /// The hop, counted from 0.
        hop: usize,
    },
    /// A limit set to 0.
    #[error("{key} must be at least 1")]
    ZeroLimit {
        /// The config key.
        key: &'static str,
    },
    /// The first hop reads the record, so it takes no selector.
    #[error("the first hop reads the record: it takes neither field nor each")]
    FirstSelector,
    /// A hop with both selectors.
    #[error("hop {hop}: field and each are set together")]
    FieldAndEach {
        /// The hop, counted from 0.
        hop: usize,
    },
    /// An `each` hop with a fallback, which only a hop that has to parse uses.
    #[error("hop {hop}: each leaves alone a value nothing takes, so it has no fallback")]
    EachFallback {
        /// The hop, counted from 0.
        hop: usize,
    },
    /// A hop written after `auto*`, which already reads every level.
    #[error("hop {hop} follows auto*, which is the last hop of a chain")]
    AfterAutoStar {
        /// The hop, counted from 0.
        hop: usize,
    },
    /// The multi-line start pattern didn't build.
    #[error("the multi-line start pattern: {0}")]
    FramingStart(crate::strmatch::BuildError),
    /// More hops than `max_depth` allows.
    #[error("the chain has {hops} hops but max_depth is {max}")]
    TooManyHops {
        /// Hops written.
        hops: usize,
        /// The depth bound.
        max: usize,
    },
}

/// How a record's parse ended. When branches end differently, the record
/// takes the later of these.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Status {
    /// Everything the chain asked for was parsed.
    Parsed,
    /// A hop that had to parse its input didn't, and its fallback kept the
    /// record: left raw, or taken by the fallback parser.
    Fallback,
    /// `auto*` stopped at `max_depth` with a candidate's signature still firing.
    DepthLimit,
    /// A bound stopped the work: `max_invocations` or the byte budget. What
    /// was parsed before it is kept.
    Truncated,
    /// A hop that had to parse its input didn't, and its fallback rejects the
    /// record. Nothing is kept.
    Rejected,
}

impl Status {
    const fn rank(self) -> u8 {
        match self {
            Self::Parsed => 0,
            Self::Fallback => 1,
            Self::DepthLimit => 2,
            Self::Truncated => 3,
            Self::Rejected => 4,
        }
    }
}

/// The result of one record.
#[derive(Debug)]
#[non_exhaustive]
pub struct Outcome {
    /// How it ended.
    pub status: Status,
    /// Parsers that took an input and kept their fields. 0 after a reject.
    pub layers: usize,
    /// The input left unparsed where the status was set, when it is a range
    /// of the record.
    pub rest: Option<Range<usize>>,
    /// The parser error behind the status, when there was one. Errors from
    /// a choice a later one made good, or on a value nothing had to parse,
    /// are in the [`Trace`] alone.
    pub error: Option<ParseError>,
}

#[derive(Debug, Clone)]
enum Selector {
    Body,
    Field(String),
    Each,
}

#[derive(Debug, Clone)]
enum Choice {
    Named(Vec<usize>),
    Auto,
    AutoStar,
}

#[derive(Debug, Clone, Copy)]
enum Fallback {
    Raw,
    Reject,
    Parser(usize),
}

#[derive(Debug, Clone)]
struct Hop {
    selector: Selector,
    choice: Choice,
    prefix: Option<String>,
    fallback: Fallback,
}

/// Parsers chosen by signature: set index `i` is parser `ids[i]`.
#[derive(Debug, Clone)]
struct Candidates {
    ids: Vec<usize>,
    set: SignatureSet,
}

#[cfg(feature = "metrics")]
pub type Counter = metrics::Counter;

#[cfg(feature = "metrics")]
pub fn counter(name: &'static str, labels: &[(&'static str, String)]) -> Counter {
    let labels: Vec<metrics::Label> = labels
        .iter()
        .map(|(k, v)| metrics::Label::new(*k, v.clone()))
        .collect();
    metrics::counter!(name, labels)
}

#[cfg(not(feature = "metrics"))]
#[derive(Debug, Clone, Default)]
pub struct Counter;

#[cfg(not(feature = "metrics"))]
impl Counter {
    #[allow(clippy::unused_self, reason = "mirrors metrics::Counter::increment")]
    pub const fn increment(&self, _: u64) {}
}

#[cfg(not(feature = "metrics"))]
pub const fn counter(_: &'static str, _: &[(&'static str, String)]) -> Counter {
    Counter
}

/// Counter handles, registered at compile so a record pays no label lookup.
#[derive(Debug, Clone)]
struct Counters {
    /// `[depth - 1][parser]`.
    layer: Vec<Vec<Counter>>,
    detected: Vec<Counter>,
    error: Vec<Counter>,
    fallback: Counter,
    truncated: Counter,
}

impl Counters {
    fn new(parsers: &[Arc<dyn Parser>], max_depth: usize) -> Self {
        let per = |name: &'static str| -> Vec<Counter> {
            parsers
                .iter()
                .map(|p| counter(name, &[("format", p.name().to_owned())]))
                .collect()
        };
        let layer = (0..max_depth)
            .map(|depth| {
                parsers
                    .iter()
                    .map(|p| {
                        counter(
                            "parse_layer_total",
                            &[
                                ("depth", depth.to_string()),
                                ("format", p.name().to_owned()),
                            ],
                        )
                    })
                    .collect()
            })
            .collect();
        Self {
            layer,
            detected: per("parse_detected_total"),
            error: per("parse_error_total"),
            fallback: counter("parse_fallback_total", &[]),
            truncated: counter("parse_truncated_total", &[]),
        }
    }
}

/// A parser's own counters, held back for a [`Batch`].
///
/// [`Parser::parse_counted`] hands a parser one. What the parser adds here
/// reaches its counters when the batch publishes. Only a batch makes one,
/// so nothing a parser adds can be dropped unpublished.
#[derive(Debug)]
pub struct ParserCounts {
    /// By the parser's own slot number: the counter, and the adds it is owed.
    held: Vec<Option<(Counter, u64)>>,
}

impl ParserCounts {
    /// Owe `n` to the counter in `slot`, which is `counter` from its first use.
    #[cfg(all(feature = "parse-grok", feature = "metrics"))]
    pub(crate) fn add(&mut self, slot: usize, counter: &Counter, n: u64) {
        if self.held.len() <= slot {
            self.held.resize_with(slot + 1, || None);
        }
        match &mut self.held[slot] {
            Some((_, owed)) => *owed += n,
            empty => *empty = Some((counter.clone(), n)),
        }
    }

    /// Add what each counter is owed, and owe nothing.
    fn publish(&mut self) {
        for (counter, owed) in self.held.iter_mut().flatten() {
            if *owed > 0 {
                counter.increment(std::mem::take(owed));
            }
        }
    }
}

/// Counts a [`Batch`] holds back from the shared counters, in the shape of
/// [`Counters`].
#[derive(Debug)]
struct Counts {
    /// Each parser's own counts, by its place in the plan.
    parsers: Vec<ParserCounts>,
    layer: Vec<Vec<u64>>,
    detected: Vec<u64>,
    error: Vec<u64>,
    fallback: u64,
    truncated: u64,
}

/// One thing the driver counts.
#[derive(Debug, Clone, Copy)]
enum Count {
    /// A parser took a record or a value, at this depth from 1.
    Layer {
        depth: usize,
        id: usize,
    },
    Detected(usize),
    Error(usize),
    Fallback,
    Truncated,
}

/// Reused per-source scan buffers.
#[derive(Debug, Clone)]
struct Scan {
    scratch: SignatureScratch,
    ranked: Vec<(Reverse<crate::strmatch::Specificity>, Reverse<u8>, usize)>,
}

/// A source's reused buffers: its framing state and its scan scratch. Keep
/// one per connection, partition or other stream. It holds nothing that
/// changes how a record parses.
#[derive(Debug, Clone)]
pub struct SourceState {
    scan: Scan,
    frames: FrameState,
}

/// A source's parse config, compiled.
pub struct ParsePlan {
    parsers: Vec<Arc<dyn Parser>>,
    /// Per parser, whether its signature rejects a span more cheaply than
    /// the parser does.
    gated: Vec<bool>,
    dotted: Vec<String>,
    hops: Vec<Hop>,
    detect: Candidates,
    counters: Counters,
    max_depth: usize,
    max_invocations: usize,
    framing: FramingConfig,
    /// The multi-line start pattern, built once.
    start: Option<crate::strmatch::StrMatcher>,
}

impl std::fmt::Debug for ParsePlan {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ParsePlan")
            .field(
                "parsers",
                &self.parsers.iter().map(|p| p.name()).collect::<Vec<_>>(),
            )
            .field("hops", &self.hops)
            .finish_non_exhaustive()
    }
}

/// Builds the plan's parser table, one entry per distinct parser.
struct Builder<'r> {
    resolve: &'r dyn Resolve,
    plan_settings: &'r Settings,
    parsers: Vec<Arc<dyn Parser>>,
    /// Plan-level settings keys some hop used.
    used: Vec<&'r str>,
}

impl Builder<'_> {
    fn intern(&mut self, parser: Arc<dyn Parser>) -> usize {
        if let Some(id) = self.parsers.iter().position(|p| Arc::ptr_eq(p, &parser)) {
            return id;
        }
        self.parsers.push(parser);
        self.parsers.len() - 1
    }

    /// Resolve `name` with the hop's settings for it, else the plan's.
    fn named(&mut self, name: &str, hop: &HopConfig) -> Result<usize, CompileError> {
        let settings = hop.settings.get(name).or_else(|| {
            let (key, value) = self.plan_settings.get_key_value(name)?;
            self.used.push(key);
            Some(value)
        });
        if !super::valid_parser_name(name) {
            return Err(ResolveError::BadName(name.to_owned()).into());
        }
        let parser = self.resolve.resolve(name, settings)?;
        Ok(self.intern(parser))
    }

    fn hop(
        &mut self,
        at: usize,
        hop: &HopConfig,
        plan_fallback: &FallbackConfig,
    ) -> Result<Hop, CompileError> {
        let selector = match (&hop.field, hop.each) {
            (Some(_), true) => return Err(CompileError::FieldAndEach { hop: at }),
            (Some(_), false) | (None, true) if at == 0 => {
                return Err(CompileError::FirstSelector);
            }
            (Some(name), false) => Selector::Field(canonical(name).into_owned()),
            (None, true) if hop.fallback.is_some() => {
                return Err(CompileError::EachFallback { hop: at });
            }
            (None, true) => Selector::Each,
            (None, false) => Selector::Body,
        };
        let mut listed: Vec<&str> = Vec::new();
        let choice = match &hop.format {
            FormatChoice::Auto => Choice::Auto,
            FormatChoice::AutoStar => Choice::AutoStar,
            FormatChoice::Named(names) if names.is_empty() => {
                return Err(CompileError::EmptyList { hop: at });
            }
            FormatChoice::Named(names) => {
                listed.extend(names.iter().map(String::as_str));
                let ids: Result<Vec<usize>, CompileError> =
                    names.iter().map(|n| self.named(n, hop)).collect();
                Choice::Named(ids?)
            }
        };
        let fallback = match hop.fallback.as_ref().unwrap_or(plan_fallback) {
            FallbackConfig::Raw => Fallback::Raw,
            FallbackConfig::Reject => Fallback::Reject,
            FallbackConfig::Format(name) => {
                listed.push(name);
                Fallback::Parser(self.named(name, hop)?)
            }
        };
        if let Some(key) = hop.settings.keys().find(|k| !listed.contains(&k.as_str())) {
            return Err(CompileError::StraySettings { key: key.clone() });
        }
        Ok(Hop {
            selector,
            choice,
            prefix: hop.prefix.clone(),
            fallback,
        })
    }
}

/// Where a hop's input came from, for the trace.
#[derive(Debug, Clone, Copy)]
enum Origin<'n> {
    Record,
    Body { parent: usize },
    Value { parent: usize, name: &'n str },
}

/// Whether the hop has to parse its input or may leave it alone.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Need {
    Required,
    Optional,
}

/// A scope from [`ParsePlan::batch`]: it parses with the plan and holds the
/// counts until it ends.
#[derive(Debug)]
pub struct Batch<'p> {
    plan: &'p ParsePlan,
    counts: Counts,
}

impl Batch<'_> {
    /// [`ParsePlan::parse`], with the counts held by this batch.
    pub fn parse<'a>(
        &mut self,
        input: &'a [u8],
        state: &mut SourceState,
        out: &mut dyn FieldSink<'a>,
    ) -> Outcome {
        let counts = Some(&mut self.counts);
        self.plan.run(input, &mut state.scan, out, None, counts)
    }

    /// Add the counts held so far to the plan's counters, and start again
    /// from zero. Dropping the batch does the same.
    pub fn publish(&mut self) {
        let shared = &self.plan.counters;
        let add = |counter: &Counter, held: &mut u64| {
            if *held > 0 {
                counter.increment(std::mem::take(held));
            }
        };
        for (counters, held) in shared.layer.iter().zip(&mut self.counts.layer) {
            for (counter, held) in counters.iter().zip(held) {
                add(counter, held);
            }
        }
        for (counter, held) in shared.detected.iter().zip(&mut self.counts.detected) {
            add(counter, held);
        }
        for (counter, held) in shared.error.iter().zip(&mut self.counts.error) {
            add(counter, held);
        }
        add(&shared.fallback, &mut self.counts.fallback);
        add(&shared.truncated, &mut self.counts.truncated);
        for own in &mut self.counts.parsers {
            own.publish();
        }
    }
}

impl Drop for Batch<'_> {
    fn drop(&mut self) {
        self.publish();
    }
}

/// One arrival at a hop.
#[derive(Debug, Clone, Copy)]
struct At<'n> {
    hop: usize,
    /// Parsers on this branch, this one included.
    depth: usize,
    origin: Origin<'n>,
    need: Need,
}

/// One record's run.
struct Run<'r> {
    scan: &'r mut Scan,
    trace: Option<&'r mut Trace>,
    budget: &'r Budget,
    /// The record's address range, to turn a slice of it into offsets.
    record: Range<usize>,
    /// The sink's position when the record started.
    mark: SinkMark,
    /// Parser calls left.
    calls: usize,
    status: Status,
    layers: usize,
    rest: Option<Range<usize>>,
    error: Option<ParseError>,
    /// Set by a reject or a spent bound: nothing more is scheduled.
    stop: bool,
    /// Where counts go for the length of a batch. `None` adds at once.
    counts: Option<&'r mut Counts>,
}

impl Run<'_> {
    /// `input`'s range in the record, when it is a slice of it.
    fn span(&self, input: &[u8]) -> Option<Range<usize>> {
        let start = input.as_ptr().addr();
        let end = start + input.len();
        (self.record.start <= start && end <= self.record.end)
            .then(|| start - self.record.start..end - self.record.start)
    }

    /// Take `status` if it outranks the record's, with the failure behind it.
    fn raise(&mut self, status: Status, rest: Option<Range<usize>>, error: Option<ParseError>) {
        if status.rank() > self.status.rank() {
            self.status = status;
            self.rest = rest;
            self.error = error;
        }
    }

    fn step(&mut self, at: At<'_>, parser: Option<&str>, event: Event) -> usize {
        let Some(trace) = self.trace.as_deref_mut() else {
            return 0;
        };
        let (parent, input) = match at.origin {
            Origin::Record => (None, Input::Record),
            Origin::Body { parent } => (Some(parent), Input::Body),
            Origin::Value { parent, name } => (Some(parent), Input::Field(name.to_owned())),
        };
        trace.steps.push(Step {
            hop: at.hop,
            parent,
            input,
            parser: parser.map(str::to_owned),
            event,
            kept: matches!(event, Event::Parsed | Event::FallbackParsed),
        });
        trace.steps.len() - 1
    }

    /// A bound ran out on `input`: end the record there.
    fn truncate(&mut self, at: At<'_>, input: &[u8]) {
        let rest = self.span(input);
        self.raise(Status::Truncated, rest, None);
        self.step(at, None, Event::Truncated);
        self.stop = true;
    }
}

/// A parser that took its input.
struct Won<'i> {
    body: Option<&'i [u8]>,
    got: Vec<Captured<'i>>,
    /// Its step in the trace.
    step: usize,
}

enum Attempt<'i> {
    Won(Won<'i>),
    NoMatch,
    Error(ParseError),
    /// A bound ran out. The run is stopped.
    Stopped,
}

enum Tried<'i> {
    Won(Won<'i>),
    /// Nothing took the input. The first error, when a parser returned one.
    Missed(Option<ParseError>),
    Stopped,
}

impl ParsePlan {
    /// Compile `config`, resolving every parser it names through `resolve`.
    ///
    /// # Errors
    ///
    /// [`CompileError`] for a chain that can't run as written, a parser that
    /// won't resolve, or settings no parser takes.
    pub fn compile(config: &ParseConfig, resolve: &dyn Resolve) -> Result<Self, CompileError> {
        let mut limits = vec![
            ("max_depth", config.max_depth),
            ("max_invocations", config.max_invocations),
        ];
        // At 0, a framing bound would refuse or release every record alone.
        limits.extend(config.framing.limits());
        if let Some(&(key, _)) = limits.iter().find(|(_, value)| *value == 0) {
            return Err(CompileError::ZeroLimit { key });
        }
        let written = &config.chain.0;
        if written.is_empty() {
            return Err(CompileError::EmptyChain);
        }
        if written.len() > config.max_depth {
            return Err(CompileError::TooManyHops {
                hops: written.len(),
                max: config.max_depth,
            });
        }
        let mut b = Builder {
            resolve,
            plan_settings: &config.settings,
            parsers: Vec::new(),
            used: Vec::new(),
        };
        let mut hops: Vec<Hop> = Vec::with_capacity(written.len());
        for (at, hop) in written.iter().enumerate() {
            if matches!(hops.last().map(|h| &h.choice), Some(Choice::AutoStar)) {
                return Err(CompileError::AfterAutoStar { hop: at });
            }
            hops.push(b.hop(at, hop, &config.fallback)?);
        }
        if let Some(key) = config
            .settings
            .keys()
            .find(|k| !b.used.contains(&k.as_str()))
        {
            return Err(CompileError::StraySettings { key: key.clone() });
        }

        let detects = hops
            .iter()
            .any(|h| matches!(h.choice, Choice::Auto | Choice::AutoStar));
        let mut detect_ids = Vec::new();
        if detects {
            for p in resolve.candidates() {
                if p.detectable() && !p.signature().is_literal_free() {
                    detect_ids.push(b.intern(p));
                }
            }
        }
        let parsers = b.parsers;
        let set = SignatureSet::new(detect_ids.iter().map(|&id| parsers[id].signature()))?;
        let dotted = parsers.iter().map(|p| format!("{}.", p.name())).collect();
        let counters = Counters::new(&parsers, config.max_depth);
        let gated = parsers.iter().map(|p| gate_pays(p.as_ref())).collect();
        Ok(Self {
            parsers,
            gated,
            dotted,
            hops,
            detect: Candidates {
                ids: detect_ids,
                set,
            },
            counters,
            max_depth: config.max_depth,
            max_invocations: config.max_invocations,
            framing: config.framing.clone(),
            start: config.framing.start().map_err(CompileError::FramingStart)?,
        })
    }

    /// Compile a chain written as a string, such as `syslog > auto`, with
    /// every other key on its default.
    ///
    /// # Errors
    ///
    /// [`CompileError`], as [`Self::compile`].
    pub fn chain(text: &str, resolve: &dyn Resolve) -> Result<Self, CompileError> {
        Self::compile(&ParseConfig::chain(text)?, resolve)
    }

    /// Fresh buffers for one source.
    #[must_use]
    pub fn source_state(&self) -> SourceState {
        SourceState {
            scan: self.scan(),
            frames: FrameState::default(),
        }
    }

    fn scan(&self) -> Scan {
        Scan {
            scratch: self.detect.set.scratch(),
            ranked: Vec::new(),
        }
    }

    /// Split or join `input` into records by the plan's framing, appending
    /// each finished one to `out` for [`Self::parse`]. With no framing it's
    /// one record, borrowed.
    ///
    /// `now` is when the input arrived, which a joined record's wait for
    /// its next line counts from. The plan never reads a clock, so one read
    /// can serve a batch, and a test or a paused runtime clock sets the time.
    /// Pass times that never go back, here and to [`Self::flush`]: an earlier
    /// one reads as no time passed.
    ///
    /// # Errors
    ///
    /// [`ParseError::Malformed`] when the input doesn't fit the framing, and
    /// [`ParseError::FrameTooLong`] for a record over the framing's cap. A
    /// stream framing skips the bad record and frames the rest of the input,
    /// so `out` still gets the records after it.
    pub fn frame<'a>(
        &self,
        input: &'a [u8],
        state: &mut SourceState,
        now: Instant,
        out: &mut Vec<Frame<'a>>,
    ) -> Result<(), ParseError> {
        self.framing
            .frame(input, &mut state.frames, now, self.start.as_ref(), out)
    }

    /// Release a record the framing holds once it has waited its timeout
    /// for a next line at `now`. Call it on a timer.
    pub fn flush(&self, state: &mut SourceState, now: Instant, out: &mut Vec<Frame<'static>>) {
        self.framing.flush(&mut state.frames, Some(now), out);
    }

    /// Release any record the framing holds, at the end of a stream.
    pub fn finish(&self, state: &mut SourceState, out: &mut Vec<Frame<'static>>) {
        self.framing.flush(&mut state.frames, None, out);
    }

    /// Whether a hop detects its parser, so a parse scans with the buffers a
    /// [`SourceState`] keeps.
    #[must_use]
    pub fn detects(&self) -> bool {
        self.hops
            .iter()
            .any(|hop| !matches!(hop.choice, Choice::Named(_)))
    }

    /// Parse one record into `out`.
    pub fn parse<'a>(
        &self,
        input: &'a [u8],
        state: &mut SourceState,
        out: &mut dyn FieldSink<'a>,
    ) -> Outcome {
        self.run(input, &mut state.scan, out, None, None)
    }

    /// A scope that parses with this plan and adds to its counters once, at
    /// the scope's end, in place of once a record.
    ///
    /// Every thread that shares a plan adds to the same counters, so with a
    /// metrics recorder installed a record's adds move one cache line
    /// between cores. A batch keeps its counts to itself until it is dropped
    /// or [published](Batch::publish), so the counters are late by at most
    /// the batch.
    #[must_use]
    pub fn batch(&self) -> Batch<'_> {
        let per_parser = || vec![0_u64; self.parsers.len()];
        Batch {
            plan: self,
            counts: Counts {
                // With no recorder to add to there is nothing to hold.
                parsers: if cfg!(feature = "metrics") {
                    let empty = || ParserCounts { held: Vec::new() };
                    self.parsers.iter().map(|_| empty()).collect()
                } else {
                    Vec::new()
                },
                layer: (0..self.max_depth).map(|_| per_parser()).collect(),
                detected: per_parser(),
                error: per_parser(),
                fallback: 0,
                truncated: 0,
            },
        }
    }

    /// Add one to a counter: to the batch's count when there is one, else
    /// to the shared counter.
    fn count(&self, counts: Option<&mut Counts>, what: Count) {
        let Some(counts) = counts else {
            match what {
                Count::Layer { depth, id } => self.counters.layer[depth - 1][id].increment(1),
                Count::Detected(id) => self.counters.detected[id].increment(1),
                Count::Error(id) => self.counters.error[id].increment(1),
                Count::Fallback => self.counters.fallback.increment(1),
                Count::Truncated => self.counters.truncated.increment(1),
            }
            return;
        };
        match what {
            Count::Layer { depth, id } => counts.layer[depth - 1][id] += 1,
            Count::Detected(id) => counts.detected[id] += 1,
            Count::Error(id) => counts.error[id] += 1,
            Count::Fallback => counts.fallback += 1,
            Count::Truncated => counts.truncated += 1,
        }
    }

    /// Parse one record into `out` with no [`SourceState`], for a caller
    /// with no one place to keep it, such as a thread pool's closure.
    ///
    /// A chain that names every parser has no signatures to scan for, so its
    /// scan buffers are empty and this costs what [`Self::parse`] does. One
    /// that [detects](Self::detects) allocates them on every call: keep a
    /// state for it.
    pub fn parse_stateless<'a>(&self, input: &'a [u8], out: &mut dyn FieldSink<'a>) -> Outcome {
        self.run(input, &mut self.scan(), out, None, None)
    }

    /// Parse one record into `out` and write what each hop did to `trace`,
    /// replacing what it held.
    pub fn parse_traced<'a>(
        &self,
        input: &'a [u8],
        state: &mut SourceState,
        out: &mut dyn FieldSink<'a>,
        trace: &mut Trace,
    ) -> Outcome {
        trace.steps.clear();
        self.run(input, &mut state.scan, out, Some(trace), None)
    }

    fn run<'a>(
        &self,
        input: &'a [u8],
        scan: &mut Scan,
        out: &mut dyn FieldSink<'a>,
        trace: Option<&mut Trace>,
        counts: Option<&mut Counts>,
    ) -> Outcome {
        let passes = PASSES_PER_LEVEL.saturating_mul(self.max_depth);
        let budget = Budget::new(input.len().saturating_mul(passes).max(BUDGET_FLOOR));
        let start = input.as_ptr().addr();
        let mut cx = Run {
            scan,
            trace,
            budget: &budget,
            record: start..start + input.len(),
            mark: out.mark(),
            calls: self.max_invocations,
            status: Status::Parsed,
            layers: 0,
            rest: None,
            error: None,
            stop: false,
            counts,
        };
        let at = At {
            hop: 0,
            depth: 1,
            origin: Origin::Record,
            need: Need::Required,
        };
        self.hop(at, input, out, &mut cx);
        match cx.status {
            Status::Parsed | Status::DepthLimit => {}
            Status::Truncated => self.count(cx.counts.as_deref_mut(), Count::Truncated),
            Status::Fallback | Status::Rejected => {
                self.count(cx.counts.as_deref_mut(), Count::Fallback);
            }
        }
        Outcome {
            status: cx.status,
            layers: cx.layers,
            rest: cx.rest,
            error: cx.error,
        }
    }

    /// Run hop `at.hop` on `input`, then the rest of the chain on what its
    /// parser produced.
    fn hop<'i>(&self, at: At<'_>, input: &'i [u8], out: &mut dyn FieldSink<'i>, cx: &mut Run<'_>) {
        if cx.stop {
            return;
        }
        let won = match self.choose(at, input, out, cx) {
            Tried::Won(won) => won,
            Tried::Stopped => return,
            Tried::Missed(_) if at.need == Need::Optional => return,
            Tried::Missed(error) => {
                let Some(won) = self.fall_back(at, Some(input), error, out, cx) else {
                    return;
                };
                won
            }
        };
        self.below(at, won, out, cx);
    }

    /// Try the hop's parsers on `input`: its names in order, or the
    /// candidates whose signature fires, best first.
    fn choose<'i>(
        &self,
        at: At<'_>,
        input: &'i [u8],
        out: &mut dyn FieldSink<'i>,
        cx: &mut Run<'_>,
    ) -> Tried<'i> {
        let mut first_error = None;
        let mut next = 0;
        let named = match &self.hops[at.hop].choice {
            Choice::Named(ids) => Some(ids),
            Choice::Auto | Choice::AutoStar => {
                if !cx.budget.charge(input.len()) {
                    cx.truncate(at, input);
                    return Tried::Stopped;
                }
                self.rank(input, cx.scan);
                None
            }
        };
        loop {
            let id = if let Some(ids) = named {
                let Some(&id) = ids.get(next) else { break };
                if self.gated[id] {
                    if !cx.budget.charge(input.len()) {
                        cx.truncate(at, input);
                        return Tried::Stopped;
                    }
                    if !self.parsers[id].signature().may_match(input) {
                        next += 1;
                        continue;
                    }
                }
                id
            } else {
                let Some(&(_, _, i)) = cx.scan.ranked.get(next) else {
                    break;
                };
                self.detect.ids[i]
            };
            next += 1;
            match self.attempt(id, at, Event::Parsed, input, out, cx) {
                Attempt::Won(won) => {
                    if named.is_none() {
                        self.count(cx.counts.as_deref_mut(), Count::Detected(id));
                    }
                    return Tried::Won(won);
                }
                Attempt::NoMatch => {}
                Attempt::Error(e) => {
                    first_error.get_or_insert(e);
                }
                Attempt::Stopped => return Tried::Stopped,
            }
        }
        Tried::Missed(first_error)
    }

    /// Rank the candidates' signatures on `bytes` into `scan.ranked`.
    fn rank(&self, bytes: &[u8], scan: &mut Scan) {
        scan.ranked.clear();
        let Scan { scratch, ranked } = scan;
        self.detect.set.for_each_match(bytes, scratch, |m| {
            let sig = self.parsers[self.detect.ids[m.index]].signature();
            ranked.push((Reverse(sig.specificity()), Reverse(sig.priority()), m.index));
        });
        ranked.sort_unstable();
    }

    /// What the hop after `hop` reads of this hop's output.
    fn want(&self, hop: usize) -> Want<'_> {
        let detect = Some(&self.detect.set);
        if matches!(self.hops[hop].choice, Choice::AutoStar) {
            return Want::Values {
                body_too: false,
                detect,
            };
        }
        let Some(next) = self.hops.get(hop + 1) else {
            return Want::Nothing;
        };
        match &next.selector {
            Selector::Body => Want::Nothing,
            Selector::Field(name) => Want::Field(name),
            // A named parser may have no signature, so it sees every value.
            Selector::Each => Want::Values {
                body_too: true,
                detect: detect.filter(|_| !matches!(next.choice, Choice::Named(_))),
            },
        }
    }

    /// Run parser `id` on `input`. Anything but a win leaves the sink as it was.
    fn attempt<'i>(
        &self,
        id: usize,
        at: At<'_>,
        win: Event,
        input: &'i [u8],
        out: &mut dyn FieldSink<'i>,
        cx: &mut Run<'_>,
    ) -> Attempt<'i> {
        if cx.calls == 0 || !cx.budget.charge(input.len()) {
            cx.truncate(at, input);
            return Attempt::Stopped;
        }
        cx.calls -= 1;
        let parser = &self.parsers[id];
        let hop = &self.hops[at.hop];
        let prefix = match &hop.prefix {
            Some(p) => p.as_str(),
            None if at.depth == 1 => "",
            None => self.dotted[id].as_str(),
        };
        let mark = out.mark();
        out.push_prefix(prefix);
        let (budget, traced) = (cx.budget, cx.trace.is_some());
        // In a batch the parser's own counts are held with the driver's.
        let own = cx
            .counts
            .as_deref_mut()
            .and_then(|held| held.parsers.get_mut(id));
        let (result, got) = match self.want(at.hop) {
            Want::Nothing => (call(parser.as_ref(), input, out, own), Vec::new()),
            want => {
                let mut capture = Capture::new(&mut *out, want, budget, traced);
                let result = call(parser.as_ref(), input, &mut capture, own);
                (result, capture.into_values())
            }
        };
        out.pop_prefix();
        if cx.budget.is_spent() {
            out.rollback(mark);
            cx.truncate(at, input);
            return Attempt::Stopped;
        }
        let body = match result {
            Ok(Parsed::Done) => None,
            Ok(Parsed::Body { span, .. }) => {
                let Some(body) = input.get(span) else {
                    out.rollback(mark);
                    let error = ParseError::Malformed {
                        offset: 0,
                        reason: "a parser returned a body outside its input",
                    };
                    cx.step(at, Some(parser.name()), Event::Error(Failure::of(&error)));
                    return Attempt::Error(error);
                };
                Some(body)
            }
            Ok(Parsed::NoMatch) => {
                out.rollback(mark);
                return Attempt::NoMatch;
            }
            Err(error) => {
                out.rollback(mark);
                self.count(cx.counts.as_deref_mut(), Count::Error(id));
                cx.step(at, Some(parser.name()), Event::Error(Failure::of(&error)));
                return Attempt::Error(error);
            }
        };
        cx.layers += 1;
        let depth = at.depth;
        self.count(cx.counts.as_deref_mut(), Count::Layer { depth, id });
        let step = cx.step(at, Some(parser.name()), win);
        Attempt::Won(Won { body, got, step })
    }

    /// A hop that had to parse didn't: apply its fallback. `Some` when the
    /// fallback parser took `input`.
    fn fall_back<'i>(
        &self,
        at: At<'_>,
        input: Option<&'i [u8]>,
        error: Option<ParseError>,
        out: &mut dyn FieldSink<'i>,
        cx: &mut Run<'_>,
    ) -> Option<Won<'i>> {
        let rest = input.and_then(|i| cx.span(i));
        match (self.hops[at.hop].fallback, input) {
            (Fallback::Reject, _) => {
                out.rollback(cx.mark);
                cx.raise(Status::Rejected, rest, error);
                cx.layers = 0;
                cx.stop = true;
                if let Some(trace) = cx.trace.as_deref_mut() {
                    trace.steps.iter_mut().for_each(|step| step.kept = false);
                }
                cx.step(at, None, Event::Rejected);
                None
            }
            (Fallback::Parser(id), Some(input)) => {
                match self.attempt(id, at, Event::FallbackParsed, input, out, cx) {
                    Attempt::Won(won) => {
                        cx.raise(Status::Fallback, None, error);
                        Some(won)
                    }
                    Attempt::Stopped => None,
                    Attempt::NoMatch | Attempt::Error(_) => {
                        cx.raise(Status::Fallback, rest, error);
                        cx.step(at, None, Event::Unparsed);
                        None
                    }
                }
            }
            (Fallback::Raw | Fallback::Parser(_), _) => {
                cx.raise(Status::Fallback, rest, error);
                cx.step(at, None, Event::Unparsed);
                None
            }
        }
    }

    /// Run what follows hop `at.hop` on what its parser produced.
    fn below<'i>(&self, at: At<'_>, won: Won<'i>, out: &mut dyn FieldSink<'i>, cx: &mut Run<'_>) {
        let parent = won.step;
        let depth = at.depth + 1;
        let body = Origin::Body { parent };
        if matches!(self.hops[at.hop].choice, Choice::AutoStar) {
            let down = At {
                hop: at.hop,
                depth,
                origin: body,
                need: Need::Optional,
            };
            if at.depth == self.max_depth {
                self.at_the_limit(down, parent, &won, cx);
            } else {
                if let Some(input) = won.body {
                    self.hop(down, input, out, cx);
                }
                for value in won.got {
                    self.value(down, parent, value, out, cx);
                }
            }
        } else if let Some(next) = self.hops.get(at.hop + 1) {
            let mut down = At {
                hop: at.hop + 1,
                depth,
                origin: body,
                need: Need::Required,
            };
            match &next.selector {
                Selector::Body => match won.body {
                    Some(input) => self.hop(down, input, out, cx),
                    None => self.missing(down, Event::NoBody, out, cx),
                },
                Selector::Field(name) => {
                    if let Some(value) = won.got.into_iter().next() {
                        self.value(down, parent, value, out, cx);
                    } else {
                        down.origin = Origin::Value { parent, name };
                        self.missing(down, Event::NoField, out, cx);
                    }
                }
                Selector::Each => {
                    down.need = Need::Optional;
                    for value in won.got {
                        self.value(down, parent, value, out, cx);
                    }
                }
            }
        }
    }

    /// Run a hop on a value its parent wrote. A value borrowed from the
    /// record goes on as it is. One the parent had to rewrite is parsed inside
    /// its own lifetime, and what its subtree writes is copied out.
    fn value<'i>(
        &self,
        at: At<'_>,
        parent: usize,
        value: Captured<'i>,
        out: &mut dyn FieldSink<'i>,
        cx: &mut Run<'_>,
    ) {
        let at = At {
            origin: Origin::Value {
                parent,
                name: value.name.as_deref().unwrap_or_default(),
            },
            ..at
        };
        match value.value.bytes {
            Cow::Borrowed(bytes) => self.hop(at, bytes, out, cx),
            Cow::Owned(bytes) => {
                self.hop(at, &bytes, &mut Promote::new(out, cx.budget), cx);
            }
        }
    }

    /// A hop that had to run has no input: its parent handed on no body, or
    /// wrote no such field.
    fn missing(&self, at: At<'_>, event: Event, out: &mut dyn FieldSink<'_>, cx: &mut Run<'_>) {
        if cx.stop {
            return;
        }
        cx.step(at, None, event);
        self.fall_back(at, None, None, out, cx);
    }

    /// `auto*` reached `max_depth`: say so when the body or a value would
    /// still be detected.
    fn at_the_limit(&self, at: At<'_>, parent: usize, won: &Won<'_>, cx: &mut Run<'_>) {
        let body = won.body.map(|input| (at.origin, input));
        let values = won.got.iter().map(|c| {
            let name = c.name.as_deref().unwrap_or_default();
            (Origin::Value { parent, name }, &*c.value.bytes)
        });
        for (origin, input) in body.into_iter().chain(values) {
            let at = At { origin, ..at };
            if cx.stop {
                return;
            }
            if !cx.budget.charge(input.len()) {
                cx.truncate(at, input);
                return;
            }
            self.rank(input, cx.scan);
            if !cx.scan.ranked.is_empty() {
                let rest = cx.span(input);
                cx.raise(Status::DepthLimit, rest, None);
                cx.step(at, None, Event::DepthLimit);
                return;
            }
        }
    }
}

/// One parse, with the parser's own counts held where a batch gave a place.
fn call<'a>(
    parser: &dyn Parser,
    input: &'a [u8],
    out: &mut dyn FieldSink<'a>,
    own: Option<&mut ParserCounts>,
) -> Result<Parsed, ParseError> {
    match own {
        Some(counts) => parser.parse_counted(input, out, counts),
        None => parser.parse(input, out),
    }
}

/// The signature runs ahead of `parser` unless both are priced and the
/// parser's own miss is cheaper, as a grok parser's DFA is.
pub fn gate_pays(parser: &dyn Parser) -> bool {
    match (parser.cost(), parser.signature().cost()) {
        (Some(p), Some(s)) => {
            s.miss.ns(crate::cost::REFERENCE_BYTES) < p.miss.ns(crate::cost::REFERENCE_BYTES)
        }
        _ => true,
    }
}