mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-29 10:43:47 +00:00
prevent provider-scoped false zeros
This commit is contained in:
parent
0455250526
commit
e9a55bb2f8
4 changed files with 246 additions and 31 deletions
|
|
@ -41,6 +41,14 @@ struct PayloadCacheKey: Hashable {
|
|||
}
|
||||
}
|
||||
|
||||
private struct ProviderPayloadConsistencyError: Error, CustomStringConvertible {
|
||||
let provider: ProviderFilter
|
||||
|
||||
var description: String {
|
||||
"Fresh \(provider.rawValue) verification still contradicted the matching all-provider payload."
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Observable
|
||||
final class AppStore {
|
||||
|
|
@ -285,7 +293,7 @@ final class AppStore {
|
|||
var payload: MenubarPayload {
|
||||
if effectiveSelectedScope == .combined {
|
||||
let combinedPayload = cache[currentKey]?.payload
|
||||
if let localPayload = cache[localCurrentKey]?.payload {
|
||||
if let localPayload = consistentCachedPayload(for: localCurrentKey) {
|
||||
if let combined = combinedPayload?.combined {
|
||||
return MenubarPayload(
|
||||
generated: combinedPayload?.generated ?? localPayload.generated,
|
||||
|
|
@ -302,7 +310,7 @@ final class AppStore {
|
|||
return combinedPayload
|
||||
}
|
||||
}
|
||||
return cache[currentKey]?.payload ?? selectionFallbackPayload ?? .empty
|
||||
return consistentCachedPayload(for: currentKey) ?? selectionFallbackPayload ?? .empty
|
||||
}
|
||||
|
||||
/// Today (across all providers) backs day-specific views in the popover.
|
||||
|
|
@ -446,7 +454,10 @@ final class AppStore {
|
|||
if effectiveSelectedScope == .combined {
|
||||
requiredKeys.insert(localCurrentKey)
|
||||
}
|
||||
return requiredKeys.contains { cache[$0]?.isFresh != true } || hasStaleLoading
|
||||
return requiredKeys.contains { key in
|
||||
guard let cached = cache[key], cached.isFresh else { return true }
|
||||
return providerPayloadContradictsAll(cached.payload, for: key)
|
||||
} || hasStaleLoading
|
||||
}
|
||||
|
||||
/// True if any cached payload reports at least one provider. Used to keep the
|
||||
|
|
@ -478,6 +489,26 @@ final class AppStore {
|
|||
cache[PayloadCacheKey(scope: scope, period: period, provider: provider, day: day, days: days, claudeConfigSourceId: claudeConfigSourceId)]?.payload
|
||||
}
|
||||
|
||||
func providerPayloadContradictsAllForTesting(_ payload: MenubarPayload,
|
||||
scope: MenubarScope = .local,
|
||||
period: Period,
|
||||
provider: ProviderFilter,
|
||||
day: String? = nil,
|
||||
days: Set<String> = [],
|
||||
claudeConfigSourceId: String? = nil) -> Bool {
|
||||
providerPayloadContradictsAll(
|
||||
payload,
|
||||
for: PayloadCacheKey(
|
||||
scope: scope,
|
||||
period: period,
|
||||
provider: provider,
|
||||
day: day,
|
||||
days: days,
|
||||
claudeConfigSourceId: claudeConfigSourceId
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
func setLastErrorForTesting(_ error: String,
|
||||
scope: MenubarScope = .local,
|
||||
period: Period,
|
||||
|
|
@ -757,6 +788,80 @@ final class AppStore {
|
|||
}
|
||||
}
|
||||
|
||||
private func consistentCachedPayload(for key: PayloadCacheKey) -> MenubarPayload? {
|
||||
guard let payload = cache[key]?.payload,
|
||||
!providerPayloadContradictsAll(payload, for: key) else { return nil }
|
||||
return payload
|
||||
}
|
||||
|
||||
/// An all-provider payload and its scoped sibling describe the same period,
|
||||
/// day selection, scope, and Claude config. If the all-provider slice has a
|
||||
/// positive contribution for the selected provider, a scoped 0/0 payload is
|
||||
/// stale or incomplete rather than an honest answer. This is the exact
|
||||
/// contract that prevents a provider tab advertising spend and then opening
|
||||
/// onto a fabricated zero.
|
||||
private func providerPayloadContradictsAll(_ payload: MenubarPayload, for key: PayloadCacheKey) -> Bool {
|
||||
guard key.scope == .local,
|
||||
key.provider != .all,
|
||||
payload.current.cost == 0,
|
||||
payload.current.calls == 0 else { return false }
|
||||
|
||||
let allKey = PayloadCacheKey(
|
||||
scope: .local,
|
||||
period: key.period,
|
||||
provider: .all,
|
||||
day: key.day,
|
||||
days: key.days,
|
||||
claudeConfigSourceId: key.claudeConfigSourceId
|
||||
)
|
||||
guard let all = cache[allKey]?.payload else { return false }
|
||||
let providerKeys = Set(key.provider.providerKeys + [key.provider.cliArg])
|
||||
if let detail = all.current.providerDetails.first(where: {
|
||||
providerKeys.contains($0.id.lowercased()) || providerKeys.contains($0.label.lowercased())
|
||||
}) {
|
||||
return detail.cost > 0 || detail.calls > 0
|
||||
}
|
||||
return key.provider.providerKeys.reduce(0.0) { sum, providerKey in
|
||||
sum + (all.current.providers[providerKey] ?? 0)
|
||||
} > 0
|
||||
}
|
||||
|
||||
private func fetchPayload(
|
||||
for key: PayloadCacheKey,
|
||||
includeOptimize: Bool,
|
||||
qualityOfService: QualityOfService
|
||||
) async throws -> MenubarPayload {
|
||||
let fresh = try await DataClient.fetch(
|
||||
period: key.period,
|
||||
day: key.day,
|
||||
days: key.days,
|
||||
provider: key.provider,
|
||||
includeOptimize: includeOptimize,
|
||||
scope: key.scope,
|
||||
claudeConfigSourceId: key.claudeConfigSourceId,
|
||||
qualityOfService: qualityOfService
|
||||
)
|
||||
guard providerPayloadContradictsAll(fresh, for: key) else { return fresh }
|
||||
|
||||
NSLog("CodeBurn: resident %@ payload contradicted its all-provider slice; verifying with a one-shot parse",
|
||||
key.provider.rawValue)
|
||||
let verified = try await DataClient.fetch(
|
||||
period: key.period,
|
||||
day: key.day,
|
||||
days: key.days,
|
||||
provider: key.provider,
|
||||
includeOptimize: includeOptimize,
|
||||
scope: key.scope,
|
||||
claudeConfigSourceId: key.claudeConfigSourceId,
|
||||
bypassResident: true,
|
||||
qualityOfService: qualityOfService
|
||||
)
|
||||
guard !providerPayloadContradictsAll(verified, for: key) else {
|
||||
throw ProviderPayloadConsistencyError(provider: key.provider)
|
||||
}
|
||||
return verified
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func recoverFromStuckLoading() async -> Bool {
|
||||
guard prepareStuckLoadingRecovery() else { return false }
|
||||
|
|
@ -849,7 +954,10 @@ final class AppStore {
|
|||
let cacheDateAtStart = cacheDate
|
||||
let generationAtStart = payloadRefreshGeneration
|
||||
if Task.isCancelled { return false }
|
||||
if !force, cache[key]?.isFresh == true { return true }
|
||||
if !force,
|
||||
let cached = cache[key],
|
||||
cached.isFresh,
|
||||
!providerPayloadContradictsAll(cached.payload, for: key) { return true }
|
||||
if inFlightKeys[key] != nil { return false }
|
||||
inFlightKeys[key] = Date()
|
||||
attemptedKeys.insert(key)
|
||||
|
|
@ -881,14 +989,9 @@ final class AppStore {
|
|||
}
|
||||
var succeeded = false
|
||||
do {
|
||||
let fresh = try await DataClient.fetch(
|
||||
period: key.period,
|
||||
day: key.day,
|
||||
days: key.days,
|
||||
provider: key.provider,
|
||||
let fresh = try await fetchPayload(
|
||||
for: key,
|
||||
includeOptimize: includeOptimize,
|
||||
scope: key.scope,
|
||||
claudeConfigSourceId: key.claudeConfigSourceId,
|
||||
qualityOfService: qualityOfService
|
||||
)
|
||||
if generationAtStart != payloadRefreshGeneration {
|
||||
|
|
@ -925,14 +1028,9 @@ final class AppStore {
|
|||
NSLog("CodeBurn: fetch failed for \(key.label)/\(key.provider.rawValue): \(error)")
|
||||
if includeOptimize, cache[key] == nil {
|
||||
do {
|
||||
let fallback = try await DataClient.fetch(
|
||||
period: key.period,
|
||||
day: key.day,
|
||||
days: key.days,
|
||||
provider: key.provider,
|
||||
let fallback = try await fetchPayload(
|
||||
for: key,
|
||||
includeOptimize: false,
|
||||
scope: key.scope,
|
||||
claudeConfigSourceId: key.claudeConfigSourceId,
|
||||
qualityOfService: qualityOfService
|
||||
)
|
||||
guard !Task.isCancelled else { return false }
|
||||
|
|
@ -1003,7 +1101,10 @@ final class AppStore {
|
|||
qualityOfService: QualityOfService = .userInitiated
|
||||
) async -> Bool {
|
||||
invalidateStaleDayCache()
|
||||
if !force, cache[key]?.isFresh == true { return true }
|
||||
if !force,
|
||||
let cached = cache[key],
|
||||
cached.isFresh,
|
||||
!providerPayloadContradictsAll(cached.payload, for: key) { return true }
|
||||
if inFlightKeys[key] != nil { return false }
|
||||
inFlightKeys[key] = Date()
|
||||
attemptedKeys.insert(key)
|
||||
|
|
@ -1016,14 +1117,9 @@ final class AppStore {
|
|||
inFlightKeys[key] = nil
|
||||
}
|
||||
do {
|
||||
let fresh = try await DataClient.fetch(
|
||||
period: key.period,
|
||||
day: key.day,
|
||||
days: key.days,
|
||||
provider: key.provider,
|
||||
let fresh = try await fetchPayload(
|
||||
for: key,
|
||||
includeOptimize: includeOptimize,
|
||||
scope: key.scope,
|
||||
claudeConfigSourceId: key.claudeConfigSourceId,
|
||||
qualityOfService: qualityOfService
|
||||
)
|
||||
if generationAtStart != payloadRefreshGeneration {
|
||||
|
|
|
|||
|
|
@ -54,6 +54,7 @@ struct DataClient {
|
|||
includeOptimize: Bool,
|
||||
scope: MenubarScope = .local,
|
||||
claudeConfigSourceId: String? = nil,
|
||||
bypassResident: Bool = false,
|
||||
qualityOfService: QualityOfService = .userInitiated) async throws -> MenubarPayload {
|
||||
let subcommand = statusSubcommand(
|
||||
period: period,
|
||||
|
|
@ -64,7 +65,11 @@ struct DataClient {
|
|||
scope: scope,
|
||||
claudeConfigSourceId: claudeConfigSourceId
|
||||
)
|
||||
let result = try await runCLI(subcommand: subcommand, qualityOfService: qualityOfService)
|
||||
let result = try await runCLI(
|
||||
subcommand: subcommand,
|
||||
bypassResident: bypassResident,
|
||||
qualityOfService: qualityOfService
|
||||
)
|
||||
guard result.exitCode == 0 else {
|
||||
throw DataClientError.nonZeroExit(code: result.exitCode, stderr: result.stderr)
|
||||
}
|
||||
|
|
@ -133,10 +138,12 @@ struct DataClient {
|
|||
|
||||
private static func runCLI(
|
||||
subcommand: [String],
|
||||
bypassResident: Bool = false,
|
||||
qualityOfService: QualityOfService = .userInitiated
|
||||
) async throws -> ProcessResult {
|
||||
try await runCLI(
|
||||
subcommand: subcommand,
|
||||
bypassResident: bypassResident,
|
||||
serveRequest: { args in
|
||||
try await ServeConnection.shared.request(args: args)
|
||||
},
|
||||
|
|
@ -164,6 +171,7 @@ struct DataClient {
|
|||
/// the shared resident and globally limited one-shot closures above.
|
||||
static func runCLI(
|
||||
subcommand: [String],
|
||||
bypassResident: Bool = false,
|
||||
serveRequest: ([String]) async throws -> Data,
|
||||
spawnFallback: () async throws -> ProcessResult
|
||||
) async throws -> ProcessResult {
|
||||
|
|
@ -172,7 +180,7 @@ struct DataClient {
|
|||
// Transport/protocol failures fall back to the spawn path below, so
|
||||
// the resident remains an optimization. Resource-policy failures stay
|
||||
// terminal and cannot bypass the resident output ceiling.
|
||||
if ServeConnection.isEligible(subcommand) {
|
||||
if !bypassResident, ServeConnection.isEligible(subcommand) {
|
||||
do {
|
||||
let stdout = try await serveRequest(subcommand)
|
||||
return ProcessResult(stdout: stdout, stderr: "", exitCode: 0)
|
||||
|
|
|
|||
|
|
@ -46,6 +46,10 @@ private func claudeConfigSelector(selectedId: String? = nil) -> ClaudeConfigSele
|
|||
}
|
||||
|
||||
private func menubarPayload(cost: Double,
|
||||
calls: Int = 1,
|
||||
sessions: Int = 1,
|
||||
providers: [String: Double]? = nil,
|
||||
providerDetails: [ProviderDetail] = [],
|
||||
combined: CombinedUsage? = nil,
|
||||
claudeConfigs: ClaudeConfigSelector? = nil) -> MenubarPayload {
|
||||
MenubarPayload(
|
||||
|
|
@ -53,8 +57,8 @@ private func menubarPayload(cost: Double,
|
|||
current: CurrentBlock(
|
||||
label: "Today",
|
||||
cost: cost,
|
||||
calls: 1,
|
||||
sessions: 1,
|
||||
calls: calls,
|
||||
sessions: sessions,
|
||||
oneShotRate: nil,
|
||||
inputTokens: 1,
|
||||
outputTokens: 1,
|
||||
|
|
@ -63,7 +67,8 @@ private func menubarPayload(cost: Double,
|
|||
topActivities: [],
|
||||
topModels: [],
|
||||
localModelSavings: LocalModelSavings(totalUSD: 0, calls: 0, byModel: [], byProvider: []),
|
||||
providers: ["claude": cost],
|
||||
providers: providers ?? ["claude": cost],
|
||||
providerDetails: providerDetails,
|
||||
topProjects: [],
|
||||
modelEfficiency: [],
|
||||
topSessions: [],
|
||||
|
|
@ -84,6 +89,89 @@ private func menubarPayload(cost: Double,
|
|||
@Suite("AppStore refresh recovery")
|
||||
@MainActor
|
||||
struct AppStoreRefreshRecoveryTests {
|
||||
@Test("an active all-provider slice rejects a contradictory scoped zero")
|
||||
func activeAllProviderSliceRejectsScopedZero() {
|
||||
let store = AppStore()
|
||||
let all = menubarPayload(
|
||||
cost: 12,
|
||||
providers: ["claude": 11.5, "hermes agent": 0.5],
|
||||
providerDetails: [
|
||||
ProviderDetail(id: "claude", label: "Claude", cost: 11.5, calls: 4, hasUsage: true),
|
||||
ProviderDetail(id: "hermes", label: "Hermes Agent", cost: 0.5, calls: 7, hasUsage: true),
|
||||
]
|
||||
)
|
||||
let falseZero = menubarPayload(
|
||||
cost: 0,
|
||||
calls: 0,
|
||||
sessions: 0,
|
||||
providers: ["hermes agent": 0],
|
||||
providerDetails: [
|
||||
ProviderDetail(id: "hermes", label: "Hermes Agent", cost: 0, calls: 0, hasUsage: false),
|
||||
]
|
||||
)
|
||||
|
||||
store.setCachedPayloadForTesting(all, period: .today, provider: .all, fetchedAt: Date())
|
||||
store.suppressRefreshesForTesting()
|
||||
store.switchTo(provider: .hermes)
|
||||
store.setCachedPayloadForTesting(falseZero, period: .today, provider: .hermes, fetchedAt: Date())
|
||||
|
||||
#expect(store.providerPayloadContradictsAllForTesting(falseZero, period: .today, provider: .hermes))
|
||||
#expect(store.payload.current.cost == 12)
|
||||
#expect(store.needsInteractivePayloadRefresh)
|
||||
}
|
||||
|
||||
@Test("flat-rate activity rejects a contradictory scoped zero")
|
||||
func flatRateActivityRejectsScopedZero() {
|
||||
let store = AppStore()
|
||||
let all = menubarPayload(
|
||||
cost: 12,
|
||||
providers: ["claude": 12, "hermes agent": 0],
|
||||
providerDetails: [
|
||||
ProviderDetail(id: "claude", label: "Claude", cost: 12, calls: 4, hasUsage: true),
|
||||
ProviderDetail(id: "hermes", label: "Hermes Agent", cost: 0, calls: 7, hasUsage: true),
|
||||
]
|
||||
)
|
||||
let falseZero = menubarPayload(
|
||||
cost: 0,
|
||||
calls: 0,
|
||||
sessions: 0,
|
||||
providers: ["hermes agent": 0],
|
||||
providerDetails: [
|
||||
ProviderDetail(id: "hermes", label: "Hermes Agent", cost: 0, calls: 0, hasUsage: false),
|
||||
]
|
||||
)
|
||||
|
||||
store.setCachedPayloadForTesting(all, period: .today, provider: .all, fetchedAt: Date())
|
||||
|
||||
#expect(store.providerPayloadContradictsAllForTesting(falseZero, period: .today, provider: .hermes))
|
||||
}
|
||||
|
||||
@Test("a genuine provider zero remains valid when the all-provider slice is also zero")
|
||||
func genuineProviderZeroRemainsValid() {
|
||||
let store = AppStore()
|
||||
let all = menubarPayload(
|
||||
cost: 12,
|
||||
providers: ["claude": 12, "hermes agent": 0],
|
||||
providerDetails: [
|
||||
ProviderDetail(id: "claude", label: "Claude", cost: 12, calls: 4, hasUsage: true),
|
||||
ProviderDetail(id: "hermes", label: "Hermes Agent", cost: 0, calls: 0, hasUsage: false),
|
||||
]
|
||||
)
|
||||
let zero = menubarPayload(
|
||||
cost: 0,
|
||||
calls: 0,
|
||||
sessions: 0,
|
||||
providers: ["hermes agent": 0],
|
||||
providerDetails: [
|
||||
ProviderDetail(id: "hermes", label: "Hermes Agent", cost: 0, calls: 0, hasUsage: false),
|
||||
]
|
||||
)
|
||||
|
||||
store.setCachedPayloadForTesting(all, period: .today, provider: .all, fetchedAt: Date())
|
||||
|
||||
#expect(!store.providerPayloadContradictsAllForTesting(zero, period: .today, provider: .hermes))
|
||||
}
|
||||
|
||||
@Test("provider switches retain the last rendered payload until the target loads")
|
||||
func providerSwitchRetainsLastRenderedPayload() {
|
||||
let store = AppStore()
|
||||
|
|
|
|||
|
|
@ -1057,6 +1057,29 @@ struct ServeConnectionTests {
|
|||
#expect(await fallback.snapshot() == 1)
|
||||
}
|
||||
|
||||
@Test("a verified-fresh request can bypass the resident worker")
|
||||
func verifiedFreshRequestBypassesResident() async throws {
|
||||
let resident = FallbackRecorder()
|
||||
let fallback = FallbackRecorder()
|
||||
|
||||
let result = try await DataClient.runCLI(
|
||||
subcommand: ["status", "--format", "menubar-json", "--provider", "hermes"],
|
||||
bypassResident: true,
|
||||
serveRequest: { _ in
|
||||
await resident.record()
|
||||
return Data("stale".utf8)
|
||||
},
|
||||
spawnFallback: {
|
||||
await fallback.record()
|
||||
return DataClient.ProcessResult(stdout: Data("fresh".utf8), stderr: "", exitCode: 0)
|
||||
}
|
||||
)
|
||||
|
||||
#expect(String(decoding: result.stdout, as: UTF8.self) == "fresh")
|
||||
#expect(await resident.snapshot() == 0)
|
||||
#expect(await fallback.snapshot() == 1)
|
||||
}
|
||||
|
||||
@Test("the first real request is the only cold-start query")
|
||||
func firstRequestIsTheWarmup() async throws {
|
||||
let dir = NSTemporaryDirectory() + "serve-connection-test-" + UUID().uuidString
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue