Skip to main content

fallow_api/runtime/
trace.rs

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