1use fallow_engine::session::AnalysisSession;
2use fallow_types::duplicates::DuplicationReport;
3use rustc_hash::FxHashSet;
4
5use crate::{
6 DependencyUsageQuery, ProgrammaticAnalysisContext, ProgrammaticError, TraceCloneOptions,
7 TraceCloneProgrammaticOutput, TraceCloneTarget, TraceDependencyOptions,
8 TraceDependencyProgrammaticOutput, TraceErrorOptions, TraceErrorProgrammaticOutput,
9 TraceExportOptions, TraceExportProgrammaticOutput, TraceExportTargetOutput, TraceFileOptions,
10 TraceFileProgrammaticOutput, TraceImportPathOptions, TraceImportPathProgrammaticOutput,
11};
12
13use super::{ProgrammaticResult, duplication, resolve_programmatic_analysis_context};
14use crate::analysis_context::validate_workspace_selection;
15use crate::run::{ProgrammaticEntry, ResolvedRun, resolve_programmatic_run};
16
17struct TraceArtifacts {
18 graph: fallow_engine::module_graph::RetainedModuleGraph,
19 script_used_packages: FxHashSet<String>,
20 trace_provenance: fallow_engine::trace::TraceProvenance,
21 results: fallow_types::results::AnalysisResults,
24}
25
26pub fn run_trace_export(
36 options: &TraceExportOptions,
37) -> ProgrammaticResult<TraceExportProgrammaticOutput> {
38 validate_non_empty("file", &options.file)?;
39 validate_non_empty("export_name", &options.export_name)?;
40 let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
41 resolved.install(|| {
42 let run = super::type_aware_config::resolve_trace_run(
43 &options.analysis,
44 super::type_aware_config::ConfigLocation::of(&resolved),
45 || resolve_programmatic_run(&options.analysis, &ProgrammaticEntry::TraceChain),
46 )?;
47 let session = load_trace_session(&resolved, &options.analysis, &run)?;
48 let artifacts = trace_artifacts(&session)?;
49 let output = if let Some(mut export) = fallow_engine::trace::trace_export(
54 &artifacts.graph,
55 session.root(),
56 &options.file,
57 &options.export_name,
58 ) {
59 export.apply_plugin_credits(&artifacts.trace_provenance);
60 TraceExportTargetOutput::Export(export)
61 } else if let Some(member) = fallow_engine::trace::trace_class_member(
62 &artifacts.graph,
63 session.root(),
64 &options.file,
65 &options.export_name,
66 ) {
67 TraceExportTargetOutput::Member(member)
68 } else {
69 return Err(ProgrammaticError::new(
70 format!(
71 "export or member '{}' not found in '{}'",
72 options.export_name, options.file
73 ),
74 2,
75 )
76 .with_code("FALLOW_TRACE_TARGET_NOT_FOUND")
77 .with_help(
78 "The name is neither a top-level export nor a class / enum / store member of this \
79 file. Run trace_file on the file to list its exports, or project_info for the \
80 project symbol set; confirm the file path is project-relative.",
81 )
82 .with_context("trace_export"));
83 };
84 Ok(TraceExportProgrammaticOutput { output })
85 })
86}
87
88pub fn run_trace_file(
95 options: &TraceFileOptions,
96) -> ProgrammaticResult<TraceFileProgrammaticOutput> {
97 validate_non_empty("file", &options.file)?;
98 let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
99 resolved.install(|| {
100 let run = resolve_programmatic_run(&options.analysis, &ProgrammaticEntry::TraceChain)?;
101 let session = load_trace_session(&resolved, &options.analysis, &run)?;
102 let artifacts = trace_artifacts(&session)?;
103 let mut output =
104 fallow_engine::trace::trace_file(&artifacts.graph, session.root(), &options.file)
105 .ok_or_else(|| {
106 ProgrammaticError::new(
107 format!("file '{}' not found in module graph", options.file),
108 2,
109 )
110 .with_code("FALLOW_TRACE_TARGET_NOT_FOUND")
111 .with_help(
112 "The file is not in the analyzed module graph. Run project_info to list \
113 discovered files; the path must be project-relative and not excluded by \
114 ignore patterns or outside the analyzed roots.",
115 )
116 .with_context("trace_file")
117 })?;
118 output.sources = artifacts.trace_provenance.file_sources(&output.file);
119 output.apply_plugin_credits(&artifacts.trace_provenance);
120 output.apply_entry_script(&artifacts.trace_provenance);
121 Ok(TraceFileProgrammaticOutput { output })
122 })
123}
124
125pub fn run_trace_import_path(
135 options: &TraceImportPathOptions,
136) -> ProgrammaticResult<TraceImportPathProgrammaticOutput> {
137 validate_non_empty("from", &options.from)?;
138 validate_non_empty("to", &options.to)?;
139 let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
140 resolved.install(|| {
141 let run = resolve_programmatic_run(&options.analysis, &ProgrammaticEntry::TracePath)?;
142 let session = load_trace_session(&resolved, &options.analysis, &run)?;
143 let artifacts = trace_artifacts(&session)?;
144 let trace = if options.eager_only {
145 fallow_engine::trace::trace_eager_import_path
146 } else {
147 fallow_engine::trace::trace_import_path
148 };
149 let output = trace(
150 &artifacts.graph,
151 session.root(),
152 &options.from,
153 &options.to,
154 )
155 .map_err(|endpoint| {
156 let label = endpoint.label();
157 let value = match endpoint {
158 fallow_engine::trace::ImportPathEndpoint::From
159 | fallow_engine::trace::ImportPathEndpoint::AmbiguousFrom => &options.from,
160 fallow_engine::trace::ImportPathEndpoint::To
161 | fallow_engine::trace::ImportPathEndpoint::AmbiguousTo => &options.to,
162 };
163 if endpoint.is_ambiguous() {
164 return ProgrammaticError::new(format!("'{value}' ({label}) matches multiple modules"), 2)
165 .with_code("FALLOW_TRACE_TARGET_AMBIGUOUS")
166 .with_help("Use the full project-relative path; run project_info to list discovered files.")
167 .with_context("trace_import_path");
168 }
169 ProgrammaticError::new(format!("'{value}' ({label}) not found in module graph"), 2)
170 .with_code("FALLOW_TRACE_TARGET_NOT_FOUND")
171 .with_help(
172 "The module is not in the analyzed module graph. Run project_info to list \
173 discovered files; both paths must be project-relative and not excluded by \
174 ignore patterns or outside the analyzed roots.",
175 )
176 .with_context("trace_import_path")
177 })?;
178 Ok(TraceImportPathProgrammaticOutput { output })
179 })
180}
181
182pub fn run_trace_error(
194 options: &TraceErrorOptions,
195) -> ProgrammaticResult<TraceErrorProgrammaticOutput> {
196 if options.trace.trim().is_empty() {
197 return Err(ProgrammaticError::new("trace must not be empty", 2)
201 .with_code("FALLOW_INVALID_TRACE_OPTIONS")
202 .with_help(
203 "Paste the stack trace text into `trace`, as your runtime printed it. \
204 trace_error resolves frames against the project graph, so it has nothing \
205 to resolve without them.",
206 )
207 .with_context("trace_error"));
208 }
209 if options.trace.len() as u64 > fallow_engine::trace_error::MAX_STACK_TRACE_BYTES {
210 let limit = fallow_engine::trace_error::MAX_STACK_TRACE_BYTES;
211 return Err(ProgrammaticError::new(
212 format!("stack trace exceeds the {limit}-byte limit"),
213 2,
214 )
215 .with_code("FALLOW_INVALID_TRACE_OPTIONS")
216 .with_help(
217 "A stack trace is a handful of kilobytes. Pass the trace itself rather than a \
218 redirected log file, and cut it to the frames that matter.",
219 )
220 .with_context("trace_error"));
221 }
222 let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
223 resolved.install(|| {
224 let run = resolve_programmatic_run(&options.analysis, &ProgrammaticEntry::TraceError)?;
225 let session = load_trace_session(&resolved, &options.analysis, &run)?;
226 let output = fallow_engine::trace_error::trace_error_with_session(
227 &session,
228 &options.trace,
229 options.source.clone(),
230 )
231 .map_err(|err| {
232 ProgrammaticError::new(format!("stack-trace resolution failed: {err}"), 2)
233 .with_code("FALLOW_ANALYSIS_FAILED")
234 .with_context("trace_error")
235 })?;
236 Ok(TraceErrorProgrammaticOutput { output })
237 })
238}
239
240pub fn run_trace_dependency(
247 options: &TraceDependencyOptions,
248) -> ProgrammaticResult<TraceDependencyProgrammaticOutput> {
249 validate_non_empty("package_name", &options.package_name)?;
250 let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
251 resolved.install(|| {
252 let run = resolve_programmatic_run(&options.analysis, &ProgrammaticEntry::TraceDependency)?;
253 let session = load_trace_session(&resolved, &options.analysis, &run)?;
254 if let Some(query) = &options.usage {
255 return trace_dependency_usage(&session, &options.package_name, query);
256 }
257 let artifacts = trace_artifacts(&session)?;
258 let workspace_roots: Vec<&std::path::Path> = session
259 .workspaces()
260 .iter()
261 .map(|ws| ws.root.as_path())
262 .collect();
263 let output = fallow_engine::trace::build_dependency_trace(
264 &fallow_engine::trace::DependencyTraceInputs {
265 graph: &artifacts.graph,
266 root: session.root(),
267 workspace_roots: &workspace_roots,
268 ignore_patterns: &session.config().ignore_patterns,
269 script_used_packages: &artifacts.script_used_packages,
270 provenance: &artifacts.trace_provenance,
271 results: &artifacts.results,
272 },
273 &options.package_name,
274 );
275 Ok(TraceDependencyProgrammaticOutput { output })
276 })
277}
278
279fn trace_dependency_usage(
281 session: &AnalysisSession,
282 package_name: &str,
283 query: &DependencyUsageQuery,
284) -> ProgrammaticResult<TraceDependencyProgrammaticOutput> {
285 let result = fallow_engine::trace::trace_dependency_with_session(session, package_name, query)
286 .map_err(|err| {
287 super::dead_code::map_engine_error(
288 &err,
289 "trace analysis failed",
290 "FALLOW_TRACE_FAILED",
291 "trace",
292 )
293 })?;
294 result
295 .map(|output| TraceDependencyProgrammaticOutput { output })
296 .map_err(|err| {
297 ProgrammaticError::new(err.to_string(), 2)
298 .with_code("FALLOW_TRACE_INVALID_CURSOR")
299 .with_context("cursor")
300 })
301}
302
303pub fn run_trace_clone(
310 options: &TraceCloneOptions,
311) -> ProgrammaticResult<TraceCloneProgrammaticOutput> {
312 validate_trace_clone_target(&options.target)?;
313 let resolved = resolve_programmatic_analysis_context(&options.duplication.analysis)?;
314 resolved.install(|| {
315 resolved.ensure_not_cancelled("config load and file discovery")?;
316 let run = resolve_programmatic_run(
317 &options.duplication.analysis,
318 &ProgrammaticEntry::Duplication,
319 )?;
320 let session = duplication::load_duplication_session(&options.duplication, &resolved, &run)?;
321 validate_workspace_selection(&resolved, session.workspaces())?;
322 resolved.ensure_not_cancelled("duplication detection")?;
323 let dupes_config =
324 duplication::build_dupes_config(&options.duplication, &session.config().duplicates);
325 let cache_dir = (!resolved.no_cache).then_some(session.config().cache_dir.as_path());
326 let report = session
327 .find_duplicates_with_defaults(&dupes_config, cache_dir)
328 .report;
329 resolved.ensure_not_cancelled("the clone trace")?;
332 let (trace, not_found) = match &options.target {
333 TraceCloneTarget::Location { file, line } => (
334 fallow_engine::trace::trace_clone(&report, session.root(), file, *line),
335 format!("no clone found at {file}:{line}"),
336 ),
337 TraceCloneTarget::Fingerprint(fingerprint) => (
338 fallow_engine::trace::trace_clone_by_fingerprint(
339 &report,
340 session.root(),
341 fingerprint,
342 ),
343 format!("no clone group with fingerprint {fingerprint}"),
344 ),
345 };
346 if trace.matched_instance.is_none() {
347 return Err(ProgrammaticError::new(not_found, 2)
348 .with_code("FALLOW_TRACE_TARGET_NOT_FOUND")
349 .with_help(
350 "No clone matched. Run find_dupes to list clone groups and their fingerprints; \
351 a location must fall inside a reported clone instance, and a fingerprint must \
352 be a find_dupes clone_groups[].fingerprint (a dup:<id> value).",
353 )
354 .with_context("trace_clone"));
355 }
356 Ok(TraceCloneProgrammaticOutput { output: trace })
357 })
358}
359
360#[doc(hidden)]
368#[expect(
369 clippy::implicit_hasher,
370 reason = "the engine trace boundary intentionally accepts the workspace-standard FxHashSet"
371)]
372pub fn benchmark_trace_graph_family_compact_json(
373 graph: &fallow_engine::module_graph::RetainedModuleGraph,
374 root: &std::path::Path,
375 script_used_packages: &FxHashSet<String>,
376) -> ProgrammaticResult<(usize, usize, usize, usize, usize)> {
377 let export =
378 fallow_engine::trace::trace_export(graph, root, "src/000-shared.ts", "sharedValue")
379 .ok_or_else(|| benchmark_trace_target_missing("src/000-shared.ts:sharedValue"))?;
380 let export_reference_count = export.direct_references.len();
381 let export_json =
382 crate::serialize_trace_export_programmatic_json(TraceExportProgrammaticOutput {
383 output: TraceExportTargetOutput::Export(export),
384 })?;
385
386 let file = fallow_engine::trace::trace_file(graph, root, "src/000-shared.ts")
387 .ok_or_else(|| benchmark_trace_target_missing("src/000-shared.ts"))?;
388 let file_export_count = file.exports.len();
389 let file_imported_by_count = file.imported_by.len();
390 let file_json = crate::serialize_trace_file_programmatic_json(TraceFileProgrammaticOutput {
391 output: file,
392 })?;
393
394 let dependency = fallow_engine::trace::trace_dependency(
395 graph,
396 root,
397 &[],
398 &fallow_config::IgnorePatternSet::empty(),
399 "trace-package",
400 script_used_packages,
401 );
402 let dependency_import_count = dependency.import_count;
403 let dependency_json =
404 crate::serialize_trace_dependency_programmatic_json(TraceDependencyProgrammaticOutput {
405 output: dependency,
406 })?;
407
408 let rendered_bytes = compact_json_len(&[export_json, file_json, dependency_json])?;
409 Ok((
410 export_reference_count,
411 file_export_count,
412 file_imported_by_count,
413 dependency_import_count,
414 rendered_bytes,
415 ))
416}
417
418#[doc(hidden)]
420#[derive(Debug, PartialEq, Eq)]
421pub struct TraceCloneBenchmarkResult {
422 pub location_file: std::path::PathBuf,
424 pub location_line: usize,
426 pub location_fingerprint: String,
428 pub fingerprint_fingerprint: String,
430 pub location_group_count: usize,
432 pub fingerprint_group_count: usize,
434 pub location_instance_count: usize,
436 pub fingerprint_instance_count: usize,
438 pub rendered_bytes: usize,
440}
441
442#[doc(hidden)]
449pub fn benchmark_trace_clone_compact_json(
450 report: &DuplicationReport,
451 root: &std::path::Path,
452 file: &str,
453 line: usize,
454 fingerprint: &str,
455) -> ProgrammaticResult<TraceCloneBenchmarkResult> {
456 let location_trace = fallow_engine::trace::trace_clone(report, root, file, line);
457 let matched_location = location_trace
458 .matched_instance
459 .as_ref()
460 .ok_or_else(|| benchmark_trace_target_missing(&format!("{file}:{line}")))?;
461 let location_file = matched_location.file.clone();
462 let location_line = matched_location.start_line;
463 let location_fingerprint = location_trace
464 .clone_groups
465 .first()
466 .map(|group| group.fingerprint.clone())
467 .ok_or_else(|| benchmark_trace_target_missing(&format!("{file}:{line}")))?;
468 let location_group_count = location_trace.clone_groups.len();
469 let location_instance_count = location_trace
470 .clone_groups
471 .iter()
472 .map(|group| group.instances.len())
473 .sum();
474 let location_json =
475 crate::serialize_trace_clone_programmatic_json(TraceCloneProgrammaticOutput {
476 output: location_trace,
477 })?;
478
479 let fingerprint_trace =
480 fallow_engine::trace::trace_clone_by_fingerprint(report, root, fingerprint);
481 if fingerprint_trace.matched_instance.is_none() {
482 return Err(benchmark_trace_target_missing(fingerprint));
483 }
484 let fingerprint_fingerprint = fingerprint_trace
485 .clone_groups
486 .first()
487 .map(|group| group.fingerprint.clone())
488 .ok_or_else(|| benchmark_trace_target_missing(fingerprint))?;
489 let fingerprint_group_count = fingerprint_trace.clone_groups.len();
490 let fingerprint_instance_count = fingerprint_trace
491 .clone_groups
492 .iter()
493 .map(|group| group.instances.len())
494 .sum();
495 let fingerprint_json =
496 crate::serialize_trace_clone_programmatic_json(TraceCloneProgrammaticOutput {
497 output: fingerprint_trace,
498 })?;
499
500 let rendered_bytes = compact_json_len(&[location_json, fingerprint_json])?;
501 Ok(TraceCloneBenchmarkResult {
502 location_file,
503 location_line,
504 location_fingerprint,
505 fingerprint_fingerprint,
506 location_group_count,
507 fingerprint_group_count,
508 location_instance_count,
509 fingerprint_instance_count,
510 rendered_bytes,
511 })
512}
513
514fn compact_json_len(values: &[serde_json::Value]) -> ProgrammaticResult<usize> {
515 serde_json::to_vec(values)
516 .map(|json| json.len())
517 .map_err(|err| {
518 ProgrammaticError::new(
519 format!("failed to serialize benchmark trace JSON: {err}"),
520 2,
521 )
522 .with_code("FALLOW_SERIALIZE_BENCHMARK_TRACE")
523 .with_context("benchmark_trace")
524 })
525}
526
527fn benchmark_trace_target_missing(target: &str) -> ProgrammaticError {
528 ProgrammaticError::new(format!("benchmark trace target not found: {target}"), 2)
529 .with_code("FALLOW_BENCHMARK_TRACE_TARGET_NOT_FOUND")
530 .with_context("benchmark_trace")
531}
532
533fn validate_non_empty(field: &str, value: &str) -> ProgrammaticResult<()> {
534 if value.trim().is_empty() {
535 return Err(
536 ProgrammaticError::new(format!("{field} must not be empty"), 2)
537 .with_code("FALLOW_INVALID_TRACE_OPTIONS")
538 .with_context(field.to_string()),
539 );
540 }
541 Ok(())
542}
543
544fn validate_trace_clone_target(target: &TraceCloneTarget) -> ProgrammaticResult<()> {
545 match target {
546 TraceCloneTarget::Location { file, line } => {
547 validate_non_empty("file", file)?;
548 if *line == 0 {
549 return Err(ProgrammaticError::new("line must be greater than 0", 2)
550 .with_code("FALLOW_INVALID_TRACE_OPTIONS")
551 .with_context("trace_clone.line"));
552 }
553 }
554 TraceCloneTarget::Fingerprint(fingerprint) => {
555 validate_non_empty("fingerprint", fingerprint)?;
556 }
557 }
558 Ok(())
559}
560
561fn load_trace_session(
562 resolved: &ProgrammaticAnalysisContext,
563 analysis: &crate::AnalysisOptions,
564 run: &ResolvedRun,
565) -> ProgrammaticResult<AnalysisSession> {
566 let session = super::dead_code::load_dead_code_session(
567 &super::dead_code::default_dead_code_options(analysis),
568 resolved,
569 run,
570 )?;
571 validate_workspace_selection(resolved, session.workspaces())?;
572 Ok(session)
573}
574
575fn trace_artifacts(session: &AnalysisSession) -> ProgrammaticResult<TraceArtifacts> {
576 let artifacts = session
577 .analyze_dead_code_with_session_artifacts(false, true, None)
578 .map_err(|err| {
579 super::dead_code::map_engine_error(
580 &err,
581 "trace analysis failed",
582 "FALLOW_TRACE_FAILED",
583 "trace",
584 )
585 })?;
586 let graph = artifacts.analysis.graph.ok_or_else(|| {
587 ProgrammaticError::new("trace requires a retained module graph", 2)
588 .with_code("FALLOW_TRACE_GRAPH_UNAVAILABLE")
589 .with_context("trace.graph")
590 })?;
591 Ok(TraceArtifacts {
592 graph,
593 script_used_packages: artifacts.analysis.script_used_packages,
594 trace_provenance: artifacts.analysis.trace_provenance,
595 results: artifacts.analysis.results,
596 })
597}
598
599#[cfg(test)]
600mod benchmark_tests {
601 use std::fmt::Write as _;
602 use std::fs;
603
604 use fallow_engine::duplicates::CloneFingerprintSet;
605
606 use super::*;
607
608 const FIXTURE_SIZE: usize = 4;
609
610 fn write_file(root: &std::path::Path, path: &str, source: impl AsRef<str>) {
611 let path = root.join(path);
612 fs::create_dir_all(path.parent().expect("fixture file has parent"))
613 .expect("fixture directory is created");
614 fs::write(path, source.as_ref()).expect("fixture file is written");
615 }
616
617 #[test]
618 fn graph_family_benchmark_boundary_uses_only_retained_artifacts() {
619 let temp_dir = tempfile::TempDir::new().expect("temporary project is created");
620 let root = temp_dir.path().to_path_buf();
621 write_file(
622 &root,
623 "package.json",
624 r#"{"name":"trace-test","type":"module","main":"src/index.ts"}"#,
625 );
626 write_file(
627 &root,
628 "src/000-shared.ts",
629 "export const sharedValue = 42;\n",
630 );
631
632 let mut index_source = String::new();
633 for index in 0..FIXTURE_SIZE {
634 write_file(
635 &root,
636 &format!("src/consumer{index}.ts"),
637 format!(
638 "import {{ sharedValue }} from './000-shared';\nimport {{ traceHelper }} from 'trace-package';\nexport const value{index} = traceHelper(sharedValue + {index});\n"
639 ),
640 );
641 writeln!(
642 index_source,
643 "import {{ value{index} }} from './consumer{index}';\nconsole.log(value{index});"
644 )
645 .expect("index source is built");
646 }
647 write_file(&root, "src/index.ts", index_source);
648
649 let session = AnalysisSession::load(&root, None).expect("trace session loads");
650 let target = session
651 .files()
652 .iter()
653 .find(|file| file.path.ends_with("src/000-shared.ts"))
654 .expect("trace target is discovered");
655 assert_eq!(
656 target.id.0, 0,
657 "the retained trace target must precede every non-matching importer"
658 );
659 let trace_root = session.root().to_path_buf();
660 let artifacts = session
661 .analyze_dead_code_with_artifacts(false, true)
662 .expect("trace graph analysis succeeds");
663 drop(session);
664 temp_dir.close().expect("temporary project is removed");
665
666 let result = benchmark_trace_graph_family_compact_json(
667 artifacts.graph.as_ref().expect("trace graph is retained"),
668 &trace_root,
669 &artifacts.script_used_packages,
670 )
671 .expect("retained trace graph serializes without project IO");
672 assert_eq!(result.0, FIXTURE_SIZE);
673 assert_eq!(result.1, 1);
674 assert_eq!(result.2, FIXTURE_SIZE);
675 assert_eq!(result.3, FIXTURE_SIZE);
676 assert!(result.4 > 0);
677 }
678
679 #[test]
680 fn clone_benchmark_boundary_uses_only_the_retained_report() {
681 let temp_dir = tempfile::TempDir::new().expect("temporary project is created");
682 let root = temp_dir.path().to_path_buf();
683 write_file(
684 &root,
685 "package.json",
686 r#"{"name":"trace-clone-test","type":"module"}"#,
687 );
688 for index in 0..FIXTURE_SIZE {
689 write_file(
690 &root,
691 &format!("src/clone{index}.ts"),
692 format!(
693 "export function normalizeRecords(records: Array<{{ active: boolean; value: number }}>) {{\n const active = records.filter((record) => record.active);\n const values = active.map((record) => record.value);\n const total = values.reduce((sum, value) => sum + value, 0);\n const average = values.length === 0 ? 0 : total / values.length;\n const maximum = values.reduce((current, value) => Math.max(current, value), 0);\n return {{ total, average, maximum, count: values.length }};\n}}\n\nexport const cloneId = {index};\n"
694 ),
695 );
696 }
697
698 let session = AnalysisSession::load(&root, None).expect("clone session loads");
699 let trace_root = session.root().to_path_buf();
700 let mut config = session.config().duplicates.clone();
701 config.min_tokens = 35;
702 config.min_lines = 5;
703 config.min_occurrences = FIXTURE_SIZE;
704 let report = session.find_duplicates_with_defaults(&config, None).report;
705 let group = report
706 .clone_groups
707 .iter()
708 .max_by_key(|group| group.instances.len())
709 .expect("clone group exists");
710 let target = group.instances.last().expect("clone instance exists");
711 let target_file = target
712 .file
713 .strip_prefix(&trace_root)
714 .expect("clone path is project-relative")
715 .to_string_lossy()
716 .replace('\\', "/");
717 let target_line = target.start_line;
718 let expected_fingerprint =
719 CloneFingerprintSet::from_groups(&report.clone_groups).fingerprint_for_group(group);
720 drop(session);
721 temp_dir.close().expect("temporary project is removed");
722
723 let result = benchmark_trace_clone_compact_json(
724 &report,
725 &trace_root,
726 &target_file,
727 target_line,
728 &expected_fingerprint,
729 )
730 .expect("retained clone report serializes without project IO");
731 assert_eq!(result.location_file, std::path::PathBuf::from(&target_file));
732 assert_eq!(result.location_line, target_line);
733 assert_eq!(result.location_fingerprint, expected_fingerprint);
734 assert_eq!(result.fingerprint_fingerprint, expected_fingerprint);
735 assert_eq!(result.location_group_count, 1);
736 assert_eq!(result.fingerprint_group_count, 1);
737 assert_eq!(result.location_instance_count, FIXTURE_SIZE);
738 assert_eq!(result.fingerprint_instance_count, FIXTURE_SIZE);
739 assert!(result.rendered_bytes > 0);
740 }
741}