perf-sentinel-core 0.8.13

Core library for perf-sentinel: polyglot performance anti-pattern detector
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
//! Sanitizer-aware classification for N+1 vs redundant.
//!
//! SQL path: gated on `looks_sanitized`, uses ORM scope + timing variance.
//! HTTP path: gated on timing variance, optionally uses HTTP placeholders.
//!
//! See `docs/design/04-DETECTION.md` ยง "Sanitizer-aware classification"
//! for the rationale and the JSONB known-limit.

use crate::normalize::NormalizedEvent;

/// How aggressively to reclassify sanitizer-collapsed SQL groups as N+1.
///
/// Wired from `[detection] sanitizer_aware_classification` in
/// `.perf-sentinel.toml`. Default is [`SanitizerAwareMode::Auto`].
///
/// Modes trade recall (catch more N+1) against precision (preserve
/// `redundant_sql` findings on legitimate repeated identical queries).
/// `Auto` favors recall, `Strict` favors precision, `Always` and `Never`
/// are the two ends of the dial.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SanitizerAwareMode {
    /// Reclassify when **either** the ORM scope signal **or** the timing
    /// variance signal fires. Default. Best recall on production stacks
    /// where the ORM scope is almost always present, at the cost of
    /// hiding `redundant_sql` findings on truly repeated identical
    /// queries served from cache.
    #[default]
    Auto,
    /// Reclassify any sanitized group with `>= threshold` occurrences.
    /// Most aggressive: may flag a single-param redundancy as N+1.
    Always,
    /// Disable the heuristic entirely. Falls back to the strict
    /// `distinct_params` check.
    Never,
    /// Reclassify when a primary signal (ORM scope, high occurrence
    /// `>= 3x` threshold, or sequential siblings) fires conjointly
    /// with a corroborating signal (timing variance or high
    /// occurrence). High occurrence serves both roles: 15+ sanitized
    /// identical templates in one trace is structurally N+1 under the
    /// `looks_sanitized` guard. See `docs/design/04-DETECTION.md`.
    Strict,
}

impl SanitizerAwareMode {
    /// Parse the TOML string. Unknown values warn and fall back to
    /// [`SanitizerAwareMode::Auto`].
    ///
    /// The warning emits a sanitized form of the offending value
    /// (control characters replaced, length capped at 32 bytes) so a
    /// stray credential-shaped string in the config file does not land
    /// verbatim in logs.
    #[must_use]
    pub fn from_config(value: Option<&str>) -> Self {
        match value.map(str::trim) {
            None | Some("") => Self::Auto,
            Some(raw) => {
                if raw.eq_ignore_ascii_case("auto") {
                    Self::Auto
                } else if raw.eq_ignore_ascii_case("always") {
                    Self::Always
                } else if raw.eq_ignore_ascii_case("never") {
                    Self::Never
                } else if raw.eq_ignore_ascii_case("strict") {
                    Self::Strict
                } else {
                    tracing::warn!(
                        value = sanitize_for_log(raw).as_ref(),
                        "unknown sanitizer_aware_classification value, defaulting to 'auto'"
                    );
                    Self::Auto
                }
            }
        }
    }

    /// Returns the lowercase string label used in the TOML config.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::Always => "always",
            Self::Never => "never",
            Self::Strict => "strict",
        }
    }
}

/// Verdict from the heuristic on a single sanitized SQL group.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SanitizerVerdict {
    /// Group looks like a sanitized N+1: emit `n_plus_one_sql`.
    LikelyNPlusOne,
    /// Heuristic could not gather enough signal: leave to the redundant
    /// detector.
    Inconclusive,
}

/// Instrumentation scope substrings that indicate an ORM is in the call
/// stack. Matched case-insensitively via `contains`, so vendor variants
/// (`io.opentelemetry.spring-data-3.0`, `io.opentelemetry.SpringData`)
/// both hit. List intentionally errs on the side of recall: a false
/// positive only swaps a `redundant_sql` finding for `n_plus_one_sql` on
/// a sanitized group, which is the harm-reduction direction.
///
/// Inclusion criterion: the library emits an `OTel` instrumentation
/// scope that names an ORM layer (not a bare SQL driver). Bare drivers
/// like `sqlx`, `pgx`, `asyncpg` and the Vert.x reactive PG client emit
/// driver-level scopes only and belong on the Strict bare-driver branch
/// (sequential-siblings signal), not in this list.
const ORM_SCOPE_MARKERS: &[&str] = &[
    // Java / JVM
    "spring-data",
    "hibernate",
    "jpa",
    "micronaut-data",
    "jdbi",
    "r2dbc",
    // .NET
    "entityframeworkcore",
    "entity-framework",
    // Python
    "sqlalchemy",
    "django",
    // Ruby
    "active-record",
    "activerecord",
    // Go
    "gorm",
    // Node.js
    "sequelize",
    "prisma",
    "typeorm",
    "mongoose",
    // Rust
    "sea-orm",
    "diesel",
];

/// Returns `true` when every span in the group looks like the `OTel`
/// SQL sanitizer (or native driver) collapsed its literals: the
/// template carries a recognized placeholder (see
/// [`template_has_placeholder`]) and `params` is empty
/// (`normalize_sql` extracts literals, not placeholders, so a
/// sanitized N+1 has `params == []` on every span). JSONB `?` caveat
/// in the module-level note.
#[must_use]
pub fn looks_sanitized(spans: &[&NormalizedEvent]) -> bool {
    !spans.is_empty()
        && spans
            .iter()
            .all(|s| s.params.is_empty() && template_has_placeholder(&s.template))
}

/// Index-based variant of [`looks_sanitized`] for the detection hot path.
/// Avoids materializing a `Vec<&NormalizedEvent>` before the cheap
/// per-span check, so the heavy `classify_sanitized_sql_group_indexed`
/// only runs on groups that already pass the fast gate.
pub(super) fn looks_sanitized_indexed(spans: &[NormalizedEvent], indices: &[usize]) -> bool {
    !indices.is_empty()
        && indices.iter().all(|&i| {
            let s = &spans[i];
            s.params.is_empty() && template_has_placeholder(&s.template)
        })
}

/// Returns `true` when the template contains a recognizable
/// database-driver placeholder, indicating the `OTel` instrumentation
/// sanitized (or preserved) parameter bindings. Recognized styles:
///
/// - `?` : JDBC agent sanitizer, also catches `$?` (`pgx`/`asyncpg`).
/// - `%s` : Python DB-API (`psycopg`, `MySQLdb`).
/// - `@` + alphanumeric : .NET (`Npgsql` `@p0`, `SqlClient` `@Name`).
/// - `:` + alphanumeric (not `::`) : `Oracle`, `SQLAlchemy` (`:oid`).
/// - `$` + digit : `PostgreSQL` native unsanitized (`$1`, `$2`).
fn template_has_placeholder(template: &str) -> bool {
    if template.contains('?') || template.contains("%s") {
        return true;
    }
    let bytes = template.as_bytes();
    for i in 0..bytes.len().saturating_sub(1) {
        let next = bytes[i + 1];
        match bytes[i] {
            // Single `@` followed by alpha, NOT preceded by another `@`
            // (excludes SQL Server system variables like `@@ROWCOUNT`).
            b'@' if next.is_ascii_alphanumeric() && (i == 0 || bytes[i - 1] != b'@') => {
                return true;
            }
            // Single `:` followed by a letter, NOT preceded by another
            // `:` (excludes PostgreSQL casts `::int` and array slices
            // `arr[1:2]` where `:digit` is NOT a placeholder).
            b':' if next.is_ascii_alphabetic() && (i == 0 || bytes[i - 1] != b':') => {
                return true;
            }
            b'$' if next.is_ascii_digit() => return true,
            _ => {}
        }
    }
    false
}

/// Returns `true` when any of the supplied instrumentation scopes contains
/// an ORM marker. Matching is ASCII-case-insensitive and word-bounded:
/// the marker substring must be preceded and followed by a non-word
/// byte (anything that is not `[A-Za-z0-9_]`) or by the start/end of the
/// scope. This prevents `jpa` from firing on `myappjpastats`.
/// Allocation-free.
#[must_use]
pub fn has_orm_scope(scopes: &[String]) -> bool {
    scopes
        .iter()
        .any(|scope| ORM_SCOPE_MARKERS.iter().any(|m| contains_marker(scope, m)))
}

/// ASCII case-insensitive substring search with word-boundary anchoring.
fn contains_marker(haystack: &str, needle: &str) -> bool {
    let h = haystack.as_bytes();
    let n = needle.as_bytes();
    if n.is_empty() || h.len() < n.len() {
        return false;
    }
    h.windows(n.len()).enumerate().any(|(i, w)| {
        if !w.eq_ignore_ascii_case(n) {
            return false;
        }
        let before_ok = i == 0 || !is_word_byte(h[i - 1]);
        let after = i + n.len();
        let after_ok = after == h.len() || !is_word_byte(h[after]);
        before_ok && after_ok
    })
}

const fn is_word_byte(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_'
}

/// Aggregate the instrumentation scopes from every span in a group,
/// deduplicated. Spans in a single ORM-induced N+1 share the same scope
/// chain, so most groups produce a single-entry vector. Bounded by the
/// per-span scope cap enforced at ingest (`event::cap_instrumentation_scopes`),
/// so the linear-scan dedup stays cheap.
#[must_use]
pub fn collect_scopes(spans: &[&NormalizedEvent]) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    for span in spans {
        for scope in &span.event.instrumentation_scopes {
            let scope_str: &str = scope.as_ref();
            if !out.iter().any(|existing| existing == scope_str) {
                out.push(scope.to_string());
            }
        }
    }
    out
}

/// Returns `true` when the coefficient of variation (std-dev / mean)
/// of the per-span `duration_us` values exceeds `0.5`: true N+1 hits
/// different rows with different cache states (durations spread),
/// redundant calls hit the same cache lines (durations cluster).
/// Requires at least 3 spans; `false` for fewer, zero mean, or empty.
///
/// The threshold favors false positives over silent misses; the harm
/// asymmetry and the Strict-mode warm-cache limit are discussed in
/// `docs/design/04-DETECTION.md`.
#[must_use]
pub fn timing_variance_suggests_n_plus_one(spans: &[&NormalizedEvent]) -> bool {
    if spans.len() < 3 {
        return false;
    }
    // Welford's online algorithm: single pass, no intermediate Vec<f64>.
    let mut count: u64 = 0;
    let mut mean: f64 = 0.0;
    let mut m2: f64 = 0.0;
    for span in spans {
        count += 1;
        #[allow(clippy::cast_precision_loss)] // duration_us fits in f64 to ~9e15 ยตs
        let d = span.event.duration_us as f64;
        let delta = d - mean;
        #[allow(clippy::cast_precision_loss)]
        let count_f = count as f64;
        mean += delta / count_f;
        m2 += delta * (d - mean);
    }
    if mean <= 0.0 {
        return false;
    }
    #[allow(clippy::cast_precision_loss)]
    let variance = m2 / count as f64;
    let cv = variance.sqrt() / mean;
    cv > 0.5
}

/// Combined verdict for `Auto` mode: ORM scope or timing variance.
/// Either signal alone is enough to return `LikelyNPlusOne`.
///
/// `high_occurrence` is deliberately NOT consulted here: Auto is the
/// precision-first mode, and 15+ identical sanitized queries can be a
/// legitimate cache-warm pattern (all hitting cache, uniform timing,
/// no ORM scope) where the correct classification is `redundant_sql`
/// not `n_plus_one_sql`. Users who need the `high_occurrence` signal
/// should set `sanitizer_aware_classification = "strict"`.
#[must_use]
pub fn classify_sanitized_sql_group(
    spans: &[&NormalizedEvent],
    scopes: &[String],
) -> SanitizerVerdict {
    if has_orm_scope(scopes) || timing_variance_suggests_n_plus_one(spans) {
        SanitizerVerdict::LikelyNPlusOne
    } else {
        SanitizerVerdict::Inconclusive
    }
}

/// Combined verdict for `Strict` mode. Two gates, both must pass:
///
/// 1. **Primary**: `orm || high_occurrence || sequential()`.
/// 2. **Corroboration**: `variance || high_occurrence`.
///
/// `high_occurrence` (>= 3x threshold, default 15) is both primary
/// and corroborator: 15+ sanitized identical templates in one trace
/// is structurally n+1 under the `looks_sanitized` guard, regardless
/// of ORM scope, sequential siblings, or variance. `sequential` is a
/// lazy `FnOnce` skipped when `orm` or `high_occurrence` is true.
#[must_use]
pub fn classify_sanitized_sql_group_strict(
    spans: &[&NormalizedEvent],
    scopes: &[String],
    sequential: impl FnOnce() -> bool,
    high_occurrence: bool,
) -> SanitizerVerdict {
    let orm = has_orm_scope(scopes);
    let primary_ok = orm || high_occurrence || sequential();
    if !primary_ok {
        return SanitizerVerdict::Inconclusive;
    }
    let variance_ok = timing_variance_suggests_n_plus_one(spans);
    let corroborated = variance_ok || high_occurrence;
    if corroborated {
        SanitizerVerdict::LikelyNPlusOne
    } else {
        SanitizerVerdict::Inconclusive
    }
}

/// Index-based variant for the detection hot path: borrows directly
/// from the trace's span vector, no intermediate `Vec<&NormalizedEvent>`.
/// Dispatches to the OR-logic (Auto) or AND-logic (Strict) classifier.
///
/// `sequential_siblings` is a lazy closure consulted only by the Strict
/// branch, so other modes skip the per-trace sibling walk entirely.
/// `Never` and `Always` short-circuit upstream in [`super::n_plus_one`];
/// the match stays exhaustive (no `_`) so a future variant fails to
/// compile rather than silently picking the OR fallback.
pub(super) fn classify_sanitized_sql_group_indexed(
    spans: &[NormalizedEvent],
    indices: &[usize],
    mode: SanitizerAwareMode,
    sequential_siblings: impl FnOnce() -> bool,
    high_occurrence: bool,
) -> SanitizerVerdict {
    let group: Vec<&NormalizedEvent> = indices.iter().map(|&i| &spans[i]).collect();
    let scopes = collect_scopes(&group);
    match mode {
        SanitizerAwareMode::Strict => classify_sanitized_sql_group_strict(
            &group,
            &scopes,
            sequential_siblings,
            high_occurrence,
        ),
        SanitizerAwareMode::Auto | SanitizerAwareMode::Always | SanitizerAwareMode::Never => {
            classify_sanitized_sql_group(&group, &scopes)
        }
    }
}

/// Returns `true` when the HTTP template contains a normalizer-generated
/// placeholder (any `{`-delimited token: `{id}`, `{uuid}`, etc.),
/// indicating the URL had variable path segments collapsed by the HTTP
/// normalizer.
pub(super) fn template_has_http_placeholder(template: &str) -> bool {
    template.contains('{')
}

/// Classify an HTTP group that failed the distinct-params rule.
///
/// HTTP has no ORM scope concept, so the classification relies on
/// timing variance, high occurrence, sequential siblings, and the
/// presence of HTTP placeholders (`{id}`, `{uuid}`).
///
/// - `Auto`/`Always`: timing variance alone is sufficient.
/// - `Strict`: (placeholder OR high occurrence OR sequential) AND
///   variance.
/// - `Never`: always inconclusive.
pub(super) fn classify_http_group_indexed(
    spans: &[NormalizedEvent],
    indices: &[usize],
    mode: SanitizerAwareMode,
    sequential_siblings: impl FnOnce() -> bool,
    high_occurrence: bool,
) -> SanitizerVerdict {
    let group: Vec<&NormalizedEvent> = indices.iter().map(|&i| &spans[i]).collect();
    let variance = timing_variance_suggests_n_plus_one(&group);
    match mode {
        SanitizerAwareMode::Never => SanitizerVerdict::Inconclusive,
        SanitizerAwareMode::Auto | SanitizerAwareMode::Always => {
            if variance {
                SanitizerVerdict::LikelyNPlusOne
            } else {
                SanitizerVerdict::Inconclusive
            }
        }
        SanitizerAwareMode::Strict => {
            let has_placeholder = indices
                .iter()
                .any(|&i| template_has_http_placeholder(&spans[i].template));
            let primary = has_placeholder || high_occurrence || sequential_siblings();
            if !primary {
                return SanitizerVerdict::Inconclusive;
            }
            // HTTP has no `looks_sanitized` guard, so high_occurrence
            // alone is not sufficient as corroboration (unlike SQL where
            // looks_sanitized already filtered out non-sanitized groups).
            if variance {
                SanitizerVerdict::LikelyNPlusOne
            } else {
                SanitizerVerdict::Inconclusive
            }
        }
    }
}

/// Sanitize an arbitrary user-controlled string for inclusion in a
/// `tracing` event: replace control characters with `_` and cap at 32
/// bytes (UTF-8 boundary preserved). Mirrors the project's pattern of
/// never letting raw config values reach the log surface unchecked.
fn sanitize_for_log(value: &str) -> std::borrow::Cow<'_, str> {
    const MAX_LEN: usize = 32;
    let truncated = if value.len() > MAX_LEN {
        let cut = value
            .char_indices()
            .take_while(|(i, _)| *i <= MAX_LEN)
            .last()
            .map_or(0, |(i, c)| i + c.len_utf8());
        &value[..cut.min(value.len())]
    } else {
        value
    };
    if truncated.chars().any(char::is_control) {
        std::borrow::Cow::Owned(
            truncated
                .chars()
                .map(|c| if c.is_control() { '_' } else { c })
                .collect(),
        )
    } else {
        std::borrow::Cow::Borrowed(truncated)
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use super::*;
    use crate::event::SpanEvent;
    use crate::normalize;
    use crate::test_helpers::make_sql_event_with_duration;

    fn sanitized_event_with_scope(span_id: &str, ts: &str, duration_us: u64) -> SpanEvent {
        let mut e = make_sql_event_with_duration(
            "trace-1",
            span_id,
            "SELECT * FROM order_items WHERE order_id = ?",
            ts,
            duration_us,
        );
        e.instrumentation_scopes = vec![Arc::from("io.opentelemetry.spring-data-jpa-3.0")];
        e
    }

    fn normalize_one(event: SpanEvent) -> NormalizedEvent {
        normalize::normalize_all(vec![event]).remove(0)
    }

    /// Build N normalized sanitized events with the supplied per-span
    /// `duration_us`, no scope. Shared by the timing-variance tests so
    /// the boilerplate (build / normalize / collect refs) stays in one
    /// place.
    fn sanitized_normalized_with_durations(durations: &[u64]) -> Vec<NormalizedEvent> {
        durations
            .iter()
            .enumerate()
            .map(|(i, d)| {
                let mut e = make_sql_event_with_duration(
                    "trace-1",
                    &format!("span-{i}"),
                    "SELECT * FROM order_items WHERE order_id = ?",
                    &format!("2025-07-10T14:32:01.{:03}Z", i * 30),
                    *d,
                );
                e.instrumentation_scopes = Vec::new();
                normalize_one(e)
            })
            .collect()
    }

    #[test]
    fn from_config_parses_known_values() {
        assert_eq!(
            SanitizerAwareMode::from_config(None),
            SanitizerAwareMode::Auto
        );
        assert_eq!(
            SanitizerAwareMode::from_config(Some("auto")),
            SanitizerAwareMode::Auto
        );
        assert_eq!(
            SanitizerAwareMode::from_config(Some("ALWAYS")),
            SanitizerAwareMode::Always
        );
        assert_eq!(
            SanitizerAwareMode::from_config(Some(" Never ")),
            SanitizerAwareMode::Never
        );
        assert_eq!(
            SanitizerAwareMode::from_config(Some("strict")),
            SanitizerAwareMode::Strict
        );
        assert_eq!(
            SanitizerAwareMode::from_config(Some("STRICT")),
            SanitizerAwareMode::Strict
        );
    }

    #[test]
    fn as_str_round_trips_every_variant() {
        for mode in [
            SanitizerAwareMode::Auto,
            SanitizerAwareMode::Always,
            SanitizerAwareMode::Never,
            SanitizerAwareMode::Strict,
        ] {
            assert_eq!(SanitizerAwareMode::from_config(Some(mode.as_str())), mode);
        }
    }

    #[test]
    fn from_config_unknown_value_warns_and_defaults_to_auto() {
        // tracing::warn! is surfaced to stderr in tests; we only assert
        // the fallback behavior here. The warn macro itself is exercised
        // by invocation.
        assert_eq!(
            SanitizerAwareMode::from_config(Some("foo")),
            SanitizerAwareMode::Auto
        );
        assert_eq!(
            SanitizerAwareMode::from_config(Some("")),
            SanitizerAwareMode::Auto
        );
    }

    #[test]
    fn looks_sanitized_true_for_sanitized_template() {
        let events: Vec<SpanEvent> = (1..=3)
            .map(|i| {
                sanitized_event_with_scope(
                    &format!("span-{i}"),
                    &format!("2025-07-10T14:32:01.{:03}Z", i * 50),
                    100,
                )
            })
            .collect();
        let normalized: Vec<NormalizedEvent> = events.into_iter().map(normalize_one).collect();
        // normalize_sql leaves the literal `?` in the template and adds
        // nothing to params (it only extracts numeric/string literals).
        for event in &normalized {
            assert_eq!(event.params, Vec::<String>::new());
            assert!(event.template.contains('?'));
        }
        let refs: Vec<&NormalizedEvent> = normalized.iter().collect();
        assert!(looks_sanitized(&refs));
    }

    #[test]
    fn looks_sanitized_false_when_any_param_is_literal() {
        let mut e1 = sanitized_event_with_scope("span-1", "2025-07-10T14:32:01.000Z", 100);
        let mut e2 = sanitized_event_with_scope("span-2", "2025-07-10T14:32:01.050Z", 100);
        e1.target = "SELECT * FROM order_items WHERE order_id = ?".to_string();
        e2.target = "SELECT * FROM order_items WHERE order_id = 42".to_string();
        let normalized: Vec<NormalizedEvent> =
            vec![e1, e2].into_iter().map(normalize_one).collect();
        let refs: Vec<&NormalizedEvent> = normalized.iter().collect();
        assert!(!looks_sanitized(&refs));
    }

    #[test]
    fn looks_sanitized_false_when_template_has_no_placeholder() {
        // No literals at all (`SELECT NOW()`): template has no `?`,
        // params is empty. Must not be flagged as sanitized.
        let event = make_sql_event_with_duration(
            "trace-1",
            "span-1",
            "SELECT NOW()",
            "2025-07-10T14:32:01.000Z",
            100,
        );
        let normalized = normalize_one(event);
        let refs = vec![&normalized];
        assert!(!looks_sanitized(&refs));
    }

    #[test]
    fn template_has_placeholder_recognizes_all_driver_styles() {
        // JDBC / generic sanitizer
        assert!(template_has_placeholder("WHERE id = ?"));
        // pgx / asyncpg sanitized
        assert!(template_has_placeholder("WHERE id = $?"));
        // Python DB-API (psycopg, MySQLdb)
        assert!(template_has_placeholder("WHERE id = %s"));
        // .NET Npgsql / SqlClient
        assert!(template_has_placeholder("WHERE id = @p0"));
        assert!(template_has_placeholder("WHERE id = @Name"));
        // Oracle / SQLAlchemy named
        assert!(template_has_placeholder("WHERE id = :oid"));
        // PostgreSQL native unsanitized
        assert!(template_has_placeholder("WHERE id = $1"));
        // PostgreSQL cast `::int` must NOT trigger
        assert!(!template_has_placeholder("SELECT count(*)::int FROM t"));
        // PostgreSQL array slice `arr[1:2]` must NOT trigger
        assert!(!template_has_placeholder("SELECT arr[1:2] FROM t"));
        // SQL Server system variables `@@ROWCOUNT` must NOT trigger
        assert!(!template_has_placeholder("SELECT @@ROWCOUNT"));
        assert!(!template_has_placeholder("SELECT @@VERSION"));
        // No placeholder
        assert!(!template_has_placeholder("SELECT NOW()"));
        assert!(!template_has_placeholder("SELECT 1"));
    }

    #[test]
    fn classify_auto_stays_inconclusive_without_orm_or_variance() {
        // No ORM scope, uniform timing (variance false). Auto mode
        // does NOT consult high_occurrence (precision-first), so the
        // group stays Inconclusive. Users who need the
        // high_occurrence signal should use Strict mode.
        let durations = [100u64, 102, 98, 101, 99, 100, 101, 99, 100, 102];
        let events: Vec<SpanEvent> = durations
            .iter()
            .enumerate()
            .map(|(i, d)| {
                let mut e = make_sql_event_with_duration(
                    "trace-1",
                    &format!("span-{i}"),
                    "SELECT * FROM order_items WHERE order_id = $?",
                    &format!("2025-07-10T14:32:01.{:03}Z", i * 30),
                    *d,
                );
                e.instrumentation_scopes = Vec::new();
                e
            })
            .collect();
        let normalized: Vec<NormalizedEvent> = events.into_iter().map(normalize_one).collect();
        let refs: Vec<&NormalizedEvent> = normalized.iter().collect();
        let scopes = collect_scopes(&refs);
        assert_eq!(
            classify_sanitized_sql_group(&refs, &scopes),
            SanitizerVerdict::Inconclusive,
            "Auto must NOT fire on high_occurrence alone (cache-warm precision guard)"
        );
    }

    #[test]
    fn has_orm_scope_matches_case_insensitively() {
        assert!(has_orm_scope(&[
            "io.opentelemetry.spring-data-3.0".to_string()
        ]));
        assert!(has_orm_scope(&[
            "IO.OPENTELEMETRY.HIBERNATE-ORM-6.0".to_string()
        ]));
        assert!(has_orm_scope(&["EntityFrameworkCore".to_string()]));
        assert!(has_orm_scope(&["opentelemetry.gorm.v1".to_string()]));
        assert!(!has_orm_scope(&["io.opentelemetry.jdbc-3.1".to_string()]));
        assert!(!has_orm_scope(&[]));
    }

    #[test]
    fn has_orm_scope_respects_word_boundary() {
        // Short markers like `jpa` must not match arbitrary substrings:
        // a hostile or coincidental scope like `myappjpastats` must NOT
        // trigger the heuristic.
        assert!(!has_orm_scope(&["myappjpastats".to_string()]));
        assert!(!has_orm_scope(&["my-jpastore".to_string()]));
        assert!(!has_orm_scope(&["spring-database".to_string()]));
        // Real OTel scope shapes still match.
        assert!(has_orm_scope(&[
            "io.opentelemetry.spring-data-jpa-3.0".to_string()
        ]));
        assert!(has_orm_scope(&["io.opentelemetry.go.gorm.v1".to_string()]));
    }

    #[test]
    fn bare_driver_sqlx_scope_does_not_match_orm_marker() {
        // Rust sqlx and Go jmoiron/sqlx are bare drivers, not ORMs. They
        // must not trigger the ORM scope signal on a sanitized group.
        // Strict mode reclassifies their n+1 via the sequential-siblings
        // + variance path instead (see `n_plus_one::sequential_siblings_indexed`).
        assert!(!has_orm_scope(&["sqlx::query".to_string()]));
        assert!(!has_orm_scope(&["sqlx_core::pool::pool_inner".to_string()]));
        assert!(!has_orm_scope(&["github.com/jmoiron/sqlx".to_string()]));
        // Positive pinning: a real ORM scope still matches, guarding
        // against an overzealous future removal from ORM_SCOPE_MARKERS.
        assert!(has_orm_scope(&[
            "io.opentelemetry.spring-data-jpa-3.0".to_string()
        ]));
    }

    #[test]
    fn sanitize_for_log_redacts_control_chars_and_truncates() {
        assert_eq!(sanitize_for_log("ab\x00c\nd").as_ref(), "ab_c_d");
        assert_eq!(sanitize_for_log("abc").as_ref(), "abc");
        let long = "x".repeat(200);
        let out = sanitize_for_log(&long);
        assert!(
            out.len() <= 40,
            "expected truncation, got {} bytes",
            out.len()
        );
    }

    #[test]
    fn timing_variance_high_cv_returns_true() {
        // Dispersed durations: cache cold/warm states across N+1 row
        // lookups. CV ~ 0.68 on this set.
        let normalized =
            sanitized_normalized_with_durations(&[100, 50, 200, 60, 250, 80, 300, 70, 150, 400]);
        let refs: Vec<&NormalizedEvent> = normalized.iter().collect();
        assert!(timing_variance_suggests_n_plus_one(&refs));
    }

    #[test]
    fn timing_variance_low_cv_returns_false() {
        let normalized =
            sanitized_normalized_with_durations(&[100, 102, 98, 101, 99, 100, 101, 99, 100, 102]);
        let refs: Vec<&NormalizedEvent> = normalized.iter().collect();
        assert!(!timing_variance_suggests_n_plus_one(&refs));
    }

    #[test]
    fn timing_variance_too_few_spans_returns_false() {
        let events: Vec<SpanEvent> = (1u64..=2)
            .map(|i| {
                sanitized_event_with_scope(
                    &format!("span-{i}"),
                    &format!("2025-07-10T14:32:01.{:03}Z", i * 30),
                    100 * i,
                )
            })
            .collect();
        let normalized: Vec<NormalizedEvent> = events.into_iter().map(normalize_one).collect();
        let refs: Vec<&NormalizedEvent> = normalized.iter().collect();
        assert!(!timing_variance_suggests_n_plus_one(&refs));
    }

    #[test]
    fn classify_returns_n_plus_one_when_orm_scope_present() {
        let events: Vec<SpanEvent> = (1..=10)
            .map(|i| {
                sanitized_event_with_scope(
                    &format!("span-{i}"),
                    &format!("2025-07-10T14:32:01.{:03}Z", i * 10),
                    100,
                )
            })
            .collect();
        let normalized: Vec<NormalizedEvent> = events.into_iter().map(normalize_one).collect();
        let refs: Vec<&NormalizedEvent> = normalized.iter().collect();
        let scopes = collect_scopes(&refs);
        assert_eq!(
            classify_sanitized_sql_group(&refs, &scopes),
            SanitizerVerdict::LikelyNPlusOne
        );
    }

    #[test]
    fn classify_returns_inconclusive_when_no_signal() {
        let durations = [100u64, 102, 98, 101, 99, 100, 101, 99, 100, 102];
        let events: Vec<SpanEvent> = durations
            .iter()
            .enumerate()
            .map(|(i, d)| {
                let mut e = make_sql_event_with_duration(
                    "trace-1",
                    &format!("span-{i}"),
                    "SELECT * FROM order_items WHERE order_id = ?",
                    &format!("2025-07-10T14:32:01.{:03}Z", i * 30),
                    *d,
                );
                e.instrumentation_scopes = Vec::new();
                e
            })
            .collect();
        let normalized: Vec<NormalizedEvent> = events.into_iter().map(normalize_one).collect();
        let refs: Vec<&NormalizedEvent> = normalized.iter().collect();
        let scopes = collect_scopes(&refs);
        assert_eq!(
            classify_sanitized_sql_group(&refs, &scopes),
            SanitizerVerdict::Inconclusive
        );
    }

    // --- Strict mode (0.5.8+): both signals required ---

    /// Helper: build a sanitized group with explicit ORM scope and
    /// per-span durations, then return `(refs, scopes)` ready to feed
    /// into either classifier.
    fn build_sanitized_group_for_strict(
        scope: Option<&str>,
        durations: &[u64],
    ) -> (Vec<NormalizedEvent>, Vec<String>) {
        let events: Vec<SpanEvent> = durations
            .iter()
            .enumerate()
            .map(|(i, d)| {
                let mut e = make_sql_event_with_duration(
                    "trace-1",
                    &format!("span-{i}"),
                    "SELECT * FROM order_items WHERE order_id = ?",
                    &format!("2025-07-10T14:32:01.{:03}Z", i * 30),
                    *d,
                );
                e.instrumentation_scopes = scope.map(|s| vec![Arc::from(s)]).unwrap_or_default();
                e
            })
            .collect();
        let normalized: Vec<NormalizedEvent> = events.into_iter().map(normalize_one).collect();
        let refs: Vec<&NormalizedEvent> = normalized.iter().collect();
        let scopes = collect_scopes(&refs);
        (normalized, scopes)
    }

    #[test]
    fn strict_orm_scope_only_low_variance_returns_inconclusive() {
        // The simulation lab redundant_sql case: 15 identical SELECT
        // count(*) from a Spring Data JPA repository, all served from
        // the same cached row. ORM scope present, timing tight.
        // Auto would reclassify, Strict must not.
        let low_variance = [
            100u64, 102, 98, 101, 99, 100, 101, 99, 100, 102, 98, 101, 99, 100, 102,
        ];
        let (normalized, scopes) =
            build_sanitized_group_for_strict(Some("io.opentelemetry.hibernate-6.0"), &low_variance);
        let refs: Vec<&NormalizedEvent> = normalized.iter().collect();
        assert_eq!(
            classify_sanitized_sql_group_strict(&refs, &scopes, || false, false),
            SanitizerVerdict::Inconclusive
        );
    }

    #[test]
    fn strict_orm_scope_and_high_variance_returns_likely_n_plus_one() {
        // Real ORM-induced N+1: 10 lookups against different rows, cache
        // hit/miss spread the durations. Both signals fire, Strict emits.
        let high_variance = [100u64, 50, 200, 60, 250, 80, 300, 70, 150, 400];
        let (normalized, scopes) = build_sanitized_group_for_strict(
            Some("io.opentelemetry.spring-data-jpa-3.0"),
            &high_variance,
        );
        let refs: Vec<&NormalizedEvent> = normalized.iter().collect();
        assert_eq!(
            classify_sanitized_sql_group_strict(&refs, &scopes, || false, false),
            SanitizerVerdict::LikelyNPlusOne
        );
    }

    #[test]
    fn strict_no_orm_scope_high_variance_returns_inconclusive_when_not_sequential() {
        // Variance alone is not enough under Strict when the spans are
        // concurrent (e.g. parallel async fan-out). Without a
        // corroborating signal (ORM scope or sequential siblings) the
        // group stays unclassified.
        let high_variance = [100u64, 50, 200, 60, 250, 80, 300, 70, 150, 400];
        let (normalized, scopes) = build_sanitized_group_for_strict(None, &high_variance);
        let refs: Vec<&NormalizedEvent> = normalized.iter().collect();
        assert_eq!(
            classify_sanitized_sql_group_strict(&refs, &scopes, || false, false),
            SanitizerVerdict::Inconclusive
        );
    }

    #[test]
    fn strict_no_signal_returns_inconclusive() {
        let low_variance = [100u64, 102, 98, 101, 99, 100, 101, 99, 100, 102];
        let (normalized, scopes) = build_sanitized_group_for_strict(None, &low_variance);
        let refs: Vec<&NormalizedEvent> = normalized.iter().collect();
        assert_eq!(
            classify_sanitized_sql_group_strict(&refs, &scopes, || false, false),
            SanitizerVerdict::Inconclusive
        );
    }

    // --- Strict mode bare-driver path: sequential siblings + high variance ---

    #[test]
    fn strict_bare_driver_sequential_and_variance_returns_likely_n_plus_one() {
        // Vert.x reactive PG / pgx / asyncpg shape: no ORM scope on the
        // spans, but the reactive concat loop emits them sequentially
        // under one parent and the row-level cache miss spread clears
        // CV > 0.5. Strict must reclassify on the sequential+variance
        // path, restoring parity with Auto for bare-driver stacks.
        let high_variance = [100u64, 50, 200, 60, 250, 80, 300, 70, 150, 400];
        let (normalized, scopes) = build_sanitized_group_for_strict(None, &high_variance);
        let refs: Vec<&NormalizedEvent> = normalized.iter().collect();
        assert_eq!(
            classify_sanitized_sql_group_strict(&refs, &scopes, || true, false),
            SanitizerVerdict::LikelyNPlusOne
        );
    }

    #[test]
    fn strict_bare_driver_sequential_but_low_variance_returns_inconclusive() {
        // Sequential cache-warming loop on a bare driver: tight timings,
        // no real N+1. Strict must not reclassify on sequentiality alone.
        let low_variance = [100u64, 102, 98, 101, 99, 100, 101, 99, 100, 102];
        let (normalized, scopes) = build_sanitized_group_for_strict(None, &low_variance);
        let refs: Vec<&NormalizedEvent> = normalized.iter().collect();
        assert_eq!(
            classify_sanitized_sql_group_strict(&refs, &scopes, || true, false),
            SanitizerVerdict::Inconclusive
        );
    }

    #[test]
    fn strict_bare_driver_concurrent_with_high_variance_returns_inconclusive() {
        // Concurrent fan-out under a bare driver: variance trips but the
        // spans overlap (computed upstream as `sequential = false`).
        // Without ORM scope or sequentiality, Strict declines.
        let high_variance = [100u64, 50, 200, 60, 250, 80, 300, 70, 150, 400];
        let (normalized, scopes) = build_sanitized_group_for_strict(None, &high_variance);
        let refs: Vec<&NormalizedEvent> = normalized.iter().collect();
        assert_eq!(
            classify_sanitized_sql_group_strict(&refs, &scopes, || false, false),
            SanitizerVerdict::Inconclusive
        );
    }

    // --- Strict ORM branch: cache-warm via high_occurrence (lab dotnet-svc) ---

    #[test]
    fn strict_orm_scope_with_high_occurrence_low_variance_returns_likely_n_plus_one() {
        // Lab dotnet-svc shape: EF Core emits the OTel scope, 15 sanitized
        // SQL spans collapse to one template, but per-span timings cluster
        // tightly because Npgsql holds the rows warm. Strict accepts the
        // high_occurrence corroborator and fires.
        let low_variance = [100u64; 15];
        let (normalized, scopes) = build_sanitized_group_for_strict(
            Some("OpenTelemetry.Instrumentation.EntityFrameworkCore"),
            &low_variance,
        );
        let refs: Vec<&NormalizedEvent> = normalized.iter().collect();
        assert_eq!(
            classify_sanitized_sql_group_strict(&refs, &scopes, || false, true),
            SanitizerVerdict::LikelyNPlusOne
        );
    }

    #[test]
    fn strict_bare_driver_high_occurrence_sequential_returns_likely_n_plus_one() {
        let low_variance = [100u64; 15];
        let (normalized, scopes) = build_sanitized_group_for_strict(None, &low_variance);
        let refs: Vec<&NormalizedEvent> = normalized.iter().collect();
        assert_eq!(
            classify_sanitized_sql_group_strict(&refs, &scopes, || true, true),
            SanitizerVerdict::LikelyNPlusOne
        );
    }

    #[test]
    fn strict_high_occurrence_alone_no_orm_no_sequential_returns_likely_n_plus_one() {
        // Stand-alone high_occurrence: no ORM scope, not sequential.
        // The looks_sanitized upstream guard is the safety net.
        let low_variance = [100u64; 15];
        let (normalized, scopes) = build_sanitized_group_for_strict(None, &low_variance);
        let refs: Vec<&NormalizedEvent> = normalized.iter().collect();
        assert_eq!(
            classify_sanitized_sql_group_strict(&refs, &scopes, || false, true),
            SanitizerVerdict::LikelyNPlusOne
        );
    }

    #[test]
    fn strict_orm_scope_with_low_occurrence_low_variance_still_inconclusive() {
        // Precision guard: 5 sanitized SQL spans on a warm cache under an
        // ORM scope (the legacy polling loop the Strict mode was designed
        // to preserve as redundant_sql). high_occurrence is false at this
        // count, variance is low, Strict correctly declines.
        let low_variance = [100u64; 5];
        let (normalized, scopes) =
            build_sanitized_group_for_strict(Some("io.opentelemetry.hibernate-6.0"), &low_variance);
        let refs: Vec<&NormalizedEvent> = normalized.iter().collect();
        assert_eq!(
            classify_sanitized_sql_group_strict(&refs, &scopes, || false, false),
            SanitizerVerdict::Inconclusive
        );
    }

    // โ”€โ”€ HTTP placeholder detection โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    #[test]
    fn http_placeholder_recognizes_id() {
        assert!(template_has_http_placeholder("GET /api/users/{id}"));
    }

    #[test]
    fn http_placeholder_recognizes_uuid() {
        assert!(template_has_http_placeholder(
            "GET /api/orders/{uuid}/items"
        ));
    }

    #[test]
    fn http_placeholder_rejects_plain_path() {
        assert!(!template_has_http_placeholder("GET /api/health"));
        assert!(!template_has_http_placeholder("GET /api/users"));
    }

    // โ”€โ”€ HTTP group classification โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    fn http_normalized_with_durations(durations: &[u64]) -> Vec<NormalizedEvent> {
        durations
            .iter()
            .enumerate()
            .map(|(i, d)| {
                let e = crate::test_helpers::make_http_event_with_duration(
                    "trace-1",
                    &format!("span-{i}"),
                    "http://user-svc:5000/api/users/42",
                    &format!("2025-07-10T14:32:01.{:03}Z", i * 30),
                    *d,
                );
                normalize_one(e)
            })
            .collect()
    }

    #[test]
    fn http_auto_reclassifies_on_high_variance() {
        let spans = http_normalized_with_durations(&[100, 50, 200, 60, 250]);
        let indices: Vec<usize> = (0..spans.len()).collect();
        let verdict = classify_http_group_indexed(
            &spans,
            &indices,
            SanitizerAwareMode::Auto,
            || false,
            false,
        );
        assert_eq!(verdict, SanitizerVerdict::LikelyNPlusOne);
    }

    #[test]
    fn http_auto_inconclusive_on_low_variance() {
        let spans = http_normalized_with_durations(&[100, 100, 100, 100, 100]);
        let indices: Vec<usize> = (0..spans.len()).collect();
        let verdict = classify_http_group_indexed(
            &spans,
            &indices,
            SanitizerAwareMode::Auto,
            || false,
            false,
        );
        assert_eq!(verdict, SanitizerVerdict::Inconclusive);
    }

    #[test]
    fn http_never_always_inconclusive() {
        let spans = http_normalized_with_durations(&[100, 50, 200, 60, 250]);
        let indices: Vec<usize> = (0..spans.len()).collect();
        let verdict = classify_http_group_indexed(
            &spans,
            &indices,
            SanitizerAwareMode::Never,
            || false,
            false,
        );
        assert_eq!(verdict, SanitizerVerdict::Inconclusive);
    }

    #[test]
    fn http_strict_placeholder_plus_variance() {
        let spans = http_normalized_with_durations(&[100, 50, 200, 60, 250]);
        let indices: Vec<usize> = (0..spans.len()).collect();
        let verdict = classify_http_group_indexed(
            &spans,
            &indices,
            SanitizerAwareMode::Strict,
            || false,
            false,
        );
        assert_eq!(verdict, SanitizerVerdict::LikelyNPlusOne);
    }

    #[test]
    fn http_strict_high_occurrence_no_variance_stays_inconclusive() {
        // Unlike SQL, high_occurrence alone is not sufficient for HTTP
        // because HTTP has no looks_sanitized guard.
        let spans = http_normalized_with_durations(&[100, 100, 100, 100, 100]);
        let indices: Vec<usize> = (0..spans.len()).collect();
        let verdict = classify_http_group_indexed(
            &spans,
            &indices,
            SanitizerAwareMode::Strict,
            || false,
            true,
        );
        assert_eq!(verdict, SanitizerVerdict::Inconclusive);
    }

    #[test]
    fn http_strict_no_signal_inconclusive() {
        let durations = [100u64; 5];
        let spans: Vec<NormalizedEvent> = durations
            .iter()
            .enumerate()
            .map(|(i, d)| {
                let e = crate::test_helpers::make_http_event_with_duration(
                    "trace-1",
                    &format!("span-{i}"),
                    "http://svc:5000/api/health",
                    &format!("2025-07-10T14:32:01.{:03}Z", i * 30),
                    *d,
                );
                normalize_one(e)
            })
            .collect();
        let indices: Vec<usize> = (0..spans.len()).collect();
        let verdict = classify_http_group_indexed(
            &spans,
            &indices,
            SanitizerAwareMode::Strict,
            || false,
            false,
        );
        assert_eq!(verdict, SanitizerVerdict::Inconclusive);
    }

    #[test]
    fn http_strict_sequential_plus_variance() {
        let spans = http_normalized_with_durations(&[100, 50, 200, 60, 250]);
        let indices: Vec<usize> = (0..spans.len()).collect();
        let verdict = classify_http_group_indexed(
            &spans,
            &indices,
            SanitizerAwareMode::Strict,
            || true,
            false,
        );
        assert_eq!(verdict, SanitizerVerdict::LikelyNPlusOne);
    }
}