diff --git a/dev/stackdiff/Sources/stackdiff/StackFormatter.swift b/dev/stackdiff/Sources/stackdiff/StackFormatter.swift new file mode 100644 index 000000000..e56b6194e --- /dev/null +++ b/dev/stackdiff/Sources/stackdiff/StackFormatter.swift @@ -0,0 +1,111 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import Stacks + +enum StackFormatter { + static func lines( + forStack stack: Stack, + prefixedWith linePrefix: String = "", + dropFirst: Int = 0, + dropLast: Int = 0, + maxWidth: Int? = nil + ) -> [String] { + var lines = [String]() + lines.reserveCapacity(stack.lines.count - dropFirst - dropLast) + + if dropFirst > 0 { + lines.append(linePrefix + "...skipping \(dropFirst) common lines...") + } + + for line in stack.lines.dropFirst(dropFirst).dropLast(dropLast) { + lines.append(linePrefix + line) + } + + if dropLast > 0 { + lines.append(linePrefix + "...skipping \(dropLast) common lines...") + } + + if let maxWidth = maxWidth { + return lines.map { $0.truncated(to: maxWidth) } + } else { + return lines + } + } + + static func lines( + forStack stack: some StackProtocol, + weightedSubstacks: [WeightedStack], + prefixedWith linePrefix: String = "", + substackPrefix: String = "", + maxWidth: Int? = nil + ) -> [String] { + var lines = [String]() + + // If theres' only a single substack, compress it into the main stack. + if weightedSubstacks.count == 1, let substack = weightedSubstacks.first { + lines.append("\(linePrefix)ALLOCATIONS: \(substack.allocations)") + lines.append( + contentsOf: Self.lines( + forStack: substack.stack, + prefixedWith: linePrefix, + maxWidth: maxWidth + ) + ) + return lines + } + + let totalAllocs = weightedSubstacks.reduce(0) { $0 + $1.allocations } + lines.append("\(linePrefix)ALLOCATIONS: \(totalAllocs)") + lines.append( + contentsOf: Self.lines( + forStack: stack, + prefixedWith: linePrefix, + maxWidth: maxWidth + ) + ) + for substack in weightedSubstacks { + // Add a divider between substacks. + lines.append("") + lines.append("\(linePrefix)\(substackPrefix)ALLOCATIONS: \(substack.allocations)") + // Treat the substack as a regular stack. + let substackLines = Self.lines( + forStack: substack.suffix(substack.lines.count - stack.lines.count), + prefixedWith: linePrefix + substackPrefix, + maxWidth: maxWidth + ) + lines.append(contentsOf: substackLines) + } + + return lines + } +} + +extension String { + func truncated(to maxLength: Int, continuation: String = "...") -> String { + let length = self.count + + if length <= maxLength { + return self + } + + let toRemove = (length - maxLength) + continuation.count + + var copy = self + copy.removeLast(toRemove) + copy.append(contentsOf: continuation) + + return copy + } +} diff --git a/dev/stackdiff/Sources/stackdiff/Stackdiff+Diff.swift b/dev/stackdiff/Sources/stackdiff/Stackdiff+Diff.swift new file mode 100644 index 000000000..add87093e --- /dev/null +++ b/dev/stackdiff/Sources/stackdiff/Stackdiff+Diff.swift @@ -0,0 +1,97 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import ArgumentParser +import Stacks + +struct Diff: ParsableCommand { + @OptionGroup + var options: StackdiffOptions + + @Argument(help: "Path of first file to analyze") + var fileA: String + + @Argument(help: "Path of second file to analyze") + var fileB: String + + @Flag + var showMergedStacks: Bool = false + + func run() throws { + let a = try self.options.load(file: self.fileA) + let b = try self.options.load(file: self.fileB) + + print("--- ONLY IN A (\(self.fileA))") + print("") + let aOnlyStacks = a.partialStacks.subtracting(b.partialStacks) + let aOnlyAggregate = a.filter { aOnlyStacks.contains($0.key) } + self.printSortedStacks(aOnlyAggregate) + + print("--- ONLY IN B (\(self.fileB))") + print("") + let bOnlyStacks = b.partialStacks.subtracting(a.partialStacks) + let bOnlyAggregate = b.filter { bOnlyStacks.contains($0.key) } + self.printSortedStacks(bOnlyAggregate) + + print("--- IN BOTH A AND B") + print("") + let inBoth = a.partialStacks.intersection(b.partialStacks) + let diff = a.subtracting(b).filter { + inBoth.contains($0.key) && $0.value.netAllocations != 0 + } + self.printSortedStacks(diff) + + print("--- SUMMARY") + print("") + + let allocsA = a.netAllocations + let allocsB = b.netAllocations + print("Allocs from all stacks in A:", allocsA) + print("Allocs from all stacks in B:", allocsB) + print("Difference:", allocsA - allocsB) + print("") + + let uniqueAllocsA = aOnlyAggregate.netAllocations + let uniqueAllocsB = bOnlyAggregate.netAllocations + print("Allocs from stacks only in A:", uniqueAllocsA) + print("Allocs from stacks only in B:", uniqueAllocsB) + print("Difference:", uniqueAllocsA - uniqueAllocsB) + print("") + + // Stacks in both A and B. + let commonStacks = a.partialStacks.intersection(b.partialStacks) + let commonAllocsA = a.filter { commonStacks.contains($0.key) }.netAllocations + let commonAllocsB = b.filter { commonStacks.contains($0.key) }.netAllocations + print("Allocs from common stacks in A:", commonAllocsA) + print("Allocs from common stacks in B:", commonAllocsB) + print("Difference:", commonAllocsA - commonAllocsB) + } + + private func printSortedStacks(_ stacks: AggregateStacks) { + let sorted = stacks.sorted(by: { $0.value.netAllocations > $1.value.netAllocations }) + if sorted.isEmpty { + print("(none)\n") + } + for (stack, weightedSubstacks) in sorted { + for line in StackFormatter.lines( + forStack: stack, + weightedSubstacks: weightedSubstacks, + substackPrefix: " " + ) { + print(line) + } + print("") + } + } +} diff --git a/dev/stackdiff/Sources/stackdiff/Stackdiff.swift b/dev/stackdiff/Sources/stackdiff/Stackdiff.swift index 3251aa3d3..1eab46b08 100644 --- a/dev/stackdiff/Sources/stackdiff/Stackdiff.swift +++ b/dev/stackdiff/Sources/stackdiff/Stackdiff.swift @@ -13,9 +13,107 @@ //===----------------------------------------------------------------------===// import ArgumentParser +import Foundation +import Stacks @main struct Stackdiff: ParsableCommand { - func run() { + static var configuration: CommandConfiguration { + CommandConfiguration(subcommands: [Diff.self]) } } + +struct StackdiffOptions: ParsableArguments { + @Option(help: "The maximum stack depth used when comparing stacks.") + var depth: Int? + + @Option(help: "The minimum number of allocations for a stack to be included.") + var minAllocations: Int = 1000 + + @Option(help: "The format of the input files.") + var format: Format + + @Option(help: "If set, only stacks containing this string are included.") + var filter: String? + + enum Format: String, ExpressibleByArgument, CaseIterable { + case heaptrack + case dtrace + case bpftrace + } +} + +extension StackdiffOptions { + func load(file: String) throws -> AggregateStacks { + try AggregateStacks.load( + contentsOf: file, + format: self.format, + depth: self.depth, + minAllocations: self.minAllocations, + filter: self.filter + ) + } +} + +extension AggregateStacks { + static func load( + contentsOf file: String, + format: StackdiffOptions.Format, + depth: Int?, + minAllocations: Int, + filter: String? + ) throws -> Self { + let lines = try readLinesOfFile(file) + + let stacks: [WeightedStack] + switch format { + case .heaptrack: + stacks = HeaptrackParser.parse(lines: lines) + case .dtrace: + fatalError("dtrace isn't supported yet, why don't you add it?") + case .bpftrace: + fatalError("bpftrace isn't supported yet, why don't you add it?") + } + + // Combine equivalent stacks. + var dedupedStacks: [Stack: Int] = [:] + for stack in stacks { + dedupedStacks[stack.stack, default: 0] += stack.allocations + } + + var aggregate = AggregateStacks() + + for (stack, allocations) in dedupedStacks { + let weightedStack = WeightedStack(stack: stack, allocations: allocations) + let partialStack = weightedStack.prefix(depth ?? .max) + aggregate.groupWeightedStack(weightedStack, by: partialStack) + } + + // Remove light stacks + for stack in aggregate.partialStacks { + if aggregate.netAllocations(groupedBy: stack) < minAllocations { + aggregate.removeWeightedStacks(groupedUnder: stack) + } + } + + // Remove stacks which don't contain the filter string. + if let filter = filter { + for stack in aggregate.partialStacks { + if stack.lines.contains(where: { $0.contains(filter) }) { + continue + } else { + aggregate.removeWeightedStacks(groupedUnder: stack) + } + } + } + + return aggregate + } +} + +private func readLinesOfFile(_ path: String) throws -> [String] { + let fileData = try Data(contentsOf: URL(filePath: path)) + let file = String(decoding: fileData, as: UTF8.self) + let lines = Array(file.components(separatedBy: .newlines)) + return lines +}