SPB Git

Repository Public License

EvalAndPerfTests.swift 8.7 KB 105 lines swift

1import Foundation2import Testing3import PrismAIOrchestrator4import PrismComponentCatalog5import PrismCore6import PrismDataRuntime7import PrismObjectModel8import PrismRenderer9import PrismSecurity10import PrismTestKit11@testable import PrismStudio1213let evalEnabled = liveKey != nil && ProcessInfo.processInfo.environment["PRISM_EVAL"] == "1"1415/// The fixed evaluation set (tests/evals/prompts.json), run against the real API. Opt-in; it costs money.16@MainActor17@Suite(.serialized, .enabled(if: evalEnabled, "Set PRISM_LIVE=1, PRISM_EVAL=1 and ANTHROPIC_API_KEY.")) struct AgentEvaluation {18    @Test func runEvaluationSet() async throws {19        let spec = try JSONValue.parse(Data(contentsOf: testRepoRoot.appendingPathComponent("tests/evals/prompts.json")))20        var cases = spec["prompts"]?.arrayValue ?? []21        if let only = ProcessInfo.processInfo.environment["PRISM_EVAL_ONLY"] { cases = cases.filter { only.split(separator: ",").map(String.init).contains($0["id"]?.stringValue ?? "") } }22        if let limit = ProcessInfo.processInfo.environment["PRISM_EVAL_LIMIT"].flatMap(Int.init) { cases = Array(cases.prefix(limit)) }23        var rows: [JSONValue] = []24        for c in cases {25            let id = c["id"]?.stringValue ?? "?"26            let workspace = BuildWorkspace(registry: Catalog.registry, baseline: c["baseline"] != nil ? try templateBlueprint() : nil)27            var settings = AgentSettings()28            if let model = ProcessInfo.processInfo.environment["PRISM_LIVE_MODEL"] { settings.model = model }29            let client = AnthropicClient(secrets: InMemorySecretStore([SecretAccount.anthropicAPIKey: liveKey ?? ""]))30            let started = Date()31            let outcome = await BuilderAgent(client: client, settings: settings).run(prompt: c["prompt"]?.stringValue ?? "", workspace: workspace)32            let bp = outcome.blueprint33            let types = Set(bp?.componentTypes ?? [])34            var failures: [String] = []35            if outcome.status != .succeeded { failures.append("status \(outcome.status.rawValue)") }36            if outcome.issues.hasErrors { failures.append("\(outcome.issues.errors.count) validation errors") }37            for t in c["requireTypes"]?.arrayValue ?? [] where !types.contains(t.stringValue ?? "") { failures.append("missing \(t.stringValue ?? "")") }38            for group in c["requireAnyType"]?.arrayValue ?? [] where types.isDisjoint(with: Set((group.arrayValue ?? []).compactMap(\.stringValue))) { failures.append("none of \(group.canonicalString())") }39            if let n = c["minTables"]?.intValue, (bp?.tables.count ?? 0) < n { failures.append("fewer than \(n) tables") }40            if let n = c["maxTables"]?.intValue, (bp?.tables.count ?? 0) > n { failures.append("more than \(n) tables") }41            if let n = c["minPages"]?.intValue, (bp?.pages.count ?? 0) < n { failures.append("fewer than \(n) pages") }42            for p in c["requirePermissions"]?.arrayValue ?? [] where bp?.permissions.contains(p.stringValue ?? "") != true { failures.append("missing permission \(p.stringValue ?? "")") }43            for p in c["forbidPermissions"]?.arrayValue ?? [] where bp?.permissions.contains(p.stringValue ?? "") == true { failures.append("forbidden permission \(p.stringValue ?? "")") }44            for w in c["expectNotImplementedMention"]?.arrayValue ?? [] where !outcome.message.lowercased().contains(w.stringValue ?? "") { failures.append("final message does not mention \(w.stringValue ?? "")") }45            if c["keepTables"] == true, let base = workspace.baseline, Set(base.tables.map(\.id)).subtracting(bp?.tables.map(\.id) ?? []).isEmpty == false { failures.append("a table was removed") }46            rows.append([47                "id": .string(id), "passed": .bool(failures.isEmpty), "failures": .array(failures.map(JSONValue.string)), "status": .string(outcome.status.rawValue),48                "validBlueprint": .bool(bp != nil && !outcome.issues.hasErrors), "coverage": .double(outcome.coverage), "toolCalls": .int(outcome.toolCalls), "turns": .int(outcome.turns),49                "tokens": .int(outcome.usage.totalTokens), "outputTokens": .int(outcome.usage.outputTokens), "estimatedCostUSD": outcome.estimatedCostUSD.map(JSONValue.double) ?? .null,50                "seconds": .double((Date().timeIntervalSince(started) * 10).rounded() / 10), "error": outcome.error.map(JSONValue.string) ?? .null, "components": .int(bp?.components.count ?? 0), "model": .string(outcome.model),51            ])52            print("EVAL \(id): \(failures.isEmpty ? "PASS" : "FAIL \(failures)") calls=\(outcome.toolCalls) cost=\(outcome.estimatedCostUSD.map { String(format: "%.3f", $0) } ?? "?") s=\(Int(Date().timeIntervalSince(started)))")53            let dir = testRepoRoot.appendingPathComponent("build/evals")54            try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)55            if let bp { try? bp.prettyData().write(to: dir.appendingPathComponent("\(id).blueprint.json")) }56            try? outcome.message.write(to: dir.appendingPathComponent("\(id).message.txt"), atomically: true, encoding: .utf8)57        }58        let valid = rows.filter { $0["validBlueprint"] == true }.count, passed = rows.filter { $0["passed"] == true }.count59        let summary: JSONValue = ["date": .string(ISO8601DateFormatter().string(from: Date())), "cases": .int(rows.count), "passed": .int(passed), "validBlueprints": .int(valid), "results": .array(rows)]60        let name = ProcessInfo.processInfo.environment["PRISM_EVAL_ONLY"] == nil ? "summary" : "summary-rerun"61        try Data(summary.prettyString().utf8).write(to: testRepoRoot.appendingPathComponent("build/evals/\(name).json"))62        print("EVAL SUMMARY: \(passed)/\(rows.count) passed, \(valid)/\(rows.count) valid blueprints")63        #expect(!rows.isEmpty)64    }65}6667/// Measured numbers for docs/STATUS.md (spec §12: report only what was measured). Opt-in: PRISM_PERF=1.68@MainActor69@Suite(.serialized, .enabled(if: ProcessInfo.processInfo.environment["PRISM_PERF"] == "1", "Set PRISM_PERF=1 to measure.")) struct PerformanceBaseline {70    func time(_ body: () throws -> Void) rethrows -> Double {71        let start = ContinuousClock.now72        try body()73        let d = ContinuousClock.now - start74        return Double(d.components.seconds) * 1000 + Double(d.components.attoseconds) / 1e1575    }7677    @Test func measure() throws {78        var lines: [String] = []79        let bp = try templateBlueprint()80        lines.append(String(format: "catalog search (40 components, 200 queries): %.3f ms per query", time { for _ in 0..<200 { _ = Catalog.registry.search("monthly chart") } } / 200))81        lines.append(String(format: "validate expense tracker blueprint (21 objects): %.2f ms", time { for _ in 0..<50 { _ = BlueprintValidator_validate(bp) } } / 50))82        var csv = "date,description,category,amount\n"83        for i in 0..<10_000 { csv += "2026-\(String(format: "%02d", i % 12 + 1))-15,Item \(i),\(["Food", "Housing", "Fun"][i % 3]),\(i % 100).25\n" }84        let runtime = try AppRuntime(blueprint: bp, store: AppDataStore(url: nil), registry: Catalog.registry)85        let data = Data(csv.utf8)86        lines.append(String(format: "import 10,000-row CSV: %.0f ms", try time { _ = try runtime.store.importCSV(data, into: "transactions") }))87        let table = bp.object("transactions_table")?.props["query"], chart = bp.object("monthly_chart")?.props["query"]88        runtime.setState("search", "Item 1")89        var matched = 090        let tableTime = time { matched = runtime.rows(table).count }91        lines.append(String(format: "table query with a text search over 10,000 rows (uncached, %d rows returned): %.1f ms", matched, tableTime))92        lines.append(String(format: "monthly aggregate over 10,000 rows: %.1f ms", time { _ = runtime.rows(chart) }))93        lines.append(String(format: "same queries again (cached): %.3f ms", time { _ = runtime.rows(table); _ = runtime.rows(chart) }))94        let cold = try time { _ = try AppRuntime(blueprint: bp, store: AppDataStore(url: nil), registry: Catalog.registry) }95        lines.append(String(format: "start a runtime for the expense tracker (in-memory store): %.1f ms", cold))96        let text = (["Measured \(Date().formatted()) on \(ProcessInfo.processInfo.operatingSystemVersionString), debug build, swift test"] + lines).joined(separator: "\n")97        print(text)98        try FileManager.default.createDirectory(at: testRepoRoot.appendingPathComponent("build"), withIntermediateDirectories: true)99        try text.write(to: testRepoRoot.appendingPathComponent("build/performance-baseline.txt"), atomically: true, encoding: .utf8)100    }101}102103import PrismComponentSDK104@MainActor func BlueprintValidator_validate(_ bp: AppBlueprint) -> Int { BlueprintValidator.validate(bp, registry: Catalog.registry).count }105
Files main
Menu

Theme