sqry-core 6.0.22

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
//! Query execution guard with timeout, memory, and resource limits
//!
//! This module provides the runtime guard that enforces security limits
//! during query execution. The guard tracks:
//! - Elapsed time vs timeout limit
//! - Result count vs result cap
//! - Memory usage vs memory limit
//!
//! All limits are NON-NEGOTIABLE per the security requirements.

use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};

use super::config::QuerySecurityConfig;

/// Query execution guard with timeout, memory, and resource limits
///
/// **MEMORY ENFORCEMENT** (per Codex review):
/// Uses a tracked allocation approach where memory usage is estimated
/// based on result sizes and checked at regular intervals.
///
/// # Example
///
/// ```
/// use sqry_core::query::security::{QuerySecurityConfig, QueryGuard};
///
/// let config = QuerySecurityConfig::default();
/// let guard = QueryGuard::new(config);
///
/// // During query execution:
/// guard.should_continue().expect("should not fail initially");
/// guard.record_result(128); // Record a result with estimated size
/// ```
pub struct QueryGuard {
    config: QuerySecurityConfig,
    start_time: Instant,
    result_count: AtomicUsize,
    memory_usage: AtomicUsize,
    check_interval: usize,
    checks_performed: AtomicUsize,
}

impl QueryGuard {
    /// Create a new query guard
    #[must_use]
    pub fn new(config: QuerySecurityConfig) -> Self {
        Self {
            config,
            start_time: Instant::now(),
            result_count: AtomicUsize::new(0),
            memory_usage: AtomicUsize::new(0),
            check_interval: 100, // Check every 100 results
            checks_performed: AtomicUsize::new(0),
        }
    }

    /// Create a new query guard with custom check interval
    ///
    /// The check interval controls how often memory limits are checked.
    /// Lower values mean more frequent checks but higher overhead.
    #[must_use]
    pub fn with_check_interval(config: QuerySecurityConfig, interval: usize) -> Self {
        Self {
            check_interval: interval.max(1), // At least check every result
            ..Self::new(config)
        }
    }

    /// Check if query should continue
    ///
    /// # Errors
    ///
    /// Returns `QuerySecurityError` if any limit is exceeded:
    /// - `Timeout`: Query has run longer than the configured timeout
    /// - `ResultCapExceeded`: More results collected than the result cap
    /// - `MemoryLimitExceeded`: Estimated memory usage exceeds limit
    ///
    /// **NOTE** (per Codex iter6): Uses getter methods since fields are private.
    pub fn should_continue(&self) -> Result<(), QuerySecurityError> {
        // Check timeout - use getter since field is private
        let elapsed = self.start_time.elapsed();
        let timeout_limit = self.config.timeout();
        if elapsed > timeout_limit {
            return Err(QuerySecurityError::Timeout {
                elapsed,
                limit: timeout_limit,
            });
        }

        // Check result cap - use getter since field is private
        let count = self.result_count.load(Ordering::Relaxed);
        let result_limit = self.config.result_cap();
        if count >= result_limit {
            return Err(QuerySecurityError::ResultCapExceeded {
                count,
                limit: result_limit,
            });
        }

        // Check memory (periodically to reduce overhead) - use getter
        let checks = self.checks_performed.fetch_add(1, Ordering::Relaxed);
        if checks.is_multiple_of(self.check_interval) {
            let usage = self.memory_usage.load(Ordering::Relaxed);
            let memory_limit = self.config.memory_limit();
            if usage >= memory_limit {
                return Err(QuerySecurityError::MemoryLimitExceeded {
                    usage,
                    limit: memory_limit,
                });
            }
        }

        Ok(())
    }

    /// Record a result and its estimated memory footprint
    ///
    /// This should be called for each result added to the result set.
    /// The estimated size should include:
    /// - The Node/TraitImpl struct size
    /// - String allocations for names, paths, etc.
    /// - Any metadata stored with the result
    pub fn record_result(&self, estimated_size: usize) {
        self.result_count.fetch_add(1, Ordering::Relaxed);
        self.memory_usage
            .fetch_add(estimated_size, Ordering::Relaxed);
    }

    /// Get elapsed time since query started
    #[must_use]
    pub fn elapsed(&self) -> Duration {
        self.start_time.elapsed()
    }

    /// Get current result count
    #[must_use]
    pub fn result_count(&self) -> usize {
        self.result_count.load(Ordering::Relaxed)
    }

    /// Get current memory usage estimate
    #[must_use]
    pub fn memory_usage(&self) -> usize {
        self.memory_usage.load(Ordering::Relaxed)
    }

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

/// Security errors from query execution
#[derive(Debug, thiserror::Error)]
pub enum QuerySecurityError {
    /// Query execution exceeded the timeout limit
    #[error("Query timeout: {elapsed:?} exceeded {limit:?}")]
    Timeout {
        /// How long the query ran before being stopped
        elapsed: Duration,
        /// The configured timeout limit
        limit: Duration,
    },

    /// Query returned more results than the result cap
    #[error("Result cap exceeded: {count} >= {limit}")]
    ResultCapExceeded {
        /// Number of results collected
        count: usize,
        /// The configured result cap
        limit: usize,
    },

    /// Query memory usage exceeded the memory limit
    #[error("Memory limit exceeded: {usage} bytes >= {limit} bytes")]
    MemoryLimitExceeded {
        /// Estimated memory usage in bytes
        usage: usize,
        /// The configured memory limit in bytes
        limit: usize,
    },

    /// Pre-execution cost estimate exceeds the cost limit
    #[error("Query cost exceeds limit: {estimated} > {limit}")]
    CostLimitExceeded {
        /// Estimated cost of the query
        estimated: usize,
        /// The configured cost limit
        limit: usize,
    },
}

impl QuerySecurityError {
    /// Convert security error to completion status for partial results (per Codex iter10)
    ///
    /// When a limit is exceeded during execution, this converts the error
    /// into a status indicator that can be returned with partial results.
    #[must_use]
    pub fn into_completion_status(self) -> QueryCompletionStatus {
        match self {
            Self::Timeout { elapsed, limit } => QueryCompletionStatus::TimedOut { elapsed, limit },
            Self::ResultCapExceeded { count, limit } => {
                QueryCompletionStatus::ResultCapReached { count, limit }
            }
            Self::MemoryLimitExceeded { usage, limit } => {
                QueryCompletionStatus::MemoryLimitReached {
                    usage_bytes: usage,
                    limit_bytes: limit,
                }
            }
            Self::CostLimitExceeded { .. } =>
            // Cost limit is checked before execution, not during
            // If we somehow hit this, treat as complete (no partial results scenario)
            {
                QueryCompletionStatus::Complete
            }
        }
    }
}

/// Completion status for query results (per Codex iter10)
///
/// Indicates whether the result set is complete or was truncated due to limits.
/// This allows callers to know if they received all matching results or only
/// a partial set.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QueryCompletionStatus {
    /// All matching results returned
    Complete,

    /// Results truncated due to result cap (see count for how many were returned)
    ResultCapReached {
        /// Number of results returned
        count: usize,
        /// The configured result cap
        limit: usize,
    },

    /// Results truncated due to memory limit
    MemoryLimitReached {
        /// Actual memory usage in bytes
        usage_bytes: usize,
        /// The configured memory limit in bytes
        limit_bytes: usize,
    },

    /// Results truncated due to timeout
    TimedOut {
        /// How long the query ran
        elapsed: Duration,
        /// The configured timeout limit
        limit: Duration,
    },
}

impl QueryCompletionStatus {
    /// Returns true if the result set is complete
    #[must_use]
    pub fn is_complete(&self) -> bool {
        matches!(self, Self::Complete)
    }

    /// Returns a user-friendly message for CLI output
    #[must_use]
    pub fn message(&self) -> String {
        match self {
            Self::Complete => "Query completed successfully".to_string(),
            Self::ResultCapReached { count, limit } => {
                format!(
                    "Results truncated: showing {count} of {limit}+ matches (result cap reached)"
                )
            }
            Self::MemoryLimitReached {
                usage_bytes,
                limit_bytes,
            } => {
                format!(
                    "Results truncated: memory limit reached ({} of {} MB)",
                    usage_bytes / (1024 * 1024),
                    limit_bytes / (1024 * 1024)
                )
            }
            Self::TimedOut { elapsed, limit } => {
                format!(
                    "Results truncated: query timed out after {:.1}s (limit: {}s)",
                    elapsed.as_secs_f64(),
                    limit.as_secs()
                )
            }
        }
    }

    /// Returns the JSON field name for this status type
    ///
    /// Used for JSON output format consistency.
    #[must_use]
    pub fn status_field(&self) -> &'static str {
        match self {
            Self::Complete => "complete",
            Self::ResultCapReached { .. } => "result_cap_reached",
            Self::MemoryLimitReached { .. } => "memory_limit_reached",
            Self::TimedOut { .. } => "timed_out",
        }
    }

    /// Returns the CLI exit code for this status
    ///
    /// - Complete: 0 (success)
    /// - Truncated results: 2 (partial success, distinct from errors)
    #[must_use]
    pub fn exit_code(&self) -> i32 {
        match self {
            Self::Complete => 0,
            _ => 2, // Partial results - distinct from error (1)
        }
    }
}

/// Result set with completion status (per Codex iter10)
///
/// Wraps query results with a status indicator so callers know whether
/// the results are complete or truncated.
#[derive(Debug)]
pub struct QueryResultSet<T> {
    /// The results (may be partial if status != Complete)
    pub results: Vec<T>,

    /// Completion status indicating if results are complete or truncated
    pub status: QueryCompletionStatus,

    /// Actual memory usage tracked during execution
    pub memory_usage_bytes: usize,

    /// Actual elapsed time
    pub elapsed: Duration,
}

impl<T> QueryResultSet<T> {
    /// Create a complete result set
    #[must_use]
    pub fn complete(results: Vec<T>, memory_usage_bytes: usize, elapsed: Duration) -> Self {
        Self {
            results,
            status: QueryCompletionStatus::Complete,
            memory_usage_bytes,
            elapsed,
        }
    }

    /// Create a truncated result set
    #[must_use]
    pub fn truncated(
        results: Vec<T>,
        status: QueryCompletionStatus,
        memory_usage_bytes: usize,
        elapsed: Duration,
    ) -> Self {
        Self {
            results,
            status,
            memory_usage_bytes,
            elapsed,
        }
    }

    /// Returns true if all results were returned
    #[must_use]
    pub fn is_complete(&self) -> bool {
        self.status.is_complete()
    }

    /// Get the number of results
    #[must_use]
    pub fn len(&self) -> usize {
        self.results.len()
    }

    /// Check if the result set is empty
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.results.is_empty()
    }
}

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

    #[test]
    fn test_guard_initial_state() {
        let guard = QueryGuard::new(QuerySecurityConfig::default());
        assert_eq!(guard.result_count(), 0);
        assert_eq!(guard.memory_usage(), 0);
        assert!(guard.should_continue().is_ok());
    }

    #[test]
    fn test_guard_record_result() {
        let guard = QueryGuard::new(QuerySecurityConfig::default());
        guard.record_result(1024);
        assert_eq!(guard.result_count(), 1);
        assert_eq!(guard.memory_usage(), 1024);
    }

    #[test]
    fn test_guard_result_cap() {
        let config = QuerySecurityConfig::default().with_result_cap(5);
        let guard = QueryGuard::new(config);

        for _ in 0..5 {
            guard.record_result(100);
        }

        let err = guard.should_continue().unwrap_err();
        assert!(matches!(
            err,
            QuerySecurityError::ResultCapExceeded { count: 5, limit: 5 }
        ));
    }

    #[test]
    fn test_guard_memory_limit() {
        // Set check interval to 1 so we check every time
        let config = QuerySecurityConfig::default().with_memory_limit(1000);
        let guard = QueryGuard::with_check_interval(config, 1);

        // Add enough to exceed limit
        guard.record_result(500);
        assert!(guard.should_continue().is_ok());

        guard.record_result(600);
        let err = guard.should_continue().unwrap_err();
        assert!(matches!(
            err,
            QuerySecurityError::MemoryLimitExceeded { .. }
        ));
    }

    #[test]
    fn test_completion_status_messages() {
        assert_eq!(
            QueryCompletionStatus::Complete.message(),
            "Query completed successfully"
        );

        let cap_status = QueryCompletionStatus::ResultCapReached {
            count: 100,
            limit: 100,
        };
        assert!(cap_status.message().contains("100"));

        let mem_status = QueryCompletionStatus::MemoryLimitReached {
            usage_bytes: 10 * 1024 * 1024,
            limit_bytes: 10 * 1024 * 1024,
        };
        assert!(mem_status.message().contains("MB"));

        let timeout_status = QueryCompletionStatus::TimedOut {
            elapsed: Duration::from_secs(5),
            limit: Duration::from_secs(5),
        };
        assert!(timeout_status.message().contains("timed out"));
    }

    #[test]
    fn test_completion_status_is_complete() {
        assert!(QueryCompletionStatus::Complete.is_complete());
        assert!(
            !QueryCompletionStatus::ResultCapReached {
                count: 10,
                limit: 10
            }
            .is_complete()
        );
    }

    #[test]
    fn test_error_to_status_conversion() {
        let timeout_err = QuerySecurityError::Timeout {
            elapsed: Duration::from_secs(10),
            limit: Duration::from_secs(5),
        };
        assert!(matches!(
            timeout_err.into_completion_status(),
            QueryCompletionStatus::TimedOut { .. }
        ));

        let cap_err = QuerySecurityError::ResultCapExceeded {
            count: 100,
            limit: 50,
        };
        assert!(matches!(
            cap_err.into_completion_status(),
            QueryCompletionStatus::ResultCapReached { .. }
        ));
    }

    #[test]
    fn test_result_set_complete() {
        let results = vec![1, 2, 3];
        let set = QueryResultSet::complete(results, 100, Duration::from_millis(10));
        assert!(set.is_complete());
        assert_eq!(set.len(), 3);
        assert!(!set.is_empty());
    }

    #[test]
    fn test_result_set_truncated() {
        let results = vec![1, 2];
        let status = QueryCompletionStatus::ResultCapReached { count: 2, limit: 2 };
        let set = QueryResultSet::truncated(results, status, 50, Duration::from_millis(5));
        assert!(!set.is_complete());
        assert_eq!(set.len(), 2);
    }

    #[test]
    fn test_exit_codes() {
        assert_eq!(QueryCompletionStatus::Complete.exit_code(), 0);
        assert_eq!(
            QueryCompletionStatus::ResultCapReached {
                count: 10,
                limit: 10
            }
            .exit_code(),
            2
        );
        assert_eq!(
            QueryCompletionStatus::TimedOut {
                elapsed: Duration::from_secs(5),
                limit: Duration::from_secs(5)
            }
            .exit_code(),
            2
        );
    }
}