sqry-core 11.0.3

Core library for sqry - semantic code search engine
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
//! Safe parsing utilities with resource limits.
//!
//! This module provides a centralized, secure parser utility that enforces
//! input size limits, parse timeouts, and supports external cancellation.
//! All language plugins should use `SafeParser` to prevent OOM vulnerabilities
//! from pathological inputs.
//!
//! # Security Background
//!
//! Tree-sitter parsers can consume unbounded memory when encountering malformed
//! input that triggers exponential backtracking in error recovery. A 103-byte
//! input can amplify to 2GB+ memory consumption (~20 millionĂ— amplification).
//!
//! # Usage
//!
//! ```ignore
//! use sqry_core::plugin::safe_parse::{SafeParser, SafeParserConfig};
//!
//! let config = SafeParserConfig::default();
//! let parser = SafeParser::new(config);
//!
//! let result = parser.parse(&language, content, Some(file_path));
//! match result {
//!     Ok(tree) => { /* use tree */ }
//!     Err(ParseError::InputTooLarge { size, max, .. }) => {
//!         log::warn!("File too large: {} bytes > {} limit", size, max);
//!     }
//!     Err(ParseError::ParseTimedOut { timeout_micros, .. }) => {
//!         log::warn!("Parse timed out after {} ms", timeout_micros / 1000);
//!     }
//!     Err(e) => { /* handle other errors */ }
//! }
//! ```

use std::ops::ControlFlow;
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;
use tree_sitter::{Language, ParseOptions, ParseState, Parser, Tree};

use super::error::ParseError;

/// Default maximum input size: 10 MiB.
///
/// This limit prevents unbounded memory allocation from large files while
/// accommodating most legitimate source files. Generated or minified code
/// may exceed this limit and require user configuration.
pub const DEFAULT_MAX_SIZE: usize = 10 * 1024 * 1024;

/// Minimum allowed size limit: 1 MiB.
///
/// Users cannot configure a limit below this threshold to ensure basic
/// functionality is preserved.
pub const MIN_MAX_SIZE: usize = 1024 * 1024;

/// Maximum allowed size limit: 32 MiB.
///
/// Users cannot configure a limit above this threshold to prevent
/// excessive memory usage from extremely large files.
pub const MAX_MAX_SIZE: usize = 32 * 1024 * 1024;

/// Default parse timeout: 2 seconds (2,000,000 microseconds).
///
/// This timeout prevents runaway parsing on pathological inputs that could
/// cause exponential backtracking. Most legitimate files parse in <100ms.
pub const DEFAULT_TIMEOUT_MICROS: u64 = 2_000_000;

/// Minimum allowed timeout: 100ms (100,000 microseconds).
///
/// Users cannot configure a timeout below this threshold as it would
/// cause false positives on normal files.
pub const MIN_TIMEOUT_MICROS: u64 = 100_000;

/// Maximum allowed timeout: 5 seconds (5,000,000 microseconds).
///
/// Users cannot configure a timeout above this threshold to ensure
/// pathological inputs are caught within reasonable time.
pub const MAX_TIMEOUT_MICROS: u64 = 5_000_000;

/// Configuration for `SafeParser` with bounded limits.
///
/// All limits are bounded to prevent users from disabling security protections.
/// Values outside the allowed range are clamped to the nearest bound.
///
/// # Bounds
///
/// - `max_input_size`: [1 MiB, 32 MiB]
/// - `timeout_micros`: [100,000 µs, 5,000,000 µs] (100ms to 5s)
///
/// # Example
///
/// ```
/// use sqry_core::plugin::safe_parse::SafeParserConfig;
///
/// // Use defaults
/// let config = SafeParserConfig::default();
/// assert_eq!(config.max_input_size(), 10 * 1024 * 1024);
/// assert_eq!(config.timeout_micros(), 2_000_000);
///
/// // Custom configuration (values are clamped to bounds)
/// let config = SafeParserConfig::new()
///     .with_max_input_size(20 * 1024 * 1024)
///     .with_timeout_micros(3_000_000);
/// ```
#[derive(Debug, Clone)]
pub struct SafeParserConfig {
    max_input_size: usize,
    timeout_micros: u64,
}

impl Default for SafeParserConfig {
    fn default() -> Self {
        Self {
            max_input_size: DEFAULT_MAX_SIZE,
            timeout_micros: DEFAULT_TIMEOUT_MICROS,
        }
    }
}

impl SafeParserConfig {
    /// Create a new configuration with default values.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set maximum input size in bytes.
    ///
    /// Value is clamped to [1 MiB, 32 MiB].
    #[must_use]
    pub fn with_max_input_size(mut self, size: usize) -> Self {
        self.max_input_size = size.clamp(MIN_MAX_SIZE, MAX_MAX_SIZE);
        self
    }

    /// Set parse timeout in microseconds.
    ///
    /// Value is clamped to [100,000 µs, 5,000,000 µs].
    #[must_use]
    pub fn with_timeout_micros(mut self, timeout: u64) -> Self {
        self.timeout_micros = timeout.clamp(MIN_TIMEOUT_MICROS, MAX_TIMEOUT_MICROS);
        self
    }

    /// Get current maximum input size.
    #[must_use]
    pub fn max_input_size(&self) -> usize {
        self.max_input_size
    }

    /// Get current timeout in microseconds.
    #[must_use]
    pub fn timeout_micros(&self) -> u64 {
        self.timeout_micros
    }
}

/// A cancellation flag for aborting long-running parse operations.
///
/// This flag uses atomic operations for thread-safe cancellation signaling.
/// The indexer can set this flag to proactively cancel parsing when needed
/// (e.g., on shutdown, file change, or resource pressure).
///
/// # Example
///
/// ```
/// use sqry_core::plugin::safe_parse::CancellationFlag;
///
/// let flag = CancellationFlag::new();
///
/// // Check if cancelled
/// assert!(!flag.is_cancelled());
///
/// // Signal cancellation
/// flag.cancel();
/// assert!(flag.is_cancelled());
///
/// // Reset for next file
/// flag.reset();
/// assert!(!flag.is_cancelled());
/// ```
#[derive(Debug, Clone, Default)]
pub struct CancellationFlag {
    cancelled: Arc<AtomicBool>,
}

impl CancellationFlag {
    /// Create a new cancellation flag (not cancelled).
    #[must_use]
    pub fn new() -> Self {
        Self {
            cancelled: Arc::new(AtomicBool::new(false)),
        }
    }

    /// Check if cancellation has been requested.
    #[must_use]
    pub fn is_cancelled(&self) -> bool {
        self.cancelled.load(Ordering::Relaxed)
    }

    /// Signal cancellation.
    pub fn cancel(&self) {
        self.cancelled.store(true, Ordering::Relaxed);
    }

    /// Reset the flag (clear cancellation).
    ///
    /// Call this between files to avoid leakage.
    pub fn reset(&self) {
        self.cancelled.store(false, Ordering::Relaxed);
    }
}

/// Internal state for tracking parse termination reason.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TerminationReason {
    /// Parse completed normally or failed for other reasons.
    None,
    /// Parse was cancelled via cancellation flag.
    Cancelled,
    /// Parse exceeded timeout.
    TimedOut,
}

/// Pure helper function for finalizing parse results with fail-closed behavior.
///
/// **SECURITY CRITICAL**: This function implements fail-closed semantics.
/// If a termination reason was triggered (timeout or cancellation), we return
/// an error regardless of whether tree-sitter produced a partial tree.
///
/// This function is extracted for deterministic testability. The parse outcome
/// decision is pure (depends only on inputs) and can be tested without
/// depending on timing or actual parsing.
///
/// # Arguments
///
/// * `termination_reason` - Why parsing terminated (`None`, `Cancelled`, `TimedOut`)
/// * `tree` - The tree-sitter result (`Some` = tree produced, `None` = no tree)
/// * `file` - Optional file path for error context
/// * `timeout_micros` - Timeout value for error reporting
///
/// # Returns
///
/// * `Ok(Tree)` only if `termination_reason` is `None` AND tree is `Some`
/// * `Err(ParseCancelled)` if `termination_reason` is `Cancelled` (regardless of tree)
/// * `Err(ParseTimedOut)` if `termination_reason` is `TimedOut` (regardless of tree)
/// * `Err(TreeSitterFailed)` if `termination_reason` is `None` but tree is `None`
fn finalize_parse_result(
    termination_reason: TerminationReason,
    tree: Option<Tree>,
    file: Option<&Path>,
    timeout_micros: u64,
) -> Result<Tree, ParseError> {
    // SECURITY: Check termination reason FIRST, before checking if tree exists.
    // Tree-sitter may return a partial tree even after timeout/cancellation.
    // We must fail-closed: if timeout or cancellation was triggered, return an error
    // regardless of whether a partial tree was produced.
    match termination_reason {
        TerminationReason::Cancelled => {
            log::warn!(
                "Parse cancelled{}",
                file.map(|f| format!(" (file: {})", f.display()))
                    .unwrap_or_default()
            );
            return Err(ParseError::ParseCancelled {
                reason: "cancelled during parsing".to_string(),
                file: file.map(Path::to_path_buf),
            });
        }
        TerminationReason::TimedOut => {
            log::warn!(
                "Parse timed out after {} ms{}",
                timeout_micros / 1000,
                file.map(|f| format!(" (file: {})", f.display()))
                    .unwrap_or_default()
            );
            return Err(ParseError::ParseTimedOut {
                timeout_micros,
                file: file.map(Path::to_path_buf),
            });
        }
        TerminationReason::None => {
            // No termination requested, proceed to check tree
        }
    }

    // If no termination was requested, check if tree-sitter produced a tree
    if let Some(t) = tree {
        Ok(t)
    } else {
        log::warn!(
            "Parse failed{}",
            file.map(|f| format!(" (file: {})", f.display()))
                .unwrap_or_default()
        );
        Err(ParseError::TreeSitterFailed)
    }
}

/// Safe parser with resource limits and cancellation support.
///
/// `SafeParser` wraps tree-sitter parsing with:
/// - Input size validation (prevents unbounded allocation)
/// - Parse timeout (prevents exponential backtracking)
/// - External cancellation (allows proactive abort)
///
/// All language plugins should use this utility instead of creating
/// parsers directly to ensure consistent security policy.
///
/// # Thread Safety
///
/// `SafeParser` is `Send + Sync` but the underlying tree-sitter `Parser`
/// is created per-call. This is intentional to avoid thread-safety issues
/// with tree-sitter's internal state.
///
/// # Example
///
/// ```ignore
/// use sqry_core::plugin::safe_parse::{SafeParser, SafeParserConfig};
/// use tree_sitter_rust::LANGUAGE;
///
/// let parser = SafeParser::new(SafeParserConfig::default());
/// let content = b"fn main() {}";
///
/// match parser.parse(&LANGUAGE.into(), content, None) {
///     Ok(tree) => println!("Parsed {} nodes", tree.root_node().child_count()),
///     Err(e) => eprintln!("Parse failed: {}", e),
/// }
/// ```
#[derive(Debug, Clone)]
pub struct SafeParser {
    config: SafeParserConfig,
    cancellation_flag: Option<CancellationFlag>,
}

impl Default for SafeParser {
    fn default() -> Self {
        Self::new(SafeParserConfig::default())
    }
}

impl SafeParser {
    /// Create a new safe parser with the given configuration.
    #[must_use]
    pub fn new(config: SafeParserConfig) -> Self {
        Self {
            config,
            cancellation_flag: None,
        }
    }

    /// Create a safe parser with default configuration.
    #[must_use]
    pub fn with_defaults() -> Self {
        Self::default()
    }

    /// Set a cancellation flag for external abort signaling.
    #[must_use]
    pub fn with_cancellation_flag(mut self, flag: CancellationFlag) -> Self {
        self.cancellation_flag = Some(flag);
        self
    }

    /// Get the current configuration.
    #[must_use]
    pub fn config(&self) -> &SafeParserConfig {
        &self.config
    }

    /// Parse source code with resource limits.
    ///
    /// # Arguments
    ///
    /// * `language` - Tree-sitter language to use
    /// * `content` - Source code as bytes (UTF-8 encoded)
    /// * `file` - Optional file path for error context
    ///
    /// # Returns
    ///
    /// Parsed tree-sitter AST on success.
    ///
    /// # Errors
    ///
    /// - `ParseError::InputTooLarge` - Input exceeds size limit
    /// - `ParseError::ParseTimedOut` - Parsing exceeded timeout
    /// - `ParseError::ParseCancelled` - Parsing was cancelled via flag
    /// - `ParseError::LanguageSetFailed` - Failed to configure parser
    /// - `ParseError::TreeSitterFailed` - Tree-sitter returned no tree
    ///
    /// # Performance
    ///
    /// Creates a new `Parser` per call. This is intentional:
    /// - Avoids thread-safety issues with tree-sitter's state
    /// - Parser creation is cheap (~1µs)
    /// - Timeout/cancellation state is per-parse
    ///
    /// # Implementation Note
    ///
    /// Uses the direct `parser.parse()` API with `set_timeout_micros()` instead of
    /// `parse_with_options()` with a chunked callback. The callback-based API has
    /// compatibility issues with some grammars (e.g., tree-sitter-groovy on multi-
    /// function files). The direct API works universally.
    ///
    /// While `set_timeout_micros` is deprecated in tree-sitter 0.25, it remains
    /// functional and provides better grammar compatibility than the callback approach.
    ///
    /// # Cancellation Limitation
    ///
    /// Mid-parse cancellation is not supported with the direct API. Cancellation is
    /// checked before and after parsing, but not during. For most source files (which
    /// parse in <100ms), this is acceptable. For very large files, the timeout provides
    /// protection.
    ///
    // DEPRECATION: We use `set_timeout_micros` because the recommended replacement,
    // `parse_with_options` (with a callback), has proven to be incompatible with
    // certain grammars (e.g., tree-sitter-groovy). This approach ensures universal
    // grammar compatibility.
    pub fn parse(
        &self,
        language: &Language,
        content: &[u8],
        file: Option<&Path>,
    ) -> Result<Tree, ParseError> {
        // Check cancellation before starting
        if let Some(ref flag) = self.cancellation_flag
            && flag.is_cancelled()
        {
            return Err(ParseError::ParseCancelled {
                reason: "cancelled before parse started".to_string(),
                file: file.map(Path::to_path_buf),
            });
        }

        // Check input size limit
        if content.len() > self.config.max_input_size {
            log::warn!(
                "Input too large: {} bytes exceeds {} limit{}",
                content.len(),
                self.config.max_input_size,
                file.map(|f| format!(" (file: {})", f.display()))
                    .unwrap_or_default()
            );
            return Err(ParseError::InputTooLarge {
                size: content.len(),
                max: self.config.max_input_size,
                file: file.map(Path::to_path_buf),
            });
        }

        // Create and configure parser
        let mut parser = Parser::new();
        parser
            .set_language(language)
            .map_err(|e| ParseError::LanguageSetFailed(e.to_string()))?;

        // Track start time for timeout enforcement
        let start_time = Instant::now();
        let timeout_micros = self.config.timeout_micros;

        // Clone the cancellation flag for use inside the progress callback.
        // The underlying AtomicBool is shared via Arc, so this is cheap.
        let cancellation_flag = self.cancellation_flag.clone();

        // Set up timeout + cancellation via progress callback (tree-sitter 0.26+).
        // set_timeout_micros was removed in tree-sitter 0.26; the progress_callback
        // is now the canonical way to abort a long-running parse.
        let mut progress_fn = move |_: &ParseState| -> ControlFlow<()> {
            if let Some(ref flag) = cancellation_flag
                && flag.is_cancelled()
            {
                return ControlFlow::Break(());
            }
            #[allow(clippy::cast_possible_truncation)]
            // u64 holds 584+ years of µs; max timeout is 5s
            if start_time.elapsed().as_micros() as u64 > timeout_micros {
                ControlFlow::Break(())
            } else {
                ControlFlow::Continue(())
            }
        };
        let options = ParseOptions::new().progress_callback(&mut progress_fn);

        // Parse with timeout/cancellation enforcement via progress callback.
        let tree = parser.parse_with_options(
            &mut |i, _| content.get(i..).unwrap_or_default(),
            None,
            Some(options),
        );

        // Determine termination reason (fail-closed semantics)
        // SECURITY: Check timeout FIRST using elapsed time, regardless of whether tree-sitter
        // produced a tree. Tree-sitter may return partial trees even after timeout.
        // We must fail-closed: if we exceeded timeout, return an error.
        #[allow(clippy::cast_possible_truncation)] // u64 holds 584+ years of µs; timeout max is 5s
        let elapsed_micros = start_time.elapsed().as_micros() as u64;
        let termination_reason = if let Some(ref flag) = self.cancellation_flag
            && flag.is_cancelled()
        {
            // Cancellation was requested (possibly during parse)
            TerminationReason::Cancelled
        } else if elapsed_micros > self.config.timeout_micros {
            // Timeout occurred - fail-closed regardless of whether tree was produced
            TerminationReason::TimedOut
        } else if tree.is_none() && elapsed_micros >= self.config.timeout_micros {
            // Edge case: tree-sitter aborted exactly at timeout boundary (returns None)
            // Treat this as timeout rather than TreeSitterFailed for accurate telemetry
            TerminationReason::TimedOut
        } else {
            TerminationReason::None
        };

        // Delegate to pure helper for fail-closed result handling
        finalize_parse_result(termination_reason, tree, file, self.config.timeout_micros)
    }

    /// Parse source code with file path context.
    ///
    /// Convenience method that always includes file path in errors.
    ///
    /// # Errors
    ///
    /// Same as [`parse`](Self::parse).
    pub fn parse_file(
        &self,
        language: &Language,
        content: &[u8],
        file: &Path,
    ) -> Result<Tree, ParseError> {
        self.parse(language, content, Some(file))
    }

    /// Log a summary of the current configuration.
    ///
    /// Call this once at startup to record active limits for incident triage.
    #[allow(clippy::cast_precision_loss)] // max_input_size <= 32 MiB, well under f64 precision limit
    pub fn log_config(&self) {
        log::info!(
            "SafeParser configured: max_size={} bytes ({:.1} MiB), timeout={} ms",
            self.config.max_input_size,
            self.config.max_input_size as f64 / (1024.0 * 1024.0),
            self.config.timeout_micros / 1000
        );
    }
}

/// Parse content using the default safe parser configuration.
///
/// This is a convenience function for simple cases. For production use,
/// prefer creating a `SafeParser` instance with explicit configuration.
///
/// # Errors
///
/// Same as [`SafeParser::parse`].
pub fn parse_safe(
    language: &Language,
    content: &[u8],
    file: Option<&Path>,
) -> Result<Tree, ParseError> {
    SafeParser::default().parse(language, content, file)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    #[test]
    fn test_config_defaults() {
        let config = SafeParserConfig::default();
        assert_eq!(config.max_input_size(), DEFAULT_MAX_SIZE);
        assert_eq!(config.timeout_micros(), DEFAULT_TIMEOUT_MICROS);
    }

    #[test]
    fn test_config_builder() {
        let config = SafeParserConfig::new()
            .with_max_input_size(20 * 1024 * 1024)
            .with_timeout_micros(3_000_000);

        assert_eq!(config.max_input_size(), 20 * 1024 * 1024);
        assert_eq!(config.timeout_micros(), 3_000_000);
    }

    #[test]
    fn test_config_clamping_min() {
        // Below minimum should clamp up
        let config = SafeParserConfig::new()
            .with_max_input_size(100) // Way below 1 MiB
            .with_timeout_micros(1000); // Way below 100ms

        assert_eq!(config.max_input_size(), MIN_MAX_SIZE);
        assert_eq!(config.timeout_micros(), MIN_TIMEOUT_MICROS);
    }

    #[test]
    fn test_config_clamping_max() {
        // Above maximum should clamp down
        let config = SafeParserConfig::new()
            .with_max_input_size(100 * 1024 * 1024) // 100 MiB > 32 MiB max
            .with_timeout_micros(10_000_000); // 10s > 5s max

        assert_eq!(config.max_input_size(), MAX_MAX_SIZE);
        assert_eq!(config.timeout_micros(), MAX_TIMEOUT_MICROS);
    }

    #[test]
    fn test_cancellation_flag() {
        let flag = CancellationFlag::new();

        assert!(!flag.is_cancelled());

        flag.cancel();
        assert!(flag.is_cancelled());

        flag.reset();
        assert!(!flag.is_cancelled());
    }

    #[test]
    fn test_cancellation_flag_clone() {
        let flag1 = CancellationFlag::new();
        let flag2 = flag1.clone();

        flag1.cancel();
        assert!(flag2.is_cancelled()); // Clone shares the same Arc
    }

    #[test]
    fn test_safe_parser_creation() {
        let parser = SafeParser::with_defaults();
        assert_eq!(parser.config().max_input_size(), DEFAULT_MAX_SIZE);
        assert_eq!(parser.config().timeout_micros(), DEFAULT_TIMEOUT_MICROS);
    }

    #[test]
    fn test_safe_parser_with_config() {
        let config = SafeParserConfig::new().with_max_input_size(5 * 1024 * 1024);
        let parser = SafeParser::new(config);

        assert_eq!(parser.config().max_input_size(), 5 * 1024 * 1024);
    }

    #[test]
    fn test_safe_parser_with_cancellation() {
        let flag = CancellationFlag::new();
        let parser = SafeParser::with_defaults().with_cancellation_flag(flag.clone());

        // Parser should have the flag
        assert!(parser.cancellation_flag.is_some());
    }

    #[test]
    fn test_input_too_large_error() {
        // Create parser with tiny limit for testing
        let config = SafeParserConfig::new().with_max_input_size(MIN_MAX_SIZE);
        let parser = SafeParser::new(config);

        // Content larger than 1 MiB
        let large_content = vec![b'x'; MIN_MAX_SIZE + 1];

        // Use a dummy language (we'll hit size check before parsing)
        let language = tree_sitter_rust::LANGUAGE.into();
        let result = parser.parse(&language, &large_content, None);

        match result {
            Err(ParseError::InputTooLarge { size, max, file }) => {
                assert_eq!(size, MIN_MAX_SIZE + 1);
                assert_eq!(max, MIN_MAX_SIZE);
                assert!(file.is_none());
            }
            _ => panic!("Expected InputTooLarge error"),
        }
    }

    #[test]
    fn test_input_too_large_with_file() {
        let config = SafeParserConfig::new().with_max_input_size(MIN_MAX_SIZE);
        let parser = SafeParser::new(config);

        let large_content = vec![b'x'; MIN_MAX_SIZE + 1];
        let file_path = PathBuf::from("/path/to/large.rs");
        let language = tree_sitter_rust::LANGUAGE.into();

        let result = parser.parse_file(&language, &large_content, &file_path);

        match result {
            Err(ParseError::InputTooLarge { file, .. }) => {
                assert_eq!(file, Some(file_path));
            }
            _ => panic!("Expected InputTooLarge error with file path"),
        }
    }

    #[test]
    fn test_cancelled_before_parse() {
        let flag = CancellationFlag::new();
        flag.cancel(); // Cancel before parsing

        let parser = SafeParser::with_defaults().with_cancellation_flag(flag);

        let content = b"fn main() {}";
        let language = tree_sitter_rust::LANGUAGE.into();
        let result = parser.parse(&language, content, None);

        match result {
            Err(ParseError::ParseCancelled { reason, .. }) => {
                assert!(reason.contains("before parse started"));
            }
            _ => panic!("Expected ParseCancelled error"),
        }
    }

    #[test]
    fn test_successful_parse() {
        let parser = SafeParser::with_defaults();
        let content = b"fn main() {}";
        let language = tree_sitter_rust::LANGUAGE.into();

        let result = parser.parse(&language, content, None);
        assert!(result.is_ok());

        let tree = result.unwrap();
        // Verify we got a valid tree by checking root node kind
        assert_eq!(tree.root_node().kind(), "source_file");
    }

    #[test]
    fn test_successful_parse_with_file() {
        let parser = SafeParser::with_defaults();
        let content = b"fn main() { let x = 42; }";
        let file_path = PathBuf::from("test.rs");
        let language = tree_sitter_rust::LANGUAGE.into();

        let result = parser.parse_file(&language, content, &file_path);
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_safe_convenience() {
        let content = b"fn foo() {}";
        let language = tree_sitter_rust::LANGUAGE.into();

        let result = parse_safe(&language, content, None);
        assert!(result.is_ok());
    }

    #[test]
    #[allow(clippy::assertions_on_constants)] // These assertions serve as documentation
    fn test_constants_sanity() {
        // Verify constant relationships
        assert!(MIN_MAX_SIZE < DEFAULT_MAX_SIZE);
        assert!(DEFAULT_MAX_SIZE < MAX_MAX_SIZE);
        assert!(MIN_TIMEOUT_MICROS < DEFAULT_TIMEOUT_MICROS);
        assert!(DEFAULT_TIMEOUT_MICROS < MAX_TIMEOUT_MICROS);

        // Verify human-friendly values
        assert_eq!(MIN_MAX_SIZE, 1024 * 1024); // 1 MiB
        assert_eq!(DEFAULT_MAX_SIZE, 10 * 1024 * 1024); // 10 MiB
        assert_eq!(MAX_MAX_SIZE, 32 * 1024 * 1024); // 32 MiB
        assert_eq!(MIN_TIMEOUT_MICROS, 100_000); // 100ms
        assert_eq!(DEFAULT_TIMEOUT_MICROS, 2_000_000); // 2s
        assert_eq!(MAX_TIMEOUT_MICROS, 5_000_000); // 5s
    }

    #[test]
    fn test_termination_reason_enum() {
        // Test that enum variants are distinct
        assert_ne!(TerminationReason::None, TerminationReason::Cancelled);
        assert_ne!(TerminationReason::None, TerminationReason::TimedOut);
        assert_ne!(TerminationReason::Cancelled, TerminationReason::TimedOut);
    }

    /// Test fail-closed behavior: timeout must return error even if tree was partially produced.
    ///
    /// This test verifies the security-critical fail-closed behavior:
    /// When a timeout is triggered during parsing, we MUST return `ParseTimedOut` error
    /// regardless of whether tree-sitter produced a partial tree.
    ///
    /// The fix for this was: check `termination_reason` BEFORE checking if a tree exists,
    /// rather than only checking `termination_reason` when `tree` is `None`.
    #[test]
    fn test_timeout_returns_error_fail_closed() {
        // Use minimum timeout (100ms) with code that might trigger timeout
        let config = SafeParserConfig::new().with_timeout_micros(MIN_TIMEOUT_MICROS);
        let parser = SafeParser::new(config);

        // Complex-ish code that might take some time to parse
        // Even if it parses faster than 100ms, this test still validates the happy path.
        // The key security guarantee is that IF the timeout triggers, we fail.
        let content = br#"
            fn complex_function() {
                let x = vec![1, 2, 3, 4, 5];
                for i in x.iter() {
                    if *i > 3 {
                        println!("{}", i);
                    }
                }
            }
        "#;

        let language = tree_sitter_rust::LANGUAGE.into();
        let result = parser.parse(&language, content, None);

        // Result should be either:
        // - Ok(tree) if parsing completed within timeout
        // - Err(ParseTimedOut) if timeout was triggered
        // The key is: it must NEVER return Ok(partial_tree) after timeout
        match result {
            Ok(_tree) => {
                // Parsing completed within timeout - that's fine
                // This test primarily documents the fail-closed requirement
            }
            Err(ParseError::ParseTimedOut { timeout_micros, .. }) => {
                // Timeout triggered - verify we got the error, not a partial tree
                assert_eq!(timeout_micros, MIN_TIMEOUT_MICROS);
            }
            Err(ParseError::TreeSitterFailed) => {
                // Callback compatibility issue - acceptable
            }
            Err(e) => {
                panic!("Unexpected error type: {e:?}");
            }
        }
    }

    /// Test fail-closed behavior with cancellation.
    ///
    /// This test verifies that when cancellation is triggered DURING parsing,
    /// we return `ParseCancelled` even if a partial tree was produced.
    #[test]
    fn test_cancellation_during_parse_fail_closed() {
        use std::thread;
        use std::time::Duration;

        let flag = CancellationFlag::new();
        let flag_clone = flag.clone();

        // Use short timeout to give cancellation time to trigger
        let config = SafeParserConfig::new().with_timeout_micros(MIN_TIMEOUT_MICROS);
        let parser = SafeParser::new(config).with_cancellation_flag(flag);

        // Spawn thread that cancels after a tiny delay
        let handle = thread::spawn(move || {
            thread::sleep(Duration::from_micros(10));
            flag_clone.cancel();
        });

        // Moderately complex code
        let content = br"
            fn foo() { let x = 1; }
            fn bar() { let y = 2; }
            fn baz() { let z = 3; }
        ";

        let language = tree_sitter_rust::LANGUAGE.into();
        let result = parser.parse(&language, content, None);

        handle.join().unwrap();

        // Result can be:
        // - Ok: parsed before cancel took effect
        // - Err(ParseCancelled): cancel triggered during parse
        // - Err(ParseTimedOut): timeout triggered
        // - Err(TreeSitterFailed): callback compatibility
        // Key: NEVER Ok(partial_tree) after cancellation was triggered
        match result {
            Ok(_)
            | Err(
                ParseError::ParseCancelled { .. }
                | ParseError::ParseTimedOut { .. }
                | ParseError::TreeSitterFailed,
            ) => {
                // All acceptable outcomes - the key is fail-closed behavior
            }
            Err(e) => {
                panic!("Unexpected error type: {e:?}");
            }
        }
    }

    // ========================================================================
    // DETERMINISTIC FAIL-CLOSED TESTS
    // These tests call finalize_parse_result directly with controlled inputs
    // to verify fail-closed behavior without depending on timing or parsing.
    // ========================================================================

    /// Helper to create a valid tree for testing `finalize_parse_result`.
    fn create_test_tree() -> Tree {
        let mut parser = tree_sitter::Parser::new();
        parser
            .set_language(&tree_sitter_rust::LANGUAGE.into())
            .unwrap();
        parser.parse(b"fn main() {}", None).unwrap()
    }

    /// DETERMINISTIC: Timeout + Some(tree) must return `ParseTimedOut` error.
    ///
    /// This is the critical fail-closed test. Even if tree-sitter produces
    /// a partial tree after timeout, we MUST return an error.
    #[test]
    fn test_finalize_timeout_with_tree_returns_error() {
        let tree = create_test_tree();
        let result =
            finalize_parse_result(TerminationReason::TimedOut, Some(tree), None, 2_000_000);

        match result {
            Err(ParseError::ParseTimedOut {
                timeout_micros,
                file,
            }) => {
                assert_eq!(timeout_micros, 2_000_000);
                assert!(file.is_none());
            }
            _ => panic!("Expected ParseTimedOut, got {result:?}"),
        }
    }

    /// DETERMINISTIC: Cancellation + Some(tree) must return `ParseCancelled` error.
    ///
    /// Same as timeout case: even with a tree, cancellation returns error.
    #[test]
    fn test_finalize_cancelled_with_tree_returns_error() {
        let tree = create_test_tree();
        let result =
            finalize_parse_result(TerminationReason::Cancelled, Some(tree), None, 2_000_000);

        match result {
            Err(ParseError::ParseCancelled { reason, file }) => {
                assert!(reason.contains("cancelled"));
                assert!(file.is_none());
            }
            _ => panic!("Expected ParseCancelled, got {result:?}"),
        }
    }

    /// DETERMINISTIC: Timeout + None must return `ParseTimedOut` error.
    #[test]
    fn test_finalize_timeout_without_tree_returns_error() {
        let result = finalize_parse_result(TerminationReason::TimedOut, None, None, 2_000_000);

        match result {
            Err(ParseError::ParseTimedOut { .. }) => {}
            _ => panic!("Expected ParseTimedOut, got {result:?}"),
        }
    }

    /// DETERMINISTIC: Cancellation + None must return `ParseCancelled` error.
    #[test]
    fn test_finalize_cancelled_without_tree_returns_error() {
        let result = finalize_parse_result(TerminationReason::Cancelled, None, None, 2_000_000);

        match result {
            Err(ParseError::ParseCancelled { .. }) => {}
            _ => panic!("Expected ParseCancelled, got {result:?}"),
        }
    }

    /// DETERMINISTIC: No termination + Some(tree) returns Ok(tree).
    #[test]
    fn test_finalize_success_with_tree() {
        let tree = create_test_tree();
        let result = finalize_parse_result(TerminationReason::None, Some(tree), None, 2_000_000);

        assert!(result.is_ok());
        assert_eq!(result.unwrap().root_node().kind(), "source_file");
    }

    /// DETERMINISTIC: No termination + None returns `TreeSitterFailed`.
    #[test]
    fn test_finalize_failure_without_tree() {
        let result = finalize_parse_result(TerminationReason::None, None, None, 2_000_000);

        match result {
            Err(ParseError::TreeSitterFailed) => {}
            _ => panic!("Expected TreeSitterFailed, got {result:?}"),
        }
    }

    /// DETERMINISTIC: Verify file path is included in timeout error.
    #[test]
    fn test_finalize_timeout_includes_file_path() {
        let tree = create_test_tree();
        let file_path = Path::new("/path/to/test.rs");
        let result = finalize_parse_result(
            TerminationReason::TimedOut,
            Some(tree),
            Some(file_path),
            1_500_000,
        );

        match result {
            Err(ParseError::ParseTimedOut {
                timeout_micros,
                file,
            }) => {
                assert_eq!(timeout_micros, 1_500_000);
                assert_eq!(file, Some(PathBuf::from("/path/to/test.rs")));
            }
            _ => panic!("Expected ParseTimedOut with file path, got {result:?}"),
        }
    }

    /// DETERMINISTIC: Verify file path is included in cancellation error.
    #[test]
    fn test_finalize_cancelled_includes_file_path() {
        let tree = create_test_tree();
        let file_path = Path::new("/some/code.rs");
        let result = finalize_parse_result(
            TerminationReason::Cancelled,
            Some(tree),
            Some(file_path),
            2_000_000,
        );

        match result {
            Err(ParseError::ParseCancelled { file, .. }) => {
                assert_eq!(file, Some(PathBuf::from("/some/code.rs")));
            }
            _ => panic!("Expected ParseCancelled with file path, got {result:?}"),
        }
    }
}