sqry-core 6.0.18

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
//! Loom tests for admission control (Step 28).
//!
//! Tests SharedBufferState atomic operations under all interleavings:
//!
//! - Reserve + commit race conditions
//! - Concurrent reservation limit checking
//! - Active guard count underflow protection
//! - Counter reset with active guards

use loom::sync::Arc;
use loom::sync::atomic::{AtomicUsize, Ordering};
use loom::thread;

/// Loom-compatible version of SharedBufferState for testing.
///
/// This replicates the core atomic operations from `admission::state::SharedBufferState`
/// using loom's atomic primitives for exhaustive interleaving testing.
#[derive(Debug)]
struct LoomSharedBufferState {
    committed_bytes: AtomicUsize,
    committed_ops: AtomicUsize,
    reserved_bytes: AtomicUsize,
    reserved_ops: AtomicUsize,
    active_guards: AtomicUsize,
}

impl LoomSharedBufferState {
    fn new() -> Self {
        Self {
            committed_bytes: AtomicUsize::new(0),
            committed_ops: AtomicUsize::new(0),
            reserved_bytes: AtomicUsize::new(0),
            reserved_ops: AtomicUsize::new(0),
            active_guards: AtomicUsize::new(0),
        }
    }

    fn committed_bytes(&self) -> usize {
        self.committed_bytes.load(Ordering::Acquire)
    }

    fn reserved_bytes(&self) -> usize {
        self.reserved_bytes.load(Ordering::Acquire)
    }

    fn active_guards(&self) -> usize {
        self.active_guards.load(Ordering::Acquire)
    }

    #[allow(dead_code)]
    fn total_bytes(&self) -> usize {
        self.committed_bytes() + self.reserved_bytes()
    }

    fn increment_active_guards(&self) {
        self.active_guards.fetch_add(1, Ordering::AcqRel);
    }

    /// Decrements active guard count.
    ///
    /// # Panics
    ///
    /// Panics if the counter would underflow (mirroring  production semantics).
    fn decrement_active_guards(&self) {
        let prev = self.active_guards.fetch_sub(1, Ordering::AcqRel);
        assert!(prev > 0, "active_guards underflow: decrement from 0");
    }

    fn add_reserved(&self, bytes: usize, ops: usize) {
        self.reserved_bytes.fetch_add(bytes, Ordering::AcqRel);
        self.reserved_ops.fetch_add(ops, Ordering::AcqRel);
    }

    /// Subtracts from reserved counters.
    ///
    /// # Panics
    ///
    /// Panics if counters would underflow (mirroring  production semantics).
    fn sub_reserved(&self, bytes: usize, ops: usize) {
        let prev_bytes = self.reserved_bytes.fetch_sub(bytes, Ordering::AcqRel);
        let prev_ops = self.reserved_ops.fetch_sub(ops, Ordering::AcqRel);
        assert!(
            prev_bytes >= bytes,
            "reserved_bytes underflow: {} < {}",
            prev_bytes,
            bytes
        );
        assert!(
            prev_ops >= ops,
            "reserved_ops underflow: {} < {}",
            prev_ops,
            ops
        );
    }

    /// Transfers from reserved to committed.
    ///
    /// # Panics
    ///
    /// Panics if actual exceeds reserved or if reserved would underflow.
    fn transfer_reserved_to_committed(
        &self,
        reserved_bytes: usize,
        reserved_ops: usize,
        actual_bytes: usize,
        actual_ops: usize,
    ) {
        assert!(
            actual_bytes <= reserved_bytes,
            "actual_bytes {} exceeds reserved_bytes {}",
            actual_bytes,
            reserved_bytes
        );
        assert!(
            actual_ops <= reserved_ops,
            "actual_ops {} exceeds reserved_ops {}",
            actual_ops,
            reserved_ops
        );

        let prev_bytes = self
            .reserved_bytes
            .fetch_sub(reserved_bytes, Ordering::AcqRel);
        let prev_ops = self.reserved_ops.fetch_sub(reserved_ops, Ordering::AcqRel);

        assert!(
            prev_bytes >= reserved_bytes,
            "reserved_bytes underflow in transfer"
        );
        assert!(
            prev_ops >= reserved_ops,
            "reserved_ops underflow in transfer"
        );

        self.committed_bytes
            .fetch_add(actual_bytes, Ordering::AcqRel);
        self.committed_ops.fetch_add(actual_ops, Ordering::AcqRel);
    }

    /// Subtracts from committed counters.
    ///
    /// # Panics
    ///
    /// Panics if counters would underflow.
    fn sub_committed(&self, bytes: usize, ops: usize) {
        let prev_bytes = self.committed_bytes.fetch_sub(bytes, Ordering::AcqRel);
        let prev_ops = self.committed_ops.fetch_sub(ops, Ordering::AcqRel);
        assert!(
            prev_bytes >= bytes,
            "committed_bytes underflow: {} < {}",
            prev_bytes,
            bytes
        );
        assert!(
            prev_ops >= ops,
            "committed_ops underflow: {} < {}",
            prev_ops,
            ops
        );
    }

    fn try_reset_to_zero(&self) -> bool {
        let active = self.active_guards.load(Ordering::Acquire);
        if active > 0 {
            return false;
        }

        self.committed_bytes.store(0, Ordering::Release);
        self.committed_ops.store(0, Ordering::Release);
        self.reserved_bytes.store(0, Ordering::Release);
        self.reserved_ops.store(0, Ordering::Release);
        true
    }
}

fn try_reserve_with_limit(
    state: &LoomSharedBufferState,
    max_bytes: usize,
    bytes: usize,
    ops: usize,
) -> bool {
    loop {
        let current_reserved = state.reserved_bytes.load(Ordering::Acquire);
        let current_committed = state.committed_bytes.load(Ordering::Acquire);
        let total = current_reserved + current_committed;

        if total + bytes > max_bytes {
            return false;
        }

        if state
            .reserved_bytes
            .compare_exchange_weak(
                current_reserved,
                current_reserved + bytes,
                Ordering::AcqRel,
                Ordering::Relaxed,
            )
            .is_ok()
        {
            state.reserved_ops.fetch_add(ops, Ordering::AcqRel);
            return true;
        }
    }
}

fn spawn_reservation_thread(
    state: Arc<LoomSharedBufferState>,
    max_bytes: usize,
    bytes: usize,
    ops: usize,
    success_count: Arc<AtomicUsize>,
) -> loom::thread::JoinHandle<()> {
    thread::spawn(move || {
        if try_reserve_with_limit(&state, max_bytes, bytes, ops) {
            success_count.fetch_add(1, Ordering::Relaxed);
        }
    })
}

fn join_threads(threads: [loom::thread::JoinHandle<()>; 2]) {
    for thread in threads {
        thread.join().unwrap();
    }
}

/// Reserve + commit race conditions.
///
/// Verifies that concurrent reserve and commit operations maintain counter invariants.
#[test]
fn test_cp16_reserve_commit_race() {
    loom::model(|| {
        let state = Arc::new(LoomSharedBufferState::new());
        let state1 = Arc::clone(&state);
        let state2 = Arc::clone(&state);

        // Thread 1: Reserve and commit
        let t1 = thread::spawn(move || {
            state1.increment_active_guards();
            state1.add_reserved(100, 1);
            state1.transfer_reserved_to_committed(100, 1, 80, 1);
            state1.decrement_active_guards();
        });

        // Thread 2: Reserve and commit
        let t2 = thread::spawn(move || {
            state2.increment_active_guards();
            state2.add_reserved(200, 2);
            state2.transfer_reserved_to_committed(200, 2, 150, 2);
            state2.decrement_active_guards();
        });

        join_threads([t1, t2]);

        // Invariant: All reservations committed, no active guards
        assert_eq!(state.active_guards(), 0);
        assert_eq!(state.reserved_bytes(), 0);
        assert_eq!(state.committed_bytes(), 230); // 80 + 150
    });
}

/// Concurrent reservation limit checking with CAS loop.
///
/// Verifies that concurrent reservations using proper CAS loops respect limits.
/// Models the AdmissionController's dual CAS loop pattern.
#[test]
fn test_cp17_concurrent_reservation_limits() {
    loom::model(|| {
        let state = Arc::new(LoomSharedBufferState::new());
        let max_bytes: usize = 150;

        // Track successful reservations
        let success_count = Arc::new(AtomicUsize::new(0));

        let t1 = spawn_reservation_thread(
            Arc::clone(&state),
            max_bytes,
            100,
            1,
            Arc::clone(&success_count),
        );
        let t2 = spawn_reservation_thread(
            Arc::clone(&state),
            max_bytes,
            100,
            1,
            Arc::clone(&success_count),
        );

        join_threads([t1, t2]);

        // With proper CAS-based limit checking:
        // - At most one thread should succeed (limit = 150, each wants 100)
        // - Total reserved should never exceed max_bytes
        let total = state.reserved_bytes();
        let successes = success_count.load(Ordering::Relaxed);

        // CRITICAL INVARIANT: Total must never exceed limit
        assert!(
            total <= max_bytes,
            "Limit violated: total {} > max {}",
            total,
            max_bytes
        );

        // Only one reservation should succeed (100 + 100 > 150)
        assert!(
            successes <= 1,
            "At most one reservation should succeed, got {}",
            successes
        );
    });
}

/// Active guard count underflow protection.
///
/// Verifies that decrementing active guards below zero is detected.
#[test]
fn test_cp18_guard_underflow_protection() {
    loom::model(|| {
        let state = Arc::new(LoomSharedBufferState::new());
        let state1 = Arc::clone(&state);
        let state2 = Arc::clone(&state);

        // Increment twice
        state.increment_active_guards();
        state.increment_active_guards();

        // Thread 1: Decrement (will panic if underflow - loom detects)
        let t1 = thread::spawn(move || {
            state1.decrement_active_guards();
        });

        // Thread 2: Decrement (will panic if underflow - loom detects)
        let t2 = thread::spawn(move || {
            state2.decrement_active_guards();
        });

        join_threads([t1, t2]);

        // Final count should be 0
        assert_eq!(state.active_guards(), 0);
    });
}

/// Counter reset with active guards.
///
/// Verifies that reset operations are rejected while guards are active.
/// Note: After guard is released, multiple resets can succeed (they're idempotent).
#[test]
fn test_cp19_reset_with_active_guards() {
    loom::model(|| {
        let state = Arc::new(LoomSharedBufferState::new());

        // Add some data and a guard
        state.add_reserved(100, 1);
        state.increment_active_guards();

        let state1 = Arc::clone(&state);
        let state2 = Arc::clone(&state);

        // Track results
        let t1_reset_succeeded = Arc::new(AtomicUsize::new(0));
        let reset1 = Arc::clone(&t1_reset_succeeded);

        // Thread 1: Try to reset (should fail while guard is active)
        let t1 = thread::spawn(move || {
            if state1.try_reset_to_zero() {
                // This can only succeed if t2 already released the guard
                reset1.fetch_add(1, Ordering::Relaxed);
            }
        });

        // Thread 2: Release guard then try reset
        let t2 = thread::spawn(move || {
            state2.decrement_active_guards();
            // After release, reset should succeed
            let _ = state2.try_reset_to_zero();
        });

        join_threads([t1, t2]);

        // The key invariant: reset only succeeds when active_guards == 0
        // Both can succeed if t2 runs first (releases guard), then both see guards=0
        // t1 fails if it runs first (guard still active)
        // This is correct behavior - we're testing that reset checks guards
        assert_eq!(state.active_guards(), 0, "Guard should be released");
    });
}

/// Test concurrent reserve and abort operations.
///
/// Verifies that reservations can be safely aborted (sub_reserved) concurrently.
#[test]
fn test_concurrent_reserve_abort() {
    loom::model(|| {
        let state = Arc::new(LoomSharedBufferState::new());

        // Pre-reserve 200 bytes
        state.add_reserved(200, 2);

        let state1 = Arc::clone(&state);
        let state2 = Arc::clone(&state);

        // Thread 1: Abort 100 bytes
        let t1 = thread::spawn(move || {
            state1.sub_reserved(100, 1);
        });

        // Thread 2: Abort 100 bytes
        let t2 = thread::spawn(move || {
            state2.sub_reserved(100, 1);
        });

        join_threads([t1, t2]);

        // Both should succeed, leaving 0
        assert_eq!(state.reserved_bytes(), 0);
    });
}

/// Test concurrent commit and compaction (sub_committed).
///
/// Verifies that sub_committed operations during/after commits are safe.
#[test]
fn test_concurrent_commit_compaction() {
    loom::model(|| {
        let state = Arc::new(LoomSharedBufferState::new());

        // Setup: Reserve and commit 200 bytes
        state.add_reserved(200, 2);
        state.transfer_reserved_to_committed(200, 2, 200, 2);

        let state1 = Arc::clone(&state);
        let state2 = Arc::clone(&state);

        // Thread 1: Compaction removes 100 bytes
        let t1 = thread::spawn(move || {
            state1.sub_committed(100, 1);
        });

        // Thread 2: Compaction removes 100 bytes
        let t2 = thread::spawn(move || {
            state2.sub_committed(100, 1);
        });

        join_threads([t1, t2]);

        // Final committed should be 0
        assert_eq!(state.committed_bytes(), 0);
    });
}