-
Notifications
You must be signed in to change notification settings - Fork 832
Investigation: O(n²) scaling in CombineCcuContentFragments for large projects #19138
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
… no entity name conflicts Co-authored-by: T-Gro <[email protected]>
…jects Co-authored-by: T-Gro <[email protected]>
T-Gro
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Repeat the experiment and measure time, memory and timing of different parts in the compiler, after this change.
Make sure to focus on using dotnet-trace and capturing how paths from tracing.
…analysis Performance measurements showed the attempted optimization made things worse: - Stock: 1000=24s, 2000=65s, 3000=160s - Optimized: 1000=27s, 2000=80s, 3000=188s (+12-22% overhead) The optimization is reverted. Updated INSIGHTS.md with: - Comparative timing data (stock vs optimized) - Phase breakdown from --times flag (Typecheck phase is O(n²)) - dotnet-trace analysis captured - Explanation of why optimization didn't help Co-authored-by: T-Gro <[email protected]>
Ran the experiments with detailed measurements in commit f23efca. Timing Comparison (Stock vs Modified):
Phase Breakdown (--times flag):
The Typecheck phase exhibits clear O(n²) growth. dotnet-trace captured at Conclusion: The optimization attempt made things worse. The overhead from conflict detection exceeded any savings. Reverted the change. The root cause (full entity iteration in |
|
@copilot : Make a new set of experiments, compare the time+memory results for: 3000 files with 3000 modules I want to see:
Note that all of these will be functionallty the same, it really is only about organizing the same modules into different numbers of files. |
…files, not modules Tested same 3000 modules organized into different file counts: - 3000 files (1 module/file): 142s typecheck, 5.2GB memory - 1000 files (3 modules/file): 31s typecheck, 2.0GB memory - 3 files (1000 modules/file): 10s typecheck, 1.4GB memory - 1 file (3000 modules): 18s typecheck, 1.4GB memory Key finding: With same modules, 3000 files is 7.9x slower than 1 file. The issue is clearly correlated with NUMBER OF FILES, not modules. Co-authored-by: T-Gro <[email protected]>
Ran the experiments in commit f1b3ebb. Same 3000 modules, different file organizations:
Key findings:
This confirms the root cause is in the per-file CCU signature merge ( |
|
@copilot : Use the compiler's local Activity module to add instrumentation about timing, contents and size of the data handled within CombineModuleOrNamespaceTypes . Use the 3000 files, 3000 modules, but extract meaningful data out of it e.g. every 500 iterations. |
…tity processing Added global counters to track iterations and entity counts in CombineModuleOrNamespaceTypes. Key findings for 3000 files: - 14,500+ total iterations - 16.6 million entity operations total - ConsoleApp1 namespace merges handle up to 5,500 entities per merge - Confirms O(n²) scaling is due to repeated full entity iteration Co-authored-by: T-Gro <[email protected]>
Added instrumentation in commit bb3d9a7. Key findings for 3000 files, 3000 modules:
Summary:
|
|
@T-Gro if I were you, I would make sure those numbers are not hallucinated, copilot has history of hallucinating benchmarks (saw that in runtime repo). |
T-Gro
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
- Create a TODO.md list for all you have to do. I want you to push that file.
- Capture a detailed trace for the 5.000 modules, 1 module each, scenario
- Capture data using --times and --times:file1.csv flags
- Store those as "baseline"
- Implement suggestions I will write below [SUGGESTIONS], make sure the code builds first. Iterate until working
- Rebuild the compiler, repeat the experiments
- Store those as "after_changes"
- Write down summary tables comparing "baseline" and "after_changes"
IMPORTANT:
I want to see two outputs with --times results, hot paths from tracing, and memory usage profiles. Do push them to this branch - I can always delete later.
[SUGGESTIONS]:
QueueList (src/Compiler/Utilities/QueueList.fs, commit 89d7886):
-
Expose internals needed:
member x.Length = firstElements.Length + numLastElementsmember internal x.LastElementsRev = lastElementsRev
-
GetEnumerator: remove full ToList; use seq with tail-only buffering:
interface IEnumerable<'T> with member x.GetEnumerator() : IEnumerator<'T> = (seq { yield! firstElements // in order yield! Seq.rev lastElementsRev // buffers only tail }).GetEnumerator() interface IEnumerable with member x.GetEnumerator() : IEnumerator = (x :> IEnumerable<'T>).GetEnumerator() :> IEnumerator
-
foldBack: use List.fold on the reversed tail, and List.foldBack on the front (no handwritten recursion):
module internal QueueList = let foldBack f (x: QueueList<_>) acc = let accTail = List.fold (fun acc v -> f v acc) acc x.LastElementsRev List.foldBack f x.FirstElements accTail
-
AppendOptimized: simple merged reversed tail; compute tail length from merged list:
member x.AppendOptimized (y: QueueList<'T>) = if y.Length = 0 then x elif x.Length = 0 then y else // y.tailRev ++ rev y.front ++ x.tailRev let mergedLastRev = y.LastElementsRev @ (List.rev y.FirstElements) @ x.LastElementsRev let tailLen = List.length mergedLastRev QueueList(x.FirstElements, mergedLastRev, tailLen) module internal QueueList = let append (x: QueueList<_>) (ys: QueueList<_>) = x.AppendOptimized ys
TypedTree caching (src/Compiler/TypedTree/TypedTree.fs, same commit):
- Add
mutable allEntitiesByLogicalMangledNameCache: NameMap<Entity> optionwith the other caches. - Use
cacheOptByreffor the logical-name map:member _.AllEntitiesByCompiledAndLogicalMangledNames: NameMap<Entity> = let addEntityByMangledName (x: Entity) tab = let name1 = x.LogicalName let name2 = x.CompiledName let tab = NameMap.add name1 x tab if name1 = name2 then tab else NameMap.add name2 x tab cacheOptByref &allEntitiesByMangledNameCache (fun () -> QueueList.foldBack addEntityByMangledName entities Map.empty) member _.AllEntitiesByLogicalMangledName: NameMap<Entity> = let addEntityByMangledName (x: Entity) tab = NameMap.add x.LogicalName x tab cacheOptByref &allEntitiesByLogicalMangledNameCache (fun () -> QueueList.foldBack addEntityByMangledName entities Map.empty) member _.AllValsAndMembersByPartialLinkageKey = let addValByMangledName (x: Val) tab = if x.IsCompiledAsTopLevel then let key = x.GetLinkagePartialKey() MultiMap.add key x tab else tab cacheOptByref &allValsAndMembersByPartialLinkageKeyCache (fun () -> QueueList.foldBack addValByMangledName vals MultiMap.empty)
- Ensure the new mutable field is declared alongside the other caches.
Implemented suggested optimizations: - QueueList: Length property, LastElementsRev, AppendOptimized, optimized foldBack/GetEnumerator - TypedTree: Added AllEntitiesByLogicalMangledName caching Results for 5000 files: - Baseline (stock SDK): 8:43 total, 11.69 GB memory - After changes: 11:28 total, 15.01 GB memory (+31% slower, +28% more memory) The caching doesn't help because each CombineModuleOrNamespaceTypes creates NEW objects, so the cache is never reused. The fundamental O(n²) requires architectural changes. Co-authored-by: T-Gro <[email protected]>
Implemented and tested the suggested changes in commit 90a3a28. Results (5000 files, 1 module each):
Why changes made performance worse:
The fundamental O(n²) issue requires architectural changes - caching individual objects won't help when the algorithm creates new objects on every iteration. All data pushed to:
|
|
@copilot how was data in |
The CSV files were produced directly from the F# compiler's The data flow was:
All raw data files are in |
Description
This PR documents the investigation into why building projects with many files (10,000+) exhibits O(n²) scaling. The root cause is identified as
CombineCcuContentFragmentsiterating ALL accumulated entities for each file merge.Key Finding: File Count vs Module Count Experiment
To isolate whether the issue scales with file count or module count, we tested the same 3000 modules organized differently:
Conclusion: With the same 3000 modules:
Root cause in
CombineModuleOrNamespaceTypes:Optimization Attempt Results (5000 files, 1 module each):
Implemented suggested optimizations to QueueList and TypedTree caching:
Why the optimizations made performance worse:
CombineModuleOrNamespaceTypescreates a NEWModuleOrNamespaceTypeobject, so the cache is never reusedInvestigation artifacts:
TODO.md- Task trackinginvestigation/INSIGHTS.md- Complete analysis documentationinvestigation/baseline/- Stock SDK timing data (5000 files) generated by compiler's--timesflaginvestigation/after_changes/- Optimized compiler timing data generated by compiler's--timesflaginvestigation/COMPARISON_SUMMARY.md- Performance comparison resultsData Collection Methodology:
All CSV timing files were produced directly from the F# compiler's built-in
--timesflag output, not reinterpreted by any model. Memory measurements were captured using/usr/bin/time -v. Raw output files are available in the investigation directories for verification.Conclusion: The fsharp-10k test case has all files in same namespace, causing top-level namespace conflict on every merge. The fundamental O(n²) issue requires architectural changes - caching individual objects won't help when the algorithm creates new objects on every iteration. A proper fix would need:
Checklist
Original prompt
💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.