Skip to main content

fallow_engine/duplication_detector/
deepdive.rs

1//! Deep-dive helpers for the `fallow dupes --trace` inspector: a stable
2//! content fingerprint that addresses a clone group across runs, a group-level
3//! refactoring suggestion, and a best-effort "dominant identifier" name for the
4//! extracted function.
5//!
6//! These are pure functions over [`CloneInstance`] / [`CloneGroup`] so every
7//! surface (human listing, `--trace dup:<fp>` lookup, the typed JSON wrappers,
8//! and `trace_clone`) computes the same values without storing a field on the
9//! core [`CloneGroup`] struct.
10
11use std::path::Path;
12
13use fallow_config::DetectionMode;
14use rustc_hash::{FxHashMap, FxHashSet};
15use xxhash_rust::xxh3::{Xxh3, xxh3_64};
16
17use super::tokenize::{
18    FragmentTokenizationKind, FragmentTokenizationStrategy, fragment_tokenization_kind,
19};
20use super::types::{CloneGroup, CloneInstance, RefactoringKind, RefactoringSuggestion};
21
22/// Prefix marking a clone-group fingerprint addressable via `--trace`.
23pub const FINGERPRINT_PREFIX: &str = "dup:";
24
25/// Canonical identity for a clone group when assigning report-scoped handles.
26///
27/// Compact digests of canonically sorted fragments and locations make report
28/// entries addressable without retaining a second copy of every source fragment
29/// and path. Collision suffixes use lexical locations instead of these digests
30/// so a different checkout prefix cannot change their order.
31/// The separately hashed, sorted, deduplicated normalized instance sequences
32/// provide the public content identity.
33#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
34pub struct CloneFingerprintKey {
35    fragments_digest: u128,
36    locations_digest: u128,
37    token_count: usize,
38    line_count: usize,
39    instance_count: usize,
40}
41
42const _: () = assert!(std::mem::size_of::<CloneFingerprintKey>() <= 64);
43
44impl CloneFingerprintKey {
45    /// Build a fingerprint key from clone-group parts.
46    #[must_use]
47    fn from_parts(instances: &[CloneInstance], token_count: usize, line_count: usize) -> Self {
48        Self {
49            fragments_digest: hash_distinct_fragments(instances),
50            locations_digest: hash_sorted_locations(instances),
51            token_count,
52            line_count,
53            instance_count: instances.len(),
54        }
55    }
56
57    fn from_group(group: &CloneGroup) -> Self {
58        Self::from_parts(&group.instances, group.token_count, group.line_count)
59    }
60}
61
62/// Report-scoped clone fingerprint assignment.
63///
64/// Most reports retain the short `dup:<8hex>` handle. If two report entries
65/// collide on those low 32 bits, only the colliding entries widen to
66/// `dup:<16hex>`. If a full 64-bit collision ever occurs inside one report,
67/// every entry in that collision bucket receives a deterministic `-rN` suffix.
68/// Legacy `-N` suffixes deliberately do not resolve, since their assignment
69/// depended on the absolute checkout path and could address a different group.
70#[derive(Debug, Clone)]
71pub struct CloneFingerprintSet {
72    by_key: FxHashMap<CloneFingerprintKey, String>,
73    key_by_fingerprint: FxHashMap<String, CloneFingerprintKey>,
74}
75
76impl CloneFingerprintSet {
77    /// Assign collision-free fingerprints for the report's clone groups.
78    #[must_use]
79    pub fn from_groups(groups: &[CloneGroup]) -> Self {
80        let entries: Vec<_> = groups
81            .iter()
82            .map(|group| (group, hash_instances(&group.instances)))
83            .collect();
84        Self::from_hashed_entries(&entries)
85    }
86
87    /// Return the assigned fingerprint for a clone group.
88    #[must_use]
89    pub fn fingerprint_for_group(&self, group: &CloneGroup) -> String {
90        self.by_key
91            .get(&CloneFingerprintKey::from_group(group))
92            .cloned()
93            .unwrap_or_else(|| clone_fingerprint(&group.instances))
94    }
95
96    /// Return the config key used by `duplicates.ignoredClones` for a group.
97    #[must_use]
98    pub fn ignored_clone_key_for_group(&self, group: &CloneGroup) -> String {
99        format!(
100            "{}:{}",
101            self.fingerprint_for_group(group),
102            group.instances.len()
103        )
104    }
105
106    /// Return the assigned fingerprint for clone-group parts.
107    #[must_use]
108    pub fn fingerprint_for_parts(
109        &self,
110        instances: &[CloneInstance],
111        token_count: usize,
112        line_count: usize,
113    ) -> String {
114        let key = CloneFingerprintKey::from_parts(instances, token_count, line_count);
115        self.by_key
116            .get(&key)
117            .cloned()
118            .unwrap_or_else(|| clone_fingerprint(instances))
119    }
120
121    /// Find the group addressed by an assigned fingerprint.
122    ///
123    /// Ambiguous short handles created by low-32 collisions are intentionally
124    /// absent from the lookup table, so callers get `None` instead of the first
125    /// matching group.
126    #[must_use]
127    pub fn find_group<'a>(
128        &self,
129        groups: &'a [CloneGroup],
130        fingerprint: &str,
131    ) -> Option<&'a CloneGroup> {
132        let key = self.key_by_fingerprint.get(fingerprint)?;
133        groups
134            .iter()
135            .find(|group| CloneFingerprintKey::from_group(group) == *key)
136    }
137
138    fn from_hashed_entries(entries: &[(&CloneGroup, u64)]) -> Self {
139        let mut short_counts: FxHashMap<u32, usize> = FxHashMap::default();
140        let mut full_counts: FxHashMap<u64, usize> = FxHashMap::default();
141        for (_, hash) in entries {
142            *short_counts.entry(*hash as u32).or_insert(0) += 1;
143            *full_counts.entry(*hash).or_insert(0) += 1;
144        }
145
146        // Only full collisions need location ordering. Within one report, a
147        // shared checkout prefix cancels in lexical comparisons. Hashing that
148        // prefix instead would arbitrarily reorder groups after relocation.
149        let mut sorted_entries: Vec<_> = entries
150            .iter()
151            .map(|(group, hash)| {
152                let locations = if full_counts.get(hash).copied().unwrap_or(0) > 1 {
153                    sorted_locations(&group.instances)
154                } else {
155                    Vec::new()
156                };
157                (CloneFingerprintKey::from_group(group), *hash, locations)
158            })
159            .collect();
160        sorted_entries.sort_unstable_by(
161            |(left, left_hash, left_locations), (right, right_hash, right_locations)| {
162                left.fragments_digest
163                    .cmp(&right.fragments_digest)
164                    .then_with(|| left_locations.cmp(right_locations))
165                    .then_with(|| left.token_count.cmp(&right.token_count))
166                    .then_with(|| left.line_count.cmp(&right.line_count))
167                    .then_with(|| left.instance_count.cmp(&right.instance_count))
168                    .then_with(|| left_hash.cmp(right_hash))
169            },
170        );
171
172        let mut full_ordinals: FxHashMap<u64, usize> = FxHashMap::default();
173        let mut ambiguous_short_handles: FxHashSet<String> = FxHashSet::default();
174        let mut by_key = FxHashMap::default();
175        let mut key_by_fingerprint = FxHashMap::default();
176
177        for (key, hash, _) in &sorted_entries {
178            let short = *hash as u32;
179            let short_handle = format!("{FINGERPRINT_PREFIX}{short:08x}");
180            let fingerprint = if short_counts.get(&short).copied().unwrap_or(0) == 1 {
181                short_handle
182            } else {
183                ambiguous_short_handles.insert(short_handle);
184                let full_handle = format!("{FINGERPRINT_PREFIX}{hash:016x}");
185                if full_counts.get(hash).copied().unwrap_or(0) == 1 {
186                    full_handle
187                } else {
188                    let ordinal = full_ordinals.entry(*hash).or_insert(0);
189                    *ordinal += 1;
190                    format!("{full_handle}-r{ordinal}")
191                }
192            };
193
194            key_by_fingerprint.insert(fingerprint.clone(), key.clone());
195            by_key.insert(key.clone(), fingerprint);
196        }
197
198        for handle in ambiguous_short_handles {
199            key_by_fingerprint.remove(&handle);
200        }
201
202        Self {
203            by_key,
204            key_by_fingerprint,
205        }
206    }
207}
208
209/// Compute a mode-independent normalized short content fingerprint for a clone
210/// group from all distinct instance token sequences.
211///
212/// Whitespace, comments, and line endings are absent from the normalized token
213/// hashes. Sorting and deduplicating sequences makes the fingerprint independent
214/// of instance order while ensuring a token edit in any distinct instance
215/// changes the group identity. Instance count is deliberately excluded and is
216/// appended separately by [`CloneFingerprintSet::ignored_clone_key_for_group`].
217///
218/// Use [`CloneFingerprintSet`] for user-facing report output, since it widens
219/// only the rare colliding handles while preserving this short form for the
220/// common case.
221///
222/// Hashes the empty string for an empty group (never produced by the detector,
223/// which guarantees `>= 2` instances), so the result is still a well-formed
224/// `dup:<8hex>` handle.
225#[must_use]
226pub fn clone_fingerprint(instances: &[CloneInstance]) -> String {
227    fingerprint_for_hash(hash_instances(instances))
228}
229
230/// The digest leaves out `\r`. It orders the groups of one full-hash
231/// collision, so a `\r` would swap their `-rN` suffixes between a CRLF and
232/// an LF checkout.
233fn hash_distinct_fragments(instances: &[CloneInstance]) -> u128 {
234    let mut fragments = instances
235        .iter()
236        .map(|instance| without_carriage_returns(&instance.fragment))
237        .collect::<Vec<_>>();
238    fragments.sort_unstable();
239    fragments.dedup();
240
241    let mut hasher = Xxh3::new();
242    for fragment in fragments {
243        update_hash_bytes(&mut hasher, fragment.as_bytes());
244    }
245    hasher.digest128()
246}
247
248fn without_carriage_returns(fragment: &str) -> std::borrow::Cow<'_, str> {
249    if fragment.contains('\r') {
250        std::borrow::Cow::Owned(fragment.replace('\r', ""))
251    } else {
252        std::borrow::Cow::Borrowed(fragment)
253    }
254}
255
256fn sorted_locations(instances: &[CloneInstance]) -> Vec<(&Path, usize, usize)> {
257    let mut locations = instances
258        .iter()
259        .map(|instance| {
260            (
261                instance.file.as_path(),
262                instance.start_line,
263                instance.end_line,
264            )
265        })
266        .collect::<Vec<_>>();
267    locations.sort_unstable();
268    locations
269}
270
271fn hash_sorted_locations(instances: &[CloneInstance]) -> u128 {
272    let mut hasher = Xxh3::new();
273    for (path, start_line, end_line) in sorted_locations(instances) {
274        update_hash_bytes(&mut hasher, path.as_os_str().as_encoded_bytes());
275        hasher.update(&start_line.to_le_bytes());
276        hasher.update(&end_line.to_le_bytes());
277    }
278    hasher.digest128()
279}
280
281fn update_hash_bytes(hasher: &mut Xxh3, bytes: &[u8]) {
282    hasher.update(&bytes.len().to_le_bytes());
283    hasher.update(bytes);
284}
285
286fn hash_instances(instances: &[CloneInstance]) -> u64 {
287    let mut sequences = distinct_fragment_inputs(instances)
288        .into_iter()
289        .map(|(kind, fragment)| normalized_fragment_sequence(kind.path(), fragment))
290        .collect::<Vec<_>>();
291    sequences.sort_unstable();
292    sequences.dedup();
293    hash_normalized_sequences(&sequences)
294}
295
296fn distinct_fragment_inputs(instances: &[CloneInstance]) -> Vec<(FragmentTokenizationKind, &str)> {
297    let mut fragments = instances
298        .iter()
299        .map(|instance| {
300            (
301                fragment_tokenization_kind(
302                    &instance.file,
303                    FragmentTokenizationStrategy::Fingerprint,
304                ),
305                instance.fragment.as_str(),
306            )
307        })
308        .collect::<Vec<_>>();
309    fragments.sort_unstable();
310    fragments.dedup();
311    fragments
312}
313
314fn normalized_fragment_sequence(path: &Path, fragment: &str) -> Vec<u64> {
315    let mut tokens = super::tokenize::tokenize_file(path, fragment, false).tokens;
316    if tokens.is_empty() {
317        // A clone can stop inside a block, so its fragment may not parse on its
318        // own. Without this fallback, every such group hashes to the same empty
319        // sequence and the baseline matches groups by report order.
320        tokens = super::tokenize::tokenize_unparsed_fragment(fragment);
321    }
322    super::normalize::normalize_and_hash(&tokens, DetectionMode::Strict)
323        .into_iter()
324        .map(|token| token.hash)
325        .collect()
326}
327
328fn hash_normalized_sequences(sequences: &[Vec<u64>]) -> u64 {
329    let byte_len = sequences
330        .iter()
331        .map(|sequence| sequence.len().saturating_add(1))
332        .sum::<usize>()
333        .saturating_mul(std::mem::size_of::<u64>());
334    let mut bytes = Vec::with_capacity(byte_len);
335    for sequence in sequences {
336        bytes.extend_from_slice(&(sequence.len() as u64).to_le_bytes());
337        for hash in sequence {
338            bytes.extend_from_slice(&hash.to_le_bytes());
339        }
340    }
341    xxh3_64(&bytes)
342}
343
344/// Report whether a baseline key comes from the shared empty-sequence bucket.
345///
346/// Versions before the fix for issue #3290 gave every clone group whose code
347/// did not parse on its own the hash of an empty token sequence, with a `-rN`
348/// suffix in report order. Such a key cannot address one group, so a baseline
349/// that contains one must be saved again. A report with only one such group
350/// had no suffix, so its key is not detected here. That group shows as new
351/// once, until the next save.
352#[must_use]
353pub fn is_unparsed_collision_key(key: &str) -> bool {
354    let bucket = format!(
355        "{FINGERPRINT_PREFIX}{:016x}-r",
356        hash_normalized_sequences(&[Vec::new()])
357    );
358    key.starts_with(&bucket)
359}
360
361fn fingerprint_for_hash(hash: u64) -> String {
362    format!("{FINGERPRINT_PREFIX}{:08x}", hash as u32)
363}
364
365/// Build a per-group `ExtractFunction` refactoring suggestion.
366///
367/// Mirrors the per-group branch of the families suggestion generator:
368/// the savings is `(instances - 1)` copies of the group's line count, since one
369/// copy survives as the extracted function and the rest collapse to call sites.
370#[must_use]
371pub fn group_refactoring_suggestion(group: &CloneGroup) -> RefactoringSuggestion {
372    let estimated_savings = group.line_count * group.instances.len().saturating_sub(1);
373    RefactoringSuggestion {
374        kind: RefactoringKind::ExtractFunction,
375        description: format!(
376            "Extract the shared {}-line block into one function and call it from {} sites",
377            group.line_count,
378            group.instances.len(),
379        ),
380        estimated_savings,
381    }
382}
383
384/// Best-effort name for the extracted function, derived from the most frequent
385/// non-generic identifier in the representative fragment.
386///
387/// Returns `None` when the dominant identifier is generic (`data`, `result`,
388/// loop counters), appears only once, or ties with another, so absence is the
389/// low-confidence signal for both human and agent consumers. This is a
390/// lexical heuristic over the raw fragment, not an AST analysis; it is advisory
391/// and consumers should verify before applying.
392#[must_use]
393pub fn dominant_identifier(group: &CloneGroup) -> Option<String> {
394    let fragment = group.instances.first().map(|inst| inst.fragment.as_str())?;
395    let mut counts: FxHashMap<&str, usize> = FxHashMap::default();
396    for word in identifier_words(fragment) {
397        if is_generic_identifier(word) {
398            continue;
399        }
400        *counts.entry(word).or_insert(0) += 1;
401    }
402
403    let mut candidates: Vec<_> = counts
404        .into_iter()
405        .map(|(word, count)| IdentifierCandidate {
406            word,
407            count,
408            score: identifier_score(word, count),
409        })
410        .collect();
411    candidates.sort_by(|a, b| {
412        b.score
413            .cmp(&a.score)
414            .then_with(|| b.count.cmp(&a.count))
415            .then_with(|| a.word.cmp(b.word))
416    });
417
418    let best = candidates.first()?;
419    if best.count < 2 {
420        return None;
421    }
422
423    let runner_up = candidates.get(1);
424    if runner_up.is_some_and(|next| best.score.saturating_sub(next.score) < 2) {
425        return None;
426    }
427
428    if is_plain_single_token(best.word) {
429        let next_count = runner_up.map_or(0, |candidate| candidate.count);
430        if best.count < 3 || best.count < next_count + 2 {
431            return None;
432        }
433    }
434
435    Some(best.word.to_string())
436}
437
438#[derive(Debug)]
439struct IdentifierCandidate<'a> {
440    word: &'a str,
441    count: usize,
442    score: usize,
443}
444
445fn identifier_score(word: &str, count: usize) -> usize {
446    let quality_bonus = if has_identifier_separator_or_case_transition(word) {
447        5
448    } else if word.chars().count() >= 8 {
449        2
450    } else {
451        0
452    };
453    count * 5 + quality_bonus
454}
455
456fn is_plain_single_token(word: &str) -> bool {
457    !has_identifier_separator_or_case_transition(word) && word.chars().count() < 8
458}
459
460fn has_identifier_separator_or_case_transition(word: &str) -> bool {
461    if word.contains('_') || word.contains('$') {
462        return true;
463    }
464
465    let mut previous = None;
466    for ch in word.chars() {
467        if previous.is_some_and(|prev: char| prev.is_ascii_lowercase() && ch.is_ascii_uppercase()) {
468            return true;
469        }
470        previous = Some(ch);
471    }
472    false
473}
474
475/// Yield identifier-like words (`[A-Za-z_$][A-Za-z0-9_$]*`) from raw source.
476fn identifier_words(source: &str) -> impl Iterator<Item = &str> {
477    source
478        .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$'))
479        .filter(|word| {
480            !word.is_empty()
481                && word
482                    .chars()
483                    .next()
484                    .is_some_and(|c| c.is_ascii_alphabetic() || c == '_' || c == '$')
485        })
486}
487
488/// Identifiers too generic to make a useful extracted-function name, plus the
489/// reserved words that show up as bare tokens in a fragment.
490const GENERIC_IDENTIFIERS: &[&str] = &[
491    "data",
492    "result",
493    "results",
494    "item",
495    "items",
496    "value",
497    "values",
498    "val",
499    "obj",
500    "object",
501    "arr",
502    "array",
503    "list",
504    "map",
505    "set",
506    "key",
507    "keys",
508    "tmp",
509    "temp",
510    "acc",
511    "cur",
512    "curr",
513    "prev",
514    "next",
515    "node",
516    "el",
517    "elem",
518    "element",
519    "args",
520    "arg",
521    "opts",
522    "options",
523    "params",
524    "param",
525    "props",
526    "ctx",
527    "context",
528    "res",
529    "req",
530    "err",
531    "error",
532    "fn",
533    "cb",
534    "callback",
535    "out",
536    "input",
537    "output",
538    "name",
539    "id",
540    "index",
541    "idx",
542    "x",
543    "y",
544    "z",
545    "i",
546    "j",
547    "k",
548    "n",
549    "m",
550    "a",
551    "b",
552    "c",
553    "e",
554    "_",
555    "const",
556    "let",
557    "var",
558    "function",
559    "return",
560    "if",
561    "else",
562    "for",
563    "while",
564    "do",
565    "switch",
566    "case",
567    "break",
568    "continue",
569    "new",
570    "this",
571    "true",
572    "false",
573    "null",
574    "undefined",
575    "void",
576    "typeof",
577    "instanceof",
578    "in",
579    "of",
580    "class",
581    "extends",
582    "super",
583    "import",
584    "export",
585    "from",
586    "default",
587    "async",
588    "await",
589    "yield",
590    "type",
591    "interface",
592    "enum",
593    "as",
594    "is",
595    "keyof",
596    "readonly",
597    "public",
598    "private",
599    "protected",
600    "static",
601    "get",
602    "delete",
603    "throw",
604    "try",
605    "catch",
606    "finally",
607    "string",
608    "number",
609    "boolean",
610    "any",
611    "unknown",
612    "never",
613    "bigint",
614    "symbol",
615    "Math",
616    "JSON",
617    "Object",
618    "Array",
619    "Promise",
620    "BigInt",
621    "Number",
622    "String",
623    "Boolean",
624    "Symbol",
625    "RegExp",
626    "Date",
627];
628
629fn is_generic_identifier(word: &str) -> bool {
630    word.chars().count() == 1 || GENERIC_IDENTIFIERS.contains(&word)
631}
632
633#[cfg(test)]
634mod tests {
635    use std::path::PathBuf;
636
637    use super::*;
638
639    fn instance(fragment: &str) -> CloneInstance {
640        CloneInstance {
641            is_symlink: false,
642            file: PathBuf::from("a.ts"),
643            start_line: 1,
644            end_line: 5,
645            start_col: 0,
646            end_col: 0,
647            fragment: fragment.to_string(),
648        }
649    }
650
651    fn group(fragments: &[&str], line_count: usize) -> CloneGroup {
652        CloneGroup {
653            instances: fragments.iter().map(|f| instance(f)).collect(),
654            token_count: 40,
655            line_count,
656            similarity: None,
657        }
658    }
659
660    fn relocated_collision_groups(root: &Path) -> Vec<CloneGroup> {
661        ["src", "other"]
662            .into_iter()
663            .map(|directory| {
664                let mut clone = group(&["alpha()", "alpha()"], 2);
665                for (index, instance) in clone.instances.iter_mut().enumerate() {
666                    instance.file = root.join(directory).join(format!("file-{index}.ts"));
667                }
668                clone
669            })
670            .collect()
671    }
672
673    /// A clone that stops before the closing brace of its function does not
674    /// parse on its own.
675    fn unclosed_function_fragment(constant: u32) -> String {
676        format!(
677            "export function scale(items: number[]): number[] {{\n  const out = items.map((item) => item * {constant});\n  return out;\n"
678        )
679    }
680
681    #[test]
682    fn unparseable_fragments_keep_distinct_fingerprints() {
683        let first = unclosed_function_fragment(7);
684        let second = unclosed_function_fragment(13);
685        assert_ne!(
686            hash_instances(&group(&[&first, &first], 3).instances),
687            hash_instances(&group(&[&second, &second], 3).instances),
688            "different code must not share the empty-sequence hash"
689        );
690    }
691
692    #[test]
693    fn detects_keys_from_the_old_empty_sequence_bucket() {
694        assert!(is_unparsed_collision_key("dup:c77b3abb6f87acd9-r3:2"));
695        assert!(!is_unparsed_collision_key("dup:c77b3abb6f87acd9:2"));
696        assert!(!is_unparsed_collision_key("dup:6f87acd9:2"));
697        let fragment = unclosed_function_fragment(7);
698        let fingerprints = CloneFingerprintSet::from_groups(&[group(&[&fragment, &fragment], 3)]);
699        let key = fingerprints.ignored_clone_key_for_group(&group(&[&fragment, &fragment], 3));
700        assert!(!is_unparsed_collision_key(&key));
701    }
702
703    #[test]
704    fn unparseable_fragments_ignore_whitespace_and_comments() {
705        let compact = unclosed_function_fragment(7);
706        let spaced = compact.replace("  return out;", "  // done\n    return   out;");
707        assert_eq!(
708            hash_instances(&group(&[&compact], 3).instances),
709            hash_instances(&group(&[&spaced], 3).instances),
710        );
711    }
712
713    #[test]
714    fn baseline_reports_only_the_new_unparseable_clone() {
715        use super::super::types::DuplicationReport;
716        use crate::baseline::{DuplicationBaselineData, filter_new_clone_groups};
717
718        let root = Path::new("/project");
719        let pair = |constant: u32, name: &str| {
720            let fragment = unclosed_function_fragment(constant);
721            let mut clone = group(&[&fragment, &fragment], 3);
722            for (index, instance) in clone.instances.iter_mut().enumerate() {
723                instance.file = root.join(format!("src/{name}-{index}.ts"));
724            }
725            clone
726        };
727        let baseline_report = DuplicationReport {
728            clone_groups: vec![pair(7, "a"), pair(13, "c"), pair(29, "e")],
729            ..Default::default()
730        };
731        let baseline = DuplicationBaselineData::from_report(&baseline_report, root);
732
733        let mut current = baseline_report.clone_groups;
734        current.push(pair(3, "g"));
735        let filtered = filter_new_clone_groups(
736            DuplicationReport {
737                clone_groups: current,
738                ..Default::default()
739            },
740            &baseline,
741            root,
742        );
743        let files: Vec<_> = filtered
744            .clone_groups
745            .iter()
746            .flat_map(|clone| clone.instances.iter().map(|i| i.file.clone()))
747            .collect();
748        assert_eq!(
749            files,
750            vec![root.join("src/g-0.ts"), root.join("src/g-1.ts")]
751        );
752    }
753
754    #[test]
755    fn fingerprint_set_relocation_preserves_collision_identity() {
756        const RELOCATIONS: usize = 32;
757        let groups = relocated_collision_groups(Path::new("/original/checkout"));
758        let fingerprints = CloneFingerprintSet::from_groups(&groups);
759        let expected = fingerprints.fingerprint_for_group(&groups[0]);
760        for index in 0..RELOCATIONS {
761            let root = PathBuf::from(format!("/different/checkout-{index}/with spaces/café"));
762            let mut relocated = relocated_collision_groups(&root);
763            relocated.reverse();
764            for group in &mut relocated {
765                group.instances.reverse();
766            }
767            let actual = CloneFingerprintSet::from_groups(&relocated);
768            assert_eq!(
769                actual.fingerprint_for_group(&relocated[1]),
770                expected,
771                "{root:?}"
772            );
773            assert!(std::ptr::eq(
774                actual
775                    .find_group(&relocated, &expected)
776                    .expect("relocated trace handle resolves"),
777                &raw const relocated[1],
778            ));
779            assert_eq!(
780                actual.fingerprint_for_parts(
781                    &relocated[1].instances,
782                    relocated[1].token_count,
783                    relocated[1].line_count
784                ),
785                expected,
786            );
787        }
788    }
789
790    #[test]
791    fn corrected_collision_handles_do_not_alias_legacy_ordinals() {
792        let groups = relocated_collision_groups(Path::new("/project"));
793        let fingerprints = CloneFingerprintSet::from_groups(&groups);
794        for group in &groups {
795            let corrected = fingerprints.fingerprint_for_group(group);
796            assert!(corrected.contains("-r"));
797            let legacy = corrected.replacen("-r", "-", 1);
798            assert!(fingerprints.find_group(&groups, &legacy).is_none());
799            assert!(fingerprints.find_group(&groups, &corrected).is_some());
800        }
801    }
802
803    #[test]
804    fn relocated_collision_suppression_matches_only_corrected_handles() {
805        use super::super::types::DuplicationReport;
806        use crate::baseline::{DuplicationBaselineData, filter_new_clone_groups};
807
808        let original = DuplicationReport {
809            clone_groups: relocated_collision_groups(Path::new("/original/checkout")),
810            ..Default::default()
811        };
812        let fingerprints = CloneFingerprintSet::from_groups(&original.clone_groups);
813        let reviewed = fingerprints.ignored_clone_key_for_group(&original.clone_groups[0]);
814        let baseline =
815            DuplicationBaselineData::from_report(&original, Path::new("/original/checkout"));
816        let root = Path::new("/relocated/with spaces/café");
817        let mut relocated = DuplicationReport {
818            clone_groups: relocated_collision_groups(root),
819            ..Default::default()
820        };
821        relocated.clone_groups.reverse();
822        for group in &mut relocated.clone_groups {
823            group.instances.reverse();
824        }
825        let remaining_location = relocated.clone_groups[0].instances[0].file.clone();
826
827        let mut ignored = relocated.clone();
828        super::super::apply_ignored_clones_filter(&mut ignored, std::slice::from_ref(&reviewed));
829        assert_eq!(ignored.clone_groups.len(), 1);
830        assert_eq!(
831            ignored.clone_groups[0].instances[0].file,
832            remaining_location
833        );
834        assert_eq!(ignored.stats.clone_groups_ignored, 1);
835
836        let mut partial_baseline =
837            DuplicationBaselineData::from_report(&original, Path::new("/original/checkout"));
838        partial_baseline.normalized_clone_fingerprints = vec![reviewed.clone()];
839        // The baseline filter returns the report order, so the instance order
840        // of the reversed input does not survive. The location still names
841        // the group that stays.
842        let filtered = filter_new_clone_groups(relocated.clone(), &partial_baseline, root);
843        assert_eq!(filtered.clone_groups.len(), 1);
844        assert!(
845            filtered.clone_groups[0]
846                .instances
847                .iter()
848                .any(|instance| instance.file == remaining_location)
849        );
850        assert!(
851            filter_new_clone_groups(relocated.clone(), &baseline, root)
852                .clone_groups
853                .is_empty()
854        );
855
856        let legacy = reviewed.replacen("-r", "-", 1);
857        super::super::apply_ignored_clones_filter(&mut relocated, std::slice::from_ref(&legacy));
858        assert_eq!(relocated.clone_groups.len(), original.clone_groups.len());
859        partial_baseline.normalized_clone_fingerprints = vec![legacy];
860        // Populated old raw/location fields must not turn a normalized-key miss
861        // into an ambiguous fallback suppression.
862        let filtered = filter_new_clone_groups(relocated, &partial_baseline, root);
863        assert_eq!(filtered.clone_groups.len(), original.clone_groups.len());
864    }
865
866    #[test]
867    fn fingerprint_is_stable_and_prefixed() {
868        let g = group(&["foo(bar)", "foo(baz)"], 3);
869        let fp1 = clone_fingerprint(&g.instances);
870        let fp2 = clone_fingerprint(&g.instances);
871        assert_eq!(fp1, fp2);
872        assert!(fp1.starts_with("dup:"));
873        assert_eq!(fp1.len(), "dup:".len() + 8);
874    }
875
876    #[test]
877    fn compact_fingerprint_key_is_independent_of_instance_order() {
878        let mut original = group(&["alpha()", "beta()"], 3);
879        original.instances[0].file = PathBuf::from("src/a.ts");
880        original.instances[0].start_line = 2;
881        original.instances[1].file = PathBuf::from("src/b.ts");
882        original.instances[1].start_line = 8;
883        let mut reordered = original.clone();
884        reordered.instances.reverse();
885
886        assert_eq!(
887            CloneFingerprintKey::from_group(&original),
888            CloneFingerprintKey::from_group(&reordered)
889        );
890    }
891
892    #[test]
893    fn duplicate_fragments_are_deduplicated_before_tokenization() {
894        let mut clones = group(&["alpha()", "alpha()", "alpha()"], 2);
895        clones.instances[0].file = PathBuf::from("src/a.ts");
896        clones.instances[1].file = PathBuf::from("src/b.ts");
897        clones.instances[2].file = PathBuf::from("src/c.ts");
898        assert_eq!(distinct_fragment_inputs(&clones.instances).len(), 1);
899
900        clones.instances[2].file = PathBuf::from("src/c.css");
901        assert_eq!(
902            distinct_fragment_inputs(&clones.instances).len(),
903            2,
904            "equal source still needs separate tokenization when syntax differs"
905        );
906    }
907
908    #[test]
909    fn fingerprint_is_sibling_stable() {
910        let group_a = group(&["computeInvoiceTotal(order)", "computeInvoiceTotal(o)"], 4);
911        let before = clone_fingerprint(&group_a.instances);
912        let _group_b_edited = group(&["totallyDifferentBody()"], 2);
913        let after = clone_fingerprint(&group_a.instances);
914        assert_eq!(before, after);
915    }
916
917    #[test]
918    fn fingerprint_differs_for_different_content() {
919        let a = group(&["alpha()"], 2);
920        let b = group(&["beta()"], 2);
921        assert_ne!(
922            clone_fingerprint(&a.instances),
923            clone_fingerprint(&b.instances)
924        );
925    }
926
927    /// Two groups whose fragments differ only in a comment share one full
928    /// hash, so the `-rN` suffix follows the order of their fragment digests.
929    fn colliding_groups(variant: usize, line_ending: &str) -> Vec<CloneGroup> {
930        ["left", "right"]
931            .into_iter()
932            .map(|side| {
933                let fragment = format!("alpha();{line_ending}// {side} {variant}{line_ending}");
934                let mut clone = group(&[&fragment, &fragment], 2);
935                for (index, instance) in clone.instances.iter_mut().enumerate() {
936                    instance.file = PathBuf::from(format!("{side}-{index}.ts"));
937                }
938                clone
939            })
940            .collect()
941    }
942
943    #[test]
944    fn collision_suffixes_ignore_line_endings() {
945        for variant in 0..16 {
946            let lf = colliding_groups(variant, "\n");
947            let crlf = colliding_groups(variant, "\r\n");
948            let lf_set = CloneFingerprintSet::from_groups(&lf);
949            let crlf_set = CloneFingerprintSet::from_groups(&crlf);
950            let lf_handles: Vec<_> = lf.iter().map(|g| lf_set.fingerprint_for_group(g)).collect();
951            let crlf_handles: Vec<_> = crlf
952                .iter()
953                .map(|g| crlf_set.fingerprint_for_group(g))
954                .collect();
955            assert!(lf_handles[0].ends_with("-r1") || lf_handles[0].ends_with("-r2"));
956            assert_eq!(lf_handles, crlf_handles, "variant {variant}");
957        }
958    }
959
960    #[test]
961    fn fingerprint_ignores_formatting_comments_and_line_endings() {
962        let compact = group(
963            &["const total = left + right;", "const total = left + right;"],
964            2,
965        );
966        let formatted = group(
967            &[
968                "const  total=left + right; // reviewed\r\n",
969                "/* reviewed */\nconst total = left + right;",
970            ],
971            3,
972        );
973
974        assert_eq!(
975            clone_fingerprint(&compact.instances),
976            clone_fingerprint(&formatted.instances)
977        );
978    }
979
980    #[test]
981    fn fingerprint_changes_when_any_distinct_instance_changes_tokens() {
982        let reviewed = group(&["alpha()", "alpha()"], 2);
983        let edited = group(&["alpha()", "beta()"], 2);
984
985        assert_ne!(
986            clone_fingerprint(&reviewed.instances),
987            clone_fingerprint(&edited.instances)
988        );
989    }
990
991    #[test]
992    fn fingerprint_is_independent_of_instance_order_and_count() {
993        let two = group(&["alpha()", "beta()"], 2);
994        let three_reordered = group(&["beta()", "alpha()", "alpha()"], 2);
995
996        assert_eq!(
997            clone_fingerprint(&two.instances),
998            clone_fingerprint(&three_reordered.instances)
999        );
1000
1001        let two_set = CloneFingerprintSet::from_groups(std::slice::from_ref(&two));
1002        let three_set = CloneFingerprintSet::from_groups(std::slice::from_ref(&three_reordered));
1003        assert_ne!(
1004            two_set.ignored_clone_key_for_group(&two),
1005            three_set.ignored_clone_key_for_group(&three_reordered)
1006        );
1007    }
1008
1009    #[test]
1010    fn fingerprint_set_widens_only_colliding_short_handles() {
1011        let a = group(&["alpha()"], 2);
1012        let b = group(&["beta()"], 2);
1013        let c = group(&["gamma()"], 2);
1014        let entries = vec![
1015            (&a, 0x0000_0001_1234_5678_u64),
1016            (&b, 0x0000_0002_1234_5678_u64),
1017            (&c, 0x0000_0003_8765_4321_u64),
1018        ];
1019
1020        let fingerprints = CloneFingerprintSet::from_hashed_entries(&entries);
1021
1022        assert_eq!(
1023            fingerprints.fingerprint_for_group(&a),
1024            "dup:0000000112345678"
1025        );
1026        assert_eq!(
1027            fingerprints.fingerprint_for_group(&b),
1028            "dup:0000000212345678"
1029        );
1030        assert_eq!(fingerprints.fingerprint_for_group(&c), "dup:87654321");
1031        assert!(
1032            fingerprints
1033                .find_group(&[a.clone(), b.clone(), c.clone()], "dup:12345678")
1034                .is_none()
1035        );
1036        assert_eq!(
1037            fingerprints
1038                .find_group(&[a, b, c], "dup:0000000212345678")
1039                .and_then(|group| group.instances.first())
1040                .map(|inst| inst.fragment.as_str()),
1041            Some("beta()")
1042        );
1043    }
1044
1045    #[test]
1046    fn fingerprint_set_suffixes_full_hash_collisions() {
1047        let a = group(&["alpha()"], 2);
1048        let b = group(&["beta()"], 2);
1049        let mut entries = vec![
1050            (&a, 0x0000_0001_1234_5678_u64),
1051            (&b, 0x0000_0001_1234_5678_u64),
1052        ];
1053
1054        let fingerprints = CloneFingerprintSet::from_hashed_entries(&entries);
1055        entries.reverse();
1056        let reversed_fingerprints = CloneFingerprintSet::from_hashed_entries(&entries);
1057
1058        let a_fingerprint = fingerprints.fingerprint_for_group(&a);
1059        let b_fingerprint = fingerprints.fingerprint_for_group(&b);
1060        assert_eq!(
1061            a_fingerprint,
1062            reversed_fingerprints.fingerprint_for_group(&a)
1063        );
1064        assert_eq!(
1065            b_fingerprint,
1066            reversed_fingerprints.fingerprint_for_group(&b)
1067        );
1068        let mut assigned = vec![a_fingerprint, b_fingerprint];
1069        assigned.sort_unstable();
1070        assert_eq!(
1071            assigned,
1072            ["dup:0000000112345678-r1", "dup:0000000112345678-r2"]
1073        );
1074        assert!(
1075            fingerprints
1076                .find_group(&[a.clone(), b.clone()], "dup:12345678")
1077                .is_none()
1078        );
1079        assert!(
1080            fingerprints
1081                .find_group(&[a, b], "dup:0000000112345678")
1082                .is_none()
1083        );
1084    }
1085
1086    #[test]
1087    fn group_suggestion_savings_is_lines_times_extra_copies() {
1088        let g = group(&["x", "x", "x"], 10); // 3 instances, 10 lines
1089        let suggestion = group_refactoring_suggestion(&g);
1090        assert_eq!(suggestion.kind, RefactoringKind::ExtractFunction);
1091        assert_eq!(suggestion.estimated_savings, 20); // 10 * (3 - 1)
1092    }
1093
1094    #[test]
1095    fn dominant_identifier_picks_repeated_domain_name() {
1096        let g = group(
1097            &["function buildInvoice(invoice) { return invoice.total + invoice.tax; }"],
1098            3,
1099        );
1100        assert_eq!(dominant_identifier(&g).as_deref(), Some("invoice"));
1101    }
1102
1103    #[test]
1104    fn dominant_identifier_none_on_generic() {
1105        let g = group(&["const data = result.map((item) => item.value);"], 3);
1106        assert_eq!(dominant_identifier(&g), None);
1107    }
1108
1109    #[test]
1110    fn dominant_identifier_skips_ts_primitive_keywords_and_globals() {
1111        let g = group(
1112            &["const parseUser = z.string(); parseUser(z.number()); parseUser.or(z.string());"],
1113            4,
1114        );
1115        assert_eq!(dominant_identifier(&g).as_deref(), Some("parseUser"));
1116        let only_keywords = group(&["const x: string = y as string; return x as any;"], 3);
1117        assert_eq!(dominant_identifier(&only_keywords), None);
1118        let g_global = group(&["Math.max(Math.floor(Math.abs(v)), 0)"], 3);
1119        assert_eq!(dominant_identifier(&g_global), None);
1120    }
1121
1122    #[test]
1123    fn dominant_identifier_none_on_single_letter_type_param() {
1124        let g = group(
1125            &["function id<T>(x: T): T { const a: T = x; return a as T; }"],
1126            3,
1127        );
1128        assert_eq!(dominant_identifier(&g), None);
1129    }
1130
1131    #[test]
1132    fn dominant_identifier_none_on_tie() {
1133        let g = group(&["alpha(); beta();"], 2); // each appears once, no count >= 2
1134        assert_eq!(dominant_identifier(&g), None);
1135    }
1136
1137    #[test]
1138    fn dominant_identifier_prefers_structured_names() {
1139        let g = group(
1140            &["parseSchema(input); parseSchema(cache); helper(); helper();"],
1141            3,
1142        );
1143        assert_eq!(dominant_identifier(&g).as_deref(), Some("parseSchema"));
1144    }
1145
1146    #[test]
1147    fn dominant_identifier_requires_plain_token_margin() {
1148        let low_signal = group(&["schema(); schema(); parseUser();"], 3);
1149        assert_eq!(dominant_identifier(&low_signal), None);
1150
1151        let strong = group(&["schema(); schema(); schema(); schema(); parseUser();"], 3);
1152        assert_eq!(dominant_identifier(&strong).as_deref(), Some("schema"));
1153    }
1154
1155    #[test]
1156    fn dominant_identifier_is_stable_across_word_order() {
1157        let first = group(
1158            &["helper(); parseSchema(input); helper(); parseSchema(cache);"],
1159            3,
1160        );
1161        let second = group(
1162            &["parseSchema(input); helper(); parseSchema(cache); helper();"],
1163            3,
1164        );
1165
1166        assert_eq!(dominant_identifier(&first), dominant_identifier(&second));
1167        assert_eq!(dominant_identifier(&first).as_deref(), Some("parseSchema"));
1168    }
1169}