grippo 0.1.0

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
// Project:   grippo
// File:      src/strmatch/mod.rs
// Purpose:   Public API for the strmatch regex->fast-path matcher
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Regex-shaped patterns, fast-path dispatch.
//!
//! Operators write a regex (the most familiar pattern language).
//! `strmatch` classifies it into a tier and dispatches at
//! match time via the cheapest engine that's correct:
//!
//! - **Byte** (<= 30 ns) -- direct byte ops: `memchr` / `memchr2` /
//!   `memchr3` / single-byte `starts_with` / `ends_with` / `==`.
//! - **Literal** (<= 200 ns) -- single multi-byte literal:
//!   `memmem::Finder` / multi-byte `starts_with` / `ends_with` / `==`.
//! - **`LiteralSet`** (<= 500 ns) -- `aho-corasick` over >= 2 literals
//!   (optional uniform anchor checked after the AC scan). Regex engine
//!   is never invoked.
//! - **Regex** (engine-bounded) -- fall through to
//!   `regex-automata::meta::Regex`. Has its own internal prefilter
//!   pipeline. Cost depends on pattern and haystack.
//! - **Backtracking** (exponential) -- lookaround and backreferences on
//!   fancy-regex, with the `strmatch-backtracking` feature and
//!   `StrMatcherBuilder::backtracking`.
//!
//! Captures, replace and split run on the same tier: see
//! [`StrMatcher::captures`], [`StrMatcher::replace_all`] and
//! [`StrMatcher::split`].
//!
//! Budgets are typical for a modern x86 server on a ~200-byte
//! haystack. See [`MatcherTier::typical_budget_ns`] and
//! `benches/strmatch.rs`.
//!
//! ## Anti-spam discipline
//!
//! When a pattern compiles to [`MatcherTier::Regex`] (the engine
//! fall-back), `strmatch` emits **one** WARN per distinct pattern per
//! process, capped at 10 distinct WARNs total. After the cap, further
//! fall-through patterns log at DEBUG. A counter
//! `strmatch_regex_fallback_total` increments on every
//! fall-through regardless of log level -- operators can scrape that
//! rather than rely on logs.
//!
//! ## Quality gates
//!
//! Use [`StrMatcher::builder`] with [`StrMatcherBuilder::min_tier`] to
//! reject (or loudly warn about) patterns that fall below an
//! operator-chosen tier. Useful for hot-path configs where regex
//! fall-through is unacceptable.
//!
//! ## Example
//!
//! ```
//! use grippo::strmatch::{MatcherTier, OnBelowMin, StrMatcher};
//!
//! // Byte tier -- anchored single byte, dispatches to hay.first() == Some(b)
//! let m = StrMatcher::new(r"^/")?;
//! assert_eq!(m.tier(), MatcherTier::Byte);
//! assert!(m.is_match(b"/api/v1/orders"));
//!
//! // Literal tier -- multi-byte literal, dispatches to memmem
//! let m = StrMatcher::new(r"AKIA")?;
//! assert_eq!(m.tier(), MatcherTier::Literal);
//! assert!(m.is_match(b"... AKIA1234 ..."));
//!
//! // LiteralSet tier -- alternation, dispatches to AhoCorasick
//! let m = StrMatcher::new(r"AKIA|ghp_|sk_live_")?;
//! assert_eq!(m.tier(), MatcherTier::LiteralSet);
//! assert!(m.is_match(b"github token: ghp_abcdef"));
//!
//! // Regex tier -- falls through to engine; refuse the build instead
//! let err = StrMatcher::builder()
//!     .min_tier(MatcherTier::LiteralSet)
//!     .on_below_min(OnBelowMin::Reject)
//!     .build(r"\w+@\w+")
//!     .unwrap_err();
//! assert!(err.to_string().contains("tier"));
//! # Ok::<(), grippo::strmatch::BuildError>(())
//! ```

mod classify;
mod dialect;
#[cfg(feature = "glob")]
mod glob;
mod ops;
mod plan;
mod signature;

use std::collections::HashSet;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{LazyLock, Mutex};

use thiserror::Error;

use classify::{Classified, Groups, Options};
use plan::Plan;

pub use crate::tier::MatcherTier;
#[cfg(feature = "glob")]
pub use glob::{GlobBuilder, GlobMatcher};
pub use ops::{Captures, ReplaceSyntax, Replacement};
pub use signature::{
    MAX_ALL_OF, MAX_VERIFY, Signature, SignatureBuilder, SignatureError, SignatureMatch,
    SignatureScratch, SignatureSet, Specificity, Verify,
};

// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------

/// Byte offsets of a match. End is exclusive: `&hay[start..end]` is the
/// matched slice.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Match {
    /// First byte of the match.
    pub start: usize,
    /// One past the last byte of the match.
    pub end: usize,
}

/// Like [`Match`] but also identifies which input pattern matched in a
/// [`StrMatcherSet`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct SetMatch {
    /// First byte of the match.
    pub start: usize,
    /// One past the last byte of the match.
    pub end: usize,
    /// Position of the matching pattern in the set's input order.
    pub pattern_idx: usize,
}

/// Failure modes during construction.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum BuildError {
    /// The pattern is empty.
    #[error(
        "strmatch: empty pattern\n  \
         hint: an empty pattern matches every position; pass a non-empty \
         literal or wrap the matcher in Option for an absent-matcher slot"
    )]
    Empty,

    /// The regex parser rejected the pattern.
    #[error(
        "strmatch: regex syntax error in pattern {pattern:?}\n  \
         reason: {source}\n  \
         hint: {hint}"
    )]
    Syntax {
        /// The pattern as given.
        pattern: String,
        /// The parser's error.
        #[source]
        source: Box<regex_syntax::Error>,
        /// What to change.
        hint: &'static str,
    },

    /// The pattern parsed, but the regex engine refused to compile it, most
    /// often because it is over the engine's size limit.
    #[error(
        "strmatch: pattern {pattern:?} does not compile\n  \
         reason: {source}\n  \
         hint: {hint}"
    )]
    Compile {
        /// The pattern as given.
        pattern: String,
        /// The engine's error.
        #[source]
        source: Box<regex_automata::meta::BuildError>,
        /// What to change.
        hint: &'static str,
    },

    /// The pattern can't be read in the dialect the builder asked for.
    #[error(
        "strmatch: pattern {pattern:?} can't be read in the dialect the builder asked for\n  \
         hint: {hint}"
    )]
    Dialect {
        /// The pattern as given.
        pattern: String,
        /// What to change.
        hint: &'static str,
    },

    /// The capture group table doesn't build, most often because the pattern
    /// has too many groups.
    #[error(
        "strmatch: the capture groups of {pattern:?} don't build\n  \
         reason: {source}\n  \
         hint: {hint}"
    )]
    Groups {
        /// The pattern as given.
        pattern: String,
        /// The group table's error.
        #[source]
        source: Box<regex_automata::util::captures::GroupInfoError>,
        /// What to change.
        hint: &'static str,
    },

    /// The literal automaton refused the literal set, most often because it is
    /// over the automaton's size limit.
    #[error(
        "strmatch: the literal automaton does not build\n  \
         reason: {source}\n  \
         hint: {hint}"
    )]
    Automaton {
        /// The automaton's error.
        #[source]
        source: Box<aho_corasick::BuildError>,
        /// What to change.
        hint: &'static str,
    },

    /// The glob does not parse.
    #[cfg(feature = "glob")]
    #[error(
        "strmatch: glob {pattern:?} does not parse\n  \
         reason: {source}\n  \
         hint: {hint}"
    )]
    Glob {
        /// The glob as given.
        pattern: String,
        /// The glob parser's error.
        #[source]
        source: Box<globset::Error>,
        /// What to change.
        hint: &'static str,
    },

    /// A glob read with glob 0.3's options doesn't parse, or asks for
    /// options that don't combine.
    #[cfg(feature = "glob")]
    #[error("strmatch: glob {pattern:?} does not parse at byte {at}\n  hint: {hint}")]
    GlobSyntax {
        /// The glob as given.
        pattern: String,
        /// The byte offset where reading stopped.
        at: usize,
        /// What to change.
        hint: &'static str,
    },

    /// The pattern compiled to a tier below the builder's minimum.
    #[error(
        "strmatch: pattern {pattern:?} compiles to tier {got}, but builder \
         requires at least {wanted}\n  \
         reason: {reason}\n  \
         hint: {hint}"
    )]
    TierTooLow {
        /// The pattern as given.
        pattern: String,
        /// The builder's minimum.
        wanted: MatcherTier,
        /// The tier the pattern compiled to.
        got: MatcherTier,
        /// Machine-readable name of the feature that set the tier.
        reason: &'static str,
        /// What to change.
        hint: &'static str,
    },
}

/// What to do when a pattern's classification falls below the
/// builder's `min_tier`.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OnBelowMin {
    /// Default -- proceed quietly. The anti-spam protocol still emits
    /// up to ten WARNs per process for fall-through patterns.
    #[default]
    Allow,
    /// Proceed, but force an immediate WARN that bypasses the anti-spam
    /// cap. Use when the caller explicitly wants every fall-through
    /// logged regardless of process-wide dedup state.
    Warn,
    /// Refuse to build. Returns [`BuildError::TierTooLow`].
    Reject,
}

// ---------------------------------------------------------------------------
// StrMatcher
// ---------------------------------------------------------------------------

/// Compiled pattern with tier-aware dispatch.
pub struct StrMatcher {
    plan: Plan,
    groups: Groups,
    tier: MatcherTier,
    pattern: String,
    /// Short machine-readable reason (e.g. `"shape:starts-with"`,
    /// `"literal-only:alternation"`, `"unbounded-quantifier"`).
    reason: &'static str,
    /// What to change to reach a faster tier. Empty on the fast tiers.
    hint: &'static str,
    /// Iterate with Java's rule for empty matches.
    java_empty: bool,
}

impl std::fmt::Debug for StrMatcher {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StrMatcher")
            .field("tier", &self.tier)
            .field("pattern", &self.pattern)
            .field("reason", &self.reason)
            .finish_non_exhaustive()
    }
}

impl StrMatcher {
    /// Compile `pattern` with default options (no minimum tier, no
    /// case-insensitivity).
    ///
    /// # Errors
    ///
    /// Returns `Err` if the pattern is empty or fails to parse. See
    /// [`BuildError`] for the structured variants.
    pub fn new(pattern: &str) -> Result<Self, BuildError> {
        Self::builder().build(pattern)
    }

    /// Start a builder.
    #[must_use]
    pub fn builder() -> StrMatcherBuilder {
        StrMatcherBuilder::new()
    }

    /// `true` if the haystack contains a match.
    #[inline]
    #[must_use]
    pub fn is_match(&self, hay: &[u8]) -> bool {
        self.plan.is_match(hay)
    }

    /// Find the first match, returning byte offsets.
    #[inline]
    #[must_use]
    pub fn find(&self, hay: &[u8]) -> Option<Match> {
        self.plan.find(hay)
    }

    /// Collect every non-overlapping match in iteration order.
    ///
    /// Eager: one allocation per call (lifetime/vtable reasons). Amortises
    /// well over scrubber workloads (0-3 matches per haystack). Anchored
    /// shapes (`StartsWith`/`EndsWith`/`ExactMatch`) yield at most one
    /// match.
    #[must_use]
    pub fn find_iter(&self, hay: &[u8]) -> std::vec::IntoIter<Match> {
        let mut out: Vec<Match> = Vec::new();
        if !self.each_match(hay, |m| {
            out.push(m);
            true
        }) {
            out.clear();
        }
        out.into_iter()
    }

    /// Call `f` on every non-overlapping match in order until it returns
    /// `false`, by the iteration rule the builder chose. Returns `false` when
    /// the backtracking tier passed its limit.
    fn each_match(&self, hay: &[u8], f: impl FnMut(Match) -> bool) -> bool {
        if self.java_empty {
            self.plan.for_each_match_java(hay, f)
        } else {
            self.plan.for_each_match(hay, f)
        }
    }

    /// The tier this matcher dispatches to. Useful for telemetry and
    /// assertions in tests.
    #[must_use]
    pub const fn tier(&self) -> MatcherTier {
        self.tier
    }

    /// What a match costs on the reference host: the measured row of the
    /// engine its tier runs. `None` for a tier with no row.
    #[must_use]
    pub fn cost(&self) -> Option<crate::cost::Cost> {
        let engine = match self.tier {
            MatcherTier::Byte => "memchr",
            MatcherTier::Literal => "memmem",
            MatcherTier::LiteralSet => "aho_corasick",
            MatcherTier::Regex => "lazy_dfa_find",
            _ => return None,
        };
        crate::cost::of(engine)
    }

    /// The original pattern string passed to [`Self::new`] (or the
    /// builder).
    #[must_use]
    pub fn pattern(&self) -> &str {
        &self.pattern
    }

    /// Short machine-readable reason for the tier choice. For the
    /// fast-path tiers this is a "success" reason (e.g.
    /// `"shape:starts-with"`). For Regex fall-through it names the
    /// disqualifying feature (`"unbounded-quantifier"`,
    /// `"word-boundary"`, ...).
    #[must_use]
    pub const fn reason(&self) -> &'static str {
        self.reason
    }

    /// What to change to reach a faster tier, empty when there is nothing to
    /// change.
    #[must_use]
    pub const fn hint(&self) -> &'static str {
        self.hint
    }
}

// ---------------------------------------------------------------------------
// StrMatcherBuilder
// ---------------------------------------------------------------------------

/// Builder for [`StrMatcher`]. Carries minimum-tier policy and the
/// case-insensitivity flag.
#[derive(Debug, Clone, Default)]
#[allow(
    clippy::struct_excessive_bools,
    reason = "independent switches, each set by its own method"
)]
pub struct StrMatcherBuilder {
    min_tier: Option<MatcherTier>,
    on_below_min: OnBelowMin,
    ascii_case_insensitive: bool,
    ascii_classes: bool,
    java_line_end: bool,
    java_dot: bool,
    java_empty_matches: bool,
    #[cfg(feature = "strmatch-backtracking")]
    backtracking: bool,
}

impl StrMatcherBuilder {
    /// Create a builder with default options (no minimum tier, no
    /// case-insensitivity).
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Reject (or warn about) patterns that classify below this tier.
    ///
    /// Tier ordering (highest -> lowest): `Byte > Literal > LiteralSet >
    /// Regex`. Setting `min_tier(LiteralSet)` allows Byte/Literal/
    /// `LiteralSet` but triggers `on_below_min` for Regex.
    #[must_use]
    pub const fn min_tier(mut self, tier: MatcherTier) -> Self {
        self.min_tier = Some(tier);
        self
    }

    /// What to do when a pattern falls below `min_tier`.
    #[must_use]
    pub const fn on_below_min(mut self, policy: OnBelowMin) -> Self {
        self.on_below_min = policy;
        self
    }

    /// Build a case-insensitive matcher that folds ASCII letters only.
    ///
    /// The literal tiers honour the flag via
    /// `aho_corasick::AhoCorasickBuilder::ascii_case_insensitive`, and
    /// shape-tier dispatch downgrades to the literal tier when this flag is
    /// set, since `memchr` does not fold case. The regex tier and the capture
    /// engine run on the pattern with each ASCII letter folded, so every tier
    /// gives the same answer. The backtracking tier folds Unicode.
    #[must_use]
    pub const fn ascii_case_insensitive(mut self, enabled: bool) -> Self {
        self.ascii_case_insensitive = enabled;
        self
    }

    /// Read `\d`, `\w` and `\s` (and `\D`, `\W`, `\S`) as their ASCII sets,
    /// `[0-9]`, `[0-9A-Za-z_]` and `[\t\n\x0B\x0C\r ]`, as Java's regex does
    /// by default. `\b` stays Unicode. A pattern that turns on verbose mode
    /// fails with [`BuildError::Dialect`].
    #[must_use]
    pub const fn ascii_classes(mut self, enabled: bool) -> Self {
        self.ascii_classes = enabled;
        self
    }

    /// Read `$` as Java's regex does without the MULTILINE flag: the end of
    /// the haystack, or just before a line terminator that ends it, `\n`,
    /// `\r\n`, `\r`, U+0085, U+2028 or U+2029. `\d+$` finds `12` in `12\n`.
    /// Off by default, when `$` is the end only. `\z` stays the end.
    ///
    /// A pattern with no `$` builds as it would without the option. One with
    /// a `$` runs its own tier on a haystack that ends in no terminator. On
    /// one that does, a literal pattern checks both places `$` holds, and any
    /// other runs a rewritten regex with its capture engine. A `$` followed
    /// by more pattern that can match text or test a position, `a$\b` say,
    /// or a multi-line `$`, fails with [`BuildError::Dialect`]. With
    /// `backtracking` on, the first runs on that tier.
    #[must_use]
    pub const fn java_line_end(mut self, enabled: bool) -> Self {
        self.java_line_end = enabled;
        self
    }

    /// Read `.` as Java's regex does without the DOTALL flag: any character
    /// but a line terminator, `\n`, `\r`, U+0085, U+2028 or U+2029. `a.b`
    /// misses `a\rb`. Off by default, when `.` leaves out `\n` only. With the
    /// s flag on, `(?s)` or `(?s:...)`, `.` matches anything as before, and a
    /// byte-level `.` under `(?-u)` leaves out `\n` and `\r`. A pattern with
    /// no `.` builds as it would without the option.
    #[must_use]
    pub const fn java_dot(mut self, enabled: bool) -> Self {
        self.java_dot = enabled;
        self
    }

    /// Iterate as Java's `Matcher.find` does: a match may be empty where the
    /// last one ended, and the search after an empty match resumes one
    /// character on. Replacing `.*` with `X` in `ab\n` gives `XX\nX`, where
    /// the regex crate's rule, the default, skips that empty match and gives
    /// `X\nX`. It holds for `find_iter`, `captures_iter`, `replace`,
    /// `replacen`, `replace_all`, `split` and `splitn`, and changes nothing
    /// for a pattern that can't match empty. `split` still gives every piece
    /// between the matches, where Java's drops some empty ones.
    #[must_use]
    pub const fn java_empty_matches(mut self, enabled: bool) -> Self {
        self.java_empty_matches = enabled;
        self
    }

    /// Build a pattern the linear engines refuse, lookaround or a
    /// backreference, on fancy-regex at [`MatcherTier::Backtracking`]. Off by
    /// default, when such a pattern fails with [`BuildError::Syntax`]. A
    /// search that passes fancy-regex's backtracking limit counts as no match.
    #[cfg(feature = "strmatch-backtracking")]
    #[must_use]
    pub const fn backtracking(mut self, enabled: bool) -> Self {
        self.backtracking = enabled;
        self
    }

    /// Build the matcher.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the pattern fails to parse or violates the
    /// `min_tier` policy with `on_below_min = Reject`.
    pub fn build(&self, pattern: &str) -> Result<StrMatcher, BuildError> {
        let opts = Options {
            case_insensitive: self.ascii_case_insensitive,
            ascii_classes: self.ascii_classes,
            java_line_end: self.java_line_end,
            java_dot: self.java_dot,
            java_empty_matches: self.java_empty_matches,
            #[cfg(feature = "strmatch-backtracking")]
            backtracking: self.backtracking,
        };
        let classified = classify::classify(pattern, opts)?;
        let tier = classified.descriptor.tier;

        if let Some(min) = self.min_tier
            && tier.rank() < min.rank()
        {
            return self.apply_below_min(pattern, min, classified);
        }

        if is_fallback(tier) {
            warn::on_regex_fallback(
                pattern,
                classified.descriptor.reason,
                classified.descriptor.hint,
                /*force=*/ false,
            );
            metrics_inc_fallback();
        }
        Ok(StrMatcher::from_classified(pattern, classified))
    }

    fn apply_below_min(
        &self,
        pattern: &str,
        wanted: MatcherTier,
        classified: Classified,
    ) -> Result<StrMatcher, BuildError> {
        let got = classified.descriptor.tier;
        let reason = classified.descriptor.reason;
        let hint = classified.descriptor.hint;

        match self.on_below_min {
            OnBelowMin::Reject => Err(BuildError::TierTooLow {
                pattern: pattern.to_string(),
                wanted,
                got,
                reason,
                hint,
            }),
            OnBelowMin::Warn => {
                warn::on_regex_fallback(pattern, reason, hint, /*force=*/ true);
                metrics_inc_fallback();
                Ok(StrMatcher::from_classified(pattern, classified))
            }
            OnBelowMin::Allow => {
                if is_fallback(got) {
                    warn::on_regex_fallback(pattern, reason, hint, /*force=*/ false);
                    metrics_inc_fallback();
                }
                Ok(StrMatcher::from_classified(pattern, classified))
            }
        }
    }
}

/// A tier that runs a regex engine, which the WARN and the counter report.
const fn is_fallback(tier: MatcherTier) -> bool {
    matches!(tier, MatcherTier::Regex | MatcherTier::Backtracking)
}

impl StrMatcher {
    fn from_classified(pattern: &str, classified: Classified) -> Self {
        Self {
            plan: classified.plan,
            groups: classified.groups,
            tier: classified.descriptor.tier,
            pattern: pattern.to_string(),
            reason: classified.descriptor.reason,
            hint: classified.descriptor.hint,
            java_empty: classified.java_empty,
        }
    }
}

// ---------------------------------------------------------------------------
// StrMatcherSet -- multi-pattern, single AC scan where possible
// ---------------------------------------------------------------------------

/// Multi-pattern matcher.
///
/// Build-time partition:
///
/// - Unanchored `Byte` / `Literal` / `LiteralSet` patterns fold into
///   one shared aho-corasick. One linear scan covers them all --
///   `O(M + total_matches)`.
/// - Anchored patterns (`^foo`, `bar$`, `^baz$`) and `Regex` fall-
///   throughs stay as per-pattern matchers.
///
/// The merged AC runs `MatchKind::LeftmostLongest` -- overlapping
/// literals like `AKIA` vs `AKIA1234` resolve to the longer match.
/// Pattern indices survive the merge: `SetMatch.pattern_idx`
/// always matches the caller's input order.
pub struct StrMatcherSet {
    merged: Option<MergedAc>,
    /// Anchored / regex-tier patterns, paired with input index.
    individual: Vec<(usize, StrMatcher)>,
    /// Tier per input pattern, in input order. Used for `tier_counts`.
    tiers: Vec<MatcherTier>,
}

/// Cross-pattern AC. `pattern_indices[ac_id]` maps an AC pattern ID
/// back to the caller's input index -- one input pattern can
/// contribute multiple literals (alternation, byte-set), so indices
/// repeat.
struct MergedAc {
    ac: aho_corasick::AhoCorasick,
    pattern_indices: Vec<usize>,
}

impl StrMatcherSet {
    /// Compile every pattern. Patterns that violate the builder's
    /// `min_tier` policy with `OnBelowMin::Reject` fail the build for
    /// the entire set -- returning the first failing pattern's error.
    ///
    /// # Errors
    ///
    /// As [`StrMatcherBuilder::build`].
    pub fn new<I, S>(patterns: I) -> Result<Self, BuildError>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        Self::builder().build_set(patterns)
    }

    /// Start a builder.
    #[must_use]
    pub fn builder() -> StrMatcherBuilder {
        StrMatcherBuilder::new()
    }

    /// `true` if any pattern matches anywhere in the haystack.
    #[must_use]
    pub fn is_match(&self, hay: &[u8]) -> bool {
        if let Some(m) = &self.merged
            && m.ac.find(hay).is_some()
        {
            return true;
        }
        self.individual.iter().any(|(_, m)| m.is_match(hay))
    }

    /// Find the earliest match across all patterns.
    ///
    /// Order:
    /// - Lower `start` wins.
    /// - At the same `start`, the merged AC applies
    ///   `MatchKind::LeftmostLongest` *within* its literal set, so
    ///   the longer literal wins among merged patterns (e.g.
    ///   `AKIA1234` over `AKIA`).
    /// - Across the merge boundary (merged-AC hit vs an individual
    ///   anchored / regex matcher at the same `start`), the
    ///   lower `pattern_idx` wins -- input-order preserved.
    #[must_use]
    pub fn earliest_match(&self, hay: &[u8]) -> Option<SetMatch> {
        let mut best: Option<SetMatch> = self.merged.as_ref().and_then(|m| {
            m.ac.find(hay).map(|hit| SetMatch {
                start: hit.start(),
                end: hit.end(),
                pattern_idx: m.pattern_indices[hit.pattern().as_usize()],
            })
        });
        for (idx, matcher) in &self.individual {
            if let Some(found) = matcher.find(hay) {
                let cand = SetMatch {
                    start: found.start,
                    end: found.end,
                    pattern_idx: *idx,
                };
                best = match best {
                    None => Some(cand),
                    Some(b) if cand.start < b.start => Some(cand),
                    Some(b) if cand.start == b.start && cand.pattern_idx < b.pattern_idx => {
                        Some(cand)
                    }
                    Some(b) => Some(b),
                };
            }
        }
        best
    }

    /// Collect every non-overlapping match across all patterns,
    /// sorted by `(start, pattern_idx)`.
    ///
    /// The merged AC runs `MatchKind::LeftmostLongest` internally,
    /// so when two literals overlap within the merged set, the
    /// longer one wins. Across the merge boundary the sort key
    /// gives input-order tie-breaking.
    ///
    /// When multiple patterns match at the same position, the
    /// lower-indexed pattern wins (consistent with the input order).
    /// Matches across different patterns may overlap.
    #[must_use]
    pub fn find_iter(&self, hay: &[u8]) -> std::vec::IntoIter<SetMatch> {
        let mut all: Vec<SetMatch> = Vec::new();
        if let Some(m) = &self.merged {
            for hit in m.ac.find_iter(hay) {
                all.push(SetMatch {
                    start: hit.start(),
                    end: hit.end(),
                    pattern_idx: m.pattern_indices[hit.pattern().as_usize()],
                });
            }
        }
        for (idx, matcher) in &self.individual {
            for hit in matcher.find_iter(hay) {
                all.push(SetMatch {
                    start: hit.start,
                    end: hit.end,
                    pattern_idx: *idx,
                });
            }
        }
        all.sort_by_key(|m| (m.start, m.pattern_idx));
        all.into_iter()
    }

    /// How many patterns landed in each tier, indexed by
    /// [`MatcherTier::index`] in [`MatcherTier::ALL`] order.
    #[must_use]
    pub fn tier_counts(&self) -> [usize; MatcherTier::ALL.len()] {
        let mut counts = [0_usize; MatcherTier::ALL.len()];
        for t in &self.tiers {
            counts[t.index()] += 1;
        }
        counts
    }

    /// Number of patterns in the set.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.tiers.len()
    }

    /// `true` if the set has no patterns.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.tiers.is_empty()
    }
}

impl StrMatcherBuilder {
    /// Build a [`StrMatcherSet`] from an iterator of patterns.
    ///
    /// `min_tier` + `on_below_min` apply per pattern. First failure
    /// short-circuits the build. Unanchored literals fold into a
    /// merged AC. Anchored / regex patterns stay individual.
    ///
    /// # Errors
    ///
    /// As [`StrMatcherBuilder::build`].
    pub fn build_set<I, S>(&self, patterns: I) -> Result<StrMatcherSet, BuildError>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let mut individual: Vec<(usize, StrMatcher)> = Vec::new();
        let mut merge_lits: Vec<Vec<u8>> = Vec::new();
        let mut pattern_indices: Vec<usize> = Vec::new();
        let mut tiers: Vec<MatcherTier> = Vec::new();

        for (idx, pat) in patterns.into_iter().enumerate() {
            let m = self.build(pat.as_ref())?;
            tiers.push(m.tier);
            match m.plan.merge_literals() {
                // The merged automaton follows the regex crate's iteration.
                Some((lits, ci)) if ci == self.ascii_case_insensitive && !m.java_empty => {
                    for lit in lits {
                        pattern_indices.push(idx);
                        merge_lits.push(lit);
                    }
                }
                _ => individual.push((idx, m)),
            }
        }

        // Each pattern's literals passed LITERAL_SET_CAP alone, but the merged
        // set has no cap, so the automaton can still refuse it.
        let merged = if merge_lits.is_empty() {
            None
        } else {
            let ac = aho_corasick::AhoCorasickBuilder::new()
                .ascii_case_insensitive(self.ascii_case_insensitive)
                .match_kind(aho_corasick::MatchKind::LeftmostLongest)
                .build(&merge_lits)
                .map_err(|e| BuildError::Automaton {
                    source: Box::new(e),
                    hint: "split the set into smaller sets",
                })?;
            Some(MergedAc {
                ac,
                pattern_indices,
            })
        };

        Ok(StrMatcherSet {
            merged,
            individual,
            tiers,
        })
    }
}

// ---------------------------------------------------------------------------
// Anti-spam log helper
// ---------------------------------------------------------------------------

mod warn {
    use super::{AtomicBool, AtomicUsize, HashSet, LazyLock, Mutex, Ordering};

    /// Distinct patterns that log a WARN before later ones drop to DEBUG.
    pub(super) const WARN_CAP: usize = 10;

    static WARNED_HASHES: LazyLock<Mutex<HashSet<u64>>> =
        LazyLock::new(|| Mutex::new(HashSet::new()));
    static DISTINCT: AtomicUsize = AtomicUsize::new(0);
    static SUMMARY_EMITTED: AtomicBool = AtomicBool::new(false);

    fn hash_pattern(pattern: &str) -> u64 {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut h = DefaultHasher::new();
        pattern.hash(&mut h);
        h.finish()
    }

    /// Log a regex fall-through once per distinct pattern, up to
    /// [`WARN_CAP`]. `force` always logs and never counts toward the cap.
    pub(super) fn on_regex_fallback(
        pattern: &str,
        reason: &'static str,
        hint: &'static str,
        force: bool,
    ) {
        let h = hash_pattern(pattern);
        let already_warned = {
            let mut set = WARNED_HASHES
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            !set.insert(h)
        };
        if already_warned && !force {
            return;
        }
        let n = if force {
            DISTINCT.load(Ordering::Relaxed)
        } else {
            DISTINCT.fetch_add(1, Ordering::Relaxed) + 1
        };
        let summary = !force && n == WARN_CAP + 1 && !SUMMARY_EMITTED.swap(true, Ordering::Relaxed);
        emit(pattern, reason, hint, force || n <= WARN_CAP, summary);
    }

    #[cfg(feature = "tracing")]
    fn emit(pattern: &str, reason: &'static str, hint: &'static str, warn: bool, summary: bool) {
        if warn {
            tracing::warn!(
                target: "grippo::strmatch",
                pattern,
                reason,
                hint,
                "pattern falls through to regex engine on hot path"
            );
        } else {
            tracing::debug!(
                target: "grippo::strmatch",
                pattern,
                reason,
                hint,
                "regex fallback (WARN suppressed past cap)"
            );
        }
        if summary {
            tracing::info!(
                target: "grippo::strmatch",
                cap = WARN_CAP,
                "{}+ distinct patterns have fallen through to the regex engine; \
                 further fall-throughs log at DEBUG. Inspect StrMatcher::tier() / \
                 StrMatcherSet::tier_counts() at runtime, or scrape the \
                 strmatch_regex_fallback_total metric.",
                WARN_CAP,
            );
        }
    }

    #[cfg(not(feature = "tracing"))]
    const fn emit(_: &str, _: &'static str, _: &'static str, _: bool, _: bool) {}

    #[cfg(test)]
    pub(super) fn reset_for_tests() {
        WARNED_HASHES
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clear();
        DISTINCT.store(0, Ordering::Relaxed);
        SUMMARY_EMITTED.store(false, Ordering::Relaxed);
    }

    #[cfg(test)]
    pub(super) fn distinct_for_tests() -> usize {
        DISTINCT.load(Ordering::Relaxed)
    }
}

#[cfg(feature = "metrics")]
fn metrics_inc_fallback() {
    metrics::counter!("strmatch_regex_fallback_total").increment(1);
}

#[cfg(not(feature = "metrics"))]
const fn metrics_inc_fallback() {}

#[cfg(test)]
pub(crate) fn reset_warn_state_for_tests() {
    warn::reset_for_tests();
}

#[cfg(test)]
mod tests;