CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
fix: 修复账户切换和时区变化引发的数据异常
Bob4b1b8699a808
diff --git a/CodexBar/Services/CodexStatus/CodexStatusService.swift b/CodexBar/Services/CodexStatus/CodexStatusService.swiftindex 339e297..31998b9 100644--- a/CodexBar/Services/CodexStatus/CodexStatusService.swift+++ b/CodexBar/Services/CodexStatus/CodexStatusService.swift@@ -57,6 +57,10 @@ private nonisolated struct CachedSupplementalRead<Value> {}}+private nonisolated enum SupplementalReadError: Error {+ case accountChanged+}+/// 只缓存同一账号下的补充数据, 账号变化时整体丢弃避免串号private nonisolated struct SupplementalDataCache {var account: CodexAccount?@@ -347,17 +351,13 @@ actor CodexStatusService {) throws -> CodexQuotaSnapshot {var didRefresh = false- func refreshTokenIfNeeded() throws {- guard !didRefresh else { throw CodexStatusError.authenticationRequired }- didRefresh = true- try Self.refreshAccount(using: connection)- }-func readWithAuthRefresh<Value>(_ read: () throws -> Value) throws -> Value {do {return try read()} catch let error as CodexStatusError where error.isAuthenticationRequired {- try refreshTokenIfNeeded()+ guard !didRefresh else { throw CodexStatusError.authenticationRequired }+ didRefresh = true+ try Self.refreshAccount(using: connection)return try read()}}@@ -366,8 +366,10 @@ actor CodexStatusService {_ request: AppServerRequest<Value>,cache: inout Value?) throws -> CachedSupplementalRead<Value> {+ let account = connection.accountResponse.account// 缓存回退只包住接口读取, 认证刷新失败必须继续上抛- try readWithAuthRefresh {+ return try readWithAuthRefresh {+ guard connection.accountResponse.account == account else { throw SupplementalReadError.accountChanged }do {let value = try Self.read(request, using: connection)cache = value@@ -400,44 +402,49 @@ actor CodexStatusService {trace.account = .skipped}- guard let account = connection.accountResponse.account else {- throw CodexStatusError.notLoggedIn- }- trace.failureStage = .snapshot+ func readSnapshot() throws -> CodexQuotaSnapshot {+ let accountResponse = connection.accountResponse+ guard let account = accountResponse.account else { throw CodexStatusError.notLoggedIn }+ trace.failureStage = .snapshot+ if supplementalDataCache.useAccount(account) {+ AppLog.app.notice("额度缓存已丢弃: reason=accountChanged")+ }- if supplementalDataCache.useAccount(account) {- AppLog.app.notice("额度缓存已丢弃: reason=accountChanged")- }+ let rateLimitsRead = try readSupplemental(AccountRequests.rateLimits, cache: &supplementalDataCache.rateLimits)+ trace.rateLimits = rateLimitsRead.step- let rateLimitsRead = try readSupplemental(- AccountRequests.rateLimits,- cache: &supplementalDataCache.rateLimits- )- trace.rateLimits = rateLimitsRead.step+ let usageRead = try readSupplemental(AccountRequests.usage, cache: &supplementalDataCache.usage)+ trace.usage = usageRead.step- let usageRead = try readSupplemental(- AccountRequests.usage,- cache: &supplementalDataCache.usage- )- trace.usage = usageRead.step+ trace.resetCredits = Self.resetCreditsStepResult(+ summary: rateLimitsRead.value?.rateLimitResetCredits,+ rateLimitsStep: rateLimitsRead.step+ )- trace.resetCredits = Self.resetCreditsStepResult(- summary: rateLimitsRead.value?.rateLimitResetCredits,- rateLimitsStep: rateLimitsRead.step- )+ // rateLimits/usage 都可为空, 只要账户有效就让 UI 展示"暂无数据"- // rateLimits/usage 都可为空, 只要账户有效就让 UI 展示"暂无数据"+ let snapshot = try CodexQuotaSnapshot(+ accountResponse: accountResponse,+ rateLimitsResponse: rateLimitsRead.value,+ usageResponse: usageRead.value,+ isRateLimitsStale: rateLimitsRead.isStale,+ isUsageStale: usageRead.isStale+ )- let snapshot = try CodexQuotaSnapshot(- accountResponse: connection.accountResponse,- rateLimitsResponse: rateLimitsRead.value,- usageResponse: usageRead.value,- isRateLimitsStale: rateLimitsRead.isStale,- isUsageStale: usageRead.isStale- )+ trace.failureStage = nil+ return snapshot+ }- trace.failureStage = nil- return snapshot+ do {+ return try readSnapshot()+ } catch SupplementalReadError.accountChanged {+ // 退出缓存字段的 inout 访问后整轮重读, 继续共用已消耗的认证预算+ trace.account = .refreshed+ trace.rateLimits = nil+ trace.usage = nil+ trace.resetCredits = nil+ return try readSnapshot()+ }}private static func resetCreditsStepResult(diff --git a/CodexBar/Services/History/HistoryDatabase.swift b/CodexBar/Services/History/HistoryDatabase.swiftindex 4fa8e3b..ca852a3 100644--- a/CodexBar/Services/History/HistoryDatabase.swift+++ b/CodexBar/Services/History/HistoryDatabase.swift@@ -405,9 +405,9 @@ final nonisolated class HistoryDatabase {}}var aggregate = rebuilding ? TokenUsageAggregate(date: date) : baseline ?? TokenUsageAggregate(date: date)+ // 沿用数据库中保存的日期, 避免切换时区后误判历史记录try entries(after: position, date: date, kind: .tokenUsage) { entry in- guard let observation = entry.record.tokenUsage, !observation.id.isEmpty,- HistoryStorage.dateKey(for: observation.aggregationDate) == date else {+ guard let observation = entry.record.tokenUsage, !observation.id.isEmpty else {throw StorageCompatibilityError.incompleteSource}try aggregate.record(observation)diff --git a/CodexBar/Services/Sync/SyncRecovery.swift b/CodexBar/Services/Sync/SyncRecovery.swiftindex 305c951..e74e3d7 100644--- a/CodexBar/Services/Sync/SyncRecovery.swift+++ b/CodexBar/Services/Sync/SyncRecovery.swift@@ -9,6 +9,15 @@ nonisolated enum SyncRecovery {case missingRecordResult}+ static func fetchedRecord(from result: Result<CKRecord, any Error>?) throws -> CKRecord? {+ switch result {+ case let .success(record): record+ case let .failure(error as CKError) where error.code == .unknownItem: nil+ case let .failure(error): throw error+ case nil: throw Failure.missingRecordResult+ }+ }+static func decodeCursor(_ data: Data) throws -> CKServerChangeToken {do {guard let token = try NSKeyedUnarchiver.unarchivedObject(ofClass: CKServerChangeToken.self, from: data) else {diff --git a/CodexBar/Services/Sync/SyncService.swift b/CodexBar/Services/Sync/SyncService.swiftindex e3bf462..c0519ae 100644--- a/CodexBar/Services/Sync/SyncService.swift+++ b/CodexBar/Services/Sync/SyncService.swift@@ -441,7 +441,7 @@ private extension SyncService {case let .failure(error):throw errorcase nil:- throw SyncError.missingRecordResult+ throw SyncRecovery.Failure.missingRecordResult}}}@@ -459,7 +459,7 @@ private extension SyncService {for (aggregate, id) in zip(aggregates, recordIDs) {do {- let existing = try Self.fetchedRecord(from: existingRecords[id])+ let existing = try SyncRecovery.fetchedRecord(from: existingRecords[id])if let existing {guard let remote = try ActivityDataRecordCodec.remoteDailyRecord(from: existing) else {throw ActivityDataSyncError.invalidRecordIdentity@@ -695,7 +695,7 @@ private extension SyncService {func fetchAccountSalt(_ recordID: CKRecord.ID) async throws -> Data? {try SyncCancellation.check(isEnabled: isEnabled)let result = try await database.records(for: [recordID], desiredKeys: nil)- guard let record = try Self.fetchedRecord(from: result[recordID]) else {+ guard let record = try SyncRecovery.fetchedRecord(from: result[recordID]) else {return nil}try StorageVersion.require(@@ -729,7 +729,7 @@ private extension SyncService {case let .failure(error):throw errorcase nil:- throw SyncError.missingRecordResult+ throw SyncRecovery.Failure.missingRecordResult}} catch let error as CKError where error.code == .serverRecordChanged || error.code == .constraintViolation {if let salt = try await fetchAccountSalt(recordID) {@@ -760,7 +760,7 @@ private extension SyncService {case let .failure(error):throw errorcase nil:- throw SyncError.missingRecordResult+ throw SyncRecovery.Failure.missingRecordResult}}@@ -824,21 +824,6 @@ extension SyncService {}private extension SyncService {- static func fetchedRecord(- from result: Result<CKRecord, Error>?- ) throws -> CKRecord? {- switch result {- case let .success(record):- return record- case let .failure(error as CKError) where error.code == .unknownItem:- return nil- case let .failure(error):- throw error- case nil:- throw SyncError.missingRecordResult- }- }-static func filteredRetained(records: [ActivityDataSyncRecord]) -> [ActivityDataSyncRecord] {@@ -899,6 +884,5 @@ nonisolated struct SyncSnapshot: Equatable {private nonisolated enum SyncError: Error {case missingAccountSaltcase missingIOPlatformUUID- case missingRecordResultcase randomSaltFailed}diff --git a/CodexBar/Services/Sync/TokenUsageSync.swift b/CodexBar/Services/Sync/TokenUsageSync.swiftindex fe9a0cd..bc5ea27 100644--- a/CodexBar/Services/Sync/TokenUsageSync.swift+++ b/CodexBar/Services/Sync/TokenUsageSync.swift@@ -123,7 +123,7 @@ actor TokenUsageSync {for candidate in batch {let id = Self.recordID(candidate.id, zoneID: zoneID)do {- let fetched = try fetchedRecord(existing[id])+ let fetched = try SyncRecovery.fetchedRecord(from: existing[id])if let remote = try fetched.flatMap(Self.dailyRecord), remote.hasSameData(as: candidate) {cache.records[candidate.id] = remotecontinue@@ -150,7 +150,7 @@ actor TokenUsageSync {cache.records[tokenUsageRecord.id] = tokenUsageRecord}case let .failure(error): failures.record(error)- case nil: failures.record(TokenUsageSyncError.missingRecordResult)+ case nil: failures.record(SyncRecovery.Failure.missingRecordResult)}}try save(cache)@@ -160,15 +160,6 @@ actor TokenUsageSync {try failures.check()}- private func fetchedRecord(_ result: Result<CKRecord, any Error>?) throws -> CKRecord? {- switch result {- case let .success(record): record- case let .failure(error as CKError) where error.code == .unknownItem: nil- case let .failure(error): throw error- case nil: throw TokenUsageSyncError.missingRecordResult- }- }-private func prune(cache: inout TokenUsageSyncCache, zoneID: CKRecordZone.ID) async throws {let cutoff = HistoryStorage.dateKey(for: HistoryStorage.retentionCutoffDate())let expired = cache.records.values.filter {@@ -179,7 +170,7 @@ actor TokenUsageSync {try SyncCancellation.check(isEnabled: isEnabled)let result = try await database.modifyRecords(saving: [], deleting: ids, savePolicy: .ifServerRecordUnchanged, atomically: false)for id in ids {- guard let deletion = result.deleteResults[id] else { throw TokenUsageSyncError.missingRecordResult }+ guard let deletion = result.deleteResults[id] else { throw SyncRecovery.Failure.missingRecordResult }do { try deletion.get() } catch let error as CKError where error.code == .unknownItem {}cache.records.removeValue(forKey: id.recordName)}@@ -278,7 +269,3 @@ nonisolated extension SyncCache where Record == TokenUsageSyncRecord, State == Treturn true}}--private nonisolated enum TokenUsageSyncError: Error {- case missingRecordResult-}diff --git a/Tests/App/CodexStatus/AccountNotificationTests.swift b/Tests/App/CodexStatus/AccountNotificationTests.swiftindex ca1fdcd..8b23ef5 100644--- a/Tests/App/CodexStatus/AccountNotificationTests.swift+++ b/Tests/App/CodexStatus/AccountNotificationTests.swift@@ -290,6 +290,101 @@ extension AccountNotificationTests {try server.finish()}+ @Test(arguments: ["account/rateLimits/read", "account/usage/read"], ["none", "account/rateLimits/read", "account/usage/read"])+ func accountChangeDuringAuthRefreshDiscardsOldData(authMethod: String, failedRead: String) async throws {+ let server = try SharedServerFixture { peer in+ func respond(_ method: String, _ result: [String: Any]) throws {+ let request = try peer.readMessage()+ try #require(request["method"] as? String == method)+ try peer.reply(to: request, result: result)+ }+ try respond("initialize", ["userAgent": "codex/0.162.0"])+ _ = try peer.readMessage()+ let firstAccount: [String: Any] = ["account": ["type": "chatgpt", "email": "[email protected]", "planType": "pro"]]+ let secondAccount: [String: Any] = ["account": ["type": "chatgpt", "email": "[email protected]", "planType": "pro"]]+ try respond("account/read", firstAccount)+ try respond("account/rateLimits/read", ["rateLimits": [:], "ordinaryUsageAllowed": true])+ try respond("account/usage/read", ["summary": ["lifetimeTokens": 123]])+ try respond("account/read", firstAccount)+ if authMethod == "account/usage/read" {+ try respond("account/rateLimits/read", ["rateLimits": [:], "ordinaryUsageAllowed": true])+ }+ let unauthorized = try peer.readMessage()+ try #require(unauthorized["method"] as? String == authMethod)+ try peer.send(["id": #require(unauthorized["id"]), "error": ["code": -32000, "message": "codex account authentication required"]])+ let refresh = try peer.readMessage()+ try #require(refresh["method"] as? String == "account/read")+ #expect((refresh["params"] as? [String: Any])?["refreshToken"] as? Bool == true)+ try peer.reply(to: refresh, result: secondAccount)+ try respond("account/rateLimits/read", failedRead == "account/rateLimits/read" ? [:] : ["rateLimits": [:], "ordinaryUsageAllowed": false])+ try respond("account/usage/read", failedRead == "account/usage/read" ? [:] : ["summary": ["lifetimeTokens": 456]])+ try respond("account/read", secondAccount)+ try respond("account/rateLimits/read", [:])+ try respond("account/usage/read", [:])+ }+ defer { server.close() }+ let service = CodexStatusService(socketURL: server.url, logStorage: nil)+ guard case .data = await service.fetchOutcome().outcome else {+ Issue.record("Initial read did not populate the cache")+ return+ }+ let result = await service.fetchOutcome()+ guard case let .data(snapshot) = result.outcome else {+ Issue.record("Account change did not restart supplemental reads")+ return+ }+ #expect(snapshot.account.email == "[email protected]")+ #expect(snapshot.ordinaryUsageAllowed == (failedRead == "account/rateLimits/read" ? nil : false))+ #expect(snapshot.usage?.summary.lifetimeTokens == (failedRead == "account/usage/read" ? nil : 456))+ #expect(!snapshot.isRateLimitsStale && !snapshot.isUsageStale)+ #expect(result.trace.account == .refreshed)+ #expect(result.trace.rateLimits == (failedRead == "account/rateLimits/read" ? .failed : .ok))+ #expect(result.trace.usage == (failedRead == "account/usage/read" ? .failed : .ok))+ guard case let .data(cached) = await service.fetchOutcome().outcome else {+ Issue.record("New account cache was unavailable")+ return+ }+ #expect(cached.account == snapshot.account)+ #expect(cached.ordinaryUsageAllowed == snapshot.ordinaryUsageAllowed)+ #expect(cached.usage?.summary.lifetimeTokens == snapshot.usage?.summary.lifetimeTokens)+ #expect(cached.isRateLimitsStale == (failedRead != "account/rateLimits/read"))+ #expect(cached.isUsageStale == (failedRead != "account/usage/read"))+ try server.finish()+ }++ @Test(arguments: ["account/rateLimits/read", "account/usage/read"])+ func accountChangeDoesNotRenewAuthenticationBudget(authMethod: String) async throws {+ let server = try SharedServerFixture { peer in+ try peer.reply(to: peer.readMessage(), result: ["userAgent": "codex/0.162.0"])+ _ = try peer.readMessage()+ try peer.reply(to: peer.readMessage(), result: ["account": ["type": "chatgpt", "email": "[email protected]", "planType": "pro"]])+ if authMethod == "account/usage/read" {+ try peer.reply(to: peer.readMessage(), result: ["rateLimits": [:], "ordinaryUsageAllowed": true])+ }+ let unauthorized = try peer.readMessage()+ try #require(unauthorized["method"] as? String == authMethod)+ let error: [String: Any] = ["code": -32000, "message": "codex account authentication required"]+ try peer.send(["id": #require(unauthorized["id"]), "error": error])+ let refresh = try peer.readMessage()+ try #require(refresh["method"] as? String == "account/read")+ #expect((refresh["params"] as? [String: Any])?["refreshToken"] as? Bool == true)+ try peer.reply(to: refresh, result: ["account": ["type": "chatgpt", "email": "[email protected]", "planType": "pro"]])+ let retried = try peer.readMessage()+ try #require(retried["method"] as? String == "account/rateLimits/read")+ try peer.send(["id": #require(retried["id"]), "error": error])+ }+ defer { server.close() }+ let result = await CodexStatusService(socketURL: server.url, logStorage: nil).fetchOutcome()+ guard case .authenticationRequired = result.outcome else {+ Issue.record("Account change renewed the authentication budget")+ return+ }+ #expect(result.trace.account == .refreshed)+ #expect(result.trace.failureStage == .snapshot)+ #expect(result.trace.rateLimits == nil && result.trace.usage == nil && result.trace.resetCredits == nil)+ try server.finish()+ }+@Test(arguments: [false, true])func quotaReadsShareOneAuthenticationRefreshBudget(repeatsOnSameMethod: Bool) async throws {let server = try SharedServerFixture { peer indiff --git a/Tests/App/History/HistoryDatabaseTests.swift b/Tests/App/History/HistoryDatabaseTests.swiftindex 0e4e4d1..b638053 100644--- a/Tests/App/History/HistoryDatabaseTests.swift+++ b/Tests/App/History/HistoryDatabaseTests.swift@@ -491,6 +491,61 @@ extension HistoryDatabaseTests {#expect(try await store.refresh(now: now) == result)}+ @Test(arguments: [-1, 1])+ func storedTokenDatesSurviveLocalDateChanges(dayOffset: Int) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = TestFixtures.now+ let localDate = HistoryStorage.dateKey(for: now)+ let storedDate = HistoryStorage.dateKey(for: now.addingTimeInterval(Double(dayOffset) * 86400))+ func sample(_ id: String, _ count: Int64) -> TokenUsageSample {+ let usage = tokenUsage(count)+ return TokenUsageSample(+ id: id, observedAt: now, threadID: "thread", turnID: "turn", turnStartedAt: now,+ current: TokenUsageUpdate(total: usage, last: usage)+ )+ }+ do {+ let database = try HistoryDatabase(directoryURL: directory.url)+ try database.appendTokenUsage(sample("baseline", 0))+ try database.appendTokenUsage(sample("first", 100))+ let initial = try database.aggregateTokenUsage(date: localDate)+ try database.appendTokenUsage(sample("pending", 130))+ // 模拟在另一时区保存的日期, 避免修改并行测试共享的系统时区+ var stored = TokenUsageAggregate(date: storedDate, tokenUsage: initial.tokenUsage, eventCount: initial.eventCount)+ stored.position = initial.position+ try database.transaction {+ try database.execute("INSERT INTO days(date) VALUES (?)", [.text(storedDate)])+ try database.execute("UPDATE events SET date = ?", [.text(storedDate)])+ try database.execute("INSERT INTO aggregates(date, tokenUsage) VALUES (?, ?)", [.text(storedDate), .data(JSONLines.stableEncoder.encode(stored))])+ try database.execute("DELETE FROM days WHERE date = ?", [.text(localDate)])+ }+ }++ let database = try HistoryDatabase(directoryURL: directory.url)+ let latest = sample("after-switch", 150)+ try database.appendTokenUsage(latest)+ try database.appendTokenUsage(latest)+ let store = TokenUsageHistoryStore(directoryURL: directory.url)+ let snapshot = try await store.loadSnapshot(now: now)+ #expect(snapshot.coverage == .complete)+ #expect(Dictionary(uniqueKeysWithValues: snapshot.aggregates.map { ($0.date, $0.tokenUsage.totalTokens) }) == [storedDate: 130, localDate: 20])+ #expect(snapshot.aggregates.reduce(0) { $0 + $1.eventCount } == 4)+ #expect(try database.pendingTokenUsageDates().isEmpty)+ #expect(try database.tokenUsageSnapshot(threadID: "thread").turns["turn"]?.totalTokens == 150)++ let rebuilt = try await store.rebuild(for: [storedDate, localDate])+ #expect(rebuilt.failedDateKeys.isEmpty)+ #expect(rebuilt.dateKeys == [storedDate, localDate].sorted())+ #expect(rebuilt.eventCount == 4)+ #expect(try await store.persistedAggregates(now: now) == snapshot.aggregates)+ let expectedDates = dayOffset > 0 ? [localDate] : [storedDate, localDate].sorted()+ #expect(TokenUsageAggregate.tokenUsageByDate(snapshot.aggregates, now: now).keys.sorted() == expectedDates)+ #expect(try TokenUsageSyncRecord.dailyRecords(local: snapshot.aggregates, deviceID: "device", now: now).map(\.date) == expectedDates)+ let later = now.addingTimeInterval(86400)+ #expect(TokenUsageAggregate.tokenUsageByDate(snapshot.aggregates, now: later).values.reduce(0) { $0 + $1.totalTokens } == 150)+ }+@Test func unchangedSnapshotReadsSavedDailyTotalsWithoutReplayingEventsOrWriting() async throws {let directory = try TestDirectory()defer { try? directory.remove() }diff --git a/Tests/App/Sync/SyncRecoveryTests.swift b/Tests/App/Sync/SyncRecoveryTests.swiftindex 224def2..67cdf50 100644--- a/Tests/App/Sync/SyncRecoveryTests.swift+++ b/Tests/App/Sync/SyncRecoveryTests.swift@@ -188,6 +188,48 @@ struct SyncRecoveryTests {#expect(await database.savedTypes.contains(TokenUsageSync.recordType) == !shared)}+ @Test(arguments: ["Metadata", "ActivityData", "TokenUsage"])+ func missingReadResultStopsAffectedUploadAndRetries(recordType: String) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let database = SyncDatabaseFixture()+ let service = SyncService(database: database, directoryURL: directory.url, isEnabled: { true })+ let initial = await service.synchronizeIfEnabled(localActivityDataAggregates: [], trigger: .manual)+ let deviceID = try #require(initial.currentDeviceID)+ let tokenUsage = Self.turn(0)+ let activityData = TestFixtures.activityDataAggregate(date: tokenUsage.date)+ let missingName: String = switch recordType {+ case "ActivityData":+ ActivityDataSyncRecord.recordName(deviceID: deviceID, date: activityData.date)+ case "TokenUsage":+ TokenUsageSyncRecord(deviceID: deviceID, date: tokenUsage.date, tokenUsage: .zero).recordName+ default:+ try #require(await database.requestedIDs.first).recordName+ }+ await database.omitReadResult(named: missingName)++ _ = await service.synchronizeIfEnabled(+ localActivityDataAggregates: [activityData], localTokenUsageAggregates: [tokenUsage], trigger: .manual+ )+ let savedTypes = await database.savedTypes+ #expect(savedTypes.filter { $0 == "Metadata" }.count == 1)+ #expect(savedTypes.contains("ActivityData") == (recordType == "TokenUsage"))+ #expect(savedTypes.contains("TokenUsage") == (recordType == "ActivityData"))+ #expect(await service.hasPendingActivityDataUpdates(local: [activityData]) == (recordType != "TokenUsage"))+ #expect(await service.hasPendingTokenUsageUpdates(local: [tokenUsage]) == (recordType != "ActivityData"))++ await database.repair()+ _ = await service.synchronizeIfEnabled(+ localActivityDataAggregates: [activityData], localTokenUsageAggregates: [tokenUsage], trigger: .manual+ )+ let recoveredTypes = await database.savedTypes+ for type in ["Metadata", "ActivityData", "TokenUsage"] {+ #expect(recoveredTypes.filter { $0 == type }.count == 1)+ }+ #expect(await service.hasPendingActivityDataUpdates(local: [activityData]) == false)+ #expect(await service.hasPendingTokenUsageUpdates(local: [tokenUsage]) == false)+ }+@Test(arguments: [false, true]) func partialTokenUsageBatchContinuesAndRetainsSuccesses(readFailure: Bool) async throws {let directory = try TestDirectory()defer { try? directory.remove() }@@ -508,6 +550,7 @@ private actor SyncDatabaseFixture: SyncDatabase {private var failingName: String?private var failingDate: String?+ private var omittedReadName: String?private let readFailure: Boolprivate let uploadFailure: CKError.Codeprivate(set) var queryCount = 0@@ -567,14 +610,19 @@ private actor SyncDatabaseFixture: SyncDatabase {changesRecordFails = true}+ func omitReadResult(named name: String) {+ omittedReadName = name+ }+func repair() {failingName = nilfailingDate = nil+ omittedReadName = nil}func records(for ids: [CKRecord.ID], desiredKeys _: [CKRecord.FieldKey]?) async throws -> Records {requestedIDs.append(contentsOf: ids)- return Dictionary(uniqueKeysWithValues: ids.map { id in+ return Dictionary(uniqueKeysWithValues: ids.filter { $0.recordName != omittedReadName }.map { id inif readFailure, id.recordName == failingName {return (id, .failure(CKError(.constraintViolation)))}