Skip to main content

fallow_api/similar_code/
mod.rs

1//! Local-provider orchestration for advisory similar-code discovery.
2
3use std::fmt::Write as _;
4use std::path::{Path, PathBuf};
5use std::time::{Duration, Instant};
6
7use fallow_engine::source::similar_code::SimilarCodeSourceDigest;
8use rustc_hash::FxHashMap;
9
10mod cache;
11mod launcher_provider;
12mod protocol;
13mod transport;
14
15pub use protocol::SimilarCodeProviderStatus;
16
17const EMBED_BATCH_SIZE: usize = 1;
18const EMBED_RUN_TIMEOUT: Duration = Duration::from_mins(15);
19
20/// Classified local-provider failure used by the programmatic runtime.
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub(crate) enum ProviderError {
23    /// The exact companion or its pinned model is not installed yet.
24    NotReady(String),
25    /// An installed companion failed execution, provenance, or protocol checks.
26    Failed(String),
27}
28
29impl ProviderError {
30    pub(crate) fn message(&self) -> &str {
31        match self {
32            Self::NotReady(message) | Self::Failed(message) => message,
33        }
34    }
35}
36
37/// Opaque, validated handle obtained before project source is read.
38pub(crate) struct ReadyProvider {
39    path: PathBuf,
40    pub(crate) status: SimilarCodeProviderStatus,
41}
42
43/// One transient source fragment selected for local embedding.
44pub(crate) struct EmbeddingInput<'a> {
45    pub(crate) source_sha256: SimilarCodeSourceDigest,
46    pub(crate) source: &'a str,
47}
48
49/// Privacy-safe cache and provider accounting for one embedding pass.
50pub(crate) struct EmbeddingResult {
51    /// Vectors in input order. Missing entries represent a bounded partial pass.
52    pub(crate) vectors: Vec<Option<Vec<f32>>>,
53    pub(crate) cache_hits: usize,
54    pub(crate) cache_misses: usize,
55    pub(crate) cache_writes: usize,
56    pub(crate) cache_invalid_entries: usize,
57    pub(crate) cache_disabled: bool,
58    pub(crate) cache_problem: Option<String>,
59    pub(crate) provider_problem: Option<String>,
60    pub(crate) inference_ms: f64,
61    pub(crate) truncated_functions: usize,
62}
63
64/// Provider-neutral validated batch used by the private orchestration seam.
65pub(crate) struct EmbeddingBatch {
66    pub(crate) vectors: Vec<EmbeddingBatchVector>,
67    pub(crate) inference_ms: f64,
68    pub(crate) problem: Option<String>,
69}
70
71/// One validated vector returned by a private provider session.
72pub(crate) struct EmbeddingBatchVector {
73    pub(crate) key: u32,
74    pub(crate) values: Vec<f32>,
75    pub(crate) truncated: bool,
76}
77
78/// Private injectable session used by production transport and hermetic tests.
79pub(crate) trait EmbeddingSession {
80    fn embed(&mut self, functions: &[(u32, &str)]) -> Result<EmbeddingBatch, String>;
81}
82
83/// Private lazy session factory. The provider is not started on an all-cache-hit run.
84pub(crate) trait EmbeddingSessionFactory {
85    fn spawn(&mut self) -> Result<Box<dyn EmbeddingSession>, String>;
86}
87
88struct LocalEmbeddingSession {
89    inner: transport::ProviderSession,
90}
91
92impl EmbeddingSession for LocalEmbeddingSession {
93    fn embed(&mut self, functions: &[(u32, &str)]) -> Result<EmbeddingBatch, String> {
94        let response = self.inner.embed(functions)?;
95        let problem = (response.status != protocol::EmbedCompletionStatus::Complete)
96            .then(|| transport::embed_problem(&response));
97        Ok(EmbeddingBatch {
98            vectors: response
99                .vectors
100                .into_iter()
101                .map(|vector| EmbeddingBatchVector {
102                    key: vector.key,
103                    values: vector.values,
104                    truncated: vector.truncated,
105                })
106                .collect(),
107            inference_ms: response.timing.inference_ms,
108            problem,
109        })
110    }
111}
112
113struct LocalEmbeddingSessionFactory<'a> {
114    path: &'a Path,
115}
116
117impl EmbeddingSessionFactory for LocalEmbeddingSessionFactory<'_> {
118    fn spawn(&mut self) -> Result<Box<dyn EmbeddingSession>, String> {
119        transport::ProviderSession::spawn(self.path)
120            .map(|inner| Box::new(LocalEmbeddingSession { inner }) as Box<dyn EmbeddingSession>)
121    }
122}
123
124struct EmbeddingMiss {
125    representative_index: usize,
126    occurrence_indices: Vec<usize>,
127}
128
129struct EmbeddingPlan {
130    vectors: Vec<Option<Vec<f32>>>,
131    misses: Vec<EmbeddingMiss>,
132    cache_hits: usize,
133    cache_misses: usize,
134    truncated_functions: usize,
135}
136
137/// Return the installed local provider status.
138///
139/// # Errors
140///
141/// Returns a structured message when the trusted sibling is missing, cannot be
142/// executed, or reports incompatible provenance.
143pub fn status() -> Result<SimilarCodeProviderStatus, String> {
144    let sidecar = transport::discover_provider(std::env::current_dir().ok().as_deref())?;
145    let status = transport::provider_status(&sidecar)?;
146    validate_status(&status)?;
147    Ok(status)
148}
149
150/// Download and verify the pinned local model through the installed provider.
151///
152/// Callers must obtain explicit human confirmation before invoking this API.
153/// MCP, NAPI, project configuration, and agent workflows intentionally do not
154/// expose this mutation.
155///
156/// # Errors
157///
158/// Returns a structured message when setup fails or provenance is invalid.
159pub fn setup_local() -> Result<SimilarCodeProviderStatus, String> {
160    let sidecar = transport::discover_provider(std::env::current_dir().ok().as_deref())?;
161    let status = transport::setup_provider(&sidecar)?;
162    validate_status(&status)?;
163    if !status.model_ready {
164        return Err("similar-code setup completed without a verified local model".to_owned());
165    }
166    Ok(status)
167}
168
169/// Immutable local provider identity used by public provenance output.
170#[must_use]
171pub fn provider_identity() -> (&'static str, &'static str, usize, &'static str) {
172    (
173        protocol::MODEL_ID,
174        protocol::MODEL_REVISION,
175        protocol::MODEL_DIMENSIONS,
176        protocol::MODEL_LICENSE,
177    )
178}
179
180/// Total bytes downloaded by an explicit local model setup.
181#[must_use]
182pub fn model_download_bytes() -> u64 {
183    protocol::MODEL_ARTIFACTS
184        .iter()
185        .map(|artifact| artifact.size)
186        .sum()
187}
188
189/// Resolve and validate the exact local companion before reading project source.
190///
191/// `project_root` is the analysis root. It only selects the package manager
192/// that the install hint names when the companion is missing.
193pub(crate) fn ready_provider(project_root: &Path) -> Result<ReadyProvider, ProviderError> {
194    let path = transport::discover_provider(Some(project_root)).map_err(ProviderError::NotReady)?;
195    let status = transport::provider_status(&path).map_err(ProviderError::Failed)?;
196    validate_status(&status).map_err(ProviderError::Failed)?;
197    if !status.model_ready {
198        let problem = status.problem.unwrap_or_else(|| {
199            "the pinned local model is not installed; run `fallow similar-code setup --local`"
200                .to_owned()
201        });
202        return Err(ProviderError::NotReady(problem));
203    }
204    Ok(ReadyProvider { path, status })
205}
206
207/// Validate an exact companion path already resolved and signature-verified
208/// by an official distribution adapter.
209///
210/// This exists for in-process hosts such as Node, whose process executable is
211/// not the Fallow binary and therefore has no meaningful sibling discovery.
212/// The path is never read from project config, PATH, or a model response.
213pub(crate) fn ready_provider_from_adapter_path(
214    path: &Path,
215) -> Result<ReadyProvider, ProviderError> {
216    if !path.is_file() {
217        return Err(ProviderError::NotReady(format!(
218            "verified similar-code companion is unavailable at {}",
219            path.display()
220        )));
221    }
222    let path = path.to_path_buf();
223    let status = transport::provider_status(&path).map_err(ProviderError::Failed)?;
224    validate_status(&status).map_err(ProviderError::Failed)?;
225    if !status.model_ready {
226        let problem = status.problem.unwrap_or_else(|| {
227            "the pinned local model is not installed; run `fallow similar-code setup --local`"
228                .to_owned()
229        });
230        return Err(ProviderError::NotReady(problem));
231    }
232    Ok(ReadyProvider { path, status })
233}
234
235/// Embed selected source fragments using the persistent source-digest cache.
236pub(crate) fn embed_selected(
237    provider: &ReadyProvider,
238    project_root: &Path,
239    no_cache: bool,
240    inputs: &[EmbeddingInput<'_>],
241) -> Result<EmbeddingResult, ProviderError> {
242    let mut factory = LocalEmbeddingSessionFactory {
243        path: &provider.path,
244    };
245    embed_selected_with_factory(
246        Path::new(&provider.status.cache_dir),
247        project_root,
248        no_cache,
249        inputs,
250        EMBED_RUN_TIMEOUT,
251        &mut factory,
252    )
253}
254
255/// Private injectable embedding seam used by production transport and crate tests.
256pub(crate) fn embed_selected_with_factory(
257    provider_cache_dir: &Path,
258    project_root: &Path,
259    no_cache: bool,
260    inputs: &[EmbeddingInput<'_>],
261    run_timeout: Duration,
262    factory: &mut dyn EmbeddingSessionFactory,
263) -> Result<EmbeddingResult, ProviderError> {
264    let mut cache = cache::VectorCache::load(provider_cache_dir, project_root, no_cache);
265    let cache_invalid_entries = usize::from(cache.load_state == cache::CacheLoadState::Corrupt);
266    let cache_disabled = cache.load_state == cache::CacheLoadState::Disabled;
267    let mut plan = prepare_embedding_plan(&mut cache, inputs);
268    let mut inference_ms = 0.0f64;
269    let mut provider_problem = None;
270    if !plan.misses.is_empty() {
271        let started = Instant::now();
272        let mut session = None;
273        let mut batch_start = 0usize;
274        while batch_start < plan.misses.len() {
275            if started.elapsed() >= run_timeout {
276                provider_problem =
277                    Some("similar-code embedding stopped at the bounded run limit".to_owned());
278                break;
279            }
280            let session = match session.as_mut() {
281                Some(session) => session,
282                None => session.insert(factory.spawn().map_err(ProviderError::Failed)?),
283            };
284            let batch_end = batch_start
285                .saturating_add(EMBED_BATCH_SIZE)
286                .min(plan.misses.len());
287            let request = (batch_start..batch_end)
288                .map(|group_index| {
289                    let miss = &plan.misses[group_index];
290                    let key = u32::try_from(group_index).map_err(|_| {
291                        ProviderError::Failed(
292                            "similar-code digest group exceeded protocol capacity".to_owned(),
293                        )
294                    })?;
295                    Ok((key, inputs[miss.representative_index].source))
296                })
297                .collect::<Result<Vec<_>, ProviderError>>()?;
298            match session.embed(&request) {
299                Ok(batch) => {
300                    validate_embedding_batch(&batch, &request).map_err(ProviderError::Failed)?;
301                    inference_ms += batch.inference_ms;
302                    if batch.problem.is_some() {
303                        provider_problem = batch.problem;
304                    }
305                    for vector in batch.vectors {
306                        let group_index = usize::try_from(vector.key).map_err(|_| {
307                            ProviderError::Failed(
308                                "similar-code provider returned an invalid digest-group key"
309                                    .to_owned(),
310                            )
311                        })?;
312                        apply_embedding_vector(
313                            &mut cache,
314                            inputs,
315                            &mut plan,
316                            group_index,
317                            &vector.values,
318                            vector.truncated,
319                        )?;
320                    }
321                }
322                Err(error) => {
323                    provider_problem = Some(error);
324                    break;
325                }
326            }
327            batch_start = batch_end;
328        }
329    }
330    let save = cache.save();
331
332    Ok(EmbeddingResult {
333        vectors: plan.vectors,
334        cache_hits: plan.cache_hits,
335        cache_misses: plan.cache_misses,
336        cache_writes: save.durable_writes,
337        cache_invalid_entries,
338        cache_disabled,
339        cache_problem: save.problem,
340        provider_problem,
341        inference_ms,
342        truncated_functions: plan.truncated_functions,
343    })
344}
345
346fn validate_embedding_batch(batch: &EmbeddingBatch, request: &[(u32, &str)]) -> Result<(), String> {
347    if !batch.inference_ms.is_finite() || batch.inference_ms < 0.0 {
348        return Err("similar-code provider returned invalid timing".to_owned());
349    }
350    let mut expected = request.iter().map(|(key, _)| *key).collect::<Vec<_>>();
351    let mut actual = batch
352        .vectors
353        .iter()
354        .map(|vector| vector.key)
355        .collect::<Vec<_>>();
356    expected.sort_unstable();
357    actual.sort_unstable();
358    if actual.windows(2).any(|pair| pair[0] == pair[1])
359        || actual
360            .iter()
361            .any(|key| expected.binary_search(key).is_err())
362        || batch.vectors.iter().any(|vector| {
363            vector.values.len() != protocol::MODEL_DIMENSIONS
364                || vector.values.iter().any(|value| !value.is_finite())
365                || vector.values.iter().all(|value| *value == 0.0)
366        })
367        || (batch.vectors.len() == request.len()) == batch.problem.is_some()
368    {
369        return Err("similar-code provider returned an invalid embedding batch".to_owned());
370    }
371    Ok(())
372}
373
374fn prepare_embedding_plan(
375    cache: &mut cache::VectorCache,
376    inputs: &[EmbeddingInput<'_>],
377) -> EmbeddingPlan {
378    let mut vectors = vec![None; inputs.len()];
379    let mut misses = Vec::<EmbeddingMiss>::new();
380    let mut miss_groups: FxHashMap<SimilarCodeSourceDigest, usize> = FxHashMap::default();
381    let mut cache_hits = 0usize;
382    let mut cache_misses = 0usize;
383    let mut truncated_functions = 0usize;
384    for (index, input) in inputs.iter().enumerate() {
385        if let Some(entry) = cache.get(&input.source_sha256) {
386            vectors[index] = Some(entry.values.clone());
387            cache_hits = cache_hits.saturating_add(1);
388            truncated_functions =
389                truncated_functions.saturating_add(usize::from(entry.token_truncated));
390            continue;
391        }
392
393        cache_misses = cache_misses.saturating_add(1);
394        if let Some(group_index) = miss_groups.get(&input.source_sha256).copied() {
395            misses[group_index].occurrence_indices.push(index);
396        } else {
397            let group_index = misses.len();
398            miss_groups.insert(input.source_sha256, group_index);
399            misses.push(EmbeddingMiss {
400                representative_index: index,
401                occurrence_indices: vec![index],
402            });
403        }
404    }
405    EmbeddingPlan {
406        vectors,
407        misses,
408        cache_hits,
409        cache_misses,
410        truncated_functions,
411    }
412}
413
414fn apply_embedding_vector(
415    cache: &mut cache::VectorCache,
416    inputs: &[EmbeddingInput<'_>],
417    plan: &mut EmbeddingPlan,
418    group_index: usize,
419    values: &[f32],
420    token_truncated: bool,
421) -> Result<(), ProviderError> {
422    let miss = plan.misses.get(group_index).ok_or_else(|| {
423        ProviderError::Failed(
424            "similar-code provider returned an unknown digest-group key".to_owned(),
425        )
426    })?;
427    let digest = inputs[miss.representative_index].source_sha256;
428    cache.insert(digest, values.to_owned(), token_truncated);
429    if token_truncated {
430        plan.truncated_functions = plan
431            .truncated_functions
432            .saturating_add(miss.occurrence_indices.len());
433    }
434    for occurrence_index in &miss.occurrence_indices {
435        plan.vectors[*occurrence_index] = Some(values.to_owned());
436    }
437    Ok(())
438}
439
440/// Remove the model-specific vector cache. Model artifacts remain installed.
441fn clear_vector_cache(provider_cache_dir: &Path, project_root: &Path) -> Result<bool, String> {
442    cache::clear(provider_cache_dir, project_root)
443}
444
445/// Remove only persisted similar-code vectors for one project.
446///
447/// The downloaded model is user-level state and is never removed here.
448///
449/// # Errors
450///
451/// Returns an error when config resolution or cache removal fails.
452pub fn clear_project_cache(
453    root: &Path,
454    config_path: Option<&Path>,
455    allow_remote_extends: bool,
456) -> Result<bool, String> {
457    let analysis = crate::AnalysisOptions {
458        root: Some(root.to_path_buf()),
459        config_path: config_path.map(Path::to_path_buf),
460        allow_remote_extends,
461        ..crate::AnalysisOptions::default()
462    };
463    let run = crate::run::resolve_programmatic_run(
464        &analysis,
465        &crate::run::ProgrammaticEntry::SimilarCode,
466    )
467    .map_err(|error| error.message)?;
468    let provider = status()?;
469    clear_vector_cache(Path::new(&provider.cache_dir), run.root().value())
470}
471
472pub(crate) fn model_artifact_sha256() -> &'static str {
473    protocol::MODEL_ARTIFACTS
474        .first()
475        .map_or("", |artifact| artifact.sha256)
476}
477
478pub(crate) fn parameter_sha256() -> String {
479    let digest = cache::parameter_digest();
480    digest.iter().fold(
481        String::with_capacity(digest.len().saturating_mul(2)),
482        |mut output, byte| {
483            let _ = write!(output, "{byte:02x}");
484            output
485        },
486    )
487}
488
489pub(crate) const fn embedding_batch_size() -> usize {
490    EMBED_BATCH_SIZE
491}
492
493pub(crate) const fn embedding_semantics_version() -> u32 {
494    protocol::EMBEDDING_SEMANTICS_VERSION
495}
496
497fn validate_status(status: &SimilarCodeProviderStatus) -> Result<(), String> {
498    if status.protocol_version != protocol::WIRE_PROTOCOL_VERSION
499        || status.embedding_semantics_version != protocol::EMBEDDING_SEMANTICS_VERSION
500        || status.sidecar_version != env!("CARGO_PKG_VERSION")
501        || status.model_id != protocol::MODEL_ID
502        || status.model_revision != protocol::MODEL_REVISION
503        || status.dimensions != protocol::MODEL_DIMENSIONS
504        || status.max_tokens != protocol::MODEL_MAX_TOKENS
505        || status.license != protocol::MODEL_LICENSE
506        || status.download_bytes != model_download_bytes()
507        || !status.analysis_offline
508        || (status.model_ready && !status.integrity_verified)
509    {
510        return Err(
511            "similar-code companion provenance does not match this Fallow release".to_owned(),
512        );
513    }
514    Ok(())
515}
516
517#[cfg(test)]
518#[expect(
519    clippy::unwrap_used,
520    reason = "test fixture construction must fail immediately"
521)]
522mod tests {
523    use super::*;
524
525    #[test]
526    fn missing_provider_names_the_package_manager_of_the_analysis_root() {
527        if std::env::var_os("FALLOW_SIMILAR_CODE_PROVIDER").is_some() {
528            return;
529        }
530        let project = tempfile::tempdir().unwrap();
531        // The fallow repository uses pnpm, so Bun proves that the analysis
532        // root decides and not the working directory of the test.
533        std::fs::write(project.path().join("bun.lock"), "").unwrap();
534        let Err(ProviderError::NotReady(message)) = ready_provider(project.path()) else {
535            panic!("the test binary has no sibling provider");
536        };
537        assert!(
538            message.contains(&format!(
539                "`bun add -d fallow-similar-code@{}`",
540                env!("CARGO_PKG_VERSION")
541            )),
542            "{message}"
543        );
544    }
545
546    #[test]
547    fn duplicate_digest_is_inferred_once_and_warm_truncation_is_occurrence_aware() {
548        let temp = tempfile::tempdir().unwrap();
549        let cache_root = temp.path().join("user-cache");
550        let provider_cache_dir = cache_root.join("models").join(protocol::MODEL_REVISION);
551        let project_root = temp.path().join("project");
552        std::fs::create_dir_all(&cache_root).unwrap();
553        std::fs::create_dir_all(&project_root).unwrap();
554        let digest = SimilarCodeSourceDigest::new([8; 32]);
555        let inputs = [
556            EmbeddingInput {
557                source_sha256: digest,
558                source: "function same() { return 1; }",
559            },
560            EmbeddingInput {
561                source_sha256: digest,
562                source: "function same() { return 1; }",
563            },
564        ];
565
566        let mut cache = cache::VectorCache::load(&provider_cache_dir, &project_root, false);
567        let mut cold = prepare_embedding_plan(&mut cache, &inputs);
568        assert_eq!(cold.cache_misses, 2);
569        assert_eq!(cold.misses.len(), 1);
570        assert_eq!(cold.misses[0].occurrence_indices, vec![0, 1]);
571        apply_embedding_vector(
572            &mut cache,
573            &inputs,
574            &mut cold,
575            0,
576            &[0.25; protocol::MODEL_DIMENSIONS],
577            true,
578        )
579        .unwrap();
580        assert_eq!(cold.truncated_functions, 2);
581        assert!(cold.vectors.iter().all(Option::is_some));
582        assert_eq!(cache.save().durable_writes, 1);
583
584        let mut cache = cache::VectorCache::load(&provider_cache_dir, &project_root, false);
585        let warm = prepare_embedding_plan(&mut cache, &inputs);
586        assert_eq!(warm.cache_hits, 2);
587        assert_eq!(warm.cache_misses, 0);
588        assert_eq!(warm.truncated_functions, 2);
589        assert!(warm.misses.is_empty());
590        assert!(warm.vectors.iter().all(Option::is_some));
591    }
592}