policy-rs 1.5.0

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

use std::collections::HashMap;
use std::ffi::CString;
use std::ptr;
use std::sync::Arc;

use crate::Policy;
use crate::error::PolicyError;
use crate::field::{LogFieldSelector, MetricFieldSelector, TraceFieldSelector};
use crate::proto::tero::policy::v1::{
    AggregationTemporality, LogField, LogMatcher, LogSampleKey, MetricField, MetricMatcher,
    MetricType, SamplingMode, SpanKind, SpanStatusCode, TraceField, TraceMatcher,
    TraceSamplingConfig, log_matcher, log_sample_key, metric_matcher, trace_matcher,
};
use crate::registry::PolicyStats;

use super::keep::CompiledKeep;
use super::match_key::MatchKey;
use super::signal::{LogSignal, MetricSignal, Signal, TraceSignal};
use super::transform::CompiledTransform;

/// Reference from a pattern match back to its policy.
#[derive(Debug, Clone)]
pub struct PolicyMatchRef {
    /// Index into CompiledMatchers::policies.
    pub policy_index: usize,
}

/// The compiled sampling mode for trace evaluation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompiledSamplingMode {
    /// Hash trace ID with seed for deterministic sampling.
    HashSeed,
    /// Adjust threshold relative to incoming probability (tracestate `th`).
    Proportional,
    /// Equalize sampling across sources with different incoming probabilities.
    Equalizing,
}

/// Compiled trace sampling configuration.
///
/// Stores precomputed values from `TraceSamplingConfig` for efficient
/// evaluation using the OTel consistent probability sampling algorithm.
#[derive(Debug, Clone)]
pub struct CompiledTraceSampling {
    /// Precomputed 56-bit rejection threshold.
    pub threshold: u64,
    /// Original probability (0.0-1.0) for result reporting.
    pub probability: f64,
    /// Number of hex digits for threshold encoding (1-14, default 4).
    pub precision: u32,
    /// If true, reject spans when randomness extraction fails.
    pub fail_closed: bool,
    /// Sampling mode.
    pub mode: CompiledSamplingMode,
    /// Hash seed for HASH_SEED mode (combined with trace ID for deterministic sampling).
    pub hash_seed: u32,
}

/// A compiled policy ready for evaluation.
#[derive(Debug)]
pub struct CompiledPolicy<S: Signal> {
    /// Policy ID.
    pub id: String,
    /// Number of matchers that must match for this policy to apply.
    pub required_match_count: usize,
    /// The keep action for this policy.
    pub keep: CompiledKeep,
    /// The transform to apply when this policy matches (if any).
    pub transform: Option<CompiledTransform<S>>,
    /// Statistics for this policy.
    pub stats: Arc<PolicyStats>,
    /// Whether this policy is enabled.
    pub enabled: bool,
    /// Optional sample key for consistent hash-based sampling.
    pub sample_key: Option<S::FieldSelector>,
    /// Trace sampling configuration (only set for trace policies).
    pub trace_sampling: Option<CompiledTraceSampling>,
}

/// Existence check that can't be handled by Vectorscan.
#[derive(Debug, Clone)]
pub struct ExistenceCheck<S: Signal> {
    /// Index into CompiledMatchers::policies.
    pub policy_index: usize,
    /// The field to check.
    pub field: S::FieldSelector,
    /// Whether the field should exist.
    pub should_exist: bool,
    /// Whether this is a negated matcher.
    pub is_negated: bool,
}

/// Pattern info for building Vectorscan databases.
#[derive(Debug)]
pub struct PatternInfo {
    /// The regex pattern.
    pub pattern: String,
    /// Index into the policies vector.
    pub policy_index: usize,
    /// Whether the pattern should be matched case-insensitively.
    pub case_insensitive: bool,
}

/// A compiled Vectorscan database with scratch space.
pub struct VectorscanDatabase {
    db: *mut vectorscan_rs_sys::hs_database_t,
    scratch: *mut vectorscan_rs_sys::hs_scratch_t,
}

// Safety: The database and scratch pointers are thread-safe for reads.
// Each thread should have its own scratch space for scanning, but we
// clone scratch for each scan operation.
unsafe impl Send for VectorscanDatabase {}
unsafe impl Sync for VectorscanDatabase {}

impl VectorscanDatabase {
    /// Compile patterns into a Vectorscan database.
    fn compile(patterns: &[String], ids: &[u32], flags: &[u32]) -> Result<Self, PolicyError> {
        assert_eq!(patterns.len(), ids.len());
        assert_eq!(patterns.len(), flags.len());

        if patterns.is_empty() {
            return Err(PolicyError::CompileError {
                reason: "no patterns to compile".to_string(),
            });
        }

        let c_patterns: Vec<CString> = patterns
            .iter()
            .map(|p| {
                CString::new(p.as_str()).map_err(|e| PolicyError::CompileError {
                    reason: format!("invalid pattern string: {}", e),
                })
            })
            .collect::<Result<Vec<_>, _>>()?;

        let pattern_ptrs: Vec<*const std::ffi::c_char> =
            c_patterns.iter().map(|s| s.as_ptr()).collect();

        let mut db: *mut vectorscan_rs_sys::hs_database_t = ptr::null_mut();
        let mut compile_error: *mut vectorscan_rs_sys::hs_compile_error_t = ptr::null_mut();

        let result = unsafe {
            vectorscan_rs_sys::hs_compile_multi(
                pattern_ptrs.as_ptr(),
                flags.as_ptr(),
                ids.as_ptr(),
                patterns.len() as u32,
                vectorscan_rs_sys::HS_MODE_BLOCK,
                ptr::null(),
                &mut db,
                &mut compile_error,
            )
        };

        if result != vectorscan_rs_sys::HS_SUCCESS as i32 {
            let error_msg = if !compile_error.is_null() {
                let msg = unsafe {
                    let msg_ptr = (*compile_error).message;
                    if msg_ptr.is_null() {
                        "unknown error".to_string()
                    } else {
                        std::ffi::CStr::from_ptr(msg_ptr)
                            .to_string_lossy()
                            .into_owned()
                    }
                };
                unsafe {
                    vectorscan_rs_sys::hs_free_compile_error(compile_error);
                }
                msg
            } else {
                format!("compile failed with code {}", result)
            };

            return Err(PolicyError::CompileError {
                reason: format!("failed to compile Vectorscan database: {}", error_msg),
            });
        }

        let mut scratch: *mut vectorscan_rs_sys::hs_scratch_t = ptr::null_mut();
        let result = unsafe { vectorscan_rs_sys::hs_alloc_scratch(db, &mut scratch) };

        if result != vectorscan_rs_sys::HS_SUCCESS as i32 {
            unsafe {
                vectorscan_rs_sys::hs_free_database(db);
            }
            return Err(PolicyError::CompileError {
                reason: format!("failed to allocate scratch space: code {}", result),
            });
        }

        Ok(VectorscanDatabase { db, scratch })
    }

    /// Scan data and return the pattern IDs that matched.
    pub fn scan(&self, data: &[u8]) -> Result<Vec<u32>, PolicyError> {
        let matches = std::cell::RefCell::new(Vec::new());

        let mut scan_scratch: *mut vectorscan_rs_sys::hs_scratch_t = ptr::null_mut();
        let result =
            unsafe { vectorscan_rs_sys::hs_clone_scratch(self.scratch, &mut scan_scratch) };

        if result != vectorscan_rs_sys::HS_SUCCESS as i32 {
            return Err(PolicyError::CompileError {
                reason: format!("failed to clone scratch space: code {}", result),
            });
        }

        unsafe extern "C" fn on_match(
            id: std::ffi::c_uint,
            _from: std::ffi::c_ulonglong,
            _to: std::ffi::c_ulonglong,
            _flags: std::ffi::c_uint,
            context: *mut std::ffi::c_void,
        ) -> std::ffi::c_int {
            unsafe {
                let matches = &*(context as *const std::cell::RefCell<Vec<u32>>);
                matches.borrow_mut().push(id);
            }
            0
        }

        let result = unsafe {
            vectorscan_rs_sys::hs_scan(
                self.db,
                data.as_ptr() as *const std::ffi::c_char,
                data.len() as u32,
                0,
                scan_scratch,
                Some(on_match),
                &matches as *const _ as *mut std::ffi::c_void,
            )
        };

        unsafe {
            vectorscan_rs_sys::hs_free_scratch(scan_scratch);
        }

        if result != vectorscan_rs_sys::HS_SUCCESS as i32
            && result != vectorscan_rs_sys::HS_SCAN_TERMINATED
        {
            return Err(PolicyError::CompileError {
                reason: format!("scan failed with code {}", result),
            });
        }

        Ok(matches.into_inner())
    }
}

impl Drop for VectorscanDatabase {
    fn drop(&mut self) {
        unsafe {
            if !self.scratch.is_null() {
                vectorscan_rs_sys::hs_free_scratch(self.scratch);
            }
            if !self.db.is_null() {
                vectorscan_rs_sys::hs_free_database(self.db);
            }
        }
    }
}

/// A compiled Vectorscan database with its pattern index.
pub struct CompiledDatabase {
    /// The Vectorscan database.
    pub database: VectorscanDatabase,
    /// Maps pattern_id to policy reference.
    pub pattern_index: Vec<PolicyMatchRef>,
}

impl std::fmt::Debug for CompiledDatabase {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CompiledDatabase")
            .field("pattern_count", &self.pattern_index.len())
            .finish()
    }
}

/// Compiled matchers ready for evaluation.
#[derive(Debug)]
pub struct CompiledMatchers<S: Signal> {
    /// Hyperscan databases keyed by (field, negated).
    pub databases: HashMap<MatchKey<S>, CompiledDatabase>,
    /// Existence checks that can't be compiled to Hyperscan.
    pub existence_checks: Vec<ExistenceCheck<S>>,
    /// Compiled policies indexed by position.
    pub policies: Vec<CompiledPolicy<S>>,
}

impl CompiledMatchers<LogSignal> {
    /// Build compiled matchers from a list of log policies.
    pub fn build(
        policies: impl Iterator<Item = (Policy, Arc<PolicyStats>)>,
    ) -> Result<Self, PolicyError> {
        let groups = PatternGroups::<LogSignal>::build_from_log_policies(policies)?;
        groups.compile()
    }
}

impl CompiledMatchers<MetricSignal> {
    /// Build compiled matchers from a list of metric policies.
    pub fn build(
        policies: impl Iterator<Item = (Policy, Arc<PolicyStats>)>,
    ) -> Result<Self, PolicyError> {
        let groups = PatternGroups::<MetricSignal>::build_from_metric_policies(policies)?;
        groups.compile()
    }
}

impl CompiledMatchers<TraceSignal> {
    /// Build compiled matchers from a list of trace policies.
    pub fn build(
        policies: impl Iterator<Item = (Policy, Arc<PolicyStats>)>,
    ) -> Result<Self, PolicyError> {
        let groups = PatternGroups::<TraceSignal>::build_from_trace_policies(policies)?;
        groups.compile()
    }
}

/// Grouped patterns ready for Hyperscan compilation.
#[derive(Debug)]
pub struct PatternGroups<S: Signal> {
    /// Patterns grouped by match key.
    pub groups: HashMap<MatchKey<S>, Vec<PatternInfo>>,
    /// Existence checks that can't be compiled to Hyperscan.
    pub existence_checks: Vec<ExistenceCheck<S>>,
    /// Compiled policies.
    pub policies: Vec<CompiledPolicy<S>>,
}

impl<S: Signal> Default for PatternGroups<S> {
    fn default() -> Self {
        Self {
            groups: HashMap::new(),
            existence_checks: Vec::new(),
            policies: Vec::new(),
        }
    }
}

impl PatternGroups<LogSignal> {
    /// Build pattern groups from a list of log policies.
    pub fn build_from_log_policies(
        policies: impl Iterator<Item = (Policy, Arc<PolicyStats>)>,
    ) -> Result<Self, PolicyError> {
        let mut result = PatternGroups::default();

        for (policy_index, (policy, stats)) in policies.enumerate() {
            let log_target = match policy.log_target() {
                Some(t) => t,
                None => continue,
            };

            let required_match_count = log_target.r#match.iter().filter(|m| !m.negate).count();

            let transform = log_target
                .transform
                .as_ref()
                .map(CompiledTransform::from_proto)
                .filter(|t| !t.is_empty());

            let sample_key = log_target
                .sample_key
                .as_ref()
                .and_then(extract_log_sample_key);

            result.policies.push(CompiledPolicy {
                id: policy.id().to_string(),
                required_match_count,
                keep: CompiledKeep::parse(&log_target.keep)?,
                transform,
                stats,
                enabled: policy.enabled(),
                sample_key,
                trace_sampling: None,
            });

            for matcher in &log_target.r#match {
                let field = extract_log_field(matcher)?;
                let is_negated = matcher.negate;
                let case_insensitive = matcher.case_insensitive;

                process_match_type(
                    matcher.r#match.as_ref(),
                    field,
                    is_negated,
                    case_insensitive,
                    policy_index,
                    &mut result.groups,
                    &mut result.existence_checks,
                );
            }
        }

        Ok(result)
    }
}

impl PatternGroups<MetricSignal> {
    /// Build pattern groups from a list of metric policies.
    pub fn build_from_metric_policies(
        policies: impl Iterator<Item = (Policy, Arc<PolicyStats>)>,
    ) -> Result<Self, PolicyError> {
        let mut result = PatternGroups::default();

        for (policy_index, (policy, stats)) in policies.enumerate() {
            let metric_target = match policy.metric_target() {
                Some(t) => t,
                None => continue,
            };

            let required_match_count = metric_target.r#match.iter().filter(|m| !m.negate).count();

            let keep = if metric_target.keep {
                CompiledKeep::All
            } else {
                CompiledKeep::None
            };

            result.policies.push(CompiledPolicy {
                id: policy.id().to_string(),
                required_match_count,
                keep,
                transform: None,
                stats,
                enabled: policy.enabled(),
                sample_key: None,
                trace_sampling: None,
            });

            for matcher in &metric_target.r#match {
                let is_negated = matcher.negate;
                let case_insensitive = matcher.case_insensitive;

                let extraction = extract_metric_field(matcher)?;

                // Use synthesized match for enum fields, otherwise use the matcher's match.
                let match_type = extraction
                    .synthesized_match
                    .as_ref()
                    .or(matcher.r#match.as_ref());

                process_match_type(
                    match_type,
                    extraction.field,
                    is_negated,
                    case_insensitive,
                    policy_index,
                    &mut result.groups,
                    &mut result.existence_checks,
                );
            }
        }

        Ok(result)
    }
}

impl PatternGroups<TraceSignal> {
    /// Build pattern groups from a list of trace policies.
    pub fn build_from_trace_policies(
        policies: impl Iterator<Item = (Policy, Arc<PolicyStats>)>,
    ) -> Result<Self, PolicyError> {
        let mut result = PatternGroups::default();

        for (policy_index, (policy, stats)) in policies.enumerate() {
            let trace_target = match policy.trace_target() {
                Some(t) => t,
                None => continue,
            };

            let required_match_count = trace_target.r#match.iter().filter(|m| !m.negate).count();

            let keep = compile_trace_keep(trace_target.keep.as_ref());
            let trace_sampling = compile_trace_sampling(trace_target.keep.as_ref());

            result.policies.push(CompiledPolicy {
                id: policy.id().to_string(),
                required_match_count,
                keep,
                transform: None,
                stats,
                enabled: policy.enabled(),
                sample_key: None,
                trace_sampling: Some(trace_sampling),
            });

            for matcher in &trace_target.r#match {
                let is_negated = matcher.negate;
                let case_insensitive = matcher.case_insensitive;

                let extraction = extract_trace_field(matcher)?;

                let match_type = extraction
                    .synthesized_match
                    .as_ref()
                    .or(matcher.r#match.as_ref());

                process_match_type(
                    match_type,
                    extraction.field,
                    is_negated,
                    case_insensitive,
                    policy_index,
                    &mut result.groups,
                    &mut result.existence_checks,
                );
            }
        }

        Ok(result)
    }
}

impl<S: Signal> PatternGroups<S> {
    /// Compile pattern groups into Vectorscan databases.
    pub fn compile(self) -> Result<CompiledMatchers<S>, PolicyError> {
        let mut databases = HashMap::new();

        for (key, patterns) in self.groups {
            if patterns.is_empty() {
                continue;
            }

            let mut pattern_strings = Vec::with_capacity(patterns.len());
            let mut pattern_ids = Vec::with_capacity(patterns.len());
            let mut pattern_flags = Vec::with_capacity(patterns.len());
            let mut pattern_index = Vec::with_capacity(patterns.len());

            for (pattern_id, info) in patterns.into_iter().enumerate() {
                pattern_strings.push(info.pattern);
                pattern_ids.push(pattern_id as u32);
                let mut flags = vectorscan_rs_sys::HS_FLAG_SINGLEMATCH;
                if info.case_insensitive {
                    flags |= vectorscan_rs_sys::HS_FLAG_CASELESS;
                }
                pattern_flags.push(flags);
                pattern_index.push(PolicyMatchRef {
                    policy_index: info.policy_index,
                });
            }

            let database =
                VectorscanDatabase::compile(&pattern_strings, &pattern_ids, &pattern_flags)?;

            databases.insert(
                key,
                CompiledDatabase {
                    database,
                    pattern_index,
                },
            );
        }

        Ok(CompiledMatchers {
            databases,
            existence_checks: self.existence_checks,
            policies: self.policies,
        })
    }
}

// =============================================================================
// Shared match type processing
// =============================================================================

/// Process a match type and add the pattern or existence check.
///
/// This is shared across log and metric matchers since the match oneof
/// (exact, regex, exists, starts_with, ends_with, contains) is structurally
/// identical across signal types.
fn process_match_type<S: Signal, M>(
    match_type: Option<&M>,
    field: S::FieldSelector,
    is_negated: bool,
    case_insensitive: bool,
    policy_index: usize,
    groups: &mut HashMap<MatchKey<S>, Vec<PatternInfo>>,
    existence_checks: &mut Vec<ExistenceCheck<S>>,
) where
    M: MatchTypeAccessor,
{
    let Some(m) = match_type else { return };

    match m.as_match_variant() {
        MatchVariant::Exact(s) => {
            let pattern = format!("^{}$", regex_escape(s));
            let key = MatchKey::new(field, is_negated);
            groups.entry(key).or_default().push(PatternInfo {
                pattern,
                policy_index,
                case_insensitive,
            });
        }
        MatchVariant::Regex(pattern) => {
            let key = MatchKey::new(field, is_negated);
            groups.entry(key).or_default().push(PatternInfo {
                pattern: pattern.to_string(),
                policy_index,
                case_insensitive,
            });
        }
        MatchVariant::Exists(should_exist) => {
            existence_checks.push(ExistenceCheck {
                policy_index,
                field,
                should_exist,
                is_negated,
            });
        }
        MatchVariant::StartsWith(s) => {
            let pattern = format!("^{}", regex_escape(s));
            let key = MatchKey::new(field, is_negated);
            groups.entry(key).or_default().push(PatternInfo {
                pattern,
                policy_index,
                case_insensitive,
            });
        }
        MatchVariant::EndsWith(s) => {
            let pattern = format!("{}$", regex_escape(s));
            let key = MatchKey::new(field, is_negated);
            groups.entry(key).or_default().push(PatternInfo {
                pattern,
                policy_index,
                case_insensitive,
            });
        }
        MatchVariant::Contains(s) => {
            let pattern = regex_escape(s);
            let key = MatchKey::new(field, is_negated);
            groups.entry(key).or_default().push(PatternInfo {
                pattern,
                policy_index,
                case_insensitive,
            });
        }
    }
}

/// Unified view of match variants across signal-specific match oneofs.
enum MatchVariant<'a> {
    Exact(&'a str),
    Regex(&'a str),
    Exists(bool),
    StartsWith(&'a str),
    EndsWith(&'a str),
    Contains(&'a str),
}

/// Trait for converting signal-specific match oneofs to MatchVariant.
trait MatchTypeAccessor {
    fn as_match_variant(&self) -> MatchVariant<'_>;
}

impl MatchTypeAccessor for log_matcher::Match {
    fn as_match_variant(&self) -> MatchVariant<'_> {
        match self {
            log_matcher::Match::Exact(s) => MatchVariant::Exact(s),
            log_matcher::Match::Regex(s) => MatchVariant::Regex(s),
            log_matcher::Match::Exists(b) => MatchVariant::Exists(*b),
            log_matcher::Match::StartsWith(s) => MatchVariant::StartsWith(s),
            log_matcher::Match::EndsWith(s) => MatchVariant::EndsWith(s),
            log_matcher::Match::Contains(s) => MatchVariant::Contains(s),
        }
    }
}

impl MatchTypeAccessor for metric_matcher::Match {
    fn as_match_variant(&self) -> MatchVariant<'_> {
        match self {
            metric_matcher::Match::Exact(s) => MatchVariant::Exact(s),
            metric_matcher::Match::Regex(s) => MatchVariant::Regex(s),
            metric_matcher::Match::Exists(b) => MatchVariant::Exists(*b),
            metric_matcher::Match::StartsWith(s) => MatchVariant::StartsWith(s),
            metric_matcher::Match::EndsWith(s) => MatchVariant::EndsWith(s),
            metric_matcher::Match::Contains(s) => MatchVariant::Contains(s),
        }
    }
}

impl MatchTypeAccessor for trace_matcher::Match {
    fn as_match_variant(&self) -> MatchVariant<'_> {
        match self {
            trace_matcher::Match::Exact(s) => MatchVariant::Exact(s),
            trace_matcher::Match::Regex(s) => MatchVariant::Regex(s),
            trace_matcher::Match::Exists(b) => MatchVariant::Exists(*b),
            trace_matcher::Match::StartsWith(s) => MatchVariant::StartsWith(s),
            trace_matcher::Match::EndsWith(s) => MatchVariant::EndsWith(s),
            trace_matcher::Match::Contains(s) => MatchVariant::Contains(s),
        }
    }
}

// =============================================================================
// Log-specific field extraction
// =============================================================================

/// Extract the field selector from a log matcher.
fn extract_log_field(matcher: &LogMatcher) -> Result<LogFieldSelector, PolicyError> {
    match &matcher.field {
        Some(log_matcher::Field::LogField(f)) => {
            let field = LogField::try_from(*f).unwrap_or(LogField::Unspecified);
            Ok(LogFieldSelector::Simple(field))
        }
        Some(log_matcher::Field::LogAttribute(path)) => {
            Ok(LogFieldSelector::from_log_attribute(path))
        }
        Some(log_matcher::Field::ResourceAttribute(path)) => {
            Ok(LogFieldSelector::from_resource_attribute(path))
        }
        Some(log_matcher::Field::ScopeAttribute(path)) => {
            Ok(LogFieldSelector::from_scope_attribute(path))
        }
        None => Err(PolicyError::FieldError {
            reason: "matcher has no field specified".to_string(),
        }),
    }
}

/// Extract the field selector from a log sample key.
fn extract_log_sample_key(sample_key: &LogSampleKey) -> Option<LogFieldSelector> {
    match &sample_key.field {
        Some(log_sample_key::Field::LogField(f)) => {
            let field = LogField::try_from(*f).unwrap_or(LogField::Unspecified);
            Some(LogFieldSelector::Simple(field))
        }
        Some(log_sample_key::Field::LogAttribute(path)) => {
            Some(LogFieldSelector::from_log_attribute(path))
        }
        Some(log_sample_key::Field::ResourceAttribute(path)) => {
            Some(LogFieldSelector::from_resource_attribute(path))
        }
        Some(log_sample_key::Field::ScopeAttribute(path)) => {
            Some(LogFieldSelector::from_scope_attribute(path))
        }
        None => None,
    }
}

// =============================================================================
// Metric-specific field extraction
// =============================================================================

/// Extracted metric field info.
///
/// For enum fields (metric_type, aggregation_temporality), the field itself
/// carries the enum value. We extract a unit field selector (`Type` or
/// `Temporality`) and synthesize an exact-match pattern on the enum's
/// string name. This lets all metric_type matchers share a single Vectorscan
/// database key.
struct MetricFieldExtraction {
    field: MetricFieldSelector,
    /// If set, overrides the matcher's match oneof with a synthesized exact match.
    synthesized_match: Option<metric_matcher::Match>,
}

fn extract_metric_field(matcher: &MetricMatcher) -> Result<MetricFieldExtraction, PolicyError> {
    match &matcher.field {
        Some(metric_matcher::Field::MetricField(f)) => {
            let field = MetricField::try_from(*f).unwrap_or(MetricField::Unspecified);
            Ok(MetricFieldExtraction {
                field: MetricFieldSelector::Simple(field),
                synthesized_match: None,
            })
        }
        Some(metric_matcher::Field::DatapointAttribute(path)) => Ok(MetricFieldExtraction {
            field: MetricFieldSelector::from_datapoint_attribute(path),
            synthesized_match: None,
        }),
        Some(metric_matcher::Field::ResourceAttribute(path)) => Ok(MetricFieldExtraction {
            field: MetricFieldSelector::from_resource_attribute(path),
            synthesized_match: None,
        }),
        Some(metric_matcher::Field::ScopeAttribute(path)) => Ok(MetricFieldExtraction {
            field: MetricFieldSelector::from_scope_attribute(path),
            synthesized_match: None,
        }),
        Some(metric_matcher::Field::MetricType(t)) => {
            let metric_type = MetricType::try_from(*t).unwrap_or(MetricType::Unspecified);
            Ok(MetricFieldExtraction {
                field: MetricFieldSelector::Type,
                synthesized_match: Some(metric_matcher::Match::Exact(
                    metric_type.as_str_name().to_string(),
                )),
            })
        }
        Some(metric_matcher::Field::AggregationTemporality(t)) => {
            let temporality =
                AggregationTemporality::try_from(*t).unwrap_or(AggregationTemporality::Unspecified);
            Ok(MetricFieldExtraction {
                field: MetricFieldSelector::Temporality,
                synthesized_match: Some(metric_matcher::Match::Exact(
                    temporality.as_str_name().to_string(),
                )),
            })
        }
        None => Err(PolicyError::FieldError {
            reason: "matcher has no field specified".to_string(),
        }),
    }
}

// =============================================================================
// Trace-specific field extraction and compilation
// =============================================================================

/// Extracted trace field info.
///
/// For enum fields (span_kind, span_status) and string-value fields
/// (event_name, link_trace_id), the extraction produces a unit field selector
/// and a synthesized exact-match pattern on the value's string representation.
struct TraceFieldExtraction {
    field: TraceFieldSelector,
    synthesized_match: Option<trace_matcher::Match>,
}

fn extract_trace_field(matcher: &TraceMatcher) -> Result<TraceFieldExtraction, PolicyError> {
    match &matcher.field {
        Some(trace_matcher::Field::TraceField(f)) => {
            let field = TraceField::try_from(*f).unwrap_or(TraceField::Unspecified);
            Ok(TraceFieldExtraction {
                field: TraceFieldSelector::Simple(field),
                synthesized_match: None,
            })
        }
        Some(trace_matcher::Field::SpanAttribute(path)) => Ok(TraceFieldExtraction {
            field: TraceFieldSelector::from_span_attribute(path),
            synthesized_match: None,
        }),
        Some(trace_matcher::Field::ResourceAttribute(path)) => Ok(TraceFieldExtraction {
            field: TraceFieldSelector::from_resource_attribute(path),
            synthesized_match: None,
        }),
        Some(trace_matcher::Field::ScopeAttribute(path)) => Ok(TraceFieldExtraction {
            field: TraceFieldSelector::from_scope_attribute(path),
            synthesized_match: None,
        }),
        Some(trace_matcher::Field::SpanKind(k)) => {
            let kind = SpanKind::try_from(*k).unwrap_or(SpanKind::Unspecified);
            Ok(TraceFieldExtraction {
                field: TraceFieldSelector::SpanKind,
                synthesized_match: Some(trace_matcher::Match::Exact(
                    kind.as_str_name().to_string(),
                )),
            })
        }
        Some(trace_matcher::Field::SpanStatus(s)) => {
            let status = SpanStatusCode::try_from(*s).unwrap_or(SpanStatusCode::Unspecified);
            Ok(TraceFieldExtraction {
                field: TraceFieldSelector::SpanStatus,
                synthesized_match: Some(trace_matcher::Match::Exact(
                    status.as_str_name().to_string(),
                )),
            })
        }
        Some(trace_matcher::Field::EventName(name)) => Ok(TraceFieldExtraction {
            field: TraceFieldSelector::EventName,
            synthesized_match: Some(trace_matcher::Match::Exact(name.clone())),
        }),
        Some(trace_matcher::Field::EventAttribute(path)) => Ok(TraceFieldExtraction {
            field: TraceFieldSelector::from_event_attribute(path),
            synthesized_match: None,
        }),
        Some(trace_matcher::Field::LinkTraceId(id)) => Ok(TraceFieldExtraction {
            field: TraceFieldSelector::LinkTraceId,
            synthesized_match: Some(trace_matcher::Match::Exact(id.clone())),
        }),
        None => Err(PolicyError::FieldError {
            reason: "matcher has no field specified".to_string(),
        }),
    }
}

/// Compile trace keep from sampling config.
///
/// Maps `TraceSamplingConfig` percentage to a `CompiledKeep` variant for the
/// standard keep/drop evaluation path.
fn compile_trace_keep(config: Option<&TraceSamplingConfig>) -> CompiledKeep {
    match config {
        None => CompiledKeep::All,
        Some(c) if c.percentage >= 100.0 => CompiledKeep::All,
        Some(c) if c.percentage <= 0.0 => CompiledKeep::None,
        Some(c) => CompiledKeep::Percentage(c.percentage as f64 / 100.0),
    }
}

/// Compile trace sampling metadata from sampling config.
///
/// Produces a `CompiledTraceSampling` with precomputed 56-bit rejection
/// threshold and encoding parameters for tracestate propagation.
fn compile_trace_sampling(config: Option<&TraceSamplingConfig>) -> CompiledTraceSampling {
    match config {
        None => CompiledTraceSampling {
            threshold: 0,
            probability: 1.0,
            precision: 4,
            fail_closed: true,
            mode: CompiledSamplingMode::HashSeed,
            hash_seed: 0,
        },
        Some(c) => {
            let probability = (c.percentage as f64 / 100.0).clamp(0.0, 1.0);
            let precision = c.sampling_precision.unwrap_or(4).clamp(1, 14);
            let mode = match c.mode.and_then(|m| SamplingMode::try_from(m).ok()) {
                Some(SamplingMode::Proportional) => CompiledSamplingMode::Proportional,
                Some(SamplingMode::Equalizing) => CompiledSamplingMode::Equalizing,
                // HashSeed, Unspecified, or None all default to HashSeed
                _ => CompiledSamplingMode::HashSeed,
            };
            CompiledTraceSampling {
                threshold: super::rejection_threshold(probability),
                probability,
                precision,
                fail_closed: c.fail_closed.unwrap_or(true),
                mode,
                hash_seed: c.hash_seed.unwrap_or(0),
            }
        }
    }
}

/// Escape special regex characters in a string.
fn regex_escape(s: &str) -> String {
    let mut result = String::with_capacity(s.len() * 2);
    for c in s.chars() {
        match c {
            '\\' | '.' | '+' | '*' | '?' | '(' | ')' | '[' | ']' | '{' | '}' | '^' | '$' | '|' => {
                result.push('\\');
                result.push(c);
            }
            _ => result.push(c),
        }
    }
    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::proto::tero::policy::v1::{
        LogAdd, LogRedact, LogTarget, LogTransform, Policy as ProtoPolicy, log_add, log_redact,
    };

    fn make_policy_with_matcher(
        id: &str,
        field: log_matcher::Field,
        match_type: log_matcher::Match,
        negate: bool,
        keep: &str,
    ) -> Policy {
        let matcher = LogMatcher {
            field: Some(field),
            r#match: Some(match_type),
            negate,
            case_insensitive: false,
        };

        let log_target = LogTarget {
            r#match: vec![matcher],
            keep: keep.to_string(),
            transform: None,
            sample_key: None,
        };

        let proto = ProtoPolicy {
            id: id.to_string(),
            name: id.to_string(),
            enabled: true,
            target: Some(crate::proto::tero::policy::v1::policy::Target::Log(
                log_target,
            )),
            ..Default::default()
        };

        Policy::new(proto)
    }

    fn attr_path(key: &str) -> crate::proto::tero::policy::v1::AttributePath {
        crate::proto::tero::policy::v1::AttributePath {
            path: vec![key.to_string()],
        }
    }

    #[test]
    fn build_pattern_groups_regex() {
        let policy = make_policy_with_matcher(
            "test",
            log_matcher::Field::LogField(LogField::Body.into()),
            log_matcher::Match::Regex("error.*".to_string()),
            false,
            "none",
        );

        let stats = Arc::new(PolicyStats::default());
        let groups = PatternGroups::build_from_log_policies([(policy, stats)].into_iter()).unwrap();

        assert_eq!(groups.policies.len(), 1);
        assert_eq!(groups.policies[0].id, "test");
        assert_eq!(groups.groups.len(), 1);

        let key = MatchKey::new(LogFieldSelector::Simple(LogField::Body), false);
        let patterns = groups.groups.get(&key).unwrap();
        assert_eq!(patterns.len(), 1);
        assert_eq!(patterns[0].pattern, "error.*");
    }

    #[test]
    fn build_pattern_groups_exact() {
        let policy = make_policy_with_matcher(
            "test",
            log_matcher::Field::LogField(LogField::SeverityText.into()),
            log_matcher::Match::Exact("ERROR".to_string()),
            false,
            "all",
        );

        let stats = Arc::new(PolicyStats::default());
        let groups = PatternGroups::build_from_log_policies([(policy, stats)].into_iter()).unwrap();

        let key = MatchKey::new(LogFieldSelector::Simple(LogField::SeverityText), false);
        let patterns = groups.groups.get(&key).unwrap();
        assert_eq!(patterns[0].pattern, "^ERROR$");
    }

    #[test]
    fn build_pattern_groups_negated() {
        let policy = make_policy_with_matcher(
            "test",
            log_matcher::Field::LogField(LogField::Body.into()),
            log_matcher::Match::Regex("debug".to_string()),
            true,
            "none",
        );

        let stats = Arc::new(PolicyStats::default());
        let groups = PatternGroups::build_from_log_policies([(policy, stats)].into_iter()).unwrap();

        let key = MatchKey::new(LogFieldSelector::Simple(LogField::Body), true);
        assert!(groups.groups.contains_key(&key));
    }

    #[test]
    fn build_pattern_groups_existence() {
        let policy = make_policy_with_matcher(
            "test",
            log_matcher::Field::LogAttribute(attr_path("trace_id")),
            log_matcher::Match::Exists(true),
            false,
            "all",
        );

        let stats = Arc::new(PolicyStats::default());
        let groups = PatternGroups::build_from_log_policies([(policy, stats)].into_iter()).unwrap();

        assert!(groups.groups.is_empty());
        assert_eq!(groups.existence_checks.len(), 1);
        assert!(groups.existence_checks[0].should_exist);
    }

    #[test]
    fn regex_escape_special_chars() {
        assert_eq!(regex_escape("hello.world"), "hello\\.world");
        assert_eq!(regex_escape("test*"), "test\\*");
        assert_eq!(regex_escape("a+b"), "a\\+b");
        assert_eq!(regex_escape("(test)"), "\\(test\\)");
        assert_eq!(regex_escape("plain"), "plain");
    }

    #[test]
    fn compile_pattern_groups() {
        let policy = make_policy_with_matcher(
            "test",
            log_matcher::Field::LogField(LogField::Body.into()),
            log_matcher::Match::Regex("error".to_string()),
            false,
            "none",
        );

        let stats = Arc::new(PolicyStats::default());
        let compiled = CompiledMatchers::<LogSignal>::build([(policy, stats)].into_iter()).unwrap();

        assert_eq!(compiled.policies.len(), 1);
        assert_eq!(compiled.databases.len(), 1);

        let key = MatchKey::new(LogFieldSelector::Simple(LogField::Body), false);
        let db = compiled.databases.get(&key).unwrap();
        assert_eq!(db.pattern_index.len(), 1);
        assert_eq!(db.pattern_index[0].policy_index, 0);
    }

    #[test]
    fn compile_policy_without_transform() {
        let policy = make_policy_with_matcher(
            "test",
            log_matcher::Field::LogField(LogField::Body.into()),
            log_matcher::Match::Regex("error".to_string()),
            false,
            "none",
        );

        let stats = Arc::new(PolicyStats::default());
        let compiled = CompiledMatchers::<LogSignal>::build([(policy, stats)].into_iter()).unwrap();

        assert!(compiled.policies[0].transform.is_none());
    }

    #[test]
    fn compile_policy_with_transform() {
        let matcher = LogMatcher {
            field: Some(log_matcher::Field::LogField(LogField::Body.into())),
            r#match: Some(log_matcher::Match::Regex("error".to_string())),
            negate: false,
            case_insensitive: false,
        };

        let transform = LogTransform {
            redact: vec![LogRedact {
                field: Some(log_redact::Field::LogAttribute(attr_path("password"))),
                replacement: "[REDACTED]".to_string(),
            }],
            add: vec![LogAdd {
                field: Some(log_add::Field::LogAttribute(attr_path("processed"))),
                value: "true".to_string(),
                upsert: false,
            }],
            ..Default::default()
        };

        let log_target = LogTarget {
            r#match: vec![matcher],
            keep: "all".to_string(),
            transform: Some(transform),
            sample_key: None,
        };

        let proto = ProtoPolicy {
            id: "test".to_string(),
            name: "test".to_string(),
            enabled: true,
            target: Some(crate::proto::tero::policy::v1::policy::Target::Log(
                log_target,
            )),
            ..Default::default()
        };

        let policy = Policy::new(proto);
        let stats = Arc::new(PolicyStats::default());
        let compiled = CompiledMatchers::<LogSignal>::build([(policy, stats)].into_iter()).unwrap();

        let transform = compiled.policies[0].transform.as_ref().unwrap();
        assert_eq!(transform.ops.len(), 2);
    }

    #[test]
    fn compile_policy_with_empty_transform() {
        let matcher = LogMatcher {
            field: Some(log_matcher::Field::LogField(LogField::Body.into())),
            r#match: Some(log_matcher::Match::Regex("error".to_string())),
            negate: false,
            case_insensitive: false,
        };

        let transform = LogTransform::default();

        let log_target = LogTarget {
            r#match: vec![matcher],
            keep: "all".to_string(),
            transform: Some(transform),
            sample_key: None,
        };

        let proto = ProtoPolicy {
            id: "test".to_string(),
            name: "test".to_string(),
            enabled: true,
            target: Some(crate::proto::tero::policy::v1::policy::Target::Log(
                log_target,
            )),
            ..Default::default()
        };

        let policy = Policy::new(proto);
        let stats = Arc::new(PolicyStats::default());
        let compiled = CompiledMatchers::<LogSignal>::build([(policy, stats)].into_iter()).unwrap();

        assert!(compiled.policies[0].transform.is_none());
    }

    #[test]
    fn build_pattern_groups_starts_with() {
        let policy = make_policy_with_matcher(
            "test",
            log_matcher::Field::LogField(LogField::Body.into()),
            log_matcher::Match::StartsWith("ERROR:".to_string()),
            false,
            "none",
        );

        let stats = Arc::new(PolicyStats::default());
        let groups = PatternGroups::build_from_log_policies([(policy, stats)].into_iter()).unwrap();

        let key = MatchKey::new(LogFieldSelector::Simple(LogField::Body), false);
        let patterns = groups.groups.get(&key).unwrap();
        assert_eq!(patterns[0].pattern, "^ERROR:");
    }

    #[test]
    fn build_pattern_groups_ends_with() {
        let policy = make_policy_with_matcher(
            "test",
            log_matcher::Field::LogField(LogField::Body.into()),
            log_matcher::Match::EndsWith(".json".to_string()),
            false,
            "none",
        );

        let stats = Arc::new(PolicyStats::default());
        let groups = PatternGroups::build_from_log_policies([(policy, stats)].into_iter()).unwrap();

        let key = MatchKey::new(LogFieldSelector::Simple(LogField::Body), false);
        let patterns = groups.groups.get(&key).unwrap();
        assert_eq!(patterns[0].pattern, "\\.json$");
    }

    #[test]
    fn build_pattern_groups_contains() {
        let policy = make_policy_with_matcher(
            "test",
            log_matcher::Field::LogField(LogField::Body.into()),
            log_matcher::Match::Contains("error".to_string()),
            false,
            "none",
        );

        let stats = Arc::new(PolicyStats::default());
        let groups = PatternGroups::build_from_log_policies([(policy, stats)].into_iter()).unwrap();

        let key = MatchKey::new(LogFieldSelector::Simple(LogField::Body), false);
        let patterns = groups.groups.get(&key).unwrap();
        assert_eq!(patterns[0].pattern, "error");
    }

    #[test]
    fn build_pattern_groups_contains_special_chars() {
        let policy = make_policy_with_matcher(
            "test",
            log_matcher::Field::LogField(LogField::Body.into()),
            log_matcher::Match::Contains("file.txt".to_string()),
            false,
            "none",
        );

        let stats = Arc::new(PolicyStats::default());
        let groups = PatternGroups::build_from_log_policies([(policy, stats)].into_iter()).unwrap();

        let key = MatchKey::new(LogFieldSelector::Simple(LogField::Body), false);
        let patterns = groups.groups.get(&key).unwrap();
        assert_eq!(patterns[0].pattern, "file\\.txt");
    }

    fn make_policy_with_case_insensitive(
        id: &str,
        match_type: log_matcher::Match,
        case_insensitive: bool,
    ) -> Policy {
        let matcher = LogMatcher {
            field: Some(log_matcher::Field::LogField(LogField::Body.into())),
            r#match: Some(match_type),
            negate: false,
            case_insensitive,
        };

        let log_target = LogTarget {
            r#match: vec![matcher],
            keep: "none".to_string(),
            transform: None,
            sample_key: None,
        };

        let proto = ProtoPolicy {
            id: id.to_string(),
            name: id.to_string(),
            enabled: true,
            target: Some(crate::proto::tero::policy::v1::policy::Target::Log(
                log_target,
            )),
            ..Default::default()
        };

        Policy::new(proto)
    }

    #[test]
    fn build_pattern_groups_case_insensitive_flag() {
        let policy = make_policy_with_case_insensitive(
            "test",
            log_matcher::Match::Exact("ERROR".to_string()),
            true,
        );

        let stats = Arc::new(PolicyStats::default());
        let groups = PatternGroups::build_from_log_policies([(policy, stats)].into_iter()).unwrap();

        let key = MatchKey::new(LogFieldSelector::Simple(LogField::Body), false);
        let patterns = groups.groups.get(&key).unwrap();
        assert!(patterns[0].case_insensitive);
    }

    #[test]
    fn build_pattern_groups_case_sensitive_flag() {
        let policy = make_policy_with_case_insensitive(
            "test",
            log_matcher::Match::Exact("ERROR".to_string()),
            false,
        );

        let stats = Arc::new(PolicyStats::default());
        let groups = PatternGroups::build_from_log_policies([(policy, stats)].into_iter()).unwrap();

        let key = MatchKey::new(LogFieldSelector::Simple(LogField::Body), false);
        let patterns = groups.groups.get(&key).unwrap();
        assert!(!patterns[0].case_insensitive);
    }

    #[test]
    fn compile_case_insensitive_patterns() {
        let policy = make_policy_with_case_insensitive(
            "test",
            log_matcher::Match::Regex("error".to_string()),
            true,
        );

        let stats = Arc::new(PolicyStats::default());
        let compiled = CompiledMatchers::<LogSignal>::build([(policy, stats)].into_iter()).unwrap();

        assert_eq!(compiled.policies.len(), 1);
        assert_eq!(compiled.databases.len(), 1);
    }

    #[test]
    fn case_insensitive_exact_match_compiles() {
        let policy = make_policy_with_case_insensitive(
            "test",
            log_matcher::Match::Exact("Error".to_string()),
            true,
        );

        let stats = Arc::new(PolicyStats::default());
        let compiled = CompiledMatchers::<LogSignal>::build([(policy, stats)].into_iter()).unwrap();

        let key = MatchKey::new(LogFieldSelector::Simple(LogField::Body), false);
        let db = compiled.databases.get(&key).unwrap();

        let matches = db.database.scan(b"error").unwrap();
        assert!(!matches.is_empty(), "Should match 'error' (lowercase)");

        let matches = db.database.scan(b"ERROR").unwrap();
        assert!(!matches.is_empty(), "Should match 'ERROR' (uppercase)");

        let matches = db.database.scan(b"Error").unwrap();
        assert!(!matches.is_empty(), "Should match 'Error' (mixed case)");

        let matches = db.database.scan(b"warning").unwrap();
        assert!(matches.is_empty(), "Should not match 'warning'");
    }

    #[test]
    fn case_sensitive_exact_match_compiles() {
        let policy = make_policy_with_case_insensitive(
            "test",
            log_matcher::Match::Exact("Error".to_string()),
            false,
        );

        let stats = Arc::new(PolicyStats::default());
        let compiled = CompiledMatchers::<LogSignal>::build([(policy, stats)].into_iter()).unwrap();

        let key = MatchKey::new(LogFieldSelector::Simple(LogField::Body), false);
        let db = compiled.databases.get(&key).unwrap();

        let matches = db.database.scan(b"Error").unwrap();
        assert!(!matches.is_empty(), "Should match 'Error' (exact case)");

        let matches = db.database.scan(b"error").unwrap();
        assert!(matches.is_empty(), "Should NOT match 'error' (wrong case)");

        let matches = db.database.scan(b"ERROR").unwrap();
        assert!(matches.is_empty(), "Should NOT match 'ERROR' (wrong case)");
    }

    #[test]
    fn case_insensitive_contains_match() {
        let policy = make_policy_with_case_insensitive(
            "test",
            log_matcher::Match::Contains("error".to_string()),
            true,
        );

        let stats = Arc::new(PolicyStats::default());
        let compiled = CompiledMatchers::<LogSignal>::build([(policy, stats)].into_iter()).unwrap();

        let key = MatchKey::new(LogFieldSelector::Simple(LogField::Body), false);
        let db = compiled.databases.get(&key).unwrap();

        let matches = db.database.scan(b"This is an ERROR message").unwrap();
        assert!(!matches.is_empty(), "Should match ERROR in message");

        let matches = db.database.scan(b"This is an Error message").unwrap();
        assert!(!matches.is_empty(), "Should match Error in message");
    }

    #[test]
    fn case_insensitive_starts_with_match() {
        let policy = make_policy_with_case_insensitive(
            "test",
            log_matcher::Match::StartsWith("error".to_string()),
            true,
        );

        let stats = Arc::new(PolicyStats::default());
        let compiled = CompiledMatchers::<LogSignal>::build([(policy, stats)].into_iter()).unwrap();

        let key = MatchKey::new(LogFieldSelector::Simple(LogField::Body), false);
        let db = compiled.databases.get(&key).unwrap();

        let matches = db.database.scan(b"ERROR: something went wrong").unwrap();
        assert!(!matches.is_empty(), "Should match ERROR at start");

        let matches = db.database.scan(b"Error: something went wrong").unwrap();
        assert!(!matches.is_empty(), "Should match Error at start");

        let matches = db.database.scan(b"Something ERROR happened").unwrap();
        assert!(matches.is_empty(), "Should NOT match ERROR in middle");
    }

    #[test]
    fn case_insensitive_ends_with_match() {
        let policy = make_policy_with_case_insensitive(
            "test",
            log_matcher::Match::EndsWith(".json".to_string()),
            true,
        );

        let stats = Arc::new(PolicyStats::default());
        let compiled = CompiledMatchers::<LogSignal>::build([(policy, stats)].into_iter()).unwrap();

        let key = MatchKey::new(LogFieldSelector::Simple(LogField::Body), false);
        let db = compiled.databases.get(&key).unwrap();

        let matches = db.database.scan(b"config.JSON").unwrap();
        assert!(!matches.is_empty(), "Should match .JSON at end");

        let matches = db.database.scan(b"config.Json").unwrap();
        assert!(!matches.is_empty(), "Should match .Json at end");

        let matches = db.database.scan(b"config.json.bak").unwrap();
        assert!(matches.is_empty(), "Should NOT match .json in middle");
    }
}