Add internals for stackdiff tool (#3286)

Motivation:

Our alloc regression workflows are somewhat disparate: on macOS we have
dtrace and a script to diff two ouputs. On Linux we have heaptrack and
bpftrace but no way to analyze their outputs.

Diffing output from these tools can be quite tedious if the stacks vary
even a little (because the compiler decided to not inline a function,
for example).

Most of the tedium in this workflow is from pairing up equivalent stacks
across the two inputs. We can make this easier to do by ranking
suggestions based on how similar they are and letting the user decide
whether to accept the match or not.

Modifications:

- Add a subpackage with some internals for parsing heaptrack,
aggregating stacks, and measuring the similarity between them
- The CLI took is currently a no-op, it'll be added in subsequent PRs

Result:

Easier to diagnose alloc regressions
This commit is contained in:
George Barnett authored and GitHub committed 2025-07-07 14:04:55 +00:00
1 parent 09030f291f
commit e84b2ce05a
9 files changed
+766

No files matched your search

@@ -0,0 +1,119 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A collection of weighted stacks aggregated by their partial stacks.
///
/// Effectively a wrapper aound `[PartialStack: [WeightedStack]]` with a few helpers.
public struct AggregateStacks {
private var storage: [PartialStack: [WeightedStack]]
public init() {
self.storage = [:]
}
/// The set of all partial stacks under which weighted stacks have been aggregated.
public var partialStacks: Set<PartialStack> {
Set(self.storage.keys)
}
/// The net allocations of all aggregated stacks.
public var netAllocations: Int {
self.storage.values.reduce(0) { partial, stackAllocs in
partial + stackAllocs.netAllocations
}
}
/// Adds a weighted stack under the given partial stack.
public mutating func groupWeightedStack(_ stack: WeightedStack, by partial: PartialStack) {
self.storage[partial, default: []].append(stack)
}
/// Regroups a set of stack from under one partial stack to another.
public mutating func regroupStacks(from source: PartialStack, to destination: PartialStack) {
guard let stacks = self.removeWeightedStacks(groupedUnder: source) else {
return
}
self.storage[destination, default: []].append(contentsOf: stacks)
}
/// Removes all weighted stacks which are grouped under the given partial stack.
@discardableResult
public mutating func removeWeightedStacks(groupedUnder partial: PartialStack) -> [WeightedStack]? {
self.storage.removeValue(forKey: partial)
}
/// Returns the net allocations of all stacks grouped under the given partial stack.
public func netAllocations(groupedBy stack: PartialStack) -> Int {
self.storage[stack]?.netAllocations ?? 0
}
/// Returns all weighted stacks grouped under the given partial stack.
public func weightedStacks(groupedBy stack: PartialStack) -> [WeightedStack] {
self.storage[stack, default: []]
}
/// Returns a new aggregate only containing pairs which return true for the given predidate.
public func filter(
isIncluded: ((key: PartialStack, value: [WeightedStack])) -> Bool
) -> AggregateStacks {
var other = AggregateStacks()
other.storage = self.storage.filter(isIncluded)
return other
}
/// Removes all pairs which return true for the given predicate.
public mutating func removeAll(
where predicate: ((key: PartialStack, value: [WeightedStack])) -> Bool
) {
for (stack, stackAllocs) in self.storage {
if predicate((stack, stackAllocs)) {
self.storage.removeValue(forKey: stack)
}
}
}
/// Returns a list of key-values pairs sorted by the given comparator.
public func sorted(
by comparator: (
(key: PartialStack, value: [WeightedStack]),
(key: PartialStack, value: [WeightedStack])
) -> Bool
) -> [(key: PartialStack, value: [WeightedStack])] {
self.storage.sorted(by: comparator)
}
}
extension AggregateStacks {
public mutating func subtract(_ other: AggregateStacks) {
for (partialStack, weightedStacks) in other.storage {
for var weightedStack in weightedStacks {
weightedStack.allocations = -weightedStack.allocations
self.groupWeightedStack(weightedStack, by: partialStack)
}
}
}
public func subtracting(_ other: AggregateStacks) -> AggregateStacks {
var copy = self
copy.subtract(other)
return copy
}
}
extension [WeightedStack] {
public var netAllocations: Int {
self.reduce(0) { $0 + $1.allocations }
}
}
@@ -0,0 +1,138 @@
//===----------------------------------------------------------------------===//
//
// 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 Foundation
/// Parses output from `heaptrack analyze`.
public struct HeaptrackParser: StackParser {
private let regex = /^(\d+) calls with/
private var state: ParseState
private var stacks: [WeightedStack]
private init() {
self.stacks = []
self.state = .parsingHeader
}
private enum ParseResult {
case needsNextLine
case parsedStack(Stack, Int)
}
private enum ParseState {
case parsingHeader
case parsingStack(ParsingStackState)
}
private struct ParsingStackState {
var count: Int
var lines: [String]
init(count: Int) {
self.count = count
self.lines = []
}
private static var prefixesToIgnore: [String] {
[" in", " at", " 0x"]
}
mutating func parse(_ line: String) -> (ParseState, ParseResult) {
if Self.prefixesToIgnore.contains(where: { line.contains($0) }) {
return (.parsingStack(self), .needsNextLine)
} else if line.starts(with: " ") {
self.lines.append(line.trimmingCharacters(in: .whitespacesAndNewlines))
return (.parsingStack(self), .needsNextLine)
} else {
return (.parsingHeader, .parsedStack(Stack(self.lines), self.count))
}
}
}
/// Parses input which looks roughly like the following:
///
/// ```
/// reading file "heaptrack.simple-handshake.b.gz" - please wait, this might take some time...
/// Debuggee command was: ./.build/release/simple-handshake
/// finished reading file, now analyzing data:
///
/// MOST CALLS TO ALLOCATION FUNCTIONS
/// 488867 calls to allocation functions with 28.16K peak consumption from
/// CNIOBoringSSL_OPENSSL_malloc
/// at Sources/CNIOBoringSSL/crypto/mem.cc:249
/// in /code/.build/aarch64-unknown-linux-gnu/release/simple-handshake
/// 3000 calls with 80B peak consumption from:
/// CNIOBoringSSL_OPENSSL_zalloc
/// at Sources/CNIOBoringSSL/crypto/mem.cc:266
/// in /code/.build/aarch64-unknown-linux-gnu/release/simple-handshake
/// CNIOBoringSSL_ASN1_item_ex_new
/// at Sources/CNIOBoringSSL/crypto/asn1/tasn_new.cc:153
/// ...
/// __libc_start_main
/// in /lib/aarch64-linux-gnu/libc.so.6
/// 3000 calls with 96B peak consumption from:
/// CNIOBoringSSL_ASN1_STRING_type_new
/// at Sources/CNIOBoringSSL/crypto/asn1/asn1_lib.cc:329
/// in /code/.build/aarch64-unknown-linux-gnu/release/simple-handshake
/// ASN1_primitive_new(ASN1_VALUE_st**, ASN1_ITEM_st const*)
/// ...
/// ```
private mutating func parse(lines: some Sequence<String>) -> [WeightedStack] {
for line in lines {
loop: while true {
switch self.parseNextState(line) {
case .parsedStack(let stack, let count):
self.stacks.append(WeightedStack(stack: stack, allocations: count))
case .needsNextLine:
break loop
}
}
}
return self.stacks
}
private mutating func parseNextState(_ line: String) -> ParseResult {
switch self.state {
case .parsingHeader:
return self.parseHeader(line)
case .parsingStack(var state):
let (state, result) = state.parse(line)
self.state = state
return result
}
}
private mutating func parseHeader(_ line: String) -> ParseResult {
if let match = line.firstMatch(of: self.regex) {
// At the start of a stack.
guard let count = Int(match.1) else {
fatalError("Failed to convert '\(match.1)' to an Int")
}
self.state = .parsingStack(ParsingStackState(count: count))
}
return .needsNextLine
}
}
extension HeaptrackParser {
public static func parse(lines: some Sequence<String>) -> [WeightedStack] {
var parser = Self()
return parser.parse(lines: lines)
}
}
@@ -0,0 +1,74 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
public protocol StackParser {
static func parse(lines: some Sequence<String>) throws -> [WeightedStack]
}
public protocol StackProtocol {
var lines: [String] { get }
}
extension StackProtocol {
/// Returns a stack with at most `maxLength` lines from the start of the current stack.
public func prefix(_ maxLength: Int) -> PartialStack {
PartialStack(self.lines.prefix(max(0, maxLength)))
}
/// Returns a stack with at most `maxLength` lines from the end of the current stack.
public func suffix(_ maxLength: Int) -> PartialStack {
PartialStack(self.lines.suffix(max(0, maxLength)))
}
}
/// The lines of a full stack trace.
public struct Stack: Hashable, StackProtocol {
public var lines: [String]
public init(_ lines: [String]) {
self.lines = lines
}
public init(_ weighted: WeightedStack) {
self = weighted.stack
}
}
/// The lines of a possibly incomplete stack trace.
public struct PartialStack: Hashable, StackProtocol {
public var lines: [String]
public init(_ lines: some Sequence<String>) {
self.lines = Array(lines)
}
}
/// A stack with an associated number of allocations
public struct WeightedStack: Hashable, StackProtocol {
public var stack: Stack
public var allocations: Int
public var lines: [String] {
self.stack.lines
}
public init(lines: [String], allocations: Int) {
self.init(stack: Stack(lines), allocations: allocations)
}
public init(stack: Stack, allocations: Int) {
self.stack = stack
self.allocations = allocations
}
}
@@ -0,0 +1,64 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
public enum Similarity {
/// Returns the Levenshtein distance between two strings and their similarity score.
///
/// See also: https://en.wikipedia.org/wiki/Levenshtein_distance
///
/// The score is normalized to 0...1, with 1 indicting an exact match. Scores are calculated
/// as `1 - levenshtein(a, b) / max(length(a), length(b))`.
public static func levenshtein(_ a: String, _ b: String) -> (distance: Int, similarity: Double) {
Self.levenshtein(Array(a.utf8), Array(b.utf8))
}
private static func levenshtein(
_ a: [UInt8],
_ b: [UInt8]
) -> (distance: Int, similarity: Double) {
if a.isEmpty, b.isEmpty {
// Perfect match.
return (0, 1.0)
} else if a.isEmpty {
// A is empty, B isn't. Distance is length of B.
return (b.count, 0.0)
} else if b.isEmpty {
// B is empty, A isn't. Distance is length of A.
return (a.count, 0.0)
}
var distance = Array(0...b.count)
for rowIndex in 1...a.count {
var previous = distance[0]
distance[0] = rowIndex
for colIndex in 1...b.count {
let temp = distance[colIndex]
if a[rowIndex - 1] == b[colIndex - 1] {
distance[colIndex] = previous
} else {
distance[colIndex] = 1 + min(distance[colIndex - 1], previous, distance[colIndex])
}
previous = temp
}
}
let editDistance = distance[b.count]
let similarity = 1 - (Double(editDistance) / Double(max(a.count, b.count)))
return (editDistance, similarity)
}
}
@@ -0,0 +1,21 @@
//===----------------------------------------------------------------------===//
//
// 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
@main
struct Stackdiff: ParsableCommand {
func run() {
}
}