forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAgentSyncBatchQueryTests.swift
More file actions
669 lines (579 loc) · 24.9 KB
/
Copy pathAgentSyncBatchQueryTests.swift
File metadata and controls
669 lines (579 loc) · 24.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
import Foundation
import GRDB
import XCTest
@testable import Omi_Computer
private actor AgentSyncDelayedTokenGate {
private var fetchCount = 0
private var firstFetchStarted = false
private var firstFetchWaiters: [CheckedContinuation<Void, Never>] = []
private var firstFetchContinuation: CheckedContinuation<Void, Never>?
private var firstFetchCancelled = false
private var firstFetchCancelWaiters: [CheckedContinuation<Void, Never>] = []
private var requests: [URLRequest] = []
private var requestWaiters: [CheckedContinuation<Void, Never>] = []
func fetchToken() async -> String {
fetchCount += 1
if fetchCount == 1 {
firstFetchStarted = true
let waiters = firstFetchWaiters
firstFetchWaiters.removeAll()
waiters.forEach { $0.resume() }
await withCheckedContinuation { continuation in
firstFetchContinuation = continuation
}
return "owner-a-token"
}
return "owner-b-token"
}
func waitUntilFirstFetchStarts() async {
guard !firstFetchStarted else { return }
await withCheckedContinuation { continuation in
firstFetchWaiters.append(continuation)
}
}
func releaseFirstFetch() {
firstFetchContinuation?.resume()
firstFetchContinuation = nil
}
/// `stop()` bumps the sync generation and only then cancels the sync task, so
/// the cancellation of the task that owns the first fetch is the observable
/// proof that the owner boundary has already moved. Waiting on it before
/// releasing the delayed token is what makes "the token resumes *after* the
/// handoff" a fact rather than a scheduling coincidence.
func noteFirstFetchCancelled() {
guard !firstFetchCancelled else { return }
firstFetchCancelled = true
let waiters = firstFetchCancelWaiters
firstFetchCancelWaiters.removeAll()
waiters.forEach { $0.resume() }
}
func waitUntilFirstFetchCancelled() async {
guard !firstFetchCancelled else { return }
await withCheckedContinuation { continuation in
firstFetchCancelWaiters.append(continuation)
}
}
func respond(to request: URLRequest) -> (Data, URLResponse) {
requests.append(request)
let waiters = requestWaiters
requestWaiters.removeAll()
waiters.forEach { $0.resume() }
let response = HTTPURLResponse(
url: request.url!,
statusCode: 200,
httpVersion: nil,
headerFields: nil)!
return (Data(), response)
}
func waitForRequest() async {
guard requests.isEmpty else { return }
await withCheckedContinuation { continuation in
requestWaiters.append(continuation)
}
}
func requestURLs() -> [URL] {
requests.compactMap(\.url)
}
}
#if DEBUG
private final class AgentSyncManualClock: @unchecked Sendable {
private let lock = NSLock()
private var value: Date
init(_ value: Date = Date(timeIntervalSince1970: 1_700_000_000)) {
self.value = value
}
func now() -> Date {
lock.withLock { value }
}
func advance(_ interval: TimeInterval) {
lock.withLock { value.addTimeInterval(interval) }
}
}
private actor AgentSyncReplacementCallbackGate {
enum Endpoint: Hashable {
case sync
case health
case upload
}
private let suspended: Set<Endpoint>
private var started: Set<Endpoint> = []
private var startWaiters: [Endpoint: [CheckedContinuation<Void, Never>]] = [:]
private var releaseContinuations: [Endpoint: CheckedContinuation<Void, Never>] = [:]
private var reuploadVMs: [String] = []
init(suspending endpoint: Endpoint) {
suspended = [endpoint]
}
func respond(to request: URLRequest) async throws -> (Data, URLResponse) {
let url = try XCTUnwrap(request.url)
let endpoint: Endpoint? =
switch url.path {
case "/sync": .sync
case "/health": .health
default: nil
}
if url.host == "old-vm", let endpoint, suspended.contains(endpoint) {
await suspend(endpoint)
}
switch url.path {
case "/auth":
return (Data(), response(url, status: 200))
case "/sync":
let payload = try XCTUnwrap(request.httpBody)
let json = try XCTUnwrap(try JSONSerialization.jsonObject(with: payload) as? [String: Any])
let table = try XCTUnwrap(json["table"] as? String)
if table == "transcription_sessions" {
return (Data("SQLite error: no such table: \(table)".utf8), response(url, status: 500))
}
return (Data(), response(url, status: 200))
case "/health":
return (try JSONSerialization.data(withJSONObject: ["databaseReady": true]), response(url, status: 200))
default:
return (Data(), response(url, status: 404))
}
}
func reupload(vmIP: String) async -> Bool {
reuploadVMs.append(vmIP)
if vmIP == "old-vm", suspended.contains(.upload) {
await suspend(.upload)
}
return true
}
func waitUntilStarted(_ endpoint: Endpoint) async {
guard !started.contains(endpoint) else { return }
await withCheckedContinuation { continuation in
startWaiters[endpoint, default: []].append(continuation)
}
}
func release(_ endpoint: Endpoint) {
releaseContinuations.removeValue(forKey: endpoint)?.resume()
}
func uploadVMs() -> [String] {
reuploadVMs
}
private func suspend(_ endpoint: Endpoint) async {
started.insert(endpoint)
let waiters = startWaiters.removeValue(forKey: endpoint) ?? []
waiters.forEach { $0.resume() }
await withCheckedContinuation { continuation in
releaseContinuations[endpoint] = continuation
}
}
private func response(_ url: URL, status: Int) -> URLResponse {
HTTPURLResponse(url: url, statusCode: status, httpVersion: nil, headerFields: nil)
?? URLResponse(url: url, mimeType: nil, expectedContentLength: 0, textEncodingName: nil)
}
}
private actor AgentSyncRecoveryProbe {
enum HealthResponse {
case ready
case malformed
case status(Int)
}
private var missingTables: Set<String>
private var healthResponse: HealthResponse = .ready
private var uploadResults: [Bool] = [true]
private var healthChecks = 0
private var uploads = 0
private var syncedTables: [String] = []
private var lastHealthAuthorization: String?
private var lastHealthTokenQuery: String?
init(missingTable: String? = "transcription_sessions") {
missingTables = missingTable.map { [$0] } ?? []
}
func respond(to request: URLRequest) throws -> (Data, URLResponse) {
let url = try XCTUnwrap(request.url)
switch url.path {
case "/auth":
return (Data(), response(url, status: 200))
case "/sync":
let payload = try XCTUnwrap(request.httpBody)
let json = try XCTUnwrap(try JSONSerialization.jsonObject(with: payload) as? [String: Any])
let table = try XCTUnwrap(json["table"] as? String)
syncedTables.append(table)
if missingTables.contains(table) {
return (Data("SQLite error: no such table: \(table)".utf8), response(url, status: 500))
}
return (Data(), response(url, status: 200))
case "/health":
healthChecks += 1
lastHealthAuthorization = request.value(forHTTPHeaderField: "Authorization")
lastHealthTokenQuery =
URLComponents(url: url, resolvingAgainstBaseURL: false)?
.queryItems?
.first(where: { $0.name == "token" })?
.value
switch healthResponse {
case .ready:
return (try JSONSerialization.data(withJSONObject: ["databaseReady": true]), response(url, status: 200))
case .malformed:
return (Data("not-json".utf8), response(url, status: 200))
case .status(let status):
return (Data(), response(url, status: status))
}
default:
return (Data(), response(url, status: 404))
}
}
func reupload() -> Bool {
uploads += 1
return uploadResults.isEmpty ? false : uploadResults.removeFirst()
}
func setMissingTable(_ table: String?) {
missingTables = table.map { [$0] } ?? []
}
func setMissingTables(_ tables: Set<String>) {
missingTables = tables
}
func setHealthResponse(_ response: HealthResponse) {
healthResponse = response
}
func setUploadResults(_ results: [Bool]) {
uploadResults = results
}
func counts() -> (healthChecks: Int, uploads: Int, syncedTables: [String]) {
(healthChecks, uploads, syncedTables)
}
func lastHealthAuth() -> (authorization: String?, tokenQuery: String?) {
(lastHealthAuthorization, lastHealthTokenQuery)
}
private func response(_ url: URL, status: Int) -> URLResponse {
HTTPURLResponse(url: url, statusCode: status, httpVersion: nil, headerFields: nil)
?? URLResponse(url: url, mimeType: nil, expectedContentLength: 0, textEncodingName: nil)
}
}
#endif
/// Regression test for the AgentSync mutable-table pagination skip: paging with a
/// strict `updatedAt > ?` cursor drops every row past the first batch when more
/// than `batchSize` rows share the same `updatedAt` (a bulk update touching >100
/// rows in one second), silently diverging the VM's copy. Mutable tables must page
/// on a compound `(updatedAt, id)` cursor.
final class AgentSyncBatchQueryTests: XCTestCase {
func testPartialSchemaIsNotReadyEvenWhenDatabaseReadyIsTrue() {
let readiness = AgentSyncService.databaseReadiness(
healthPayload: ["databaseReady": true],
syncFailureBody: "SQLite error: no such table: transcription_sessions"
)
XCTAssertEqual(
readiness,
.missingRequiredSchema,
"A VM that reports databaseReady while rejecting a required sync table must be re-provisioned by the existing upload owner"
)
}
func testUnrelatedSQLiteTableFailureDoesNotTriggerDatabaseReupload() {
let readiness = AgentSyncService.databaseReadiness(
healthPayload: ["databaseReady": true],
syncFailureBody: "SQLite error: no such table: scratch_cache"
)
XCTAssertEqual(
readiness,
.ready,
"Only tables owned by AgentSync prove its uploaded schema is partial; unrelated server faults must keep bounded retry behavior"
)
}
func testMalformedOrMissingHealthReadinessIsNotMissingDatabase() {
XCTAssertEqual(AgentSyncService.databaseReadiness(healthPayload: [:]), .unknown)
XCTAssertEqual(AgentSyncService.databaseReadiness(healthPayload: ["databaseReady": "false"]), .unknown)
}
func testMutableTableUsesCompoundCursor() {
let (sql, args) = AgentSyncService.buildBatchQuery(
tableName: "action_items",
selectCols: "\"id\", \"updatedAt\"",
appendOnly: false,
lastId: 42,
lastUpdatedAt: "2026-04-09T12:00:00",
batchSize: 100
)
// Must include the compound clause and id-tiebreaker ordering — not a bare
// strict `updatedAt > ?` that would skip same-timestamp rows.
XCTAssertTrue(sql.contains("updatedAt > ? OR (updatedAt = ? AND id > ?)"), sql)
XCTAssertTrue(sql.contains("ORDER BY updatedAt ASC, id ASC"), sql)
XCTAssertEqual(
args,
[.text("2026-04-09T12:00:00"), .text("2026-04-09T12:00:00"), .int(42), .int(100)])
}
func testAppendOnlyTablePagesById() {
let (sql, args) = AgentSyncService.buildBatchQuery(
tableName: "screenshots",
selectCols: "\"id\"",
appendOnly: true,
lastId: 7,
lastUpdatedAt: "1970-01-01T00:00:00",
batchSize: 100
)
XCTAssertTrue(sql.contains("WHERE id > ? ORDER BY id ASC"), sql)
XCTAssertFalse(sql.contains("updatedAt"), sql)
XCTAssertEqual(args, [.int(7), .int(100)])
}
@MainActor
func testDelayedOwnerATokenCannotResumeIntoOwnerBVM() async {
let originalPhase = AuthState.shared.sessionPhase
AuthState.shared.transition(to: .authenticated)
defer { AuthState.shared.transition(to: originalPhase) }
let gate = AgentSyncDelayedTokenGate()
let service = AgentSyncService(
networkHooks: AgentSyncService.NetworkHooks(
fetchIDToken: {
await withTaskCancellationHandler {
await gate.fetchToken()
} onCancel: {
Task { await gate.noteFirstFetchCancelled() }
}
},
dataForRequest: { request in await gate.respond(to: request) },
reuploadDatabase: { _, _ in true },
now: Date.init,
tableSyncEnabled: false))
await service.start(vmIP: "owner-a-vm", authToken: "owner-a-auth")
await gate.waitUntilFirstFetchStarts()
let stopOwnerA = Task { await service.stop(flushPendingChanges: false) }
await gate.waitUntilFirstFetchCancelled()
await gate.releaseFirstFetch()
await stopOwnerA.value
await service.start(vmIP: "owner-b-vm", authToken: "owner-b-auth")
await gate.waitForRequest()
await service.stop(flushPendingChanges: false)
let requestURLs = await gate.requestURLs()
XCTAssertEqual(requestURLs.count, 1)
XCTAssertEqual(requestURLs.first?.host, "owner-b-vm")
XCTAssertEqual(requestURLs.first?.path, "/auth")
}
}
#if DEBUG
// omi-release-compile: this suite drives AgentSyncService's DEBUG-only
// startForTesting/syncOnceForTesting seam; the release-mode notification
// regression step must compile the bundle without it.
/// These tests drive `syncTick` through the same table reads and HTTP paths as
/// the loop. The DEBUG-only clock/hook seam avoids a scheduler or bridge fault
/// protocol while preserving production ownership and recovery behavior.
/// Release CI (`swift test -c release`) must skip this suite because
/// `startForTesting` / `syncOnceForTesting` are DEBUG-only.
final class AgentSyncRecoveryTests: XCTestCase {
private var storageFixture: RewindStorageTestIsolation.Fixture?
private var authSnapshot: RewindStorageTestIsolation.AuthSnapshot?
override func setUp() async throws {
try await super.setUp()
let fixture = try await RewindStorageTestIsolation.setUp(userIdPrefix: "agent-sync-recovery")
storageFixture = fixture
authSnapshot = await MainActor.run { RewindStorageTestIsolation.captureAuthSnapshot() }
await MainActor.run { RewindStorageTestIsolation.signInForTests(userId: fixture.testUserId) }
try await insertSyncRows()
}
override func tearDown() async throws {
if let authSnapshot {
await MainActor.run { RewindStorageTestIsolation.restoreAuthSnapshot(authSnapshot) }
}
await RewindStorageTestIsolation.tearDown(userDir: storageFixture?.userDir)
try await super.tearDown()
}
func testMixedSuccessStillRecoversTheRepeatedRequiredTableFailure() async {
let probe = AgentSyncRecoveryProbe()
let service = makeService(probe: probe)
await service.startForTesting(vmIP: "127.0.0.1", authToken: "test-token")
await service.syncOnceForTesting()
await service.syncOnceForTesting()
await service.syncOnceForTesting()
let counts = await probe.counts()
XCTAssertTrue(
counts.syncedTables.contains("action_items"), "The control table must take the real /sync success path")
XCTAssertEqual(counts.syncedTables.filter { $0 == "transcription_sessions" }.count, 3)
XCTAssertEqual(counts.healthChecks, 1, "Three causal failures trigger one fail-closed /health check")
XCTAssertEqual(counts.uploads, 1, "The existing database-upload owner repairs the missing table exactly once")
let healthAuth = await probe.lastHealthAuth()
XCTAssertEqual(healthAuth.authorization, "Bearer test-token")
XCTAssertEqual(healthAuth.tokenQuery, "test-token")
}
func testTwoMissingRequiredTablesDoNotAlternateAwayTheSelectedRecovery() async {
let probe = AgentSyncRecoveryProbe()
await probe.setMissingTables(["transcription_sessions", "action_items"])
let service = makeService(probe: probe)
await service.startForTesting(vmIP: "127.0.0.1", authToken: "test-token")
for _ in 0..<3 { await service.syncOnceForTesting() }
let counts = await probe.counts()
XCTAssertEqual(counts.syncedTables.filter { $0 == "transcription_sessions" }.count, 3)
XCTAssertEqual(counts.syncedTables.filter { $0 == "action_items" }.count, 3)
XCTAssertTrue(
counts.syncedTables.contains("memories"),
"A successful required table must not suppress recovery for the selected missing table"
)
XCTAssertEqual(
counts.healthChecks, 1, "Alternating missing tables must still reach the causal recovery threshold")
XCTAssertEqual(counts.uploads, 1, "One selected causal table produces one bounded repair")
}
func testMatchingTableSuccessClearsRecoveryButUnrelatedSuccessDoesNot() async throws {
let probe = AgentSyncRecoveryProbe()
let service = makeService(probe: probe)
await service.startForTesting(vmIP: "127.0.0.1", authToken: "test-token")
await service.syncOnceForTesting()
await service.syncOnceForTesting()
await probe.setMissingTable(nil) // The previously failing table now succeeds.
await service.syncOnceForTesting()
await probe.setMissingTable("transcription_sessions")
try await touchTranscriptionSession()
await service.syncOnceForTesting()
await service.syncOnceForTesting()
var counts = await probe.counts()
XCTAssertEqual(counts.uploads, 0, "A matching success clears the earlier table's causal evidence")
await service.syncOnceForTesting()
counts = await probe.counts()
XCTAssertEqual(counts.uploads, 1, "Only three new failures of the same required table recover it")
}
func testMalformedAndNonSuccessHealthNeverUpload() async {
let probe = AgentSyncRecoveryProbe()
await probe.setHealthResponse(.malformed)
let service = makeService(probe: probe)
await service.startForTesting(vmIP: "127.0.0.1", authToken: "test-token")
for _ in 0..<3 { await service.syncOnceForTesting() }
var counts = await probe.counts()
XCTAssertEqual(counts.healthChecks, 1)
XCTAssertEqual(counts.uploads, 0)
await probe.setHealthResponse(.status(503))
await service.syncOnceForTesting()
counts = await probe.counts()
XCTAssertEqual(counts.uploads, 0, "Non-2xx health responses fail closed before upload")
}
func testSameOwnerRestartPreservesCooldownAndFailedUploadsStayBounded() async {
let probe = AgentSyncRecoveryProbe()
await probe.setUploadResults([false, false, false])
let clock = AgentSyncManualClock()
let service = makeService(probe: probe, clock: clock)
await service.startForTesting(vmIP: "127.0.0.1", authToken: "test-token")
for _ in 0..<3 { await service.syncOnceForTesting() }
var counts = await probe.counts()
XCTAssertEqual(counts.uploads, 1)
await service.startForTesting(vmIP: "127.0.0.1", authToken: "test-token")
await service.syncOnceForTesting()
counts = await probe.counts()
XCTAssertEqual(counts.uploads, 1, "Same-owner restart cannot mint a new cooldown allowance")
clock.advance(30 * 60 + 1)
await service.syncOnceForTesting()
counts = await probe.counts()
XCTAssertEqual(counts.uploads, 2)
clock.advance(30 * 60 + 1)
await service.syncOnceForTesting()
counts = await probe.counts()
XCTAssertEqual(counts.uploads, 2, "Failed recovery uploads stop at the existing bounded policy")
}
func testSameOwnerReplacementVMResetsOldRecoveryEvidenceCooldownAndBudget() async {
let probe = AgentSyncRecoveryProbe()
await probe.setUploadResults([false, false, false])
let clock = AgentSyncManualClock()
let service = makeService(probe: probe, clock: clock)
await service.startForTesting(vmIP: "old-vm", authToken: "test-token")
for _ in 0..<3 { await service.syncOnceForTesting() }
clock.advance(30 * 60 + 1)
await service.syncOnceForTesting()
var counts = await probe.counts()
XCTAssertEqual(counts.uploads, 2, "The old VM exhausts its bounded retry budget")
await service.startForTesting(vmIP: "replacement-vm", authToken: "test-token")
await service.syncOnceForTesting()
await service.syncOnceForTesting()
counts = await probe.counts()
XCTAssertEqual(counts.uploads, 2, "Replacement must not upload from stale old-VM evidence")
await service.syncOnceForTesting()
counts = await probe.counts()
XCTAssertEqual(counts.uploads, 3, "Replacement gets a fresh causal threshold and bounded retry budget")
}
func testDelayedOldVMSyncResponseCannotCreateReplacementRecoveryEvidence() async {
let gate = AgentSyncReplacementCallbackGate(suspending: .sync)
let service = makeService(gate: gate)
await service.startForTesting(vmIP: "old-vm", authToken: "test-token")
let oldTick = Task { await service.syncOnceForTesting() }
await gate.waitUntilStarted(.sync)
await service.startForTesting(vmIP: "replacement-vm", authToken: "test-token")
await gate.release(.sync)
await oldTick.value
for _ in 0..<3 { await service.syncOnceForTesting() }
let uploadVMs = await gate.uploadVMs()
XCTAssertEqual(uploadVMs, ["replacement-vm"])
}
func testDelayedOldVMHealthResponseCannotSpendReplacementRecoveryBudget() async {
let gate = AgentSyncReplacementCallbackGate(suspending: .health)
let service = makeService(gate: gate)
await service.startForTesting(vmIP: "old-vm", authToken: "test-token")
await service.syncOnceForTesting()
await service.syncOnceForTesting()
let oldTick = Task { await service.syncOnceForTesting() }
await gate.waitUntilStarted(.health)
await service.startForTesting(vmIP: "replacement-vm", authToken: "test-token")
await gate.release(.health)
await oldTick.value
for _ in 0..<3 { await service.syncOnceForTesting() }
let uploadVMs = await gate.uploadVMs()
XCTAssertEqual(uploadVMs, ["replacement-vm"])
}
func testDelayedOldVMUploadResponseCannotClearReplacementRecoveryEvidence() async {
let gate = AgentSyncReplacementCallbackGate(suspending: .upload)
let service = makeService(gate: gate)
await service.startForTesting(vmIP: "old-vm", authToken: "test-token")
await service.syncOnceForTesting()
await service.syncOnceForTesting()
let oldTick = Task { await service.syncOnceForTesting() }
await gate.waitUntilStarted(.upload)
await service.startForTesting(vmIP: "replacement-vm", authToken: "test-token")
await service.syncOnceForTesting()
await service.syncOnceForTesting()
await gate.release(.upload)
await oldTick.value
await service.syncOnceForTesting()
let uploadVMs = await gate.uploadVMs()
XCTAssertEqual(uploadVMs, ["old-vm", "replacement-vm"])
}
private func makeService(
probe: AgentSyncRecoveryProbe,
clock: AgentSyncManualClock = AgentSyncManualClock()
) -> AgentSyncService {
AgentSyncService(
networkHooks: AgentSyncService.NetworkHooks(
fetchIDToken: { "test-firebase-token" },
dataForRequest: { request in try await probe.respond(to: request) },
reuploadDatabase: { _, _ in await probe.reupload() },
now: { clock.now() },
tableSyncEnabled: true))
}
private func makeService(gate: AgentSyncReplacementCallbackGate) -> AgentSyncService {
AgentSyncService(
networkHooks: AgentSyncService.NetworkHooks(
fetchIDToken: { "test-firebase-token" },
dataForRequest: { request in try await gate.respond(to: request) },
reuploadDatabase: { vmIP, _ in await gate.reupload(vmIP: vmIP) },
now: Date.init,
tableSyncEnabled: true))
}
private func insertSyncRows() async throws {
guard let dbQueue = await RewindDatabase.shared.getDatabaseQueue() else {
return XCTFail("Rewind database should be initialized")
}
let now = Date(timeIntervalSince1970: 1_700_000_000)
try await dbQueue.write { db in
try db.execute(
sql: """
INSERT INTO transcription_sessions (startedAt, source, createdAt, updatedAt)
VALUES (?, ?, ?, ?)
""",
arguments: [now, "desktop", now, now])
try db.execute(
sql: """
INSERT INTO action_items (description, createdAt, updatedAt)
VALUES (?, ?, ?)
""",
arguments: ["mixed-success control", now, now])
try db.execute(
sql: """
INSERT INTO memories (content, category, createdAt, updatedAt)
VALUES (?, ?, ?, ?)
""",
arguments: ["mixed-success recovery control", "system", now, now])
}
}
private func touchTranscriptionSession() async throws {
guard let dbQueue = await RewindDatabase.shared.getDatabaseQueue() else {
return XCTFail("Rewind database should be initialized")
}
try await dbQueue.write { db in
try db.execute(
sql: "UPDATE transcription_sessions SET updatedAt = ? WHERE id = 1",
arguments: [Date(timeIntervalSince1970: 1_700_000_001)])
}
}
}
#endif