SPB Git

Repository Public License

BudgetAndCancellationTests.swift 14.0 KB 269 lines swift

1import Foundation2import NavigatorCore3import ProviderKit4import Testing5@testable import AgentRuntime67/// Every limit ends the run with `budgetExhausted` and a reason that names it.8@Suite struct BudgetTests {9    @Test func stepLimit() async {10        let h = await Harness.make([], steps: 3, fallback: .tools([call(.inspect)]))11        let (result, events) = await h.run()12        #expect(result.run.status == .budgetExhausted)13        #expect(result.reason.contains("step limit of 3"))14        #expect(result.usage.stepsUsed == 3)15        #expect(events.toolSteps.count == 3)16        #expect(h.provider.requests.count == 3)17        #expect(result.run.budget.maxSteps == 3)18    }1920    @Test func stepLimitInsideOneModelTurn() async {21        // Five calls in one answer cannot buy more than the steps that are left.22        let h = await Harness.make([.tools((0..<5).map { _ in call(.inspect) })], steps: 3)23        let (result, events) = await h.run()24        #expect(result.run.status == .budgetExhausted)25        #expect(events.toolSteps.count == 3)26        #expect(await h.host.calls.filter { $0 == "outline" }.count == 3)27    }2829    @Test func wallClockLimitWhileTheModelIsSilent() async throws {30        let h = await Harness.make([.hang])31        await h.session.start()32        try await eventually("request in flight and watchdog armed") { h.provider.requests.count == 1 && h.clock.sleeperCount == 1 }33        h.clock.advance(by: 299)34        try await Task.sleep(for: .milliseconds(30))35        #expect(await !h.session.isFinished)36        h.clock.advance(by: 2)37        let (result, events) = await h.finish()38        #expect(result.run.status == .budgetExhausted)39        #expect(result.reason.contains("time limit of 300 s"))40        #expect(events.finished?.run.status == .budgetExhausted)41        try await eventually("provider stream cancelled") { h.provider.cancellations == 1 }42    }4344    @Test func wallClockLimitBetweenSteps() async {45        let clock = ManualClock()46        let slow = Turn.dynamic { _ in clock.advance(by: 200); return .tools([call(.inspect)]) }47        let h = await Harness.make([slow, slow, slow], clock: clock)48        let (result, _) = await h.run()49        #expect(result.run.status == .budgetExhausted)50        #expect(result.reason.contains("time limit"))51        #expect(h.provider.requests.count == 2)52        #expect(result.usage.elapsedSeconds >= 300)53    }5455    @Test func wallClockLimitWhileWaitingForConfirmation() async throws {56        let host = FakeHost()57        await host.setPage(Harness.start, ConfirmationTests.shopPage)58        let delegate = ScriptedDelegate(.hang)59        let h = await Harness.make([.tools([call(.click, ["ref": "buy"])])], delegate: delegate, host: host)60        await h.session.start()61        try await eventually("confirmation shown") { delegate.requests.count == 1 }62        h.clock.advance(by: 301)63        let (result, events) = await h.finish()64        #expect(result.run.status == .budgetExhausted)65        #expect(events.contains(.confirmationResolved(id: 1, decision: .cancelled)))66        #expect(await !h.host.called("click"))67    }6869    @Test func tokenBudgetFromReportedUsage() async {70        let heavy = ProviderUsage(inputTokens: 60_000, outputTokens: 1_000)71        let h = await Harness.make([.tools([call(.inspect)], usage: heavy), .tools([call(.inspect)], usage: heavy), .tools([call(.inspect)], usage: heavy)],72                                   limits: { $0.budget.maxTokens = 100_000 })73        let (result, _) = await h.run()74        #expect(result.run.status == .budgetExhausted)75        #expect(result.reason.contains("token budget of 100000"))76        #expect(h.provider.requests.count == 2)77        #expect(result.usage.usage.inputTokens + result.usage.usage.outputTokens == 122_000)78        #expect(await h.host.calls.filter { $0 == "outline" }.count == 1)       // the second turn's call was not executed79    }8081    @Test func tokenBudgetWhenUsageIsUnknown() async {82        let host = FakeHost()83        await host.setPage(Harness.start, .text(String(repeating: "many words on this page ", count: 400)))84        let h = await Harness.make([], limits: { $0.budget.maxTokens = 12_000 }, fallback: .tools([call(.read)], usage: nil), host: host)85        let (result, _) = await h.run()86        #expect(result.run.status == .budgetExhausted)87        #expect(result.reason.contains("token budget of 12000"))88        #expect(result.usage.tokensAreEstimated)89    }9091    @Test func aRequestThatCannotFitIsNotSent() async {92        let h = await Harness.make([.tools([call(.read)])], limits: { $0.budget.maxTokens = 50 })93        let (result, _) = await h.run()94        #expect(result.run.status == .budgetExhausted)95        #expect(result.reason.contains("cannot cover the next request"))96        #expect(h.provider.requests.isEmpty)97    }9899    @Test func costLimit() async {100        let h = await Harness.make([.tools([call(.inspect)]), .tools([call(.inspect)]), .tools([call(.inspect)])],101                                   limits: { $0.budget.maxCostUSD = 0.15 }, price: ModelPrice(inputPerMillion: 1_000, outputPerMillion: 1_000))102        let (result, _) = await h.run()                                         // 110 tokens × $1000/M = $0.11 per turn103        #expect(result.run.status == .budgetExhausted)104        #expect(result.reason.contains("cost limit of $0.15"))105        #expect(h.provider.requests.count == 2)106        #expect(abs((result.usage.usage.estimatedCostUSD ?? 0) - 0.22) < 0.0001)107    }108109    @Test func costLimitUsesTheCostTheProviderReports() async {110        let reported = ProviderUsage(inputTokens: 10, outputTokens: 10, reportedCostUSD: 0.6)111        let h = await Harness.make([.tools([call(.inspect)], usage: reported), .tools([call(.inspect)], usage: reported)], limits: { $0.budget.maxCostUSD = 1 })112        let (result, _) = await h.run()113        #expect(result.run.status == .budgetExhausted)114        #expect(result.usage.costIsKnown)115    }116117    @Test func tabLimit() async {118        let h = await Harness.make([.tools([call(.createTab), call(.createTab, ["url": "https://example.com/a"]), call(.createTab)])], limits: { $0.maxTabsCreated = 2 })119        let (result, _) = await h.run()120        #expect(result.run.status == .budgetExhausted)121        #expect(result.reason.contains("limit of 2 tabs"))122        #expect(await h.host.calls.filter { $0.hasPrefix("createTab") }.count == 2)123    }124125    @Test func downloadCountLimit() async {126        let delegate = ScriptedDelegate(.approve)127        let h = await Harness.make([.tools([call(.download, ["url": "https://example.com/a.pdf"]), call(.download, ["url": "https://example.com/b.pdf"])])],128                                   delegate: delegate, limits: { $0.maxDownloads = 1 })129        let (result, _) = await h.run()130        #expect(result.run.status == .budgetExhausted)131        #expect(result.reason.contains("limit of 1 download"))132        #expect(await h.host.calls.filter { $0.hasPrefix("download") }.count == 1)133    }134135    @Test func downloadSizeLimitFromTheAnnouncedSize() async {136        let delegate = ScriptedDelegate(.approve)137        let h = await Harness.make([.tools([call(.download, ["url": "https://example.com/big.zip"])])], delegate: delegate, limits: { $0.maxDownloadBytes = 1_000 })138        await h.host.setProbe("https://example.com/big.zip", AgentDownloadProbe(url: url("https://example.com/big.zip"), filename: "big.zip", expectedBytes: 5_000))139        let (result, _) = await h.run()140        #expect(result.run.status == .budgetExhausted)141        #expect(result.reason.contains("download size limit of 1000 bytes"))142        #expect(delegate.requests.isEmpty)143        #expect(await !h.host.called("download "))144    }145146    @Test func downloadSizeLimitWhenTheSizeWasNotAnnounced() async {147        let delegate = ScriptedDelegate(.approve)148        let h = await Harness.make([.tools([call(.download, ["url": "https://example.com/stream.bin2"])])], delegate: delegate, limits: { $0.maxDownloadBytes = 1_000 })149        await h.host.setProbe("https://example.com/stream.bin2", AgentDownloadProbe(url: url("https://example.com/stream.bin2"), filename: "stream.dat"))150        await h.host.setDownloadedBytes(4_096)151        let (result, _) = await h.run()152        #expect(result.run.status == .budgetExhausted)153        #expect(result.reason.contains("exceeded the download size limit"))154        #expect(delegate.requests.first?.data.contains { $0.value.contains("unknown (stopped at 1000 bytes)") } == true)155    }156157    @Test func hostReportingTooLargeEndsTheRun() async {158        let delegate = ScriptedDelegate(.approve)159        let h = await Harness.make([.tools([call(.download, ["url": "https://example.com/a.pdf"])])], delegate: delegate)160        await h.host.setFailure("download", .downloadTooLarge)161        let (result, _) = await h.run()162        #expect(result.run.status == .budgetExhausted)163    }164165    @Test func theBudgetStoredWithTheRunIsTheUsersBudget() async {166        let h = await Harness.make([.finish("Nothing.")], steps: 7, limits: { $0.maxAnswerRevisions = 0 })167        let (result, _) = await h.run()168        #expect(result.run.budget == AgentBudget(maxSteps: 7, maxDurationSeconds: 300, maxTokens: 200_000, maxCostUSD: 1, allowedDomains: ["example.com"]))169        #expect(h.session.configuration.limits.budget == result.run.budget)170    }171}172173/// "Stop" at every phase: the run ends as cancelled at once, whatever was pending is cancelled.174@Suite struct CancellationTests {175    @Test func beforeStart() async {176        let h = await Harness.make([.finish("x")])177        await h.session.stop()178        await h.session.start()                         // does nothing after a stop179        let (result, events) = await h.finish()180        #expect(result.run.status == .cancelled)181        #expect(h.provider.requests.isEmpty)182        #expect(events.finished?.reason == "Stopped by the user.")183    }184185    @Test func whileTheModelIsStreaming() async throws {186        let sink = RecordingSink()187        let h = await Harness.make([.tools([call(.read)]), .hang], sink: sink)188        await h.session.start()189        try await eventually("second request") { h.provider.requests.count == 2 }190        let before = Date()191        await h.session.stop()192        #expect(Date().timeIntervalSince(before) < 1)193        #expect(await h.session.isFinished)             // finished when stop() returns194        let (result, events) = await h.finish()195        #expect(result.run.status == .cancelled)196        #expect(events.finished != nil)197        try await eventually("provider stream cancelled") { h.provider.cancellations == 1 }198        #expect(await sink.saves.last?.status == .cancelled)199        #expect(result.run.steps.last?.kind == .error && result.run.steps.last?.status == .cancelled)200        #expect(result.run.citations.count == 1)201    }202203    @Test func whileAToolIsRunning() async throws {204        let h = await Harness.make([.tools([call(.navigate, ["url": "https://example.com/slow"])])])205        await h.host.hang(on: "navigate")206        await h.session.start()207        try await eventually("navigation started") { await h.host.called("navigate") }208        await h.session.stop()209        let (result, events) = await h.finish()210        #expect(result.run.status == .cancelled)211        #expect(events.toolSteps.first?.status == .cancelled)212        try await eventually("host call cancelled") { await h.host.sawCancellation }213        #expect(h.provider.requests.count == 1)         // no further model call214    }215216    @Test func whileWaitingForConfirmation() async throws {217        let host = FakeHost()218        await host.setPage(Harness.start, ConfirmationTests.shopPage)219        let delegate = ScriptedDelegate(.hang)220        let sink = RecordingSink()221        let h = await Harness.make([.tools([call(.submitForm, ["ref": "contact"])])], delegate: delegate, sink: sink, host: host)222        await h.session.start()223        try await eventually("confirmation shown") { delegate.requests.count == 1 }224        #expect(await h.session.snapshot.status == .awaitingConfirmation)225        #expect(await sink.saves.last?.status == .awaitingConfirmation)226        await h.session.stop()227        let (result, events) = await h.finish()228        #expect(result.run.status == .cancelled)229        #expect(events.contains(.confirmationResolved(id: 1, decision: .cancelled)))230        #expect(events.steps.first { $0.kind == .confirmation }?.status == .cancelled)231        #expect(await !h.host.called("submitForm"))232        if case .finished = events.last {} else { Issue.record(".finished must be the last event") }233    }234235    @Test func whileWaitingForAHandOff() async throws {236        let host = FakeHost()237        await host.setPage(Harness.start, FakePage(title: "Just a moment...", headings: [AgentHeading(level: 1, text: "Verify you are human")]))238        let delegate = ScriptedDelegate(.approve, handoff: nil)239        let h = await Harness.make([.tools([call(.inspect)])], delegate: delegate, host: host)240        await h.session.start()241        try await eventually("hand-off shown") { delegate.handoffs.count == 1 }242        await h.session.stop()243        let (result, events) = await h.finish()244        #expect(result.run.status == .cancelled)245        #expect(events.contains(.handoffResolved(id: 1, decision: .cancelled)))246    }247248    @Test func afterCompletionAndTwice() async {249        let h = await Harness.make([.tools([call(.read)]), .finish("Paris is the capital of France [1].")])250        let (result, events) = await h.run()251        await h.session.stop()252        await h.session.stop()253        #expect(await h.session.result() == result)254        #expect(result.run.status == .completed)255        #expect(events.filter { if case .finished = $0 { true } else { false } }.count == 1)256    }257258    @Test func nothingIsEmittedAfterFinished() async throws {259        let h = await Harness.make([.tools([call(.navigate, ["url": "https://example.com/slow"])])])260        await h.host.hang(on: "navigate")261        await h.session.start()262        try await eventually("navigation started") { await h.host.called("navigate") }263        await h.session.stop()264        let (_, events) = await h.finish()265        let index = events.firstIndex { if case .finished = $0 { true } else { false } }266        #expect(index == events.count - 1)267    }268}269
Files main
Menu

Theme