import CryptoKit import Foundation import ParcelTestSupport import Testing struct BenchmarkMachine: Equatable { let hostKey: String let model: String let cores: Int init(hostKey: String, model: String, cores: Int) throws { let safe = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,._-") guard !hostKey.isEmpty, !model.isEmpty, hostKey.unicodeScalars.allSatisfy(safe.contains), model.unicodeScalars.allSatisfy(safe.contains), cores > 0 else { throw BenchmarkFailure.measurement("machine identity") } self.hostKey = hostKey self.model = model self.cores = cores } init(identity: String) throws { let parts = identity.components(separatedBy: ";") guard parts.count == 3, parts[0].hasPrefix("host="), parts[1].hasPrefix("model="), parts[2].hasPrefix("cores="), let cores = Int(parts[2].dropFirst(6)) else { throw BenchmarkFailure.measurement("machine identity") } try self.init(hostKey: String(parts[0].dropFirst(5)), model: String(parts[1].dropFirst(6)), cores: cores) } var identity: String { "host=\(hostKey);model=\(model);cores=\(cores)" } var fileName: String { "\(hostKey)-\(model)-\(cores).json" } static func command(_ executable: String, _ arguments: [String]) throws -> String { let process = Process() process.executableURL = URL(fileURLWithPath: executable) process.arguments = arguments let output = Pipe() process.standardOutput = output process.standardError = output try process.run() let data = output.fileHandleForReading.readDataToEndOfFile() process.waitUntilExit() guard process.terminationStatus == 0, let text = String(data: data, encoding: .utf8) else { throw BenchmarkFailure.measurement("host command failed: \(executable)") } return text.trimmingCharacters(in: .whitespacesAndNewlines) } static func key(localHostName: String, platformUUID: String) throws -> String { guard UUID(uuidString: platformUUID) != nil else { throw BenchmarkFailure.measurement("platform UUID") } let digest = SHA256.hash(data: Data(platformUUID.uppercased().utf8)) let suffix = digest.prefix(4).map { String(format: "%02x", $0) }.joined() let machine = try Self(hostKey: localHostName + "-" + suffix, model: "validation", cores: 1) return machine.hostKey } static func current() throws -> Self { let host = try command("/usr/sbin/scutil", ["--get", "LocalHostName"]) let data = Data(try command("/usr/sbin/ioreg", ["-a", "-r", "-d", "1", "-c", "IOPlatformExpertDevice"]).utf8) struct RegistryRecord: Decodable { let platformUUID: String enum CodingKeys: String, CodingKey { case platformUUID = "IOPlatformUUID" } } let records = try PropertyListDecoder().decode([RegistryRecord].self, from: data) guard let uuid = records.first?.platformUUID, let cores = Int(try command("/usr/sbin/sysctl", ["-n", "hw.ncpu"])) else { throw BenchmarkFailure.measurement("hardware identity") } return try Self( hostKey: key(localHostName: host, platformUUID: uuid), model: command("/usr/sbin/sysctl", ["-n", "hw.model"]), cores: cores) } func host(source: BenchmarkCounterSource, quietURL: URL? = nil) throws -> BenchmarkHost { let quiet = try quietURL.map { try JSONDecoder().decode(BenchmarkQuiet.self, from: Data(contentsOf: $0)) } #if DEBUG let configuration = "debug" #else let configuration = "release" #endif return try BenchmarkHost( hostKey: hostKey, model: model, cores: cores, osBuild: Self.command("/usr/sbin/sysctl", ["-n", "kern.osversion"]), swiftVersion: Self.command("/usr/bin/env", ["swift", "--version"]), buildConfiguration: configuration, counterSource: source, quiet: quiet) } } enum BenchmarkBaselines { static let repository = URL(fileURLWithPath: #filePath) .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() static let directory = repository.appendingPathComponent("Benchmarks/baselines", isDirectory: true) static func url(for machine: BenchmarkMachine) -> URL { directory.appendingPathComponent(machine.fileName) } static func read(_ url: URL, caseNames: Set) throws -> BenchmarkReport { guard FileManager.default.fileExists(atPath: url.path) else { throw BenchmarkFailure.missingBaseline(url.path) } let data = try Data(contentsOf: url) struct Header: Decodable { let version: Int } guard try JSONDecoder().decode(Header.self, from: data).version == BenchmarkReport.currentVersion else { throw BenchmarkFailure.schema } let report = try JSONDecoder().decode(BenchmarkReport.self, from: data) try report.validate(caseNames: caseNames) return report } static func write(_ report: BenchmarkReport, to url: URL, caseNames: Set) throws { try report.validate(caseNames: caseNames) let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys] let data = try encoder.encode(report) try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) try data.write(to: url, options: .atomic) } } extension PerformanceTestSuite { @Suite("Checked-in benchmark baselines", .tags(.benchmark, .appKit)) struct BenchmarkBaselineFileTests { @Test func checkedInBaselinesHaveHostIdentityAndCoverage() throws { let files = try FileManager.default.contentsOfDirectory( at: BenchmarkBaselines.directory, includingPropertiesForKeys: nil) for file in files where file.pathExtension == "json" { let report = try BenchmarkBaselines.read(file, caseNames: BenchmarkCases.names) let machine = try BenchmarkMachine(identity: report.machine) #expect(file.lastPathComponent == machine.fileName) #expect(report.results.allSatisfy { $0.samples == 15 }) #expect(report.host.buildConfiguration == "release") } } } } extension PerformanceTestSuite { @Suite("Benchmark baseline identity", .tags(.benchmark)) struct BenchmarkBaselineTests { @Test func matchingModelsOnDifferentHostsHaveDifferentFiles() throws { let first = try BenchmarkMachine(hostKey: "first-12345678", model: "Mac", cores: 14) let second = try BenchmarkMachine(hostKey: "second-87654321", model: "Mac", cores: 14) #expect(first.fileName != second.fileName) #expect(try BenchmarkMachine(identity: first.identity) == first) #expect(throws: BenchmarkFailure.self) { try BenchmarkMachine(hostKey: "../other", model: "Mac", cores: 14) } #expect(throws: BenchmarkFailure.self) { try BenchmarkMachine(hostKey: "test", model: "Mac", cores: 0) } #expect(throws: BenchmarkFailure.self) { try BenchmarkMachine(identity: "Mac;cores=oops") } } @Test func uuidHashIsStableAndOnlyEightHexDigitsAreExposed() throws { let uuid = "00000000-0000-4000-8000-000000000001" let first = try BenchmarkMachine.key(localHostName: "test", platformUUID: uuid) #expect(first.count == 13) #expect(try BenchmarkMachine.key(localHostName: "test", platformUUID: uuid.lowercased()) == first) #expect(throws: BenchmarkFailure.self) { try BenchmarkMachine.key(localHostName: "test", platformUUID: "bad") } } @Test func baselineRoundTripAndMalformedFiles() throws { let directory = FileManager.default.temporaryDirectory.appendingPathComponent( "parcel-baseline-" + UUID().uuidString) defer { do { try FileManager.default.removeItem(at: directory) } catch { Issue.record(error) } } let url = directory.appendingPathComponent("test.json") let report = BenchmarkComparisonTests().report() #expect(throws: BenchmarkFailure.self) { try BenchmarkBaselines.read(url, caseNames: ["layout"]) } try BenchmarkBaselines.write(report, to: url, caseNames: ["layout"]) #expect(try BenchmarkBaselines.read(url, caseNames: ["layout"]).results == report.results) #expect(throws: BenchmarkFailure.self) { try BenchmarkBaselines.read(url, caseNames: ["other"]) } try Data("not json".utf8).write(to: url) #expect(throws: DecodingError.self) { try BenchmarkBaselines.read(url, caseNames: ["layout"]) } try Data("{\"version\":4}".utf8).write(to: url) #expect(throws: BenchmarkFailure.self) { try BenchmarkBaselines.read(url, caseNames: ["layout"]) } } } }