perf-sentinel-core 0.10.0

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
//! Ignore rules / acknowledgments for findings.
//!
//! Loads `.perf-sentinel-acknowledgments.toml`, computes a canonical
//! signature per [`Finding`], filters findings flagged as acknowledged
//! at the post-processing stage, and re-evaluates the quality gate on
//! the surviving set so an ack can flip a previously failing gate to
//! green.
//!
//! This is the CI / batch-mode side of the ack workflow. The daemon
//! runtime ack store lives at `crate::daemon::ack` and shares the
//! signature format defined here. The two are unioned at query time
//! with TOML winning on conflict (immutable baseline shipped via PR
//! review).

use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;
use std::io::Read;
use std::path::Path;

use chrono::{DateTime, NaiveDate, Utc};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use crate::config::Config;
use crate::detect::Finding;
use crate::quality_gate;
use crate::report::{AcknowledgedFinding, Report, Warning, warnings};

/// Hard cap on the size of `.perf-sentinel-acknowledgments.toml`. Mirrors
/// the trace-ingest payload-cap discipline so a stray
/// `--acknowledgments /dev/zero` or a multi-GB malformed TOML cannot
/// silently exhaust process memory.
pub const MAX_ACKNOWLEDGMENTS_FILE_BYTES: u64 = 16 * 1024 * 1024;

/// Where the report handed to [`apply_to_report`] comes from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReportOrigin {
    /// Traces analyzed by this process, findings unfiltered.
    FreshAnalysis,
    /// A parsed Report JSON (baseline file, daemon snapshot), possibly
    /// already ack-filtered and with foreign or absent I/O op counts.
    Precomputed,
}

/// A single acknowledgment entry deserialized from the TOML file.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Acknowledgment {
    /// Canonical signature: `<finding_type>:<service>:<sanitized_endpoint>:<sha256-prefix>`.
    pub signature: String,
    /// Email or identifier of the user who created the ack.
    pub acknowledged_by: String,
    /// ISO 8601 date when the ack was created (`YYYY-MM-DD`).
    pub acknowledged_at: String,
    /// Free-text reason / context for the ack.
    pub reason: String,
    /// Optional ISO 8601 date (`YYYY-MM-DD`) at which the ack expires.
    /// `None` means the ack is permanent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<String>,
    /// Optional service of the acked finding (`.findings[].service`).
    /// With `source_endpoint`, lets an unmatched ack say whether its
    /// endpoint was exercised by the run at all.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub service: Option<String>,
    /// Optional endpoint of the acked finding (`.findings[].source_endpoint`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_endpoint: Option<String>,
}

/// Container for the deserialized TOML file.
///
/// The TOML root is `[[acknowledged]]` blocks. Empty file (no blocks)
/// deserializes to a default value, making "file exists but is empty" a
/// no-op.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AcknowledgmentsFile {
    #[serde(default)]
    pub acknowledged: Vec<Acknowledgment>,
}

/// Compute the canonical signature of a finding.
///
/// Format: `<finding_type>:<service>:<sanitized_endpoint>:<sha256-prefix-of-template>`.
/// The `sha256` prefix uses the first 16 bytes (32 hex characters), giving
/// ~128 bits of collision resistance. The triple
/// `(finding_type, service, sanitized_endpoint)` is already part of the
/// signature, so the hash only needs to disambiguate templates within the
/// same triple, an extremely small population in practice. The 32-char
/// prefix is defense in depth against accidental ack masking after a SQL
/// refactor or a service rename.
///
/// Sanitization replaces `/` and ` ` (space) inside `source_endpoint`
/// with `_` so the resulting signature uses `:` as a single, unambiguous
/// separator that operators can split on in shell pipelines. `BiDi`
/// override and invisible-format characters (Trojan Source, CVE-2021-42574)
/// are stripped from both `service` and `source_endpoint` so two visually
/// identical signatures cannot map to distinct ack entries.
#[must_use]
pub fn compute_signature(finding: &Finding) -> String {
    let mut hasher = Sha256::new();
    hasher.update(finding.pattern.template.as_bytes());
    let digest = hasher.finalize();
    let safe_service = crate::text_safety::strip_bidi_and_invisible(&finding.service);
    let sanitized_endpoint = sanitize_endpoint(&finding.source_endpoint);
    let safe_endpoint = crate::text_safety::strip_bidi_and_invisible(&sanitized_endpoint);
    let kind = finding.finding_type.as_str();
    // Pre-size: type + 2 separators + service + endpoint + ':' + 32 hex.
    let mut out = String::with_capacity(kind.len() + safe_service.len() + safe_endpoint.len() + 35);
    out.push_str(kind);
    out.push(':');
    out.push_str(safe_service.as_ref());
    out.push(':');
    out.push_str(safe_endpoint.as_ref());
    out.push(':');
    for byte in &digest[..16] {
        let _ = write!(out, "{byte:02x}");
    }
    out
}

fn sanitize_endpoint(endpoint: &str) -> Cow<'_, str> {
    if endpoint.bytes().any(|b| matches!(b, b'/' | b' ')) {
        Cow::Owned(endpoint.replace(['/', ' '], "_"))
    } else {
        Cow::Borrowed(endpoint)
    }
}

/// Fill in the `signature` field of every finding in place.
///
/// Idempotent: an existing signature is overwritten so re-running this
/// function on a baseline that already carries signatures (e.g. a
/// pre-0.5.17 dump that was just re-emitted) keeps the values fresh
/// against the current signature scheme.
pub fn enrich_with_signatures(findings: &mut [Finding]) {
    for finding in findings.iter_mut() {
        finding.signature = compute_signature(finding);
    }
}

/// Load acknowledgments from a TOML file.
///
/// Returns `Ok(default)` when the file does not exist, so a project
/// without any acks observes the legacy behavior with zero error noise.
/// Returns `Err` on TOML parse failure or on a malformed `expires_at`
/// date so a typo in the ack file fails the run loud rather than
/// silently widening the matched set.
///
/// Reads with a hard cap of [`MAX_ACKNOWLEDGMENTS_FILE_BYTES`]. The TOML
/// crate has no public depth limiter, but the size cap keeps the worst
/// case bounded and rejects `/dev/zero` and the like.
///
/// # Errors
///
/// - [`AcknowledgmentLoadError::Io`] when the file exists but cannot be read.
/// - [`AcknowledgmentLoadError::TooLarge`] when the file exceeds the cap.
/// - [`AcknowledgmentLoadError::Parse`] when the TOML cannot be parsed.
/// - [`AcknowledgmentLoadError::InvalidDate`] when an `expires_at` value is
///   not a valid `YYYY-MM-DD` ISO 8601 date.
pub fn load_from_file(path: &Path) -> Result<AcknowledgmentsFile, AcknowledgmentLoadError> {
    // Use symlink_metadata so a symlink at the configured path does not
    // redirect the read to a sensitive file (e.g. a hostile collaborator
    // landing a symlink to /etc/passwd in a CI runner working tree). The
    // daemon JSONL store applies the same discipline at write time, this
    // mirrors it for the read-side baseline.
    match std::fs::symlink_metadata(path) {
        Ok(meta) => {
            if meta.file_type().is_symlink() {
                return Err(AcknowledgmentLoadError::SymlinkRefused);
            }
        }
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
            return Ok(AcknowledgmentsFile::default());
        }
        Err(err) => return Err(AcknowledgmentLoadError::Io(err)),
    }
    let file = std::fs::File::open(path).map_err(AcknowledgmentLoadError::Io)?;
    // `take(cap + 1)` closes the TOCTOU window between metadata().len()
    // and read(): we read at most cap+1 bytes, and reject if we hit the
    // cap+1th byte. Same pattern as `read_file_capped` in the CLI.
    let mut buf = String::new();
    file.take(MAX_ACKNOWLEDGMENTS_FILE_BYTES + 1)
        .read_to_string(&mut buf)
        .map_err(AcknowledgmentLoadError::Io)?;
    if buf.len() as u64 > MAX_ACKNOWLEDGMENTS_FILE_BYTES {
        return Err(AcknowledgmentLoadError::TooLarge {
            cap: MAX_ACKNOWLEDGMENTS_FILE_BYTES,
        });
    }
    let parsed: AcknowledgmentsFile =
        toml::from_str(&buf).map_err(AcknowledgmentLoadError::Parse)?;

    for (idx, ack) in parsed.acknowledged.iter().enumerate() {
        if let Some(ref expires) = ack.expires_at {
            NaiveDate::parse_from_str(expires, "%Y-%m-%d").map_err(|e| {
                AcknowledgmentLoadError::InvalidDate {
                    entry_index: idx,
                    field: "expires_at",
                    value: expires.clone(),
                    message: e.to_string(),
                }
            })?;
        }
    }

    Ok(parsed)
}

/// Apply acknowledgments to a `Report` in place.
///
/// 1. Clears any prior `report.acknowledged_findings` so a Report fed
///    back through this function (e.g. a baseline JSON round-trip)
///    cannot accumulate stale ack pairs across runs.
/// 2. Filters `report.findings`, moving acked entries into
///    `report.acknowledged_findings`.
/// 3. Re-evaluates the quality gate on the surviving set so an ack can
///    flip a previously failing gate to green (the entire point of
///    "won't fix / accepted" semantics). Re-evaluation runs even when no
///    ack matched, so the gate field is always self-consistent with the
///    final `findings` slice.
///
/// Acks with an `expires_at` strictly before `now` are treated as inactive
/// and the corresponding finding is preserved in `report.findings`.
///
/// `origin` gates the unmatched-ack warnings: they are only derivable
/// from a fresh analysis. A pre-computed report may already be
/// ack-filtered, so an entry matching nothing there means "consumed on
/// the previous pass", not "fixed", and its `per_endpoint_io_ops` (empty
/// on daemon snapshots) describes another run entirely.
pub fn apply_to_report(
    report: &mut Report,
    acks: &AcknowledgmentsFile,
    config: &Config,
    now: DateTime<Utc>,
    origin: ReportOrigin,
) {
    // Drop any prior ack pairs from the source Report. The caller may
    // have loaded a baseline that already carried `acknowledged_findings`
    // from a previous `--show-acknowledged` run, which we do not want to
    // double-count or treat as authoritative.
    report.acknowledged_findings.clear();
    // Same reasoning for the warnings this function owns: a baseline
    // loaded from a previous run may already carry them.
    report
        .warning_details
        .retain(|w| w.kind != warnings::UNMATCHED_ACKNOWLEDGMENT);

    let active: HashMap<&str, &Acknowledgment> = acks
        .acknowledged
        .iter()
        .filter(|a| is_ack_active(a, now))
        .map(|a| (a.signature.as_str(), a))
        .collect();

    if !active.is_empty() {
        let mut matched: HashSet<&str> = HashSet::with_capacity(active.len());
        let original = std::mem::take(&mut report.findings);
        let mut kept = Vec::with_capacity(original.len());
        for finding in original {
            let sig: Cow<'_, str> = if finding.signature.is_empty() {
                Cow::Owned(compute_signature(&finding))
            } else {
                Cow::Borrowed(finding.signature.as_str())
            };
            if let Some((ack_sig, ack)) = active.get_key_value(sig.as_ref()) {
                matched.insert(ack_sig);
                report.acknowledged_findings.push(AcknowledgedFinding {
                    finding,
                    acknowledgment: (*ack).clone(),
                });
            } else {
                kept.push(finding);
            }
        }
        report.findings = kept;

        // An ack that suppressed nothing is the "maybe fixed" signal.
        // Sorted so two runs of the same report stay diffable.
        if origin == ReportOrigin::FreshAnalysis {
            let mut unmatched: Vec<&Acknowledgment> = active
                .values()
                .filter(|a| !matched.contains(a.signature.as_str()))
                .copied()
                .collect();
            unmatched.sort_unstable_by(|a, b| a.signature.cmp(&b.signature));
            let observed: HashSet<(&str, &str)> = report
                .per_endpoint_io_ops
                .iter()
                .map(|e| (e.service.as_str(), e.endpoint.as_str()))
                .collect();
            let new_warnings: Vec<Warning> = unmatched
                .iter()
                .map(|ack| {
                    Warning::from_untrusted(
                        warnings::UNMATCHED_ACKNOWLEDGMENT,
                        &unmatched_message(ack, &observed),
                    )
                })
                .collect();
            report.warning_details.extend(new_warnings);
        }
    }

    report.quality_gate = quality_gate::evaluate(
        &report.findings,
        &report.green_summary,
        &config.thresholds,
        report.analysis.ingest.as_ref(),
    );
}

/// Message for an active ack that suppressed nothing. When the entry
/// names its service and endpoint, the run's per-endpoint I/O ops say
/// whether that endpoint did I/O, which splits "fixed" from "scenario
/// did not run". The counts only hold endpoints that emitted I/O spans,
/// so absence stays ambiguous (not exercised, or a fix that removed the
/// I/O outright) and the message says so. Entries without the fields
/// keep the indeterminate double reading.
fn unmatched_message(ack: &Acknowledgment, observed: &HashSet<(&str, &str)>) -> String {
    let sig = &ack.signature;
    match (&ack.service, &ack.source_endpoint) {
        (Some(service), Some(endpoint)) => {
            if observed.contains(&(service.as_str(), endpoint.as_str())) {
                format!(
                    "acknowledgment {sig} matched no finding in this run: \
                     {service} {endpoint} was exercised and the finding did not \
                     fire, the problem looks fixed and the entry can be removed"
                )
            } else {
                format!(
                    "acknowledgment {sig} matched no finding in this run: \
                     {service} {endpoint} emitted no I/O in this run (not \
                     exercised, or its I/O was removed outright), so this \
                     proves nothing, keep the entry"
                )
            }
        }
        _ => format!(
            "acknowledgment {sig} matched no finding in this run: \
             the problem is either fixed, and the entry can be removed, \
             or the scenario that produced it did not run (add service and \
             source_endpoint to the entry to tell the two apart)"
        ),
    }
}

pub(crate) fn is_ack_active(ack: &Acknowledgment, now: DateTime<Utc>) -> bool {
    let Some(ref expires) = ack.expires_at else {
        return true;
    };
    let Ok(parsed) = NaiveDate::parse_from_str(expires, "%Y-%m-%d") else {
        // Malformed dates are rejected at load time; defensively treat a
        // bad value as inactive rather than ack-everything.
        return false;
    };
    // Treat the entire expiry day as still valid: an ack `expires_at =
    // 2026-12-31` is honored through 2026-12-31 23:59:59 UTC.
    let Some(end_of_day) = parsed.and_hms_opt(23, 59, 59) else {
        return false;
    };
    end_of_day.and_utc() >= now
}

/// Errors that can occur when loading the acknowledgments file.
#[derive(Debug, thiserror::Error)]
pub enum AcknowledgmentLoadError {
    #[error("Failed to read acknowledgments file: {0}")]
    Io(#[from] std::io::Error),

    #[error("Acknowledgments file exceeds the {cap}-byte cap")]
    TooLarge { cap: u64 },

    #[error("Failed to parse acknowledgments TOML: {0}")]
    Parse(toml::de::Error),

    #[error("Entry {entry_index}: invalid {field} value '{value}': {message}")]
    InvalidDate {
        entry_index: usize,
        field: &'static str,
        value: String,
        message: String,
    },

    #[error("Acknowledgments file is a symlink, refusing to follow")]
    SymlinkRefused,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::detect::{FindingType, Severity};
    use crate::report::{Analysis, GreenSummary, QualityGate};
    use crate::test_helpers::make_finding;
    use chrono::TimeZone;
    use core::assert_matches;

    fn empty_report(findings: Vec<Finding>) -> Report {
        Report {
            analysis: Analysis {
                duration_ms: 0,
                events_processed: findings.len(),
                traces_analyzed: 1,
                ingest: None,
            },
            findings,
            green_summary: GreenSummary::disabled(0),
            quality_gate: QualityGate {
                passed: true,
                rules: vec![],
            },
            per_endpoint_io_ops: vec![],
            correlations: vec![],
            embedded_traces: vec![],
            warnings: vec![],
            warning_details: vec![],
            acknowledged_findings: vec![],
            binary_version: String::new(),
            detection_config: None,
            disclosure_waste: None,
        }
    }

    fn ack(signature: &str, expires_at: Option<&str>) -> Acknowledgment {
        Acknowledgment {
            signature: signature.to_string(),
            acknowledged_by: "test@example.com".to_string(),
            acknowledged_at: "2026-05-02".to_string(),
            reason: "test".to_string(),
            expires_at: expires_at.map(str::to_string),
            service: None,
            source_endpoint: None,
        }
    }

    fn now_2026_05_02() -> DateTime<Utc> {
        Utc.with_ymd_and_hms(2026, 5, 2, 12, 0, 0).unwrap()
    }

    #[test]
    fn compute_signature_deterministic() {
        let f = make_finding(FindingType::NPlusOneSql, Severity::Warning);
        let sig1 = compute_signature(&f);
        let sig2 = compute_signature(&f);
        assert_eq!(sig1, sig2);
    }

    #[test]
    fn compute_signature_differs_with_template() {
        let mut f1 = make_finding(FindingType::NPlusOneSql, Severity::Warning);
        let mut f2 = f1.clone();
        f1.pattern.template = "SELECT * FROM users WHERE id = ?".to_string();
        f2.pattern.template = "SELECT * FROM orders WHERE id = ?".to_string();
        assert_ne!(compute_signature(&f1), compute_signature(&f2));
    }

    #[test]
    fn compute_signature_sanitizes_endpoint() {
        let mut f = make_finding(FindingType::NPlusOneSql, Severity::Warning);
        f.source_endpoint = "GET /api/foo bar".to_string();
        let sig = compute_signature(&f);
        let parts: Vec<&str> = sig.split(':').collect();
        assert_eq!(
            parts.len(),
            4,
            "signature must have 4 colon-separated parts: {sig}"
        );
        assert!(
            !parts[2].contains('/'),
            "endpoint segment must not contain '/'"
        );
        assert!(
            !parts[2].contains(' '),
            "endpoint segment must not contain ' '"
        );
    }

    #[test]
    fn compute_signature_strips_bidi_and_invisible_from_service_and_endpoint() {
        // service "alice<RLO>@evil.com" should produce the same signature as
        // "alice@evil.com" so a hostile span attribute cannot fork ack matching.
        let mut f1 = make_finding(FindingType::NPlusOneSql, Severity::Warning);
        let mut f2 = f1.clone();
        f1.service = "alice\u{202E}@evil.com".to_string();
        f1.source_endpoint = "GET /api/items\u{200B}".to_string();
        f2.service = "alice@evil.com".to_string();
        f2.source_endpoint = "GET /api/items".to_string();
        assert_eq!(
            compute_signature(&f1),
            compute_signature(&f2),
            "BiDi/invisible characters must be stripped before signature construction"
        );
    }

    #[test]
    fn compute_signature_format_matches_brief() {
        let mut f = make_finding(FindingType::RedundantSql, Severity::Warning);
        f.service = "order-service".to_string();
        f.source_endpoint = "POST /api/orders".to_string();
        f.pattern.template = "SELECT 1".to_string();
        let sig = compute_signature(&f);
        // Format: redundant_sql:order-service:POST_/api/orders → after sanitization
        // POST_/api/orders becomes POST__api_orders.
        let mut parts = sig.splitn(4, ':');
        assert_eq!(parts.next(), Some("redundant_sql"));
        assert_eq!(parts.next(), Some("order-service"));
        assert_eq!(parts.next(), Some("POST__api_orders"));
        let hex = parts.next().expect("hex prefix present");
        assert_eq!(hex.len(), 32, "hex prefix is 32 characters (16 bytes)");
        assert!(
            hex.chars().all(|c| c.is_ascii_hexdigit()),
            "hex prefix is hex"
        );
    }

    #[test]
    fn signature_stable_across_trace_id_changes() {
        // Core ack contract: a service restart produces new trace_id and
        // span_id values, but the same finding type on the same service /
        // endpoint / template must yield the same signature. Without this
        // invariant, ack entries silently stop matching after a restart.
        let mut f1 = make_finding(FindingType::NPlusOneSql, Severity::Warning);
        let mut f2 = f1.clone();
        f1.trace_id = "aaaaaaaaaaaaaaaa0000000000000000".to_string();
        f2.trace_id = "ffffffffffffffff1111111111111111".to_string();
        assert_ne!(f1.trace_id, f2.trace_id);
        assert_eq!(
            compute_signature(&f1),
            compute_signature(&f2),
            "signature must not depend on trace_id (acks survive service restarts)"
        );
    }

    #[test]
    fn compute_signature_differs_with_endpoint() {
        let mut f1 = make_finding(FindingType::NPlusOneSql, Severity::Warning);
        let mut f2 = f1.clone();
        f1.source_endpoint = "POST /api/orders".to_string();
        f2.source_endpoint = "POST /api/users".to_string();
        assert_ne!(compute_signature(&f1), compute_signature(&f2));
    }

    #[test]
    fn compute_signature_differs_with_service() {
        let mut f1 = make_finding(FindingType::NPlusOneSql, Severity::Warning);
        let mut f2 = f1.clone();
        f1.service = "order-svc".to_string();
        f2.service = "user-svc".to_string();
        assert_ne!(compute_signature(&f1), compute_signature(&f2));
    }

    #[test]
    fn compute_signature_differs_with_finding_type() {
        let f1 = make_finding(FindingType::NPlusOneSql, Severity::Warning);
        let f2 = make_finding(FindingType::RedundantSql, Severity::Warning);
        assert_ne!(compute_signature(&f1), compute_signature(&f2));
    }

    #[test]
    fn load_from_file_rejects_oversized_input() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("acks.toml");
        let payload = vec![b'x'; (MAX_ACKNOWLEDGMENTS_FILE_BYTES + 1) as usize];
        std::fs::write(&path, &payload).unwrap();
        let err = load_from_file(&path).expect_err("oversized file must fail");
        assert!(
            matches!(err, AcknowledgmentLoadError::TooLarge { .. }),
            "expected TooLarge, got: {err:?}"
        );
    }

    #[test]
    fn apply_to_report_clears_prior_acked_entries() {
        // Simulate a Report fed back from a previous --show-acknowledged
        // run: it carries one stale ack pair. Applying a fresh empty
        // ack file must drop the stale pair, the gate is re-evaluated,
        // and findings are unchanged.
        let stale_finding = make_finding(FindingType::SlowSql, Severity::Warning);
        let stale_ack = Acknowledgment {
            signature: "stale".to_string(),
            acknowledged_by: "stale@example.com".to_string(),
            acknowledged_at: "2020-01-01".to_string(),
            reason: "from a previous run".to_string(),
            expires_at: None,
            service: None,
            source_endpoint: None,
        };
        let mut findings = vec![make_finding(FindingType::NPlusOneSql, Severity::Warning)];
        enrich_with_signatures(&mut findings);
        let mut report = empty_report(findings);
        report.acknowledged_findings.push(AcknowledgedFinding {
            finding: stale_finding,
            acknowledgment: stale_ack,
        });
        let acks = AcknowledgmentsFile::default();
        let config = Config::default();
        apply_to_report(
            &mut report,
            &acks,
            &config,
            now_2026_05_02(),
            ReportOrigin::FreshAnalysis,
        );
        assert!(
            report.acknowledged_findings.is_empty(),
            "stale ack pair must be cleared on entry"
        );
        assert_eq!(report.findings.len(), 1, "active findings preserved");
    }

    #[test]
    fn load_from_file_nonexistent_returns_empty() {
        let path = std::path::PathBuf::from("/tmp/perf-sentinel-acks-does-not-exist.toml");
        let result = load_from_file(&path).expect("missing file should be Ok");
        assert!(result.acknowledged.is_empty());
    }

    #[test]
    fn load_from_file_valid_parses() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("acks.toml");
        std::fs::write(
            &path,
            r#"
[[acknowledged]]
signature = "n_plus_one_sql:svc:GET_/a:abcd1234abcd1234abcd1234abcd1234"
acknowledged_by = "alice@example.com"
acknowledged_at = "2026-04-15"
reason = "documented"

[[acknowledged]]
signature = "redundant_sql:svc:POST_/b:11223344112233441122334411223344"
acknowledged_by = "bob@example.com"
acknowledged_at = "2026-04-20"
reason = "won't fix"
expires_at = "2026-12-31"
"#,
        )
        .unwrap();
        let parsed = load_from_file(&path).expect("valid TOML parses");
        assert_eq!(parsed.acknowledged.len(), 2);
        assert_eq!(parsed.acknowledged[0].acknowledged_by, "alice@example.com");
        assert_eq!(
            parsed.acknowledged[1].expires_at.as_deref(),
            Some("2026-12-31")
        );
    }

    #[test]
    fn load_from_file_missing_signature_field_fails() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("acks.toml");
        std::fs::write(
            &path,
            r#"
[[acknowledged]]
acknowledged_by = "alice@example.com"
acknowledged_at = "2026-04-15"
reason = "missing signature"
"#,
        )
        .unwrap();
        let err = load_from_file(&path).expect_err("missing field must fail");
        assert_matches!(err, AcknowledgmentLoadError::Parse(_));
    }

    #[test]
    fn load_from_file_invalid_expires_at_fails() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("acks.toml");
        std::fs::write(
            &path,
            r#"
[[acknowledged]]
signature = "redundant_sql:svc:POST_/b:11223344112233441122334411223344"
acknowledged_by = "alice@example.com"
acknowledged_at = "2026-04-15"
reason = "bad date"
expires_at = "not-a-date"
"#,
        )
        .unwrap();
        let err = load_from_file(&path).expect_err("invalid date must fail");
        assert_matches!(
            err,
            AcknowledgmentLoadError::InvalidDate {
                field: "expires_at",
                ..
            }
        );
    }

    #[test]
    fn apply_to_report_filters_matching() {
        let mut findings = vec![
            make_finding(FindingType::NPlusOneSql, Severity::Warning),
            make_finding(FindingType::RedundantSql, Severity::Warning),
            make_finding(FindingType::SlowSql, Severity::Warning),
        ];
        // Distinguish the templates so signatures differ.
        findings[0].pattern.template = "T1".to_string();
        findings[1].pattern.template = "T2".to_string();
        findings[2].pattern.template = "T3".to_string();
        enrich_with_signatures(&mut findings);
        let target_sig = findings[1].signature.clone();
        let mut report = empty_report(findings);
        let acks = AcknowledgmentsFile {
            acknowledged: vec![ack(&target_sig, None)],
        };
        let config = Config::default();
        apply_to_report(
            &mut report,
            &acks,
            &config,
            now_2026_05_02(),
            ReportOrigin::FreshAnalysis,
        );
        assert_eq!(report.findings.len(), 2);
        assert_eq!(report.acknowledged_findings.len(), 1);
        assert_eq!(
            report.acknowledged_findings[0].finding.signature,
            target_sig
        );
    }

    #[test]
    fn apply_to_report_no_match_keeps_all() {
        let mut findings = vec![make_finding(FindingType::NPlusOneSql, Severity::Warning)];
        enrich_with_signatures(&mut findings);
        let mut report = empty_report(findings);
        let acks = AcknowledgmentsFile {
            acknowledged: vec![ack(
                "n_plus_one_sql:nope:nope:00000000000000000000000000000000",
                None,
            )],
        };
        let config = Config::default();
        apply_to_report(
            &mut report,
            &acks,
            &config,
            now_2026_05_02(),
            ReportOrigin::FreshAnalysis,
        );
        assert_eq!(report.findings.len(), 1);
        assert!(report.acknowledged_findings.is_empty());
    }

    #[test]
    fn apply_to_report_expired_ack_ignored() {
        let mut findings = vec![make_finding(FindingType::NPlusOneSql, Severity::Warning)];
        enrich_with_signatures(&mut findings);
        let target_sig = findings[0].signature.clone();
        let mut report = empty_report(findings);
        let acks = AcknowledgmentsFile {
            acknowledged: vec![ack(&target_sig, Some("2020-01-01"))],
        };
        let config = Config::default();
        apply_to_report(
            &mut report,
            &acks,
            &config,
            now_2026_05_02(),
            ReportOrigin::FreshAnalysis,
        );
        assert_eq!(report.findings.len(), 1);
        assert!(report.acknowledged_findings.is_empty());
    }

    /// The signal a fix produces: the entry is still active, nothing in
    /// the run carries its signature, so it is reported as removable.
    #[test]
    fn apply_to_report_reports_an_ack_that_matched_nothing() {
        let mut findings = vec![make_finding(FindingType::NPlusOneSql, Severity::Warning)];
        enrich_with_signatures(&mut findings);
        let mut report = empty_report(findings);
        let acks = AcknowledgmentsFile {
            acknowledged: vec![ack("deadbeef", None)],
        };
        apply_to_report(
            &mut report,
            &acks,
            &Config::default(),
            now_2026_05_02(),
            ReportOrigin::FreshAnalysis,
        );

        assert_eq!(report.findings.len(), 1, "the unrelated finding survives");
        let unmatched: Vec<&Warning> = report
            .warning_details
            .iter()
            .filter(|w| w.kind == warnings::UNMATCHED_ACKNOWLEDGMENT)
            .collect();
        assert_eq!(unmatched.len(), 1);
        assert!(
            unmatched[0].message.contains("deadbeef"),
            "the warning must name the entry to remove, got: {}",
            unmatched[0].message
        );
    }

    /// A pre-computed report may already be ack-filtered and its I/O op
    /// counts describe another run, so no unmatched warning may be derived
    /// from it, not even the indeterminate one.
    #[test]
    fn apply_to_report_precomputed_origin_emits_no_unmatched_warning() {
        let mut report = empty_report(vec![]);
        report.per_endpoint_io_ops = vec![crate::report::PerEndpointIoOps {
            service: "order-service".to_string(),
            endpoint: "GET /api/orders".to_string(),
            io_ops: 12,
        }];
        let acks = AcknowledgmentsFile {
            acknowledged: vec![Acknowledgment {
                service: Some("order-service".to_string()),
                source_endpoint: Some("GET /api/orders".to_string()),
                ..ack("deadbeef", None)
            }],
        };
        apply_to_report(
            &mut report,
            &acks,
            &Config::default(),
            now_2026_05_02(),
            ReportOrigin::Precomputed,
        );
        assert!(
            !report
                .warning_details
                .iter()
                .any(|w| w.kind == warnings::UNMATCHED_ACKNOWLEDGMENT),
            "a precomputed report must not claim anything, got: {:?}",
            report.warning_details
        );
    }

    /// With service and endpoint on the entry, an exercised endpoint that
    /// produced no finding reads as fixed, an absent one proves nothing.
    #[test]
    fn apply_to_report_unmatched_ack_splits_fixed_from_not_run() {
        let mut findings = vec![make_finding(FindingType::NPlusOneSql, Severity::Warning)];
        enrich_with_signatures(&mut findings);
        let mut report = empty_report(findings);
        report.per_endpoint_io_ops = vec![crate::report::PerEndpointIoOps {
            service: "order-service".to_string(),
            endpoint: "GET /api/orders".to_string(),
            io_ops: 12,
        }];
        let located = |sig: &str, endpoint: &str| Acknowledgment {
            service: Some("order-service".to_string()),
            source_endpoint: Some(endpoint.to_string()),
            ..ack(sig, None)
        };
        let acks = AcknowledgmentsFile {
            acknowledged: vec![
                located("aaaa-exercised", "GET /api/orders"),
                located("bbbb-not-run", "GET /api/legacy/export"),
            ],
        };
        apply_to_report(
            &mut report,
            &acks,
            &Config::default(),
            now_2026_05_02(),
            ReportOrigin::FreshAnalysis,
        );

        let messages: Vec<&str> = report
            .warning_details
            .iter()
            .filter(|w| w.kind == warnings::UNMATCHED_ACKNOWLEDGMENT)
            .map(|w| w.message.as_str())
            .collect();
        assert_eq!(messages.len(), 2);
        assert!(
            messages[0].contains("aaaa-exercised") && messages[0].contains("looks fixed"),
            "exercised endpoint must read as fixed, got: {}",
            messages[0]
        );
        assert!(
            messages[1].contains("bbbb-not-run") && messages[1].contains("proves nothing"),
            "absent endpoint must prove nothing, got: {}",
            messages[1]
        );
    }

    /// An ack doing its job is not noise, and an expired one is inactive,
    /// so neither may be reported as removable.
    #[test]
    fn apply_to_report_does_not_report_matched_or_expired_acks() {
        let mut findings = vec![make_finding(FindingType::NPlusOneSql, Severity::Warning)];
        enrich_with_signatures(&mut findings);
        let target_sig = findings[0].signature.clone();
        let mut report = empty_report(findings);
        let acks = AcknowledgmentsFile {
            acknowledged: vec![
                ack(&target_sig, None),
                ack("expired-and-unmatched", Some("2020-01-01")),
            ],
        };
        apply_to_report(
            &mut report,
            &acks,
            &Config::default(),
            now_2026_05_02(),
            ReportOrigin::FreshAnalysis,
        );

        assert_eq!(report.acknowledged_findings.len(), 1);
        assert!(
            !report
                .warning_details
                .iter()
                .any(|w| w.kind == warnings::UNMATCHED_ACKNOWLEDGMENT),
            "got: {:?}",
            report.warning_details
        );
    }

    /// Re-applying over a baseline that already carries the warnings must
    /// not stack them, the same reason ack pairs are cleared on entry.
    #[test]
    fn apply_to_report_does_not_accumulate_unmatched_warnings() {
        let mut report = empty_report(vec![]);
        let acks = AcknowledgmentsFile {
            acknowledged: vec![ack("deadbeef", None)],
        };
        let config = Config::default();
        apply_to_report(
            &mut report,
            &acks,
            &config,
            now_2026_05_02(),
            ReportOrigin::FreshAnalysis,
        );
        apply_to_report(
            &mut report,
            &acks,
            &config,
            now_2026_05_02(),
            ReportOrigin::FreshAnalysis,
        );

        assert_eq!(
            report
                .warning_details
                .iter()
                .filter(|w| w.kind == warnings::UNMATCHED_ACKNOWLEDGMENT)
                .count(),
            1
        );
    }

    #[test]
    fn apply_to_report_future_ack_applied() {
        let mut findings = vec![make_finding(FindingType::NPlusOneSql, Severity::Warning)];
        enrich_with_signatures(&mut findings);
        let target_sig = findings[0].signature.clone();
        let mut report = empty_report(findings);
        let acks = AcknowledgmentsFile {
            acknowledged: vec![ack(&target_sig, Some("2030-01-01"))],
        };
        let config = Config::default();
        apply_to_report(
            &mut report,
            &acks,
            &config,
            now_2026_05_02(),
            ReportOrigin::FreshAnalysis,
        );
        assert!(report.findings.is_empty());
        assert_eq!(report.acknowledged_findings.len(), 1);
    }

    #[test]
    fn apply_to_report_no_expires_at_permanent() {
        let mut findings = vec![make_finding(FindingType::NPlusOneSql, Severity::Warning)];
        enrich_with_signatures(&mut findings);
        let target_sig = findings[0].signature.clone();
        let mut report = empty_report(findings);
        let acks = AcknowledgmentsFile {
            acknowledged: vec![ack(&target_sig, None)],
        };
        let config = Config::default();
        apply_to_report(
            &mut report,
            &acks,
            &config,
            now_2026_05_02(),
            ReportOrigin::FreshAnalysis,
        );
        assert_eq!(report.acknowledged_findings.len(), 1);
    }

    #[test]
    fn apply_to_report_reevaluates_quality_gate() {
        // 1 critical N+1 SQL finding, default config has
        // n_plus_one_sql_critical_max = 0, so the gate fails before the
        // ack and must pass after.
        let mut findings = vec![make_finding(FindingType::NPlusOneSql, Severity::Critical)];
        enrich_with_signatures(&mut findings);
        let target_sig = findings[0].signature.clone();
        let config = Config::default();
        let pre_gate = quality_gate::evaluate(
            &findings,
            &GreenSummary::disabled(0),
            &config.thresholds,
            None,
        );
        assert!(!pre_gate.passed, "baseline gate must fail before ack");

        let mut report = empty_report(findings);
        report.quality_gate = pre_gate;
        let acks = AcknowledgmentsFile {
            acknowledged: vec![ack(&target_sig, None)],
        };
        apply_to_report(
            &mut report,
            &acks,
            &config,
            now_2026_05_02(),
            ReportOrigin::FreshAnalysis,
        );
        assert!(
            report.quality_gate.passed,
            "gate must flip green after the offending finding is acked"
        );
    }

    #[test]
    fn enrich_with_signatures_overwrites() {
        let mut findings = vec![
            make_finding(FindingType::NPlusOneSql, Severity::Warning),
            make_finding(FindingType::RedundantSql, Severity::Warning),
        ];
        // Simulate stale signatures (e.g. computed under an older scheme).
        findings[0].signature = "stale".to_string();
        findings[1].signature = "also-stale".to_string();
        enrich_with_signatures(&mut findings);
        assert_ne!(findings[0].signature, "stale");
        assert_ne!(findings[1].signature, "also-stale");
        assert!(!findings[0].signature.is_empty());
        assert!(!findings[1].signature.is_empty());
    }
}