SPB Git

Repository Public

BenchmarkTests.swift 19.6 KB 427 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraBenchmarksTests/BenchmarkTests.swift8// Module           : Tests9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0413//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import Synchronization43import Testing4445@testable import QyvoraBenchmarks4647/// A benchmark that only spins; `work` is the number of loop turns of one operation.48private func synthetic(_ id: String, family: BenchmarkFamily = .hash, cost: BenchmarkCost = .standard, work: Int = 200) -> Benchmark {49    Benchmark(id: id, family: family, algorithm: "Synthetic", operation: id, cost: cost) {50        var state: UInt64 = 151        return {52            for i in 0..<work { state = state &* 6_364_136_223_846_793_005 &+ UInt64(i) }53            BlackBox.consume(state)54        }55    }56}5758@Suite struct StatisticsTests {59    @Test func knownSamples() {60        let s = BenchmarkStatistics(samples: [5, 1, 4, 2, 3])61        #expect(s.sampleCount == 5)62        #expect(s.min == 1)63        #expect(s.max == 5)64        #expect(s.median == 3)65        #expect(s.mean == 3)66        // Sample variance of 1...5 is 2.5.67        #expect(abs(s.standardDeviation - 2.5.squareRoot()) < 1e-12)68        // Rank 0.95 * 4 = 3.8 -> 4 + 0.8 * (5 - 4).69        #expect(abs(s.p95 - 4.8) < 1e-12)70        #expect(abs(s.coefficientOfVariation - 2.5.squareRoot() / 3) < 1e-12)71    }7273    @Test func evenCountMedianInterpolates() {74        let s = BenchmarkStatistics(samples: [4, 1, 3, 2])75        #expect(s.median == 2.5)76        #expect(s.mean == 2.5)77    }7879    @Test func hundredSamplesPercentile() {80        let s = BenchmarkStatistics(samples: (1...100).map(Double.init).reversed())81        // Rank 0.95 * 99 = 94.05 -> 95 + 0.05.82        #expect(abs(s.p95 - 95.05) < 1e-9)83        #expect(s.median == 50.5)84    }8586    @Test func singleAndEmpty() {87        let one = BenchmarkStatistics(samples: [0.25])88        #expect(one.min == 0.25 && one.max == 0.25 && one.median == 0.25 && one.mean == 0.25 && one.p95 == 0.25)89        #expect(one.standardDeviation == 0)90        let none = BenchmarkStatistics(samples: [])91        #expect(none.sampleCount == 0)92        #expect(none.mean == 0 && none.median == 0 && none.standardDeviation == 0)93        #expect(none.coefficientOfVariation == 0)94    }9596    @Test func constantSamplesHaveNoSpread() {97        let s = BenchmarkStatistics(samples: [Double](repeating: 0.002, count: 40))98        #expect(s.standardDeviation < 1e-15)99        #expect(s.min == s.max)100    }101}102103@Suite struct CatalogueTests {104    @Test func identifiersAreUnique() {105        let ids = BenchmarkCatalogue.all.map(\.id)106        #expect(Set(ids).count == ids.count)107    }108109    @Test func familiesHaveTheExpectedCounts() {110        #expect(BenchmarkCatalogue.benchmarks(in: .mlkem).count == 9)111        #expect(BenchmarkCatalogue.benchmarks(in: .mldsa).count == 9)112        #expect(BenchmarkCatalogue.benchmarks(in: .slhdsa).count == 36)113        #expect(BenchmarkCatalogue.benchmarks(in: .hash).count == 10)114        #expect(BenchmarkCatalogue.benchmarks(in: .symmetric).count == 7)115        #expect(BenchmarkCatalogue.benchmarks(in: .kdf).count == 3)116        #expect(BenchmarkCatalogue.benchmarks(in: .ntt).count == 4)117        #expect(BenchmarkCatalogue.benchmarks(in: .secp256k1).count == 6)118        #expect(BenchmarkCatalogue.all.count == 84)119    }120121    @Test func slowSetsAreMarked() {122        let slow = Set(BenchmarkCatalogue.all.filter { $0.cost == .slow }.map(\.id))123        #expect(slow.contains("slh-dsa-sha2-128s.sign"))124        #expect(slow.contains("slh-dsa-shake-256s.keygen"))125        #expect(slow.contains("slh-dsa-sha2-128f.sign"))126        #expect(!slow.contains("slh-dsa-sha2-128f.keygen"))127        #expect(slow.contains("argon2id.64-mib-t3-p4"))128        #expect(!slow.contains("ml-kem-768.encaps"))129    }130131    @Test func filtering() {132        let all = BenchmarkCatalogue.all133        #expect(all.filtered(by: nil).count == all.count)134        #expect(all.filtered(by: "").count == all.count)135        #expect(all.filtered(by: "ML-KEM-768").map(\.id) == ["ml-kem-768.keygen", "ml-kem-768.encaps", "ml-kem-768.decaps"])136        #expect(all.filtered(by: "ml-kem-768.decaps").count == 1)137        // The family identifier and title match too.138        #expect(all.filtered(by: "secp256k1").count == 6)139        #expect(all.filtered(by: "FIPS 205").count == 36)140        #expect(all.filtered(by: "ntt").count == 4)141        #expect(all.filtered(by: "no such benchmark").isEmpty)142    }143144    @Test func sizeTableMatchesTheStandards() throws {145        let table = BenchmarkCatalogue.sizeTable146        #expect(table.count == 3 + 3 + 12 + 2)147        func row(_ name: String) throws -> ParameterSetSizes { try #require(table.first { $0.name == name }) }148        let kem = try row("ML-KEM-768")149        #expect(kem.publicKey == 1184 && kem.privateKey == 2400 && kem.output == 1088 && kem.sharedSecret == 32)150        let dsa = try row("ML-DSA-65")151        #expect(dsa.publicKey == 1952 && dsa.privateKey == 4032 && dsa.output == 3309)152        let slh = try row("SLH-DSA-SHA2-128s")153        #expect(slh.publicKey == 32 && slh.privateKey == 64 && slh.output == 7856)154        let fast = try row("SLH-DSA-SHAKE-256f")155        #expect(fast.publicKey == 64 && fast.privateKey == 128 && fast.output == 49856)156        #expect(MarkdownRenderer.sizeTable().contains("| ML-KEM-1024 | FIPS 203 | KEM | 5 | 1568 | 3168 | 1568 | 32 |"))157    }158159    @Test func patternIsDeterministic() {160        #expect(BenchmarkCatalogue.pattern(100, seed: 3) == BenchmarkCatalogue.pattern(100, seed: 3))161        #expect(BenchmarkCatalogue.pattern(100, seed: 3) != BenchmarkCatalogue.pattern(100, seed: 4))162        #expect(BenchmarkCatalogue.pattern(13, seed: 1).count == 13)163    }164}165166@Suite struct RunnerTests {167    @Test func measuresASyntheticBenchmark() throws {168        let configuration = BenchmarkConfiguration(name: "test", timeBudget: 0.02, minimumSamples: 4, slowMinimumSamples: 1)169        let result = try BenchmarkRunner(configuration: configuration).measure(synthetic("spin"))170        let s = result.statistics171        #expect(s.sampleCount >= 4)172        #expect(result.iterations == s.sampleCount * result.operationsPerSample)173        #expect(s.min > 0)174        #expect(s.min <= s.median && s.median <= s.p95 && s.p95 <= s.max)175        #expect(s.min <= s.mean && s.mean <= s.max)176        #expect(result.warmedUp)177        #expect(result.wallTime > 0)178        #expect(result.cpuTime >= 0)179        #expect(result.operationsPerSecond > 0)180        #expect(result.megabytesPerSecond == nil)181        #expect(!result.headline.isEmpty)182    }183184    @Test func slowBenchmarkKeepsItsCalibrationRun() throws {185        // One operation (a few milliseconds) exceeds the budget: a single sample, no warm-up.186        let configuration = BenchmarkConfiguration(name: "test", timeBudget: 0.000_001, minimumSamples: 3, slowMinimumSamples: 1)187        let result = try BenchmarkRunner(configuration: configuration).measure(synthetic("slow", cost: .slow, work: 2_000_000))188        #expect(result.statistics.sampleCount == 1)189        #expect(result.iterations == 1)190        #expect(!result.warmedUp)191        #expect(result.wallTime >= result.statistics.min)192    }193194    @Test func derivedMetrics() throws {195        let units = 1_000_000.0196        let throughput = Benchmark(197            id: "t", family: .hash, algorithm: "T", operation: "1 MB", metric: .throughput, unitsPerOperation: units198        ) {199            var state: UInt64 = 1200            return {201                for i in 0..<500 { state = state &* 31 &+ UInt64(i) }202                BlackBox.consume(state)203            }204        }205        let result = try BenchmarkRunner(configuration: .smoke).measure(throughput)206        let mbps = try #require(result.megabytesPerSecond)207        #expect(abs(mbps - 1 / result.statistics.median) < 1e-6 * mbps)208        #expect(result.headline.hasSuffix("MB/s"))209        #expect(result.itemsPerSecond == nil)210    }211212    @Test func progressAndFailuresAreReported() async throws {213        struct Boom: Error {}214        let failing = Benchmark(id: "boom", family: .kdf, algorithm: "Synthetic", operation: "boom") { throw Boom() }215        let events = Mutex<[String]>([])216        let report = try await BenchmarkRunner(configuration: .smoke).run([synthetic("a"), failing, synthetic("b")]) { progress in217            events.withLock {218                switch progress {219                case let .started(benchmark, index, total): $0.append("start \(benchmark.id) \(index)/\(total)")220                case let .finished(result, index, total): $0.append("done \(result.id) \(index)/\(total)")221                case let .failed(failure, index, total): $0.append("fail \(failure.id) \(index)/\(total)")222                }223            }224        }225        #expect(events.withLock { $0 } == ["start a 0/3", "done a 0/3", "start boom 1/3", "fail boom 1/3", "start b 2/3", "done b 2/3"])226        #expect(report.results.map(\.id) == ["a", "b"])227        #expect(report.failures.map(\.id) == ["boom"])228        #expect(report.environment.buildConfiguration == SystemProbe.buildConfiguration)229        #expect(report.environment.logicalCores > 0)230        #expect(report.wallTime > 0)231    }232233    @Test func cancellationStopsTheRun() async throws {234        // Far more work than the test may take: only cancellation can end this run early.235        let many = (0..<400).map { synthetic("spin-\($0)", work: 20_000) }236        let configuration = BenchmarkConfiguration(name: "test", timeBudget: 0.25, minimumSamples: 5, slowMinimumSamples: 1)237        let finished = Atomic<Int>(0)238        let task = Task.detached {239            try await BenchmarkRunner(configuration: configuration).run(many) { progress in240                if case .finished = progress { finished.wrappingAdd(1, ordering: .relaxed) }241            }242        }243        try await Task.sleep(for: .milliseconds(300))244        task.cancel()245        let started = ContinuousClock.now246        await #expect(throws: CancellationError.self) { _ = try await task.value }247        #expect(ContinuousClock.now - started < .seconds(5))248        #expect(finished.load(ordering: .relaxed) < many.count)249    }250251    @Test func eventStreamEndsWithTheReport() async throws {252        var finished = 0253        var report: BenchmarkReport?254        for try await event in BenchmarkRunner(configuration: .smoke).events([synthetic("a"), synthetic("b")]) {255            switch event {256            case let .progress(progress):257                if case .finished = progress { finished += 1 }258            case let .completed(value):259                report = value260            }261        }262        #expect(finished == 2)263        #expect(report?.results.count == 2)264    }265}266267@Suite struct RendererTests {268    private func sampleReport() async throws -> BenchmarkReport {269        let sized = Benchmark(270            id: "sized", family: .mlkem, algorithm: "Synthetic-KEM", operation: "encaps",271            sizes: BenchmarkSizes(publicKey: 1184, privateKey: 2400, output: 1088, outputLabel: "ciphertext")272        ) {273            { BlackBox.consume(true) }274        }275        return try await BenchmarkRunner(configuration: .smoke).run([sized, synthetic("plain")])276    }277278    @Test func jsonRoundTrip() async throws {279        let report = try await sampleReport()280        let data = try report.jsonData()281        let decoded = try BenchmarkReport(jsonData: data)282        // Dates are ISO 8601 with second precision: compare everything else exactly.283        #expect(decoded.results == report.results)284        #expect(decoded.failures == report.failures)285        #expect(decoded.environment == report.environment)286        #expect(decoded.configuration == report.configuration)287        #expect(decoded.powerAtStart == report.powerAtStart && decoded.powerAtEnd == report.powerAtEnd)288        #expect(decoded.schemaVersion == BenchmarkReport.currentSchemaVersion)289        #expect(decoded.loadAverageAtStart == report.loadAverageAtStart)290        #expect(report.loadAverageAtStart != nil)291        #expect(abs(decoded.startedAt.timeIntervalSince(report.startedAt)) < 1)292        // A second encoding of the decoded value is byte-identical.293        #expect(try decoded.jsonData() == BenchmarkReport(jsonData: decoded.jsonData()).jsonData())294        let text = try report.jsonString()295        #expect(text.contains("\"buildConfiguration\""))296        #expect(text.contains("\"thermalState\""))297    }298299    @Test func markdownContainsEveryResult() async throws {300        let report = try await sampleReport()301        let markdown = report.markdown()302        #expect(markdown.contains("# QYVORA benchmark report"))303        #expect(markdown.contains("## ML-KEM (FIPS 203)"))304        #expect(markdown.contains("| Synthetic-KEM encaps |"))305        #expect(markdown.contains("1184 / 2400 / 1088"))306        #expect(markdown.contains("| Synthetic plain |"))307        #expect(markdown.contains("Energy: not measured"))308        #expect(markdown.contains("Thermal state:"))309    }310311    @Test func formatting() {312        #expect(BenchmarkFormat.duration(1.5) == "1.50 s")313        #expect(BenchmarkFormat.duration(0.0123) == "12.3 ms")314        #expect(BenchmarkFormat.duration(0.000_045_6) == "45.6 µs")315        #expect(BenchmarkFormat.duration(0.000_000_321) == "321 ns")316        #expect(BenchmarkFormat.count(5_230_000) == "5.23 M")317        #expect(BenchmarkFormat.count(12_300) == "12.3 k")318        #expect(BenchmarkFormat.memory(nil) == "n/a")319        #expect(BenchmarkFormat.memory(64 * 1_048_576) == "+64.0 MiB")320        #expect(BenchmarkFormat.memory(0) == "0 B")321    }322}323324@Suite struct ProbeTests {325    @Test func environmentIsDescribed() {326        let e = BenchmarkEnvironment.current()327        #expect(!e.deviceModel.isEmpty)328        #expect(e.physicalCores > 0 && e.logicalCores >= e.physicalCores)329        #expect(e.memoryBytes > 0)330        #expect(!e.osVersion.isEmpty)331        #expect(e.buildConfiguration == "debug" || e.buildConfiguration == "release")332        #expect(!e.summary.isEmpty)333    }334335    @Test func probesReturnPlausibleValues() throws {336        let memory = try #require(SystemProbe.residentMemory())337        #expect(memory.current > 0)338        #expect(memory.peak >= memory.current)339        #expect(try #require(SystemProbe.rawResidentMemory()).current > 0)340        let before = SystemProbe.processCPUTime()341        var x: UInt64 = 1342        for i in 0..<3_000_000 { x = x &* 6_364_136_223_846_793_005 &+ UInt64(i) }343        BlackBox.consume(x)344        #expect(SystemProbe.processCPUTime() >= before)345        #expect(["nominal", "fair", "serious", "critical", "unknown"].contains(PowerState.current().thermalState))346    }347348    /// The probe while the process grows on other threads: this is the situation in which the test above failed once349    /// in three runs (`memory.peak >= memory.current`), when it compared the kernel's two figures directly. Other350    /// suites of the test process were allocating at that moment: the resident size is computed when `task_info` is351    /// called, the kernel's high-water mark is a separate counter that can trail it. The probe's own mark cannot:352    /// every answer has `peak >= current`, and `peak` never decreases. How often the kernel's pair was inconsistent353    /// during the run is printed, not asserted: it depends on the machine and on the load.354    @Test func thePeakNeverTrailsTheCurrentSizeWhileTheProcessGrows() async throws {355        let stop = ManagedAtomicFlag()356        let growers = (0..<4).map { index in357            Task.detached {358                var blocks = [[UInt8]]()359                var round = 0360                while !stop.isSet {361                    // touch every page so that it becomes resident, then let some of it go362                    blocks.append([UInt8](repeating: UInt8(truncatingIfNeeded: index &+ round), count: 2 << 20))363                    if blocks.count > 24 { blocks.removeFirst(12) }364                    round += 1365                    await Task.yield()366                }367                BlackBox.consume(UInt64(blocks.count))368            }369        }370        var previousPeak: UInt64 = 0, samples = 0, rawInversions = 0, largestInversion: UInt64 = 0371        let end = ContinuousClock.now + .milliseconds(600)372        while ContinuousClock.now < end {373            let raw = try #require(SystemProbe.rawResidentMemory())374            if raw.kernelPeak < raw.current {375                rawInversions += 1376                largestInversion = max(largestInversion, raw.current - raw.kernelPeak)377            }378            let memory = try #require(SystemProbe.residentMemory())379            #expect(memory.peak >= memory.current)380            #expect(memory.peak >= previousPeak)381            previousPeak = memory.peak382            samples += 1383        }384        stop.set()385        for grower in growers { await grower.value }386        #expect(samples > 100)387        print("PROBE raw resident pairs with kernel peak < current: \(rawInversions) of \(samples) samples, largest gap \(largestInversion) bytes")388    }389390    @Test func blackBoxAccumulates() {391        let before = BlackBox.checksum392        BlackBox.consume([1, 2, 3])393        BlackBox.consume(true)394        BlackBox.consume(UInt64(7))395        #expect(BlackBox.checksum != before)396    }397}398399@Suite(.serialized) struct SmokeTests {400    /// Runs the whole catalogue once with the smallest budget. In debug builds the seconds-long401    /// benchmarks (SLH-DSA, Argon2id at 64 MiB) are skipped: unoptimized, they take minutes.402    @Test func wholeCatalogueRuns() async throws {403        var benchmarks = BenchmarkCatalogue.all404        #if DEBUG405        benchmarks = benchmarks.filter { $0.family != .slhdsa && $0.cost != .slow }406        #endif407        let report = try await BenchmarkRunner(configuration: .smoke).run(benchmarks)408        #expect(report.failures.isEmpty, "failures: \(report.failures)")409        #expect(report.results.count == benchmarks.count)410        for result in report.results {411            #expect(result.statistics.min > 0, "\(result.id) measured no time")412            #expect(result.iterations >= 1)413        }414        // The report renders and survives a JSON round trip.415        #expect(try BenchmarkReport(jsonData: report.jsonData()).results == report.results)416        #expect(report.markdown().contains("## secp256k1"))417    }418}419420/// A flag shared between a test and its helper tasks.421final class ManagedAtomicFlag: @unchecked Sendable {422    private let lock = NSLock()423    private var value = false424    var isSet: Bool { lock.withLock { value } }425    func set() { lock.withLock { value = true } }426}427
Files main
Menu

Theme