xberg 1.1.4

High-performance document intelligence library for Rust. Extract text, metadata, and structured data from PDFs, Office documents, images, and 107 formats and 371 programming languages via tree-sitter code intelligence with async/sync APIs.
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
//! Bounded global model pool for ONNX-based models.
//!
//! Expensive sessions are checked out through an RAII lease. The pool caps
//! both live leases and in-progress construction, preventing concurrent cache
//! misses from creating an unbounded number of duplicate sessions.

use std::ops::{Deref, DerefMut};
use std::sync::{Condvar, Mutex, MutexGuard};

struct PoolState<T> {
    available: Vec<T>,
    checked_out: usize,
}

/// A bounded pool of reusable model instances.
#[cfg_attr(alef, alef(skip))]
pub struct ModelCache<T: Send> {
    capacity: usize,
    state: Mutex<PoolState<T>>,
    returned: Condvar,
}

/// Exclusive model checkout that returns the model to its pool on drop.
#[cfg_attr(alef, alef(skip))]
pub(crate) struct ModelLease<'a, T: Send> {
    model: Option<T>,
    cache: &'a ModelCache<T>,
}

struct ConstructionReservation<'a, T: Send> {
    cache: &'a ModelCache<T>,
    active: bool,
}

impl<T: Send> Default for ModelCache<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Send> ModelCache<T> {
    /// Create a single-instance model pool.
    pub(crate) const fn new() -> Self {
        Self::with_capacity(1)
    }

    /// Create a pool capped at `capacity` live or constructing models.
    pub(crate) const fn with_capacity(capacity: usize) -> Self {
        assert!(capacity > 0, "model cache capacity must be positive");
        Self {
            capacity,
            state: Mutex::new(PoolState {
                available: Vec::new(),
                checked_out: 0,
            }),
            returned: Condvar::new(),
        }
    }

    fn lock_state(&self) -> MutexGuard<'_, PoolState<T>> {
        self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Checkout a cached model, construct one within the capacity reservation,
    /// or wait until an existing lease is returned.
    #[cfg(test)]
    pub(crate) fn take_or_create<E>(&self, create_fn: impl FnOnce() -> Result<T, E>) -> Result<ModelLease<'_, T>, E> {
        self.take_or_create_matching(|_| true, create_fn)
    }

    /// Checkout a matching cached model while preserving the global capacity.
    ///
    /// When the pool is full of idle mismatches, one mismatch is evicted before
    /// construction. If every slot is checked out or constructing, the caller
    /// waits for a return before deciding whether to reuse or evict it.
    pub(crate) fn take_or_create_matching<E>(
        &self,
        mut matches: impl FnMut(&T) -> bool,
        create_fn: impl FnOnce() -> Result<T, E>,
    ) -> Result<ModelLease<'_, T>, E> {
        let mut state = self.lock_state();
        loop {
            if let Some(index) = state.available.iter().position(&mut matches) {
                let model = state.available.swap_remove(index);
                state.checked_out += 1;
                let lease = ModelLease {
                    model: Some(model),
                    cache: self,
                };
                drop(state);
                tracing::debug!(capacity = self.capacity, "Reusing pooled model");
                return Ok(lease);
            }

            let total_models = state.checked_out + state.available.len();
            if total_models < self.capacity || !state.available.is_empty() {
                let evicted = if total_models >= self.capacity {
                    state.available.pop()
                } else {
                    None
                };
                state.checked_out += 1;
                let mut reservation = ConstructionReservation {
                    cache: self,
                    active: true,
                };
                drop(state);
                drop(evicted);
                tracing::debug!(capacity = self.capacity, "Creating pooled model");
                let model = create_fn()?;
                let lease = ModelLease {
                    model: Some(model),
                    cache: self,
                };
                reservation.active = false;
                return Ok(lease);
            }

            state = self
                .returned
                .wait(state)
                .unwrap_or_else(std::sync::PoisonError::into_inner);
        }
    }

    fn release_reservation(&self) {
        let mut state = self.lock_state();
        debug_assert!(state.checked_out > 0);
        state.checked_out -= 1;
        self.returned.notify_one();
    }

    fn return_model(&self, model: T) {
        let mut state = self.lock_state();
        debug_assert!(state.checked_out > 0);
        state.checked_out -= 1;
        state.available.push(model);
        self.returned.notify_one();
    }
}

impl<T: Send> Drop for ConstructionReservation<'_, T> {
    fn drop(&mut self) {
        if self.active {
            self.cache.release_reservation();
        }
    }
}

impl<T: Send> Deref for ModelLease<'_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.model.as_ref().expect("model lease must contain a model")
    }
}

impl<T: Send> DerefMut for ModelLease<'_, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.model.as_mut().expect("model lease must contain a model")
    }
}

impl<T: Send> Drop for ModelLease<'_, T> {
    fn drop(&mut self) {
        if let Some(model) = self.model.take() {
            self.cache.return_model(model);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::{Arc, Barrier};
    use std::time::Duration;

    #[test]
    fn concurrent_misses_never_construct_beyond_capacity() {
        let cache = Arc::new(ModelCache::with_capacity(2));
        let created = Arc::new(AtomicUsize::new(0));
        let active = Arc::new(AtomicUsize::new(0));
        let max_active = Arc::new(AtomicUsize::new(0));
        let holders = Arc::new(AtomicUsize::new(0));
        let start = Arc::new(Barrier::new(5));
        let first_two_holding = Arc::new(Barrier::new(3));
        let release_first_two = Arc::new(Barrier::new(3));

        let handles: Vec<_> = (0..4)
            .map(|_| {
                let cache = Arc::clone(&cache);
                let created = Arc::clone(&created);
                let active = Arc::clone(&active);
                let max_active = Arc::clone(&max_active);
                let holders = Arc::clone(&holders);
                let start = Arc::clone(&start);
                let first_two_holding = Arc::clone(&first_two_holding);
                let release_first_two = Arc::clone(&release_first_two);
                std::thread::spawn(move || {
                    start.wait();
                    let lease = cache
                        .take_or_create(|| {
                            created.fetch_add(1, Ordering::SeqCst);
                            Ok::<_, ()>(())
                        })
                        .unwrap();
                    let now = active.fetch_add(1, Ordering::SeqCst) + 1;
                    max_active.fetch_max(now, Ordering::SeqCst);
                    if holders.fetch_add(1, Ordering::SeqCst) < 2 {
                        first_two_holding.wait();
                        release_first_two.wait();
                    }
                    active.fetch_sub(1, Ordering::SeqCst);
                    drop(lease);
                })
            })
            .collect();

        start.wait();
        first_two_holding.wait();
        assert_eq!(created.load(Ordering::SeqCst), 2);
        assert_eq!(active.load(Ordering::SeqCst), 2);
        release_first_two.wait();
        for handle in handles {
            handle.join().unwrap();
        }

        assert_eq!(created.load(Ordering::SeqCst), 2);
        assert_eq!(max_active.load(Ordering::SeqCst), 2);
    }

    #[test]
    fn constructor_failure_releases_capacity_for_waiter() {
        let cache = Arc::new(ModelCache::with_capacity(1));
        let (constructor_started_tx, constructor_started_rx) = std::sync::mpsc::channel();
        let (release_constructor_tx, release_constructor_rx) = std::sync::mpsc::channel();
        let failing_cache = Arc::clone(&cache);
        let failing = std::thread::spawn(move || {
            failing_cache
                .take_or_create(|| {
                    constructor_started_tx.send(()).unwrap();
                    release_constructor_rx.recv().unwrap();
                    Err::<usize, _>("failed")
                })
                .map(|_| ())
                .unwrap_err()
        });
        constructor_started_rx.recv().unwrap();

        let waiting_cache = Arc::clone(&cache);
        let waiter = std::thread::spawn(move || {
            let lease = waiting_cache.take_or_create(|| Ok::<_, &str>(7)).unwrap();
            *lease
        });
        release_constructor_tx.send(()).unwrap();

        assert_eq!(failing.join().unwrap(), "failed");
        assert_eq!(waiter.join().unwrap(), 7);
    }

    #[test]
    fn dropped_lease_wakes_waiter_and_reuses_model() {
        let cache = Arc::new(ModelCache::with_capacity(1));
        let first = cache.take_or_create(|| Ok::<_, ()>(11)).unwrap();
        let (waiting_tx, waiting_rx) = std::sync::mpsc::channel();
        let (result_tx, result_rx) = std::sync::mpsc::channel();
        let waiting_cache = Arc::clone(&cache);
        let handle = std::thread::spawn(move || {
            waiting_tx.send(()).unwrap();
            let lease = waiting_cache.take_or_create(|| Ok::<_, ()>(99)).unwrap();
            result_tx.send(*lease).unwrap();
        });

        waiting_rx.recv().unwrap();
        assert!(matches!(
            result_rx.recv_timeout(Duration::from_millis(20)),
            Err(std::sync::mpsc::RecvTimeoutError::Timeout)
        ));
        drop(first);

        assert_eq!(result_rx.recv().unwrap(), 11);
        handle.join().unwrap();
    }

    #[test]
    fn constructor_panic_releases_capacity() {
        let cache = ModelCache::with_capacity(1);
        let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _ = cache.take_or_create(|| -> Result<usize, ()> { panic!("constructor panic") });
        }));
        assert!(panic.is_err());

        let lease = cache.take_or_create(|| Ok::<_, ()>(17)).unwrap();
        assert_eq!(*lease, 17);
    }

    #[test]
    fn consistent_nested_pool_order_makes_progress() {
        let primary = Arc::new(ModelCache::with_capacity(2));
        let classifier = Arc::new(ModelCache::with_capacity(2));
        let alternate = Arc::new(ModelCache::with_capacity(2));
        let start = Arc::new(Barrier::new(5));

        let handles: Vec<_> = (0..4)
            .map(|_| {
                let primary = Arc::clone(&primary);
                let classifier = Arc::clone(&classifier);
                let alternate = Arc::clone(&alternate);
                let start = Arc::clone(&start);
                std::thread::spawn(move || {
                    start.wait();
                    let _primary = primary.take_or_create(|| Ok::<_, ()>(())).unwrap();
                    let _classifier = classifier.take_or_create(|| Ok::<_, ()>(())).unwrap();
                    let _alternate = alternate.take_or_create(|| Ok::<_, ()>(())).unwrap();
                })
            })
            .collect();

        start.wait();
        for handle in handles {
            handle.join().unwrap();
        }
    }

    #[test]
    fn matching_checkout_reuses_only_matching_model() {
        let cache = ModelCache::with_capacity(2);
        drop(cache.take_or_create(|| Ok::<_, ()>(("a", 1))).unwrap());

        let matching = cache
            .take_or_create_matching(|model| model.0 == "a", || Ok::<_, ()>(("new", 2)))
            .unwrap();

        assert_eq!(*matching, ("a", 1));
    }

    #[test]
    fn mismatch_is_evicted_when_pool_is_full() {
        let cache = ModelCache::with_capacity(1);
        drop(cache.take_or_create(|| Ok::<_, ()>(("old", 1))).unwrap());

        let replacement = cache
            .take_or_create_matching(|model| model.0 == "new", || Ok::<_, ()>(("new", 2)))
            .unwrap();
        assert_eq!(*replacement, ("new", 2));
        drop(replacement);

        let reused = cache
            .take_or_create_matching(|model| model.0 == "new", || Ok::<_, ()>(("unexpected", 3)))
            .unwrap();
        assert_eq!(*reused, ("new", 2));
    }

    #[test]
    fn evicted_model_drop_panic_releases_construction_reservation() {
        struct PanicOnDrop {
            value: usize,
            panic_on_drop: bool,
        }

        impl Drop for PanicOnDrop {
            fn drop(&mut self) {
                assert!(!self.panic_on_drop, "evicted model drop panic");
            }
        }

        let cache = ModelCache::with_capacity(1);
        drop(
            cache
                .take_or_create(|| {
                    Ok::<_, ()>(PanicOnDrop {
                        value: 1,
                        panic_on_drop: true,
                    })
                })
                .unwrap(),
        );

        let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _ = cache.take_or_create_matching(
                |model| model.value == 2,
                || {
                    Ok::<_, ()>(PanicOnDrop {
                        value: 2,
                        panic_on_drop: false,
                    })
                },
            );
        }));
        assert!(panic.is_err());

        let recovered = cache
            .take_or_create_matching(
                |_| true,
                || {
                    Ok::<_, ()>(PanicOnDrop {
                        value: 3,
                        panic_on_drop: false,
                    })
                },
            )
            .unwrap();
        assert_eq!(recovered.value, 3);
    }

    #[test]
    fn retained_and_checked_out_models_share_one_capacity() {
        let cache = ModelCache::with_capacity(2);
        drop(cache.take_or_create(|| Ok::<_, ()>(1)).unwrap());
        let checked_out = cache
            .take_or_create_matching(|model| *model == 2, || Ok::<_, ()>(2))
            .unwrap();

        let state = cache.lock_state();
        assert_eq!(state.available.len(), 1);
        assert_eq!(state.checked_out, 1);
        assert_eq!(state.available.len() + state.checked_out, 2);
        drop(state);
        drop(checked_out);
    }
}