1use std::collections::VecDeque;
8use std::fmt;
9use std::mem::size_of;
10
11use rustc_hash::FxHashMap;
12use sha2::{Digest, Sha256};
13
14pub use fallow_types::similar_code::{
15 SIMILAR_CODE_EXTRACTION_SEMANTICS_VERSION as EXTRACTION_SEMANTICS_VERSION,
16 SimilarCodeFunctionLocation as FunctionLocation, SimilarCodeSourceDigest,
17};
18
19#[derive(Debug, Clone)]
21pub struct FunctionVector {
22 pub location: FunctionLocation,
24 pub source_sha256: SimilarCodeSourceDigest,
26 pub extraction_semantics_version: u32,
28 pub values: Vec<f32>,
30}
31
32#[derive(Debug, Clone, Copy)]
34pub struct SimilarCodeSelectionInput<'a> {
35 pub location: &'a FunctionLocation,
37 pub source_sha256: SimilarCodeSourceDigest,
39 pub in_scope: bool,
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub struct SimilarCodeLimits {
46 pub dimensions: usize,
48 pub max_functions: usize,
50 pub max_comparisons: usize,
52 pub max_candidates: usize,
54 pub max_neighbors_per_function: usize,
56 pub max_vector_bytes: usize,
58}
59
60impl SimilarCodeLimits {
61 #[must_use]
63 pub const fn for_dimensions(dimensions: usize) -> Self {
64 Self {
65 dimensions,
66 max_functions: 10_000,
67 max_comparisons: 1_000_000,
68 max_candidates: 4_096,
69 max_neighbors_per_function: 20,
70 max_vector_bytes: 256 * 1024 * 1024,
71 }
72 }
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
77#[non_exhaustive]
78pub enum SimilarCodeSkipReason {
79 FunctionLimit,
81 VectorMemoryLimit,
83 ComparisonLimit,
85 CandidateLimit,
87 NeighborLimit,
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93pub struct SimilarCodeSkip {
94 pub reason: SimilarCodeSkipReason,
96 pub count: usize,
98}
99
100#[derive(Debug, Clone, PartialEq, Eq)]
102pub struct SimilarCodeCorpusSelection {
103 pub selected_indices: Vec<usize>,
105 pub selected_in_scope: Vec<bool>,
107 pub skipped: Vec<SimilarCodeSkip>,
109}
110
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub enum SimilarCodeCompletionStatus {
114 Complete,
116 Partial,
118}
119
120#[derive(Debug, Clone, PartialEq, Eq)]
122pub struct SimilarCodeCompletion {
123 pub status: SimilarCodeCompletionStatus,
125 pub limits: SimilarCodeLimits,
127 pub functions_considered: usize,
129 pub comparisons_performed: usize,
131 pub skipped: Vec<SimilarCodeSkip>,
133}
134
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137#[non_exhaustive]
138pub enum SimilarCodeVerificationStatus {
139 Unverified,
141}
142
143#[derive(Debug, Clone, PartialEq)]
145pub struct SimilarCodeCandidate {
146 pub candidate_id: String,
148 pub review_key: String,
150 pub left: FunctionLocation,
152 pub right: FunctionLocation,
154 pub similarity: f64,
156 pub verification_status: SimilarCodeVerificationStatus,
158}
159
160#[derive(Debug, Clone, PartialEq)]
162pub struct SimilarCodeEvaluation {
163 pub candidates: Vec<SimilarCodeCandidate>,
165 pub completion: SimilarCodeCompletion,
167}
168
169#[derive(Debug, Clone, PartialEq, Eq)]
171#[non_exhaustive]
172pub enum SimilarCodeError {
173 ZeroDimensions,
175 InvalidThreshold,
177 ExtractionVersion {
179 location: FunctionLocation,
181 expected: u32,
183 actual: u32,
185 },
186 DimensionMismatch {
188 location: FunctionLocation,
190 expected: usize,
192 actual: usize,
194 },
195 NonFiniteVector {
197 location: FunctionLocation,
199 },
200 ZeroMagnitudeVector {
202 location: FunctionLocation,
204 },
205 DuplicateFunctionIdentity {
207 location: FunctionLocation,
209 },
210 SelectionLengthMismatch {
212 expected: usize,
214 actual: usize,
216 },
217 SelectionLimitExceeded {
219 reason: SimilarCodeSkipReason,
221 observed: usize,
223 limit: usize,
225 },
226}
227
228impl fmt::Display for SimilarCodeError {
229 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
230 match self {
231 Self::ZeroDimensions => formatter.write_str("similar-code dimensions must be positive"),
232 Self::InvalidThreshold => {
233 formatter.write_str("similar-code threshold must be finite and between -1 and 1")
234 }
235 Self::ExtractionVersion {
236 location,
237 expected,
238 actual,
239 } => write!(
240 formatter,
241 "{}:{} uses extraction version {actual}, expected {expected}",
242 location.file, location.start_line
243 ),
244 Self::DimensionMismatch {
245 location,
246 expected,
247 actual,
248 } => write!(
249 formatter,
250 "{}:{} has {actual} vector dimensions, expected {expected}",
251 location.file, location.start_line
252 ),
253 Self::NonFiniteVector { location } => write!(
254 formatter,
255 "{}:{} contains a non-finite vector value",
256 location.file, location.start_line
257 ),
258 Self::ZeroMagnitudeVector { location } => write!(
259 formatter,
260 "{}:{} has a zero-magnitude vector",
261 location.file, location.start_line
262 ),
263 Self::DuplicateFunctionIdentity { location } => write!(
264 formatter,
265 "{}:{}:{} has duplicate similar-code vector input",
266 location.file, location.start_line, location.start_column_utf8
267 ),
268 Self::SelectionLengthMismatch { expected, actual } => write!(
269 formatter,
270 "similar-code selection expected {expected} aligned entries, received {actual}"
271 ),
272 Self::SelectionLimitExceeded {
273 reason,
274 observed,
275 limit,
276 } => write!(
277 formatter,
278 "similar-code preselection exceeded {reason:?}: observed {observed}, limit {limit}"
279 ),
280 }
281 }
282}
283
284impl std::error::Error for SimilarCodeError {}
285
286#[derive(Debug, Clone, PartialEq, Eq, Hash)]
288pub struct VectorCacheKey {
289 pub function_source_sha256: SimilarCodeSourceDigest,
291 pub extraction_semantics_version: u32,
293 pub model_id: String,
295 pub model_revision: String,
297 pub dimensions: usize,
299 pub provider_parameter_digest: u64,
301}
302
303#[derive(Debug)]
308pub struct SimilarCodeVectorCache {
309 max_payload_bytes: usize,
310 used_payload_bytes: usize,
311 entries: FxHashMap<VectorCacheKey, Box<[f32]>>,
312 insertion_order: VecDeque<VectorCacheKey>,
313}
314
315impl SimilarCodeVectorCache {
316 #[must_use]
318 pub fn new(max_bytes: usize) -> Self {
319 Self {
320 max_payload_bytes: max_bytes,
321 used_payload_bytes: 0,
322 entries: FxHashMap::default(),
323 insertion_order: VecDeque::new(),
324 }
325 }
326
327 #[must_use]
329 pub fn get(&self, key: &VectorCacheKey) -> Option<&[f32]> {
330 self.entries.get(key).map(AsRef::as_ref)
331 }
332
333 pub fn insert(&mut self, key: VectorCacheKey, values: Vec<f32>) -> bool {
338 if values.len() != key.dimensions
339 || values.iter().any(|value| !value.is_finite())
340 || values.iter().all(|value| is_zero(*value))
341 {
342 return false;
343 }
344 let bytes = vector_bytes(values.len());
345 if bytes > self.max_payload_bytes {
346 return false;
347 }
348
349 if let Some(existing) = self.entries.get_mut(&key) {
350 self.used_payload_bytes = self
351 .used_payload_bytes
352 .saturating_sub(vector_bytes(existing.len()))
353 .saturating_add(bytes);
354 *existing = values.into_boxed_slice();
355 return true;
356 }
357
358 while self.used_payload_bytes.saturating_add(bytes) > self.max_payload_bytes {
359 let Some(oldest) = self.insertion_order.pop_front() else {
360 return false;
361 };
362 if let Some(removed) = self.entries.remove(&oldest) {
363 self.used_payload_bytes = self
364 .used_payload_bytes
365 .saturating_sub(vector_bytes(removed.len()));
366 }
367 }
368
369 self.used_payload_bytes = self.used_payload_bytes.saturating_add(bytes);
370 self.insertion_order.push_back(key.clone());
371 self.entries.insert(key, values.into_boxed_slice());
372 true
373 }
374
375 #[must_use]
377 pub fn len(&self) -> usize {
378 self.entries.len()
379 }
380
381 #[must_use]
383 pub fn is_empty(&self) -> bool {
384 self.entries.is_empty()
385 }
386}
387
388#[derive(Debug, Clone)]
389struct ScoredPair {
390 left: usize,
391 right: usize,
392 similarity: f64,
393}
394
395#[derive(Debug, Clone, Copy)]
396struct SelectedVector {
397 index: usize,
398 inverse_norm: f64,
399 in_scope: bool,
400}
401
402pub fn validate_function_vectors(
404 vectors: &[FunctionVector],
405 dimensions: usize,
406 extraction_semantics_version: u32,
407) -> Result<(), SimilarCodeError> {
408 if dimensions == 0 {
409 return Err(SimilarCodeError::ZeroDimensions);
410 }
411
412 for vector in vectors {
413 let _inverse_norm = validate_vector(vector, dimensions, extraction_semantics_version)?;
414 }
415 Ok(())
416}
417
418pub fn evaluate_similar_code(
420 vectors: &[FunctionVector],
421 threshold: f64,
422 limits: SimilarCodeLimits,
423 extraction_semantics_version: u32,
424) -> Result<SimilarCodeEvaluation, SimilarCodeError> {
425 if limits.dimensions == 0 {
426 return Err(SimilarCodeError::ZeroDimensions);
427 }
428 if !threshold.is_finite() || !(-1.0..=1.0).contains(&threshold) {
429 return Err(SimilarCodeError::InvalidThreshold);
430 }
431 let mut skips = FxHashMap::default();
432 let selected = select_vectors(vectors, limits, extraction_semantics_version, &mut skips)?;
433 let (ranked, comparisons_performed) = score_pairs(vectors, &selected, threshold, limits);
434 let candidates = build_candidates(
435 vectors,
436 &selected,
437 ranked,
438 limits,
439 extraction_semantics_version,
440 &mut skips,
441 );
442
443 let mut skipped = skips
444 .into_iter()
445 .filter(|(_, count)| *count > 0)
446 .map(|(reason, count)| SimilarCodeSkip { reason, count })
447 .collect::<Vec<_>>();
448 skipped.sort_by_key(|skip| skip.reason);
449
450 Ok(SimilarCodeEvaluation {
451 candidates,
452 completion: SimilarCodeCompletion {
453 status: if skipped.is_empty() {
454 SimilarCodeCompletionStatus::Complete
455 } else {
456 SimilarCodeCompletionStatus::Partial
457 },
458 limits,
459 functions_considered: selected.len(),
460 comparisons_performed,
461 skipped,
462 },
463 })
464}
465
466pub fn evaluate_selected_similar_code(
471 vectors: &[FunctionVector],
472 selection: &SimilarCodeCorpusSelection,
473 threshold: f64,
474 limits: SimilarCodeLimits,
475 extraction_semantics_version: u32,
476) -> Result<SimilarCodeEvaluation, SimilarCodeError> {
477 if selection.selected_in_scope.len() != selection.selected_indices.len() {
478 return Err(SimilarCodeError::SelectionLengthMismatch {
479 expected: selection.selected_indices.len(),
480 actual: selection.selected_in_scope.len(),
481 });
482 }
483 if vectors.len() != selection.selected_indices.len() {
484 return Err(SimilarCodeError::SelectionLengthMismatch {
485 expected: selection.selected_indices.len(),
486 actual: vectors.len(),
487 });
488 }
489
490 if limits.dimensions == 0 {
491 return Err(SimilarCodeError::ZeroDimensions);
492 }
493 if !threshold.is_finite() || !(-1.0..=1.0).contains(&threshold) {
494 return Err(SimilarCodeError::InvalidThreshold);
495 }
496 validate_preselection_limits(&selection.selected_in_scope, limits)?;
497 let selection_inputs = vectors
498 .iter()
499 .zip(&selection.selected_in_scope)
500 .map(|(vector, &in_scope)| SimilarCodeSelectionInput {
501 location: &vector.location,
502 source_sha256: vector.source_sha256,
503 in_scope,
504 })
505 .collect::<Vec<_>>();
506 validated_occurrence_identities(&selection_inputs)?;
507 let selected = vectors
508 .iter()
509 .zip(&selection.selected_in_scope)
510 .enumerate()
511 .map(|(index, (vector, &in_scope))| {
512 let inverse_norm =
513 validate_vector(vector, limits.dimensions, extraction_semantics_version)?;
514 Ok(SelectedVector {
515 index,
516 inverse_norm,
517 in_scope,
518 })
519 })
520 .collect::<Result<Vec<_>, SimilarCodeError>>()?;
521 let mut skips = FxHashMap::default();
522 let (ranked, comparisons_performed) = score_pairs(vectors, &selected, threshold, limits);
523 let candidates = build_candidates(
524 vectors,
525 &selected,
526 ranked,
527 limits,
528 extraction_semantics_version,
529 &mut skips,
530 );
531 let mut evaluation = SimilarCodeEvaluation {
532 candidates,
533 completion: SimilarCodeCompletion {
534 status: SimilarCodeCompletionStatus::Complete,
535 limits,
536 functions_considered: selected.len(),
537 comparisons_performed,
538 skipped: skips
539 .into_iter()
540 .map(|(reason, count)| SimilarCodeSkip { reason, count })
541 .collect(),
542 },
543 };
544 let mut skipped = evaluation
545 .completion
546 .skipped
547 .drain(..)
548 .map(|skip| (skip.reason, skip.count))
549 .collect::<FxHashMap<_, _>>();
550 for skip in &selection.skipped {
551 record_skip(&mut skipped, skip.reason, skip.count);
552 }
553 evaluation.completion.skipped = skipped
554 .into_iter()
555 .map(|(reason, count)| SimilarCodeSkip { reason, count })
556 .collect();
557 evaluation
558 .completion
559 .skipped
560 .sort_by_key(|skip| skip.reason);
561 if !evaluation.completion.skipped.is_empty() {
562 evaluation.completion.status = SimilarCodeCompletionStatus::Partial;
563 }
564 Ok(evaluation)
565}
566
567fn validate_preselection_limits(
568 selected_in_scope: &[bool],
569 limits: SimilarCodeLimits,
570) -> Result<(), SimilarCodeError> {
571 let functions = selected_in_scope.len();
572 if functions > limits.max_functions {
573 return Err(SimilarCodeError::SelectionLimitExceeded {
574 reason: SimilarCodeSkipReason::FunctionLimit,
575 observed: functions,
576 limit: limits.max_functions,
577 });
578 }
579 let vector_bytes = functions.saturating_mul(vector_bytes(limits.dimensions));
580 if vector_bytes > limits.max_vector_bytes {
581 return Err(SimilarCodeError::SelectionLimitExceeded {
582 reason: SimilarCodeSkipReason::VectorMemoryLimit,
583 observed: vector_bytes,
584 limit: limits.max_vector_bytes,
585 });
586 }
587 let scoped_functions = selected_in_scope
588 .iter()
589 .filter(|&&in_scope| in_scope)
590 .count();
591 let comparisons = scoped_pair_count(functions, scoped_functions);
592 if comparisons > limits.max_comparisons {
593 return Err(SimilarCodeError::SelectionLimitExceeded {
594 reason: SimilarCodeSkipReason::ComparisonLimit,
595 observed: comparisons,
596 limit: limits.max_comparisons,
597 });
598 }
599 Ok(())
600}
601
602pub fn select_similar_code_corpus(
608 functions: &[SimilarCodeSelectionInput<'_>],
609 limits: SimilarCodeLimits,
610) -> Result<SimilarCodeCorpusSelection, SimilarCodeError> {
611 if limits.dimensions == 0 {
612 return Err(SimilarCodeError::ZeroDimensions);
613 }
614
615 let scoped_functions = functions
616 .iter()
617 .filter(|function| function.in_scope)
618 .count();
619 if scoped_functions == 0 {
620 return Ok(SimilarCodeCorpusSelection {
621 selected_indices: Vec::new(),
622 selected_in_scope: Vec::new(),
623 skipped: Vec::new(),
624 });
625 }
626
627 let occurrence_identities = validated_occurrence_identities(functions)?;
628
629 let memory_function_limit = limits
630 .max_vector_bytes
631 .checked_div(vector_bytes(limits.dimensions))
632 .unwrap_or(0);
633 let function_limit = functions.len().min(limits.max_functions);
634 let memory_considered = function_limit.min(memory_function_limit);
635 let considered = functions_within_scoped_comparison_budget(
636 memory_considered,
637 scoped_functions,
638 limits.max_comparisons,
639 );
640
641 let order = selected_corpus_order(functions, &occurrence_identities, considered);
642
643 let mut skips = FxHashMap::default();
644 record_skip(
645 &mut skips,
646 SimilarCodeSkipReason::FunctionLimit,
647 functions.len().saturating_sub(function_limit),
648 );
649 record_skip(
650 &mut skips,
651 SimilarCodeSkipReason::VectorMemoryLimit,
652 function_limit.saturating_sub(memory_considered),
653 );
654 record_skip(
655 &mut skips,
656 SimilarCodeSkipReason::ComparisonLimit,
657 scoped_pair_count(memory_considered, scoped_functions.min(memory_considered))
658 .saturating_sub(scoped_pair_count(
659 considered,
660 scoped_functions.min(considered),
661 )),
662 );
663 let mut skipped = skips
664 .into_iter()
665 .map(|(reason, count)| SimilarCodeSkip { reason, count })
666 .collect::<Vec<_>>();
667 skipped.sort_by_key(|skip| skip.reason);
668
669 let selected_in_scope = order
670 .iter()
671 .map(|&index| functions[index].in_scope)
672 .collect();
673 Ok(SimilarCodeCorpusSelection {
674 selected_indices: order,
675 selected_in_scope,
676 skipped,
677 })
678}
679
680fn validated_occurrence_identities(
681 functions: &[SimilarCodeSelectionInput<'_>],
682) -> Result<Vec<String>, SimilarCodeError> {
683 let occurrence_identities = functions
684 .iter()
685 .map(|function| occurrence_identity_for_location(function.location))
686 .collect::<Vec<_>>();
687 let mut identity_order = (0..functions.len()).collect::<Vec<_>>();
688 identity_order.sort_by(|&left, &right| {
689 occurrence_identities[left]
690 .cmp(&occurrence_identities[right])
691 .then_with(|| {
692 functions[left]
693 .source_sha256
694 .cmp(&functions[right].source_sha256)
695 })
696 });
697 for duplicate in identity_order.windows(2) {
698 if occurrence_identities[duplicate[0]] == occurrence_identities[duplicate[1]] {
699 return Err(SimilarCodeError::DuplicateFunctionIdentity {
700 location: functions[duplicate[0]].location.clone(),
701 });
702 }
703 }
704 Ok(occurrence_identities)
705}
706
707fn selected_corpus_order(
708 functions: &[SimilarCodeSelectionInput<'_>],
709 occurrence_identities: &[String],
710 considered: usize,
711) -> Vec<usize> {
712 let selection_keys = functions.iter().map(selection_key).collect::<Vec<_>>();
713 let compare_selection = |&left: &usize, &right: &usize| {
714 selection_keys[left]
715 .cmp(&selection_keys[right])
716 .then_with(|| {
717 functions[left]
718 .source_sha256
719 .cmp(&functions[right].source_sha256)
720 })
721 .then_with(|| occurrence_identities[left].cmp(&occurrence_identities[right]))
722 };
723 let mut scoped = (0..functions.len())
724 .filter(|&index| functions[index].in_scope)
725 .collect::<Vec<_>>();
726 let mut background = (0..functions.len())
727 .filter(|&index| !functions[index].in_scope)
728 .collect::<Vec<_>>();
729 scoped.sort_by(compare_selection);
730 background.sort_by(compare_selection);
731 scoped.truncate(considered);
732 background.truncate(considered.saturating_sub(scoped.len()));
733 scoped.extend(background);
734 scoped.sort_by(|&left, &right| {
735 occurrence_identities[left]
736 .cmp(&occurrence_identities[right])
737 .then_with(|| {
738 functions[left]
739 .source_sha256
740 .cmp(&functions[right].source_sha256)
741 })
742 });
743 scoped
744}
745
746fn select_vectors(
747 vectors: &[FunctionVector],
748 limits: SimilarCodeLimits,
749 extraction_semantics_version: u32,
750 skips: &mut FxHashMap<SimilarCodeSkipReason, usize>,
751) -> Result<Vec<SelectedVector>, SimilarCodeError> {
752 let functions = vectors
753 .iter()
754 .map(|vector| SimilarCodeSelectionInput {
755 location: &vector.location,
756 source_sha256: vector.source_sha256,
757 in_scope: true,
758 })
759 .collect::<Vec<_>>();
760 let selection = select_similar_code_corpus(&functions, limits)?;
761 for skip in selection.skipped {
762 record_skip(skips, skip.reason, skip.count);
763 }
764 selection
765 .selected_indices
766 .into_iter()
767 .zip(selection.selected_in_scope)
768 .map(|(index, in_scope)| {
769 let inverse_norm = validate_vector(
770 &vectors[index],
771 limits.dimensions,
772 extraction_semantics_version,
773 )?;
774 Ok(SelectedVector {
775 index,
776 inverse_norm,
777 in_scope,
778 })
779 })
780 .collect::<Result<Vec<_>, SimilarCodeError>>()
781}
782
783fn score_pairs(
784 vectors: &[FunctionVector],
785 selected: &[SelectedVector],
786 threshold: f64,
787 limits: SimilarCodeLimits,
788) -> (Vec<ScoredPair>, usize) {
789 let scoped_functions = selected.iter().filter(|vector| vector.in_scope).count();
790 let possible_comparisons = scoped_pair_count(selected.len(), scoped_functions);
791 debug_assert!(possible_comparisons <= limits.max_comparisons);
792 let mut comparisons_performed = 0usize;
793 let mut ranked = Vec::with_capacity(possible_comparisons);
794
795 for left in 0..selected.len() {
796 for right in left + 1..selected.len() {
797 if !selected[left].in_scope && !selected[right].in_scope {
798 continue;
799 }
800 comparisons_performed += 1;
801 let similarity = cosine_similarity(
802 &vectors[selected[left].index],
803 &vectors[selected[right].index],
804 selected[left].inverse_norm,
805 selected[right].inverse_norm,
806 );
807 if similarity < threshold {
808 continue;
809 }
810 ranked.push(ScoredPair {
811 left,
812 right,
813 similarity,
814 });
815 }
816 }
817
818 ranked.sort_by(|left, right| {
819 right
820 .similarity
821 .total_cmp(&left.similarity)
822 .then_with(|| left.left.cmp(&right.left))
823 .then_with(|| left.right.cmp(&right.right))
824 });
825 (ranked, comparisons_performed)
826}
827
828fn build_candidates(
829 vectors: &[FunctionVector],
830 selected: &[SelectedVector],
831 ranked: Vec<ScoredPair>,
832 limits: SimilarCodeLimits,
833 extraction_semantics_version: u32,
834 skips: &mut FxHashMap<SimilarCodeSkipReason, usize>,
835) -> Vec<SimilarCodeCandidate> {
836 let mut neighbors = vec![0usize; selected.len()];
837 let mut candidates = Vec::with_capacity(ranked.len().min(limits.max_candidates));
838 for pair in ranked {
839 if candidates.len() >= limits.max_candidates {
840 record_skip(skips, SimilarCodeSkipReason::CandidateLimit, 1);
841 continue;
842 }
843 if neighbors[pair.left] >= limits.max_neighbors_per_function
844 || neighbors[pair.right] >= limits.max_neighbors_per_function
845 {
846 record_skip(skips, SimilarCodeSkipReason::NeighborLimit, 1);
847 continue;
848 }
849 neighbors[pair.left] += 1;
850 neighbors[pair.right] += 1;
851
852 let left = &vectors[selected[pair.left].index];
853 let right = &vectors[selected[pair.right].index];
854 let (left, right) = canonical_pair(left, right);
855 candidates.push(SimilarCodeCandidate {
856 candidate_id: candidate_id(left, right, extraction_semantics_version),
857 review_key: review_key(left, right, extraction_semantics_version),
858 left: normalized_location(&left.location),
859 right: normalized_location(&right.location),
860 similarity: pair.similarity,
861 verification_status: SimilarCodeVerificationStatus::Unverified,
862 });
863 }
864 candidates
865}
866
867fn validate_vector(
868 vector: &FunctionVector,
869 dimensions: usize,
870 extraction_semantics_version: u32,
871) -> Result<f64, SimilarCodeError> {
872 if vector.extraction_semantics_version != extraction_semantics_version {
873 return Err(SimilarCodeError::ExtractionVersion {
874 location: vector.location.clone(),
875 expected: extraction_semantics_version,
876 actual: vector.extraction_semantics_version,
877 });
878 }
879 if vector.values.len() != dimensions {
880 return Err(SimilarCodeError::DimensionMismatch {
881 location: vector.location.clone(),
882 expected: dimensions,
883 actual: vector.values.len(),
884 });
885 }
886 if vector.values.iter().any(|value| !value.is_finite()) {
887 return Err(SimilarCodeError::NonFiniteVector {
888 location: vector.location.clone(),
889 });
890 }
891 if vector.values.iter().all(|value| is_zero(*value)) {
892 return Err(SimilarCodeError::ZeroMagnitudeVector {
893 location: vector.location.clone(),
894 });
895 }
896 let squared_norm = vector.values.iter().fold(0.0, |norm, &value| {
897 let value = f64::from(value);
898 value.mul_add(value, norm)
899 });
900 Ok(squared_norm.sqrt().recip())
901}
902
903fn cosine_similarity(
904 left: &FunctionVector,
905 right: &FunctionVector,
906 left_inverse_norm: f64,
907 right_inverse_norm: f64,
908) -> f64 {
909 let mut dot = 0.0;
910 for (&left_value, &right_value) in left.values.iter().zip(&right.values) {
911 let left_value = f64::from(left_value);
912 let right_value = f64::from(right_value);
913 dot = left_value.mul_add(right_value, dot);
914 }
915 (dot * left_inverse_norm * right_inverse_norm).clamp(-1.0, 1.0)
916}
917
918const fn is_zero(value: f32) -> bool {
919 value.to_bits().trailing_zeros() >= 31
920}
921
922fn candidate_id(
923 left: &FunctionVector,
924 right: &FunctionVector,
925 extraction_semantics_version: u32,
926) -> String {
927 let mut hasher = Sha256::new();
928 hasher.update(b"fallow:similar-code:candidate-snapshot:v1\0");
929 hasher.update(extraction_semantics_version.to_be_bytes());
930 update_snapshot_identity(&mut hasher, left);
931 update_snapshot_identity(&mut hasher, right);
932 format_digest_id("similar-code:candidate:v1:", hasher.finalize().as_ref())
933}
934
935fn review_key(
936 left: &FunctionVector,
937 right: &FunctionVector,
938 extraction_semantics_version: u32,
939) -> String {
940 let (first, second) = if left.source_sha256 <= right.source_sha256 {
941 (left.source_sha256, right.source_sha256)
942 } else {
943 (right.source_sha256, left.source_sha256)
944 };
945 let mut hasher = Sha256::new();
946 hasher.update(b"fallow:similar-code:review-key:v1\0");
947 hasher.update(extraction_semantics_version.to_be_bytes());
948 hasher.update(first.as_bytes());
949 hasher.update(second.as_bytes());
950 format_digest_id("similar-code:review:v1:", hasher.finalize().as_ref())
951}
952
953fn canonical_pair<'a>(
954 left: &'a FunctionVector,
955 right: &'a FunctionVector,
956) -> (&'a FunctionVector, &'a FunctionVector) {
957 let left_occurrence = occurrence_identity(left);
958 let right_occurrence = occurrence_identity(right);
959 if (left.source_sha256, left_occurrence) <= (right.source_sha256, right_occurrence) {
960 (left, right)
961 } else {
962 (right, left)
963 }
964}
965
966fn update_snapshot_identity(hasher: &mut Sha256, vector: &FunctionVector) {
967 hasher.update(vector.source_sha256.as_bytes());
968 let occurrence = occurrence_identity(vector);
969 hasher.update(
970 u64::try_from(occurrence.len())
971 .unwrap_or(u64::MAX)
972 .to_be_bytes(),
973 );
974 hasher.update(occurrence.as_bytes());
975}
976
977fn selection_key(function: &SimilarCodeSelectionInput<'_>) -> [u8; 32] {
978 let mut hasher = Sha256::new();
979 hasher.update(b"fallow:similar-code:corpus-selection:v1\0");
980 hasher.update(function.source_sha256.as_bytes());
981 let occurrence = occurrence_identity_for_location(function.location);
982 hasher.update(
983 u64::try_from(occurrence.len())
984 .unwrap_or(u64::MAX)
985 .to_be_bytes(),
986 );
987 hasher.update(occurrence.as_bytes());
988 hasher.finalize().into()
989}
990
991fn format_digest_id(prefix: &str, digest: &[u8]) -> String {
992 const HEX: &[u8; 16] = b"0123456789abcdef";
993 let mut output = String::with_capacity(prefix.len().saturating_add(digest.len() * 2));
994 output.push_str(prefix);
995 for byte in digest {
996 output.push(char::from(HEX[usize::from(byte >> 4)]));
997 output.push(char::from(HEX[usize::from(byte & 0x0f)]));
998 }
999 output
1000}
1001
1002fn occurrence_identity(vector: &FunctionVector) -> String {
1003 occurrence_identity_for_location(&vector.location)
1004}
1005
1006fn occurrence_identity_for_location(location: &FunctionLocation) -> String {
1007 let location = normalized_location(location);
1008 let path = location.file;
1009 format!(
1010 "{}:{path}:{}:{}:{}:{}:{}:{}",
1011 path.len(),
1012 location.start_byte,
1013 location.end_byte,
1014 location.start_line,
1015 location.start_column_utf8,
1016 location.end_line,
1017 location.end_column_utf8
1018 )
1019}
1020
1021fn normalized_location(location: &FunctionLocation) -> FunctionLocation {
1022 FunctionLocation {
1023 file: location.file.replace('\\', "/"),
1024 start_byte: location.start_byte,
1025 end_byte: location.end_byte,
1026 start_line: location.start_line,
1027 start_column_utf8: location.start_column_utf8,
1028 end_line: location.end_line,
1029 end_column_utf8: location.end_column_utf8,
1030 }
1031}
1032
1033fn record_skip(
1034 skips: &mut FxHashMap<SimilarCodeSkipReason, usize>,
1035 reason: SimilarCodeSkipReason,
1036 count: usize,
1037) {
1038 if count > 0 {
1039 let value = skips.entry(reason).or_default();
1040 *value = value.saturating_add(count);
1041 }
1042}
1043
1044const fn vector_bytes(dimensions: usize) -> usize {
1045 dimensions.saturating_mul(size_of::<f32>())
1046}
1047
1048const fn pair_count(functions: usize) -> usize {
1049 functions.saturating_mul(functions.saturating_sub(1)) / 2
1050}
1051
1052const fn scoped_pair_count(functions: usize, scoped_functions: usize) -> usize {
1053 pair_count(functions).saturating_sub(pair_count(functions.saturating_sub(scoped_functions)))
1054}
1055
1056fn functions_within_scoped_comparison_budget(
1057 max_functions: usize,
1058 scoped_functions: usize,
1059 max_comparisons: usize,
1060) -> usize {
1061 if scoped_functions == 0 {
1062 return 0;
1063 }
1064 let mut low = 0usize;
1065 let mut high = max_functions;
1066 while low < high {
1067 let middle = low + (high - low).div_ceil(2);
1068 let comparisons = scoped_pair_count(middle, scoped_functions.min(middle));
1069 if comparisons <= max_comparisons {
1070 low = middle;
1071 } else {
1072 high = middle.saturating_sub(1);
1073 }
1074 }
1075 low
1076}
1077
1078#[cfg(test)]
1079mod tests {
1080 use super::*;
1081
1082 const DIMENSIONS: usize = 256;
1083
1084 fn digest(seed: u64) -> SimilarCodeSourceDigest {
1085 let mut bytes = [0; 32];
1086 bytes[24..].copy_from_slice(&seed.to_be_bytes());
1087 SimilarCodeSourceDigest::new(bytes)
1088 }
1089
1090 fn vector(file: &str, hash: u64, first: f32, second: f32) -> FunctionVector {
1091 let mut values = vec![0.0; DIMENSIONS];
1092 values[0] = first;
1093 values[1] = second;
1094 FunctionVector {
1095 location: FunctionLocation {
1096 file: file.into(),
1097 start_byte: 0,
1098 end_byte: 100,
1099 start_line: 1,
1100 start_column_utf8: 0,
1101 end_line: 10,
1102 end_column_utf8: 1,
1103 },
1104 source_sha256: digest(hash),
1105 extraction_semantics_version: EXTRACTION_SEMANTICS_VERSION,
1106 values,
1107 }
1108 }
1109
1110 fn limits() -> SimilarCodeLimits {
1111 SimilarCodeLimits {
1112 dimensions: DIMENSIONS,
1113 max_functions: 100,
1114 max_comparisons: 100,
1115 max_candidates: 100,
1116 max_neighbors_per_function: 100,
1117 max_vector_bytes: 100 * DIMENSIONS * size_of::<f32>(),
1118 }
1119 }
1120
1121 #[test]
1122 fn recorded_vectors_find_only_the_similar_pair() {
1123 let result = evaluate_similar_code(
1124 &[
1125 vector("src/a.ts", 0x10, 1.0, 0.0),
1126 vector("src/b.ts", 0x20, 0.98, 0.02),
1127 vector("src/c.ts", 0x30, 0.0, 1.0),
1128 ],
1129 0.95,
1130 limits(),
1131 EXTRACTION_SEMANTICS_VERSION,
1132 )
1133 .unwrap();
1134
1135 assert_eq!(result.candidates.len(), 1);
1136 assert!(
1137 result.candidates[0]
1138 .candidate_id
1139 .starts_with("similar-code:candidate:v1:")
1140 );
1141 assert!(
1142 result.candidates[0]
1143 .review_key
1144 .starts_with("similar-code:review:v1:")
1145 );
1146 assert_eq!(
1147 result.candidates[0].verification_status,
1148 SimilarCodeVerificationStatus::Unverified
1149 );
1150 assert_eq!(
1151 result.completion.status,
1152 SimilarCodeCompletionStatus::Complete
1153 );
1154 }
1155
1156 #[test]
1157 fn candidate_identity_and_order_ignore_input_order() {
1158 let forward = vec![
1159 vector("src/a.ts", 0x30, 1.0, 0.0),
1160 vector("src/b.ts", 0x10, 1.0, 0.0),
1161 vector("src/c.ts", 0x20, 1.0, 0.0),
1162 ];
1163 let mut reverse = forward.clone();
1164 reverse.reverse();
1165
1166 let forward =
1167 evaluate_similar_code(&forward, 0.9, limits(), EXTRACTION_SEMANTICS_VERSION).unwrap();
1168 let reverse =
1169 evaluate_similar_code(&reverse, 0.9, limits(), EXTRACTION_SEMANTICS_VERSION).unwrap();
1170
1171 assert_eq!(forward, reverse);
1172 }
1173
1174 #[test]
1175 fn candidate_identity_and_output_normalize_path_separators() {
1176 let unix = evaluate_similar_code(
1177 &[
1178 vector("src/a.ts", 0x10, 1.0, 0.0),
1179 vector("src/b.ts", 0x20, 1.0, 0.0),
1180 ],
1181 0.9,
1182 limits(),
1183 EXTRACTION_SEMANTICS_VERSION,
1184 )
1185 .unwrap();
1186 let windows = evaluate_similar_code(
1187 &[
1188 vector("src\\a.ts", 0x10, 1.0, 0.0),
1189 vector("src\\b.ts", 0x20, 1.0, 0.0),
1190 ],
1191 0.9,
1192 limits(),
1193 EXTRACTION_SEMANTICS_VERSION,
1194 )
1195 .unwrap();
1196
1197 assert_eq!(unix, windows);
1198 }
1199
1200 #[test]
1201 fn repeated_content_at_distinct_locations_has_unique_candidate_ids() {
1202 let result = evaluate_similar_code(
1203 &[
1204 vector("src/a.ts", 1, 1.0, 0.0),
1205 vector("src/b.ts", 1, 1.0, 0.0),
1206 vector("src/c.ts", 1, 1.0, 0.0),
1207 ],
1208 0.9,
1209 limits(),
1210 EXTRACTION_SEMANTICS_VERSION,
1211 )
1212 .unwrap();
1213 let ids = result
1214 .candidates
1215 .iter()
1216 .map(|candidate| candidate.candidate_id.as_str())
1217 .collect::<rustc_hash::FxHashSet<_>>();
1218 let review_keys = result
1219 .candidates
1220 .iter()
1221 .map(|candidate| candidate.review_key.as_str())
1222 .collect::<rustc_hash::FxHashSet<_>>();
1223
1224 assert_eq!(ids.len(), result.candidates.len());
1225 assert_eq!(review_keys.len(), 1);
1226 }
1227
1228 #[test]
1229 fn review_key_survives_moves_while_candidate_id_tracks_snapshot() {
1230 let original = evaluate_similar_code(
1231 &[
1232 vector("src/a.ts", 1, 1.0, 0.0),
1233 vector("src/b.ts", 2, 1.0, 0.0),
1234 ],
1235 0.9,
1236 limits(),
1237 EXTRACTION_SEMANTICS_VERSION,
1238 )
1239 .unwrap();
1240 let moved = evaluate_similar_code(
1241 &[
1242 vector("packages/core/a.ts", 1, 1.0, 0.0),
1243 vector("packages/core/b.ts", 2, 1.0, 0.0),
1244 ],
1245 0.9,
1246 limits(),
1247 EXTRACTION_SEMANTICS_VERSION,
1248 )
1249 .unwrap();
1250
1251 assert_ne!(
1252 original.candidates[0].candidate_id,
1253 moved.candidates[0].candidate_id
1254 );
1255 assert_eq!(
1256 original.candidates[0].review_key,
1257 moved.candidates[0].review_key
1258 );
1259 }
1260
1261 #[test]
1262 fn comparison_budget_selects_a_stable_fair_corpus_and_checks_every_pair() {
1263 let vectors = (0..6)
1264 .map(|index| vector(&format!("src/{index}.ts"), index, 1.0, 0.0))
1265 .collect::<Vec<_>>();
1266 let mut bounded = limits();
1267 bounded.max_functions = vectors.len();
1268 bounded.max_comparisons = 3;
1269 bounded.max_candidates = 3;
1270
1271 let inputs = vectors
1272 .iter()
1273 .map(|vector| SimilarCodeSelectionInput {
1274 location: &vector.location,
1275 source_sha256: vector.source_sha256,
1276 in_scope: true,
1277 })
1278 .collect::<Vec<_>>();
1279 let corpus = select_similar_code_corpus(&inputs, bounded).unwrap();
1280 let expected = corpus
1281 .selected_indices
1282 .iter()
1283 .copied()
1284 .map(|index| vectors[index].location.file.as_str())
1285 .collect::<rustc_hash::FxHashSet<_>>();
1286
1287 let direct =
1288 evaluate_similar_code(&vectors, 0.9, bounded, EXTRACTION_SEMANTICS_VERSION).unwrap();
1289 let embedded = corpus
1290 .selected_indices
1291 .iter()
1292 .map(|&index| vectors[index].clone())
1293 .collect::<Vec<_>>();
1294 let result = evaluate_selected_similar_code(
1295 &embedded,
1296 &corpus,
1297 0.9,
1298 bounded,
1299 EXTRACTION_SEMANTICS_VERSION,
1300 )
1301 .unwrap();
1302 let selected = result
1303 .candidates
1304 .iter()
1305 .flat_map(|candidate| [candidate.left.file.as_str(), candidate.right.file.as_str()])
1306 .collect::<rustc_hash::FxHashSet<_>>();
1307
1308 assert_eq!(result.completion.functions_considered, 3);
1309 assert_eq!(result.completion.comparisons_performed, 3);
1310 assert_eq!(selected, expected);
1311 assert_eq!(result.completion.skipped, corpus.skipped);
1312 assert_eq!(result, direct);
1313 }
1314
1315 #[test]
1316 fn scoped_functions_receive_priority_inside_the_comparison_budget() {
1317 let vectors = (0..6)
1318 .map(|index| vector(&format!("src/{index}.ts"), index, 1.0, 0.0))
1319 .collect::<Vec<_>>();
1320 let mut bounded = limits();
1321 bounded.max_functions = vectors.len();
1322 bounded.max_comparisons = 3;
1323 let inputs = vectors
1324 .iter()
1325 .enumerate()
1326 .map(|(index, vector)| SimilarCodeSelectionInput {
1327 location: &vector.location,
1328 source_sha256: vector.source_sha256,
1329 in_scope: index == 5,
1330 })
1331 .collect::<Vec<_>>();
1332
1333 let selection = select_similar_code_corpus(&inputs, bounded).unwrap();
1334
1335 assert!(selection.selected_indices.contains(&5));
1336 assert_eq!(selection.selected_indices.len(), 4);
1337 assert_eq!(
1338 selection
1339 .selected_in_scope
1340 .iter()
1341 .filter(|&&value| value)
1342 .count(),
1343 1
1344 );
1345 }
1346
1347 #[test]
1348 fn empty_scope_does_not_admit_or_embed_background_functions() {
1349 let vectors = (0..6)
1350 .map(|index| vector(&format!("src/{index}.ts"), index, 1.0, 0.0))
1351 .collect::<Vec<_>>();
1352 let inputs = vectors
1353 .iter()
1354 .map(|vector| SimilarCodeSelectionInput {
1355 location: &vector.location,
1356 source_sha256: vector.source_sha256,
1357 in_scope: false,
1358 })
1359 .collect::<Vec<_>>();
1360
1361 let mut bounded = limits();
1362 bounded.max_functions = 1;
1363 bounded.max_vector_bytes = vector_bytes(DIMENSIONS);
1364 bounded.max_comparisons = 0;
1365 let selection = select_similar_code_corpus(&inputs, bounded).unwrap();
1366
1367 assert!(selection.selected_indices.is_empty());
1368 assert!(selection.selected_in_scope.is_empty());
1369 assert!(selection.skipped.is_empty());
1370 }
1371
1372 #[test]
1373 fn scoped_evaluation_rejects_background_only_pairs() {
1374 let vectors = vec![
1375 vector("src/scoped.ts", 1, 1.0, 0.0),
1376 vector("src/background-a.ts", 2, 1.0, 0.0),
1377 vector("src/background-b.ts", 3, 1.0, 0.0),
1378 ];
1379 let selection = SimilarCodeCorpusSelection {
1380 selected_indices: vec![0, 1, 2],
1381 selected_in_scope: vec![true, false, false],
1382 skipped: Vec::new(),
1383 };
1384
1385 let result = evaluate_selected_similar_code(
1386 &vectors,
1387 &selection,
1388 0.9,
1389 limits(),
1390 EXTRACTION_SEMANTICS_VERSION,
1391 )
1392 .unwrap();
1393
1394 assert_eq!(result.completion.comparisons_performed, 2);
1395 assert_eq!(result.candidates.len(), 2);
1396 assert!(result.candidates.iter().all(|candidate| {
1397 candidate.left.file == "src/scoped.ts" || candidate.right.file == "src/scoped.ts"
1398 }));
1399 }
1400
1401 #[test]
1402 fn preselected_evaluation_enforces_every_hard_corpus_limit() {
1403 let vectors = vec![
1404 vector("src/a.ts", 1, 1.0, 0.0),
1405 vector("src/b.ts", 2, 1.0, 0.0),
1406 vector("src/c.ts", 3, 1.0, 0.0),
1407 ];
1408 let selection = SimilarCodeCorpusSelection {
1409 selected_indices: vec![0, 1, 2],
1410 selected_in_scope: vec![true, true, true],
1411 skipped: Vec::new(),
1412 };
1413
1414 let mut bounded = limits();
1415 bounded.max_functions = 2;
1416 assert!(matches!(
1417 evaluate_selected_similar_code(
1418 &vectors,
1419 &selection,
1420 0.9,
1421 bounded,
1422 EXTRACTION_SEMANTICS_VERSION,
1423 ),
1424 Err(SimilarCodeError::SelectionLimitExceeded {
1425 reason: SimilarCodeSkipReason::FunctionLimit,
1426 ..
1427 })
1428 ));
1429
1430 bounded = limits();
1431 bounded.max_vector_bytes = vector_bytes(DIMENSIONS) * 2;
1432 assert!(matches!(
1433 evaluate_selected_similar_code(
1434 &vectors,
1435 &selection,
1436 0.9,
1437 bounded,
1438 EXTRACTION_SEMANTICS_VERSION,
1439 ),
1440 Err(SimilarCodeError::SelectionLimitExceeded {
1441 reason: SimilarCodeSkipReason::VectorMemoryLimit,
1442 ..
1443 })
1444 ));
1445
1446 bounded = limits();
1447 bounded.max_comparisons = 2;
1448 assert!(matches!(
1449 evaluate_selected_similar_code(
1450 &vectors,
1451 &selection,
1452 0.9,
1453 bounded,
1454 EXTRACTION_SEMANTICS_VERSION,
1455 ),
1456 Err(SimilarCodeError::SelectionLimitExceeded {
1457 reason: SimilarCodeSkipReason::ComparisonLimit,
1458 ..
1459 })
1460 ));
1461 }
1462
1463 #[test]
1464 fn preselected_evaluation_rejects_duplicate_physical_functions() {
1465 let duplicate = vector("src/a.ts", 1, 1.0, 0.0);
1466 let vectors = vec![duplicate.clone(), duplicate];
1467 let selection = SimilarCodeCorpusSelection {
1468 selected_indices: vec![0, 1],
1469 selected_in_scope: vec![true, true],
1470 skipped: Vec::new(),
1471 };
1472
1473 assert!(matches!(
1474 evaluate_selected_similar_code(
1475 &vectors,
1476 &selection,
1477 0.9,
1478 limits(),
1479 EXTRACTION_SEMANTICS_VERSION,
1480 ),
1481 Err(SimilarCodeError::DuplicateFunctionIdentity { .. })
1482 ));
1483 }
1484
1485 #[test]
1486 fn neighbor_filter_backfills_before_the_global_candidate_limit() {
1487 let mut bounded = limits();
1488 bounded.max_comparisons = 6;
1489 bounded.max_candidates = 2;
1490 bounded.max_neighbors_per_function = 1;
1491
1492 let result = evaluate_similar_code(
1493 &[
1494 vector("src/a.ts", 1, 1.0, 0.0),
1495 vector("src/b.ts", 2, 1.0, 0.0),
1496 vector("src/c.ts", 3, 1.0, 0.0),
1497 vector("src/d.ts", 4, 1.0, 0.0),
1498 ],
1499 0.9,
1500 bounded,
1501 EXTRACTION_SEMANTICS_VERSION,
1502 )
1503 .unwrap();
1504
1505 assert_eq!(result.candidates.len(), 2);
1506 assert!(result.completion.skipped.iter().any(|skip| {
1507 skip.reason == SimilarCodeSkipReason::NeighborLimit && skip.count == 4
1508 }));
1509 assert!(
1510 !result
1511 .completion
1512 .skipped
1513 .iter()
1514 .any(|skip| skip.reason == SimilarCodeSkipReason::CandidateLimit)
1515 );
1516 }
1517
1518 #[test]
1519 fn invalid_vectors_fail_closed() {
1520 let mut wrong_dimensions = vector("src/a.ts", 1, 1.0, 0.0);
1521 wrong_dimensions.values.pop();
1522 assert!(matches!(
1523 validate_function_vectors(
1524 &[wrong_dimensions],
1525 DIMENSIONS,
1526 EXTRACTION_SEMANTICS_VERSION
1527 ),
1528 Err(SimilarCodeError::DimensionMismatch { .. })
1529 ));
1530
1531 let mut non_finite = vector("src/a.ts", 1, 1.0, 0.0);
1532 non_finite.values[0] = f32::NAN;
1533 assert!(matches!(
1534 validate_function_vectors(&[non_finite], DIMENSIONS, EXTRACTION_SEMANTICS_VERSION),
1535 Err(SimilarCodeError::NonFiniteVector { .. })
1536 ));
1537
1538 let mut zero = vector("src/a.ts", 1, 1.0, 0.0);
1539 zero.values.fill(0.0);
1540 assert!(matches!(
1541 validate_function_vectors(&[zero], DIMENSIONS, EXTRACTION_SEMANTICS_VERSION),
1542 Err(SimilarCodeError::ZeroMagnitudeVector { .. })
1543 ));
1544 }
1545
1546 #[test]
1547 fn limits_report_partial_work_with_stable_reasons() {
1548 let mut bounded = limits();
1549 bounded.max_functions = 3;
1550 bounded.max_comparisons = 1;
1551 bounded.max_candidates = 1;
1552 bounded.max_neighbors_per_function = 0;
1553 let result = evaluate_similar_code(
1554 &[
1555 vector("src/d.ts", 4, 1.0, 0.0),
1556 vector("src/c.ts", 3, 1.0, 0.0),
1557 vector("src/b.ts", 2, 1.0, 0.0),
1558 vector("src/a.ts", 1, 1.0, 0.0),
1559 ],
1560 0.9,
1561 bounded,
1562 EXTRACTION_SEMANTICS_VERSION,
1563 )
1564 .unwrap();
1565
1566 assert!(result.candidates.is_empty());
1567 assert_eq!(
1568 result.completion.status,
1569 SimilarCodeCompletionStatus::Partial
1570 );
1571 assert_eq!(
1572 result.completion.skipped,
1573 vec![
1574 SimilarCodeSkip {
1575 reason: SimilarCodeSkipReason::FunctionLimit,
1576 count: 1,
1577 },
1578 SimilarCodeSkip {
1579 reason: SimilarCodeSkipReason::ComparisonLimit,
1580 count: 2,
1581 },
1582 SimilarCodeSkip {
1583 reason: SimilarCodeSkipReason::NeighborLimit,
1584 count: 1,
1585 },
1586 ]
1587 );
1588 }
1589
1590 #[test]
1591 fn pathological_candidate_limit_does_not_preallocate_without_pairs() {
1592 let mut untrusted = limits();
1593 untrusted.max_functions = usize::MAX;
1594 untrusted.max_comparisons = usize::MAX;
1595 untrusted.max_candidates = usize::MAX;
1596
1597 let result =
1598 evaluate_similar_code(&[], 0.9, untrusted, EXTRACTION_SEMANTICS_VERSION).unwrap();
1599
1600 assert!(result.candidates.is_empty());
1601 assert_eq!(
1602 result.completion.status,
1603 SimilarCodeCompletionStatus::Complete
1604 );
1605 }
1606
1607 #[test]
1608 fn duplicate_stable_function_identity_fails_independent_of_input_order() {
1609 let first = vector("src/a.ts", 1, 1.0, 0.0);
1610 let mut conflicting = first.clone();
1611 conflicting.source_sha256 = digest(2);
1612 conflicting.values[0] = 0.5;
1613 conflicting.values[1] = 0.5;
1614
1615 for vectors in [
1616 vec![first.clone(), conflicting.clone()],
1617 vec![conflicting, first],
1618 ] {
1619 assert!(matches!(
1620 evaluate_similar_code(&vectors, 0.9, limits(), EXTRACTION_SEMANTICS_VERSION,),
1621 Err(SimilarCodeError::DuplicateFunctionIdentity { .. })
1622 ));
1623 }
1624 }
1625
1626 #[test]
1627 fn vector_cache_is_separate_bounded_and_revision_keyed() {
1628 let key = |hash, revision: &str| VectorCacheKey {
1629 function_source_sha256: digest(hash),
1630 extraction_semantics_version: EXTRACTION_SEMANTICS_VERSION,
1631 model_id: "fixture-model".to_string(),
1632 model_revision: revision.to_string(),
1633 dimensions: 2,
1634 provider_parameter_digest: 7,
1635 };
1636 let mut cache = SimilarCodeVectorCache::new(2 * 2 * size_of::<f32>());
1637
1638 assert!(cache.insert(key(1, "model@a"), vec![1.0, 0.0]));
1639 assert!(!cache.insert(key(9, "model@a"), vec![f32::NAN, 0.0]));
1640 assert!(!cache.insert(key(9, "model@a"), vec![0.0, -0.0]));
1641 assert!(cache.insert(key(2, "model@a"), vec![0.0, 1.0]));
1642 assert!(cache.insert(key(3, "model@b"), vec![0.5, 0.5]));
1643
1644 assert!(cache.get(&key(1, "model@a")).is_none());
1645 assert_eq!(cache.get(&key(2, "model@a")), Some([0.0, 1.0].as_slice()));
1646 assert_eq!(cache.get(&key(3, "model@b")), Some([0.5, 0.5].as_slice()));
1647 assert_eq!(cache.len(), 2);
1648 assert_eq!(cache.used_payload_bytes, 4 * size_of::<f32>());
1649 }
1650}