airust 0.6.5

Rust-native knowledge and memory engine for AI agents and local LLM applications: lexical search, optional semantic retrieval, versioned memory, source-bound evidence and MCP
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
//! Explicit local-model profiles. Loading never downloads model assets.
use crate::{
    pilot_support::write_new,
    reference_support::{bounded_read, encode_bounded, sha256, Result, Workspace, MAX_JSON},
};
use airust::{
    execution::WorkControl,
    hybrid::HybridSearchOptions,
    mcp::McpSearchBackend,
    reranking::{RerankOptions, Reranker},
    retrieval::{
        HybridSource, LexicalSource, RetrievalBatch, RetrievalError, RetrievalOptions,
        RetrievalResponse, RetrievalSource, Retriever,
    },
    semantic::{
        Embedding, EmbeddingError, EmbeddingProvider, EmbeddingPurpose, EmbeddingSpace,
        SemanticIndex,
    },
    Engine, SearchAlgorithm, SearchOptions,
};
use reqwest::blocking::Client;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::{
    collections::BTreeMap,
    io::Read,
    path::{Path, PathBuf},
    sync::{Mutex, MutexGuard, TryLockError},
    time::Duration,
};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Kind {
    Bm25,
    Hybrid,
    HybridRerank,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum FailurePolicy {
    Error,
    LexicalFallback,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Model {
    pub url: String,
    pub model: String,
    pub digest: String,
    pub dimensions: usize,
    pub timeout_ms: u64,
}
impl Model {
    fn space(&self) -> Result<EmbeddingSpace> {
        let url = reqwest::Url::parse(&self.url)?;
        if url.scheme() != "http"
            || !matches!(
                url.host_str(),
                Some("127.0.0.1" | "localhost" | "[::1]" | "::1")
            )
            || !url.username().is_empty()
            || url.password().is_some()
            || url.query().is_some()
            || url.fragment().is_some()
            || url.path() != "/"
            || self.model.trim().is_empty()
            || self.model.len() > 128
            || self.model.chars().any(char::is_control)
            || self.digest.len() != 64
            || !self
                .digest
                .bytes()
                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
            || self.dimensions == 0
            || self.dimensions > 4096
            || self.timeout_ms == 0
            || self.timeout_ms > 30_000
        {
            return Err(
                "invalid explicit local embedding endpoint, model identity or budget".into(),
            );
        }
        Ok(EmbeddingSpace::new(
            format!(
                "ollama:{}@{};raw;truncate=false;l2-f32-v1",
                self.model, self.digest
            ),
            self.dimensions,
        )?)
    }
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NativeReranker {
    pub directory: PathBuf,
    pub runtime: PathBuf,
    pub threads: usize,
    #[serde(default = "default_rerank_batch_size")]
    pub batch_size: usize,
    #[serde(default)]
    pub candidates: Option<usize>,
    #[serde(default)]
    pub model_snapshot_directory: Option<PathBuf>,
    #[serde(default)]
    pub isolated: bool,
}
fn default_rerank_batch_size() -> usize {
    16
}
impl NativeReranker {
    fn options(&self, limit: usize) -> std::result::Result<RerankOptions, RetrievalError> {
        Ok(RerankOptions::new(limit)
            .with_candidates(self.candidates.unwrap_or_else(|| limit.max(20)))?
            .with_batch_size(self.batch_size)?)
    }
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    pub schema_version: u32,
    pub profile: Kind,
    pub failure_policy: FailurePolicy,
    pub embedding: Option<Model>,
    pub vectors: Option<PathBuf>,
    pub reranker: Option<NativeReranker>,
}
impl Config {
    pub fn read(path: &Path) -> Result<Self> {
        let mut config: Self = serde_json::from_slice(&bounded_read(path, 16 * 1024)?)?;
        if config.schema_version != 1 {
            return Err("unsupported profile version".into());
        }
        let parent = path.parent().unwrap_or(Path::new("."));
        if let Some(p) = config.vectors.as_mut() {
            if p.is_relative() {
                *p = parent.join(&*p);
            }
        }
        if let Some(r) = config.reranker.as_mut() {
            if r.directory.is_relative() {
                r.directory = parent.join(&r.directory);
            }
            if r.runtime.is_relative() {
                r.runtime = parent.join(&r.runtime);
            }
            if let Some(directory) = r.model_snapshot_directory.as_mut() {
                if directory.is_relative() {
                    *directory = parent.join(&*directory);
                }
            }
            if r.threads == 0 || r.threads > 64 {
                return Err("reranker threads must be 1..64".into());
            }
            if r.isolated && r.model_snapshot_directory.is_none() {
                return Err("isolated reranking requires model_snapshot_directory".into());
            }
            if r.batch_size > 16 || r.candidates.is_some_and(|n| n > 100) {
                return Err(
                    "reranker batch_size must be 1..16 and candidates must be 1..100".into(),
                );
            }
            r.options(0)?;
        }
        match config.profile {
            Kind::Bm25
                if config.embedding.is_none()
                    && config.vectors.is_none()
                    && config.reranker.is_none() => {}
            Kind::Hybrid
                if config.embedding.is_some()
                    && config.vectors.is_some()
                    && config.reranker.is_none() => {}
            Kind::HybridRerank
                if config.embedding.is_some()
                    && config.vectors.is_some()
                    && config.reranker.is_some() => {}
            _ => {
                return Err(
                    "profile and explicit model/vector/reranker configuration differ".into(),
                )
            }
        }
        if let Some(model) = &config.embedding {
            model.space()?;
        }
        Ok(config)
    }
}

struct Ollama {
    client: Client,
    model: Model,
    space: EmbeddingSpace,
    control: Option<WorkControl>,
}
impl Ollama {
    fn new(model: Model) -> Result<Self> {
        let space = model.space()?;
        let client = Client::builder()
            .no_proxy()
            .redirect(reqwest::redirect::Policy::none())
            .timeout(Duration::from_millis(model.timeout_ms))
            .build()?;
        Ok(Self {
            client,
            model,
            space,
            control: None,
        })
    }
    fn request(&self, path: &str, body: Option<Value>, maximum: usize) -> Result<Value> {
        if let Some(control) = &self.control {
            control.checkpoint()?;
        }
        let timeout = self
            .control
            .as_ref()
            .and_then(WorkControl::remaining)
            .unwrap_or(Duration::from_millis(self.model.timeout_ms))
            .min(Duration::from_millis(self.model.timeout_ms));
        if timeout.is_zero() {
            return Err("embedding deadline expired".into());
        }
        let url = format!("{}{}", self.model.url.trim_end_matches('/'), path);
        let request = if let Some(body) = body {
            self.client.post(url).json(&body)
        } else {
            self.client.get(url)
        };
        let response = request.timeout(timeout).send()?;
        if !response.status().is_success() {
            return Err(format!("local embedding service HTTP {}", response.status()).into());
        }
        let mut bytes = Vec::new();
        response.take(maximum as u64 + 1).read_to_end(&mut bytes)?;
        if bytes.len() > maximum {
            return Err("embedding response byte budget exceeded".into());
        }
        if let Some(control) = &self.control {
            control.checkpoint()?;
        }
        Ok(serde_json::from_slice(&bytes)?)
    }
    fn verify(&self) -> Result<()> {
        let response = self.request("/api/tags", None, 2 * 1024 * 1024)?;
        let model = response["models"]
            .as_array()
            .and_then(|models| models.iter().find(|m| m["name"] == self.model.model))
            .ok_or("configured embedding model is unavailable")?;
        if model["digest"] != self.model.digest {
            return Err("embedding model digest changed".into());
        }
        Ok(())
    }
}
impl EmbeddingProvider for Ollama {
    fn space(&self) -> &EmbeddingSpace {
        &self.space
    }
    fn embed(
        &mut self,
        texts: &[&str],
        _purpose: EmbeddingPurpose,
    ) -> std::result::Result<Vec<Vec<f32>>, EmbeddingError> {
        let run = || -> Result<Vec<Vec<f32>>> {
            if texts.len() > 16 || texts.iter().map(|t| t.len()).sum::<usize>() > 64 * 1024 {
                return Err("embedding input batch budget exceeded".into());
            }
            self.verify()?;
            let result=self.request("/api/embed",Some(json!({"model":self.model.model,"input":texts,"truncate":false,"keep_alive":"10m"})),2*1024*1024)?;
            let vectors: Vec<Vec<f32>> = serde_json::from_value(result["embeddings"].clone())?;
            if vectors.len() != texts.len() {
                return Err("embedding count mismatch".into());
            }
            for vector in &vectors {
                Embedding::new(self.space.clone(), vector.clone())?;
            }
            self.verify()?;
            Ok(vectors)
        };
        run().map_err(|e| EmbeddingError::Provider(e.to_string()))
    }
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Cache {
    schema_version: u32,
    workspace_sha256: String,
    embedding_recipe: String,
    dimensions: usize,
    vectors: BTreeMap<String, Vec<f32>>,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Envelope {
    payload_sha256: String,
    payload: String,
}

pub fn prepare(workspace: &Workspace, config_path: &Path, output: &Path) -> Result<Value> {
    if output.exists() {
        return Err("vector destination already exists".into());
    }
    let config = Config::read(config_path)?;
    let model = config
        .embedding
        .ok_or("a model profile is required to prepare vectors")?;
    let mut provider = Ollama::new(model)?;
    if workspace.index.len() > MAX_JSON / std::mem::size_of::<f32>() / provider.space.dimensions() {
        return Err("raw vector values exceed the 64 MiB preparation budget".into());
    }
    let entries: Vec<_> = workspace.index.entries().collect();
    let mut vectors = BTreeMap::new();
    let mut deduplicated = BTreeMap::<String, Vec<f32>>::new();
    for batch in entries.chunks(16) {
        let fresh: Vec<_> = batch
            .iter()
            .filter(|entry| !deduplicated.contains_key(&entry.text))
            .map(|entry| entry.text.as_str())
            .collect();
        if !fresh.is_empty() {
            for (text, values) in fresh
                .iter()
                .zip(provider.embed(&fresh, EmbeddingPurpose::Document)?)
            {
                deduplicated.insert((*text).to_owned(), values);
            }
        }
        for entry in batch {
            vectors.insert(entry.id.clone(), deduplicated[&entry.text].clone());
        }
    }
    let cache = Cache {
        schema_version: 1,
        workspace_sha256: workspace.identity(),
        embedding_recipe: provider.space.model().into(),
        dimensions: provider.space.dimensions(),
        vectors,
    };
    let payload = String::from_utf8(encode_bounded(&cache, MAX_JSON)?)?;
    let encoded = encode_bounded(
        &Envelope {
            payload_sha256: sha256(payload.as_bytes()),
            payload,
        },
        MAX_JSON,
    )?;
    write_new(output, &encoded)?;
    Ok(
        json!({"vectors":cache.vectors.len(),"unique_texts":deduplicated.len(),"workspace_sha256":cache.workspace_sha256,"embedding_recipe":cache.embedding_recipe,"bytes":encoded.len()}),
    )
}

struct State {
    semantic: Option<SemanticIndex>,
    provider: Option<Ollama>,
    reranker: Option<Box<dyn Reranker + Send>>,
}
pub struct Profile {
    config: Config,
    recipe: String,
    state: Mutex<State>,
}
struct Tagged<S> {
    source: S,
    recipe: String,
    fallback: Option<String>,
}
impl<S: RetrievalSource> RetrievalSource for Tagged<S> {
    fn retrieve<'a>(
        &'a mut self,
        query: &str,
        options: &RetrievalOptions,
    ) -> std::result::Result<RetrievalBatch<'a>, RetrievalError> {
        let mut batch = self.source.retrieve(query, options)?;
        batch.recipe = self.recipe.clone();
        if self.fallback.is_some() {
            batch.fallback_reason = self.fallback.clone();
        }
        Ok(batch)
    }
}
impl Profile {
    pub fn load(workspace: &Workspace, path: &Path) -> Result<Self> {
        let config = Config::read(path)?;
        if config.profile == Kind::Bm25 {
            return Ok(Self {
                config,
                recipe: "airust-pilot-bm25-v1".into(),
                state: Mutex::new(State {
                    semantic: None,
                    provider: None,
                    reranker: None,
                }),
            });
        }
        let provider = Ollama::new(
            config
                .embedding
                .clone()
                .ok_or("missing embedding configuration")?,
        )?;
        let envelope: Envelope = serde_json::from_slice(&bounded_read(
            config.vectors.as_deref().ok_or("missing vector path")?,
            MAX_JSON,
        )?)?;
        if sha256(envelope.payload.as_bytes()) != envelope.payload_sha256 {
            return Err("vector cache checksum mismatch".into());
        }
        let cache: Cache = serde_json::from_str(&envelope.payload)?;
        if cache.schema_version != 1
            || cache.workspace_sha256 != workspace.identity()
            || cache.embedding_recipe != provider.space.model()
            || cache.dimensions != provider.space.dimensions()
            || cache.vectors.len() != workspace.index.len()
        {
            return Err("vector cache workspace, model recipe or count mismatch".into());
        }
        let mut semantic = SemanticIndex::new(provider.space.clone());
        for entry in workspace.index.entries() {
            let values = cache
                .vectors
                .get(&entry.id)
                .ok_or("missing document vector")?;
            semantic.upsert_embedded(
                entry.clone(),
                Embedding::new(provider.space.clone(), values.clone())?,
            )?;
        }
        let reranker = match &config.reranker {
            Some(paths) => Some(native(paths)?),
            None => None,
        };
        let recipe = format!(
            "airust-pilot-{:?}-v1;{}",
            config.profile,
            provider.space.model()
        );
        Ok(Self {
            config,
            recipe,
            state: Mutex::new(State {
                semantic: Some(semantic),
                provider: Some(provider),
                reranker,
            }),
        })
    }
    fn lock(
        &self,
        options: &RetrievalOptions,
    ) -> std::result::Result<MutexGuard<'_, State>, RetrievalError> {
        loop {
            if let Some(control) = options.control() {
                control.checkpoint()?;
            }
            match self.state.try_lock() {
                Ok(guard) => return Ok(guard),
                Err(TryLockError::Poisoned(_)) => {
                    return Err(RetrievalError::Source("model state is poisoned".into()))
                }
                Err(TryLockError::WouldBlock) => {
                    std::thread::park_timeout(Duration::from_millis(1))
                }
            }
        }
    }
    pub fn query(
        &self,
        index: &Engine,
        query: &str,
        algorithm: SearchAlgorithm,
        options: &RetrievalOptions,
    ) -> std::result::Result<RetrievalResponse, RetrievalError> {
        if self.config.profile == Kind::Bm25 {
            return Retriever::new(Tagged {
                source: LexicalSource::new(index).with_options(SearchOptions {
                    algorithm,
                    ..Default::default()
                }),
                recipe: if algorithm == SearchAlgorithm::Tfidf {
                    "airust-pilot-tfidf-v1".into()
                } else {
                    self.recipe.clone()
                },
                fallback: None,
            })
            .query(query, options);
        }
        if algorithm != SearchAlgorithm::Bm25 {
            return Err(RetrievalError::Configuration(
                "model profiles require BM25 fusion; TF-IDF is an explicit lexical profile",
            ));
        }
        if let Some(control) = options.control() {
            control.checkpoint()?;
        }
        let rerank_options = self
            .config
            .reranker
            .as_ref()
            .map(|config| config.options(options.limit()))
            .transpose()?;
        let mut state = self.lock(options)?;
        let State {
            semantic,
            provider,
            reranker,
        } = &mut *state;
        let semantic = semantic
            .as_ref()
            .ok_or(RetrievalError::Configuration("missing semantic index"))?;
        if semantic.lexical().stats() != index.stats() {
            return Err(RetrievalError::Output("profile and server index differ"));
        }
        let provider = provider
            .as_mut()
            .ok_or(RetrievalError::Configuration("missing embedding provider"))?;
        provider.control = options.control().cloned();
        let source = Tagged {
            source: HybridSource::new(semantic, provider)
                .with_options(HybridSearchOptions::new(options.limit())),
            recipe: self.recipe.clone(),
            fallback: None,
        };
        let mut retriever = Retriever::new(source);
        if let (Some(model), Some(rerank_options)) = (reranker.as_mut(), rerank_options) {
            retriever = retriever.with_reranker(model.as_mut(), rerank_options);
        }
        let result = retriever.query(query, options);
        drop(retriever);
        // Model state outlives individual requests; release their cancellation
        // and observer references as soon as inference returns.
        provider.control = None;
        if let Some(control) = options.control() {
            control.checkpoint()?;
        }
        match result {
            Err(error @ (RetrievalError::Source(_) | RetrievalError::Rerank(_)))
                if self.config.failure_policy == FailurePolicy::LexicalFallback =>
            {
                let reason = format!(
                    "explicit lexical fallback from {:?}: {error}",
                    self.config.profile
                );
                Retriever::new(Tagged {
                    source: LexicalSource::new(index),
                    recipe: format!("airust-pilot-lexical-fallback-v1;{}", self.recipe),
                    fallback: Some(reason),
                })
                .query(query, options)
            }
            other => other,
        }
    }
}
impl McpSearchBackend for Profile {
    fn retrieve(
        &self,
        index: &Engine,
        query: &str,
        algorithm: SearchAlgorithm,
        options: &RetrievalOptions,
    ) -> std::result::Result<RetrievalResponse, RetrievalError> {
        self.query(index, query, algorithm, options)
    }
}
fn native(paths: &NativeReranker) -> Result<Box<dyn Reranker + Send>> {
    #[cfg(feature = "local-reranking")]
    {
        use airust::reranking::local::FastEmbedReranker;
        if paths.isolated {
            use airust::reranking::process::{ProcessOptions, ProcessReranker};
            let options = ProcessOptions::new(std::env::current_exe()?);
            let model = match &paths.model_snapshot_directory {
                Some(directory) => ProcessReranker::multilingual_minilm_v2_from_snapshot(
                    options,
                    &paths.directory,
                    &paths.runtime,
                    paths.threads,
                    directory,
                )?,
                None => return Err("isolated reranking requires model_snapshot_directory".into()),
            };
            return Ok(Box::new(model));
        }
        let model = match &paths.model_snapshot_directory {
            Some(directory) => FastEmbedReranker::multilingual_minilm_v2_from_snapshot(
                &paths.directory,
                &paths.runtime,
                paths.threads,
                directory,
            )?,
            None => FastEmbedReranker::multilingual_minilm_v2(
                &paths.directory,
                &paths.runtime,
                paths.threads,
            )?,
        };
        Ok(Box::new(model))
    }
    #[cfg(not(feature = "local-reranking"))]
    {
        let _ = paths;
        Err("enable local-reranking and supply the verified native assets explicitly".into())
    }
}

#[cfg(test)]
mod configuration_tests {
    use super::*;
    use airust::{execution::CancellationToken, reranking::RerankError};

    fn profile() -> Value {
        json!({
            "schema_version": 1, "profile": "hybrid_rerank", "failure_policy": "error",
            "embedding": {"url": "http://127.0.0.1:1", "model": "fixture:local", "digest": "1".repeat(64), "dimensions": 3, "timeout_ms": 1000},
            "vectors": "missing-vectors.json",
            "reranker": {"directory": "missing-model", "runtime": "missing-runtime", "threads": 2},
        })
    }
    fn read(value: &Value) -> Config {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("profile.json");
        std::fs::write(&path, serde_json::to_vec(value).unwrap()).unwrap();
        Config::read(&path).unwrap()
    }

    #[test]
    fn existing_profiles_keep_batch_and_automatic_candidate_defaults() {
        let config = read(&profile());
        let native = config.reranker.unwrap();
        assert_eq!(native.batch_size, 16);
        assert_eq!(native.candidates, None);
        assert_eq!(native.model_snapshot_directory, None);
        assert!(!native.isolated);
        for limit in [0, 6, 20, 25, 100] {
            let options = native.options(limit).unwrap();
            assert_eq!(options.limit(), limit);
            assert_eq!(options.batch_size(), 16);
            assert_eq!(options.candidates(), limit.max(20));
        }
    }

    #[test]
    fn explicit_batch_and_candidate_budget_reuse_validated_reranking_options() {
        let mut value = profile();
        value["reranker"]["batch_size"] = json!(1);
        value["reranker"]["candidates"] = json!(20);
        let config = read(&value);
        let native = config.reranker.unwrap();
        let options = native.options(6).unwrap();
        assert_eq!(options.candidates(), 20);
        assert_eq!(options.batch_size(), 1);
        assert!(matches!(
            native.options(21),
            Err(RetrievalError::Rerank(RerankError::Configuration(_)))
        ));
    }

    #[test]
    fn invalid_native_bounds_and_unknown_fields_fail_without_loading_assets() {
        for (name, invalid) in [
            ("batch_size", json!(0)),
            ("batch_size", json!(17)),
            ("candidates", json!(0)),
            ("candidates", json!(101)),
            ("threads", json!(0)),
            ("threads", json!(65)),
            ("batch_size", json!(1.5)),
            ("candidates", json!(-1)),
            ("batch_szie", json!(1)),
            ("model_snapshot_directory", json!(true)),
            ("isolated", json!("yes")),
        ] {
            let mut value = profile();
            value["reranker"][name] = invalid;
            let dir = tempfile::tempdir().unwrap();
            let path = dir.path().join("profile.json");
            let original = serde_json::to_vec(&value).unwrap();
            std::fs::write(&path, &original).unwrap();
            assert!(Config::read(&path).is_err(), "{name}");
            assert_eq!(std::fs::read(&path).unwrap(), original);
        }
    }

    #[test]
    fn preflight_resolves_relative_paths_without_accessing_cache_model_or_service() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("profile.json");
        let mut value = profile();
        value["reranker"]["model_snapshot_directory"] = json!("not-created-snapshots");
        value["reranker"]["isolated"] = json!(true);
        std::fs::write(&path, serde_json::to_vec(&value).unwrap()).unwrap();
        let config = Config::read(&path).unwrap();
        assert_eq!(
            config.vectors.unwrap(),
            dir.path().join("missing-vectors.json")
        );
        let native = config.reranker.unwrap();
        assert!(native.isolated);
        assert_eq!(native.directory, dir.path().join("missing-model"));
        assert_eq!(native.runtime, dir.path().join("missing-runtime"));
        assert_eq!(
            native.model_snapshot_directory.unwrap(),
            dir.path().join("not-created-snapshots")
        );
        assert!(!dir.path().join("not-created-snapshots").exists());
        assert!(!native.directory.exists() && !native.runtime.exists());
        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
    }

    #[test]
    fn isolated_profile_requires_an_explicit_snapshot_parent_without_asset_work() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("profile.json");
        let mut value = profile();
        value["reranker"]["isolated"] = json!(true);
        let original = serde_json::to_vec(&value).unwrap();
        std::fs::write(&path, &original).unwrap();
        assert!(Config::read(&path).is_err());
        assert_eq!(std::fs::read(&path).unwrap(), original);
        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
    }

    fn unloaded(config: Config) -> Profile {
        Profile {
            config,
            recipe: "not-loaded".into(),
            state: Mutex::new(State {
                semantic: None,
                provider: None,
                reranker: None,
            }),
        }
    }

    #[test]
    fn request_cannot_expand_explicit_window_or_turn_configuration_into_fallback() {
        let mut value = profile();
        value["failure_policy"] = json!("lexical_fallback");
        value["reranker"]["candidates"] = json!(5);
        let profile = unloaded(read(&value));
        assert!(matches!(
            profile.query(
                &Engine::new(),
                "Rust",
                SearchAlgorithm::Bm25,
                &RetrievalOptions::new(6)
            ),
            Err(RetrievalError::Rerank(RerankError::Configuration(_)))
        ));
    }

    #[test]
    fn cancellation_retains_priority_over_invalid_explicit_window() {
        let mut value = profile();
        value["reranker"]["candidates"] = json!(5);
        let profile = unloaded(read(&value));
        let cancel = CancellationToken::new();
        cancel.cancel();
        let options = RetrievalOptions::new(6).with_control(WorkControl::new(cancel));
        assert!(matches!(
            profile.query(&Engine::new(), "Rust", SearchAlgorithm::Bm25, &options),
            Err(RetrievalError::Execution(
                airust::execution::ExecutionError::Cancelled
            ))
        ));
    }

    #[test]
    fn expired_deadline_retains_priority_over_invalid_explicit_window() {
        let mut value = profile();
        value["reranker"]["candidates"] = json!(5);
        let profile = unloaded(read(&value));
        let control =
            WorkControl::new(CancellationToken::new()).with_deadline(std::time::Instant::now());
        let options = RetrievalOptions::new(6).with_control(control);
        assert!(matches!(
            profile.query(&Engine::new(), "Rust", SearchAlgorithm::Bm25, &options),
            Err(RetrievalError::Execution(
                airust::execution::ExecutionError::DeadlineExceeded
            ))
        ));
    }
}