Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : App/Sources/BenchmarksView.swift8// Module : Sources9// 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 SwiftUI42import QyvoraBenchmarks43import QyvoraUI4445extension BenchmarkFamily {46 var shortTitle: String {47 switch self {48 case .mlkem: return "ML-KEM"49 case .mldsa: return "ML-DSA"50 case .slhdsa: return "SLH-DSA"51 case .hash: return "Hash"52 case .symmetric: return "Symmetric"53 case .kdf: return "KDF"54 case .ntt: return "NTT"55 case .secp256k1: return "secp256k1"56 }57 }58}5960/// State of one benchmark run. The measurements themselves come from `BenchmarkRunner`.61@MainActor62@Observable63final class BenchmarkSession {64 enum Mode: String, CaseIterable, Identifiable {65 case quick, full66 var id: String { rawValue }67 var title: String { self == .quick ? "Quick" : "Full" }68 var configuration: BenchmarkConfiguration { self == .quick ? .quick : .full }69 var detail: String {70 self == .quick71 ? "About 0.15 s per benchmark, at least 3 samples (1 for the slow ones)."72 : "About 1 s per benchmark, at least 5 samples (3 for the slow ones)."73 }74 }7576 enum State: Equatable {77 case idle78 case running79 case finished80 case cancelled81 case failed(String)82 }8384 var mode: Mode = .quick85 /// Empty means every family.86 var families: Set<BenchmarkFamily> = []87 private(set) var state: State = .idle88 private(set) var results: [BenchmarkResult] = []89 private(set) var failures: [BenchmarkFailure] = []90 private(set) var report: BenchmarkReport?91 private(set) var currentName: String?92 private(set) var completed = 093 private(set) var total = 094 private(set) var powerAtStart: PowerState?95 private(set) var thermalNow: String = PowerState.current().thermalState96 private(set) var markdownFile: URL?97 private(set) var jsonFile: URL?98 private(set) var runMode: Mode = .quick99 private var task: Task<Void, Never>?100101 let environment = BenchmarkEnvironment.current()102103 var selection: [Benchmark] {104 families.isEmpty ? BenchmarkCatalogue.all : BenchmarkCatalogue.all.filter { families.contains($0.family) }105 }106107 var isRunning: Bool { state == .running }108109 func toggle(_ family: BenchmarkFamily) {110 if families.contains(family) { families.remove(family) } else { families.insert(family) }111 if families.count == BenchmarkFamily.allCases.count { families = [] }112 }113114 func start() {115 guard !isRunning else { return }116 let list = selection117 guard !list.isEmpty else { return }118 results = []119 failures = []120 report = nil121 markdownFile = nil122 jsonFile = nil123 completed = 0124 total = list.count125 currentName = nil126 powerAtStart = .current()127 thermalNow = PowerState.current().thermalState128 runMode = mode129 state = .running130 let runner = BenchmarkRunner(configuration: mode.configuration)131 task = Task { [weak self] in132 do {133 for try await event in runner.events(list) {134 guard let self else { return }135 self.handle(event)136 }137 guard let self else { return }138 if self.report == nil { self.finish(.cancelled) }139 } catch is CancellationError {140 self?.finish(.cancelled)141 } catch {142 self?.finish(.failed(String(describing: error)))143 }144 }145 }146147 func cancel() {148 task?.cancel()149 }150151 private func handle(_ event: BenchmarkEvent) {152 switch event {153 case .progress(.started(let benchmark, _, _)):154 currentName = benchmark.displayName155 case .progress(.finished(let result, let index, _)):156 results.append(result)157 completed = index + 1158 thermalNow = result.thermalStateAtEnd159 case .progress(.failed(let failure, let index, _)):160 failures.append(failure)161 completed = index + 1162 case .completed(let finished):163 report = finished164 thermalNow = finished.powerAtEnd.thermalState165 writeExports(finished)166 finish(.finished)167 }168 }169170 private func finish(_ newState: State) {171 currentName = nil172 task = nil173 state = newState174 }175176 private func writeExports(_ report: BenchmarkReport) {177 let formatter = DateFormatter()178 formatter.locale = Locale(identifier: "en_US_POSIX")179 formatter.timeZone = TimeZone(identifier: "UTC")180 formatter.dateFormat = "yyyyMMdd'T'HHmmss'Z'"181 let stamp = formatter.string(from: report.startedAt)182 let directory = FileManager.default.temporaryDirectory.appendingPathComponent("qyvora-benchmarks", isDirectory: true)183 try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)184 let base = "qyvora-bench-\(report.configuration.name)-\(stamp)"185 let markdown = directory.appendingPathComponent(base + ".md")186 if (try? Data(report.markdown().utf8).write(to: markdown, options: .atomic)) != nil { markdownFile = markdown }187 let json = directory.appendingPathComponent(base + ".json")188 if let data = try? report.jsonData(), (try? data.write(to: json, options: .atomic)) != nil { jsonFile = json }189 }190}191192/// Runs the engine benchmark suite on this device and shows the results as they arrive.193struct BenchmarksView: View {194 @State private var session = BenchmarkSession()195 @Environment(\.accessibilityReduceMotion) private var reduceMotion196197 var body: some View {198 ScrollView {199 VStack(alignment: .leading, spacing: QSpace.xl) {200 if session.environment.buildConfiguration.lowercased() == "debug" {201 WarningBanner(.warning, title: "Debug build",202 message: "This build is not optimised. Its timings are much slower than those of a Release build and are not representative of the engine.")203 }204 configurationSection205 runSection206 resultSections207 if !session.failures.isEmpty { failureSection }208 environmentSection209 energySection210 if session.report != nil { exportSection }211 }212 .padding(.horizontal, QMetric.screenPadding)213 .padding(.top, QSpace.m)214 .padding(.bottom, QSpace.xxl)215 .frame(maxWidth: 640, alignment: .leading)216 .frame(maxWidth: .infinity)217 }218 .debugScroll()219 .qScreen()220 .navigationTitle("Benchmarks")221 .navigationBarTitleDisplayMode(.inline)222 .qAnimation(value: session.results.count)223 .qAnimation(value: session.state)224 .sensoryFeedback(trigger: session.state) { _, new in225 switch new {226 case .finished: return .success227 case .failed: return .error228 case .cancelled: return .warning229 default: return nil230 }231 }232 .onDisappear { session.cancel() }233 #if DEBUG234 .task {235 if let families = DebugLaunch.benchFamilies { session.families = families }236 if DebugLaunch.benchAutorun { session.start() }237 }238 #endif239 }240241 // MARK: Configuration242243 var configurationSection: some View {244 QListSection("Run", footnote: "\(session.mode.detail) \(session.selection.count) benchmarks selected.", separatorInset: QMetric.padding) {245 Picker("Depth", selection: $session.mode) {246 ForEach(BenchmarkSession.Mode.allCases) { Text($0.title).tag($0) }247 }248 .pickerStyle(.segmented)249 .disabled(session.isRunning)250 .accessibilityLabel("Run depth")251 .padding(.vertical, QSpace.m)252253 VStack(alignment: .leading, spacing: QSpace.s) {254 Text("Families").font(QFont.callout).foregroundStyle(QColor.textSecondary)255 FlowLayout(spacing: 8) {256 chip("All", selected: session.families.isEmpty) { session.families = [] }257 ForEach(BenchmarkFamily.allCases) { family in258 chip(family.shortTitle, selected: session.families.contains(family)) { session.toggle(family) }259 .accessibilityLabel(family.title)260 }261 }262 }263 .padding(.vertical, QSpace.m)264 .disabled(session.isRunning)265 }266 }267268 func chip(_ title: String, selected: Bool, action: @escaping () -> Void) -> some View {269 Button(action: action) {270 HStack(spacing: 5) {271 if selected { Image(systemName: "checkmark").font(.caption2.weight(.bold)) }272 Text(title).font(.footnote.weight(.medium))273 }274 .foregroundStyle(selected ? QColor.textPrimary : QColor.textSecondary)275 .padding(.horizontal, 12)276 .frame(minHeight: 36)277 .background(selected ? QColor.surfaceRaised : Color.clear, in: Capsule())278 .overlay(Capsule().strokeBorder(selected ? QColor.violet : QColor.stroke, lineWidth: 1))279 .contentShape(Capsule())280 }281 .buttonStyle(.qPressable)282 .qHaptic(.selection, trigger: selected)283 .accessibilityAddTraits(selected ? [.isSelected] : [])284 }285286 // MARK: Run and progress287288 @ViewBuilder var runSection: some View {289 QListSection(footnote: session.isRunning ? "Keep the app open. Cancellation takes effect between two samples, so a slow signature finishes first." : nil,290 separatorInset: QMetric.padding) {291 if session.isRunning {292 VStack(alignment: .leading, spacing: QSpace.s) {293 HStack(alignment: .firstTextBaseline) {294 Text("\(session.completed) of \(session.total)")295 .font(Font.system(.title3, design: .rounded, weight: .semibold).monospacedDigit())296 .foregroundStyle(QColor.textPrimary)297 .qNumericTransition()298 Spacer()299 StatusDot(thermalTone(session.thermalNow), label: "Thermal state: \(session.thermalNow)")300 }301 ProgressView(value: Double(session.completed), total: Double(max(1, session.total)))302 .tint(QColor.violet)303 Text(session.currentName ?? "Preparing")304 .font(QFont.mono)305 .foregroundStyle(QColor.textSecondary)306 .lineLimit(1)307 }308 .padding(.vertical, QSpace.m)309 .accessibilityElement(children: .combine)310 Button(role: .cancel) {311 session.cancel()312 } label: {313 Label("Cancel", systemImage: "stop.fill").font(.body.weight(.medium)).foregroundStyle(QColor.negative)314 .frame(minHeight: QMetric.minTap)315 }316 .buttonStyle(.qRow)317 } else {318 Button {319 session.start()320 } label: {321 Label(session.results.isEmpty ? "Run benchmarks" : "Run again", systemImage: "play.fill")322 .font(.body.weight(.semibold))323 .foregroundStyle(QColor.violet)324 .frame(minHeight: QMetric.minTap)325 }326 .buttonStyle(.qRow)327 .disabled(session.selection.isEmpty)328 switch session.state {329 case .cancelled:330 SecTextRow(text: "Cancelled. The results below are partial and no report was produced.", systemImage: "stop.circle", tone: .warning)331 case .failed(let message):332 SecTextRow(text: "The run stopped: \(message)", systemImage: "xmark.octagon", tone: .critical)333 case .finished:334 if let report = session.report {335 SecTextRow(text: "Completed \(report.results.count) benchmarks in \(BenchmarkFormat.duration(report.wallTime)).",336 systemImage: "checkmark.circle", tone: .positive)337 }338 default:339 EmptyView()340 }341 }342 }343 .id("run")344 }345346 func thermalTone(_ state: String) -> QTone {347 switch state {348 case "nominal": return .positive349 case "fair": return .info350 case "serious": return .warning351 case "critical": return .critical352 default: return .neutral353 }354 }355356 // MARK: Results357358 @ViewBuilder var resultSections: some View {359 if session.results.isEmpty, !session.isRunning, session.state == .idle {360 EmptyStateView(systemImage: "gauge.with.needle", title: "No measurement yet",361 message: "Run the suite to time the engine on this device. Nothing is shown until it has been measured here.")362 }363 ForEach(BenchmarkFamily.allCases) { family in364 let rows = session.results.filter { $0.family == family }365 if !rows.isEmpty {366 QListSection(family.title, separatorInset: QMetric.padding) {367 ForEach(rows) { row in368 BenchmarkResultRow(result: row)369 }370 }371 .id("results-\(family.rawValue)")372 }373 }374 }375376 var failureSection: some View {377 QListSection("Failures", separatorInset: QMetric.padding) {378 ForEach(session.failures) { failure in379 VStack(alignment: .leading, spacing: 4) {380 Label(failure.displayName, systemImage: "xmark.octagon").font(QFont.callout).foregroundStyle(QColor.negative)381 Text(failure.message).font(QFont.mono).foregroundStyle(QColor.textSecondary)382 }383 .fixedSize(horizontal: false, vertical: true)384 .frame(maxWidth: .infinity, alignment: .leading)385 .padding(.vertical, QSpace.m)386 }387 }388 }389390 // MARK: Environment, energy, export391392 var environmentSection: some View {393 let e = session.report?.environment ?? session.environment394 return QListSection("Environment",395 footnote: "Low Power Mode and a raised thermal state slow the processor down: compare runs taken in the same conditions.",396 separatorInset: QMetric.padding) {397 SecFactRow(label: "Device", value: e.deviceModel)398 if !e.cpuBrand.isEmpty { SecFactRow(label: "Processor", value: e.cpuBrand) }399 SecFactRow(label: "Cores", value: coresText(e))400 SecFactRow(label: "Memory", value: String(format: "%.0f GiB", Double(e.memoryBytes) / 1_073_741_824))401 SecFactRow(label: "System", value: "\(e.osName) \(e.osVersion)")402 SecFactRow(label: "Build configuration", value: e.buildConfiguration)403 SecFactRow(label: "Engine version", value: e.engineVersion)404 if let report = session.report {405 SecFactRow(label: "Suite", value: report.configuration.name)406 SecFactRow(label: "Thermal state, start → end", value: report.thermalTransition)407 SecFactRow(label: "Low Power Mode, start → end", value: "\(report.powerAtStart.lowPowerMode ? "on" : "off") → \(report.powerAtEnd.lowPowerMode ? "on" : "off")")408 SecFactRow(label: "Wall-clock time", value: BenchmarkFormat.duration(report.wallTime))409 SecFactRow(label: "CPU time", value: BenchmarkFormat.duration(report.cpuTime))410 } else if let start = session.powerAtStart {411 SecFactRow(label: "Thermal state, start → now", value: "\(start.thermalState) → \(session.thermalNow)")412 SecFactRow(label: "Low Power Mode at start", value: start.lowPowerMode ? "on" : "off")413 } else {414 SecFactRow(label: "Thermal state now", value: session.thermalNow)415 }416 }417 .id("environment")418 }419420 func coresText(_ e: BenchmarkEnvironment) -> String {421 if let p = e.performanceCores, let eff = e.efficiencyCores { return "\(e.physicalCores) (\(p) performance + \(eff) efficiency)" }422 return "\(e.physicalCores)"423 }424425 var energySection: some View {426 QListSection("Energy", separatorInset: QMetric.padding) {427 SecTextRow(text: "Energy is not measured. iOS gives an application no per-process energy counter, so the report contains no joule and no watt. CPU time, thermal state and Low Power Mode are recorded as indirect indications.",428 systemImage: "bolt.slash")429 }430 .id("energy")431 }432433 var exportSection: some View {434 QListSection("Export", footnote: "The report holds timings and the device description above. It contains no key, no address and no wallet data.") {435 if let url = session.markdownFile {436 ShareLink(item: url) {437 SecRowLabel(title: "Share the Markdown report", subtitle: url.lastPathComponent, systemImage: "doc.richtext", tint: QColor.violet)438 }439 .buttonStyle(.qRow)440 }441 if let url = session.jsonFile {442 ShareLink(item: url) {443 SecRowLabel(title: "Share the JSON report", subtitle: url.lastPathComponent, systemImage: "curlybraces", tint: QColor.violet)444 }445 .buttonStyle(.qRow)446 }447 if session.markdownFile == nil, session.jsonFile == nil {448 UnavailableDataView(reason: "The report files could not be written to temporary storage.", title: "Export unavailable", compact: true)449 .padding(.vertical, QSpace.m)450 }451 }452 .id("export")453 }454}455456/// One result: name and headline figure, then median, 95th percentile and iterations, then sizes.457struct BenchmarkResultRow: View {458 let result: BenchmarkResult459 @Environment(\.dynamicTypeSize) private var typeSize460461 var statistics: String {462 "median \(BenchmarkFormat.duration(result.statistics.median)) · p95 \(BenchmarkFormat.duration(result.statistics.p95)) · \(result.iterations.formatted()) iterations"463 }464465 var sizes: String? {466 guard let s = result.sizes else { return nil }467 var parts = [String]()468 if let v = s.publicKey { parts.append("public key \(v) B") }469 if let v = s.privateKey { parts.append("private key \(v) B") }470 if let v = s.output { parts.append("\(s.outputLabel ?? "output") \(v) B") }471 return parts.isEmpty ? nil : parts.joined(separator: " · ")472 }473474 var headline: some View {475 Text(result.headline)476 .font(Font.system(.body, design: .rounded, weight: .semibold).monospacedDigit())477 .foregroundStyle(QColor.textPrimary)478 .lineLimit(1)479 }480481 var name: some View {482 Text(result.displayName)483 .font(Font.system(.callout, design: .monospaced))484 .foregroundStyle(QColor.textPrimary)485 .fixedSize(horizontal: false, vertical: true)486 }487488 var body: some View {489 VStack(alignment: .leading, spacing: 5) {490 if typeSize.isAccessibilitySize {491 name492 headline493 } else {494 HStack(alignment: .firstTextBaseline, spacing: 10) {495 name496 Spacer(minLength: 8)497 headline.layoutPriority(1)498 }499 }500 Text(statistics).font(QFont.caption.monospacedDigit()).foregroundStyle(QColor.textSecondary)501 if let sizes {502 Text(sizes).font(QFont.caption.monospacedDigit()).foregroundStyle(QColor.textTertiary)503 }504 if !result.warmedUp {505 Text("No warm-up: a single call exceeded the time budget.").font(QFont.caption).foregroundStyle(QColor.warning)506 }507 }508 .frame(maxWidth: .infinity, alignment: .leading)509 .padding(.vertical, QSpace.m)510 .accessibilityElement(children: .ignore)511 .accessibilityLabel("\(result.displayName): \(result.headline). \(statistics)\(sizes.map { ". " + $0 } ?? "")")512 }513}514515/// Wrapping row layout for the family chips.516struct FlowLayout: Layout {517 var spacing: CGFloat = 8518519 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {520 let rows = arrange(width: proposal.width ?? .infinity, subviews: subviews)521 return CGSize(width: proposal.width ?? rows.width, height: rows.height)522 }523524 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {525 let arrangement = arrange(width: bounds.width, subviews: subviews)526 for (index, origin) in arrangement.origins.enumerated() {527 subviews[index].place(at: CGPoint(x: bounds.minX + origin.x, y: bounds.minY + origin.y), proposal: .unspecified)528 }529 }530531 func arrange(width: CGFloat, subviews: Subviews) -> (origins: [CGPoint], width: CGFloat, height: CGFloat) {532 var origins = [CGPoint]()533 var x: CGFloat = 0, y: CGFloat = 0, rowHeight: CGFloat = 0, maxWidth: CGFloat = 0534 for subview in subviews {535 let size = subview.sizeThatFits(.unspecified)536 if x > 0, x + size.width > width {537 x = 0538 y += rowHeight + spacing539 rowHeight = 0540 }541 origins.append(CGPoint(x: x, y: y))542 x += size.width + spacing543 rowHeight = max(rowHeight, size.height)544 maxWidth = max(maxWidth, x - spacing)545 }546 return (origins, maxWidth, y + rowHeight)547 }548}549