oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1import Foundation
2import CryptoKit
3import RastrilloApple
4import RastrilloNative
5import RastrilloTestSupport
6import XCTest
7@testable import DocsKit
8
9/// Uses the production WASM replica: a lost response really integrates bytes.
10private actor IntegratingServer: NativeTransport {
11 nonisolated let origin = URL(string: "http://localhost:8099")!
12 var creationTokens: Set<String> = []
13 func documentCount() -> Int { creationTokens.count }
14 var online = true
15 var title = "Document"
16 var titleFailures = 0
17 var titleDelay = false
18 var updateDelay = false
19 var updateRequests = 0
20 func delayUpdates() { updateDelay = true }
21 func updateRequestCount() -> Int { updateRequests }
22 var titleRequests = 0
23 func delayTitles() { titleDelay = true }
24 func titleRequestCount() -> Int { titleRequests }
25 func failTitles(_ count: Int) { titleFailures = count }
26 func savedTitle() -> String { title }
27
28 var loseNextResponse = false
29 var sequence: Int64 = 0
30 var rows: [Int64: Data] = [:]
31 /// Replies carrying the whole state (no `since`, or `since=0`).
32 var fullDownloads = 0
33 func fullDownloadCount() -> Int { fullDownloads }
34 func advance(to sequence: Int64) { self.sequence = sequence }
35 func parked() async throws -> String { try await replica.parked() }
36 var failingFullDownloads = 0, fullDownloadAttempts = 0
37 func failFullDownloads(_ count: Int) { failingFullDownloads = count }
38 func fullDownloadAttemptCount() -> Int { fullDownloadAttempts }
39 var listeners: [UUID: AsyncStream<Int64>.Continuation] = [:]
40 func setOnline(_ value: Bool) { online = value }
41 let replica = CRDTReplica(guid: "offline-property")
42 var accepted: [UUID: Data] = [:]
43 func open(_ initial: Data) async throws { _ = try await replica.open(update: initial) }
44 func accept(_ entries: [OutboxEntry]) async throws {
45 for entry in entries { _ = try await replica.apply(entry.payload); accepted[entry.id] = entry.payload }
46 }
47 func snapshot() async throws -> Data { try await replica.persistentState().state }
48 func text() async throws -> String { try await replica.projection().children.map(\.plainText).joined() }
49 func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse {
50 guard online else { throw NativeClientError.offline(.notConnectedToInternet) }
51 if method == "POST", path == "/documents", let body {
52 let token = URLComponents(string: "?" + String(decoding: body, as: UTF8.self))?.queryItems?.first(where: { $0.name == "creation_token" })?.value ?? ""
53 creationTokens.insert(token)
54 return NativeResponse(data: Data(#"{"sqid":"doc","title":"Document"}"#.utf8), status: 201, headers: [:])
55 }
56 if method == "POST", path.hasSuffix("/title"), let body {
57 titleRequests += 1
58 if titleDelay { try await Task.sleep(for: .milliseconds(200)) }
59 if titleFailures > 0 { titleFailures -= 1; throw NativeClientError.server(status: 503) }
60 title = URLComponents(string: "?" + String(decoding: body, as: UTF8.self))?.queryItems?.first(where: { $0.name == "title" })?.value ?? ""
61 return NativeResponse(data: Data(), status: 200, headers: [:])
62 }
63 if path.hasPrefix("/?") {
64 return NativeResponse(data: Data(#"{"documents":[],"can_create":true}"#.utf8), status: 200, headers: [:])
65 }
66 if method == "POST", path.hasSuffix("/updates"), let body {
67 updateRequests += 1
68 if updateDelay { try await Task.sleep(for: .milliseconds(300)) }
69 _ = try await replica.apply(body); sequence += 1
70 rows[sequence] = body
71 for listener in listeners.values { listener.yield(sequence) }
72 if loseNextResponse { loseNextResponse = false; throw NativeClientError.offline(.networkConnectionLost) }
73 return NativeResponse(data: Data(), status: 204, headers: [:])
74 }
75 if path.contains("/updates") {
76 let since = URLComponents(string: path)?.queryItems?.first(where: { $0.name == "since" })?.value.flatMap(Int64.init) ?? 0
77 // Docs-Seq from the rows in hand, before any await (see the same
78 // note in RealtimeSyncTests' SequencedServer).
79 let data: Data, highest: Int64
80 if since > 0 {
81 let kept = rows.keys.sorted().filter { $0 > since }
82 highest = kept.last ?? since
83 let updates = kept.compactMap { rows[$0] }
84 data = updates.isEmpty ? Data() : try await replica.mergeUpdates(updates)
85 } else {
86 fullDownloadAttempts += 1
87 if failingFullDownloads > 0 { failingFullDownloads -= 1; throw NativeClientError.server(status: 503) }
88 highest = sequence
89 fullDownloads += 1; data = try await snapshot()
90 }
91 return NativeResponse(data: data, status: 200, headers: ["Docs-Seq": String(highest)])
92 }
93 let detail = DocumentDetail(sqid: "doc", title: title, guid: "offline-property", can_write: true, can_share: false)
94 return NativeResponse(data: try JSONEncoder().encode(detail), status: 200, headers: [:])
95 }
96 func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws {
97 guard online else { throw NativeClientError.offline(.notConnectedToInternet) }
98 let id = UUID(), events = AsyncStream<Int64>.makeStream(bufferingPolicy: .bufferingNewest(1))
99 listeners[id] = events.continuation
100 defer { listeners.removeValue(forKey: id) }
101 try await onOpen(); try await onLine("data: \(sequence)")
102 for await sequence in events.stream { try Task.checkCancellation(); try await onLine("data: \(sequence)") }
103 }
104 func download(_ path: String, to destination: URL) async throws { throw NativeClientError.notFound }
105
106 func contains(_ id: UUID) -> Bool { accepted[id] != nil }
107}
108private final class MetadataLockStore: BlobStore, @unchecked Sendable {
109 let base = MemoryBlobStore()
110 private let lock = NSLock()
111 private var locked = true
112 func unlock() { lock.withLock { locked = false } }
113 func read(_ path: String) throws -> Data? { try base.read(path) }
114 func list(_ path: String) throws -> [String] { try base.list(path) }
115 func remove(_ path: String) throws { try base.remove(path) }
116 func write(_ bytes: Data, to path: String) throws {
117 if path.hasSuffix("/meta"), lock.withLock({ locked }) { throw BlobStoreError.unavailable }
118 try base.write(bytes, to: path)
119 }
120}
121private struct OfflineRandom: RandomNumberGenerator {
122 var seed: UInt64
123 mutating func next() -> UInt64 { seed = seed &* 6364136223846793005 &+ 1442695040888963407; return seed }
124}
125@MainActor final class OfflineDurabilityTests: XCTestCase {
126 /// Every file the replica of `key` is stored in (base and segments).
127 private func replicaFiles(_ store: MemoryBlobStore, _ key: String = "doc") -> [String: Data] {
128 store.contents.filter { $0.key == DocsReplicaCache.basePath(key) || $0.key.hasPrefix(DocsReplicaCache.logPath(key) + "/") }
129 }
130 /// The stored replica's text: its base and every segment.
131 private func storedText(_ store: BlobStore, _ key: String = "doc") async throws -> String? {
132 guard let stored = try DocsReplicaCache(store: store).load(key) else { return nil }
133 let replica = CRDTReplica(guid: stored.replica.guid)
134 try await replica.open(update: stored.replica.state)
135 for segment in stored.segments { try await replica.apply(segment.update) }
136 let text = try await replica.projection().children.map(\.plainText).joined()
137 await replica.close()
138 return text
139 }
140 private func initial() async throws -> Data {
141 let seed = CRDTReplica(guid: "offline-property")
142 _ = try await seed.open(update: Data())
143 let update = try await seed.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")])
144 await seed.close(); return update
145 }
146 private func edit(_ replica: CRDTReplica, _ text: String) async throws -> Data {
147 let projection = try await replica.projection()
148 let at = projection.children.map(\.plainText).joined().utf16.count
149 return try await replica.command(["op": .string("display_edit"), "at": .number(Double(at)), "length": .number(0), "text": .string(text)])
150 }
151 func testMissingOrCorruptMetadataHoldsOnlyItsLane() async throws {
152 for damage in 0..<3 {
153 let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
154 defer { try? FileManager.default.removeItem(at: root) }
155 let disk = NativeSealedStore(root: root, accountID: "a", keys: ScriptedKeyProvider())
156 let connectivity = NativeConnectivity(source: ScriptedPathSource(.satisfied))
157 while !connectivity.isPathSatisfied { await Task.yield() }
158 let transport = ScriptedTransport([])
159 let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: connectivity, transport: { transport })
160 if damage > 0 { try disk.write(Data("invalid metadata".utf8), to: "cache/docs/a/meta") }
161 if damage == 2 { try Data([0]).write(to: root.appendingPathComponent("cache/docs/a/meta")) }
162 try await account.outbox.enqueue(lane: "doc:a", kind: "metadata", payload: Data())
163 let detail = DocumentDetail(sqid: "b", title: "B", guid: "b", can_write: true, can_share: false)
164 try account.saveMetadata(DocsOfflineMetadata(detail: detail), key: "b")
165 try await account.outbox.enqueue(lane: "doc:b", kind: "metadata", payload: Data())
166 await account.drainer.drain()
167 let broken = await account.outbox.entries(lane: "doc:a")
168 let good = await account.outbox.entries(lane: "doc:b")
169 XCTAssertEqual(broken.first?.hold, Hold(.rejected("metadata")))
170 XCTAssertTrue(good.isEmpty, "Missing metadata must not block another document")
171 }
172 }
173
174 func testHeldMetadataMarkerDoesNotMultiplyOnFlush() async throws {
175 let account = DocsOfflineAccount(store: MemoryBlobStore(), accountID: "a", connectivity: NativeConnectivity(source: ScriptedPathSource(.unsatisfied)), transport: { ScriptedTransport([]) })
176 let detail = DocumentDetail(sqid: "doc", title: "Title", guid: "doc", can_write: true, can_share: false)
177 try account.saveMetadata(DocsOfflineMetadata(detail: detail, pendingTitle: "Rename"), key: "doc")
178 try await account.ensureMetadataEntry("doc")
179 let original = await account.outbox.entries(lane: "doc:doc")
180 try await account.outbox.hold(original.map(\.id), Hold(.accessLost))
181 for _ in 0..<4 { try await account.ensureMetadataEntry("doc") }
182 let entries = await account.outbox.entries(lane: "doc:doc")
183 XCTAssertEqual(entries.map(\.id), original.map(\.id))
184 }
185
186 func testDurableOfflineLaneUsesSyncStatusWithoutAnErrorMessage() async throws {
187 let server = IntegratingServer(); try await server.open(initial())
188 let path = ScriptedPathSource(.satisfied)
189 let connectivity = NativeConnectivity(source: path)
190 let account = DocsOfflineAccount(store: MemoryBlobStore(), accountID: "a", connectivity: connectivity, transport: { server })
191 let model = DocsModel(transport: { server }, connectivity: connectivity, offlineAccount: account)
192 await model.open("doc"); _ = await model.saveAll()
193 path.send(.unsatisfied)
194 while connectivity.isPathSatisfied { await Task.yield() }
195 model.didRender(model.projectionGeneration)
196 XCTAssertTrue(model.enqueue(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("Offline")]))
197 while model.hasPendingInput { await Task.yield() }
198 await model.flush()
199 XCTAssertNil(model.errorKey, "A durable pending lane does not require keeping this window open")
200 XCTAssertEqual(model.syncStatus, .offline(pending: 1))
201 await model.stop(); account.drainer.stop()
202 }
203
204 func testWriterBetweenCommandAndEnqueueCannotPersistTheCommand() async throws {
205 let disk = MemoryBlobStore(), initial = try await initial()
206 let replica = CRDTReplica(guid: "offline-property")
207 let lane = DocsPersistence(store: disk, outbox: Outbox(store: disk, account: "a"), key: "doc", replica: replica)
208 try await lane.reopen(fallback: initial, sequence: 17)
209 let wroteInitial = try await lane.persist()
210 XCTAssertTrue(wroteInitial)
211 let before = replicaFiles(disk)
212 let update = try await edit(replica, "A")
213 let premature = try await lane.persist()
214 XCTAssertFalse(premature, "I1a: command returned, but enqueue has not")
215 XCTAssertEqual(replicaFiles(disk), before)
216 try await lane.enqueue(update)
217 let wrote = try await lane.persist()
218 XCTAssertTrue(wrote)
219 let stored = try XCTUnwrap(DocsReplicaCache(store: disk).load("doc"))
220 XCTAssertEqual(stored.sequence, 17)
221 XCTAssertEqual(stored.segments.count, 1, "The edit is appended, not a rewrite of the replica")
222 let text = try await storedText(disk)
223 XCTAssertEqual(text, "A")
224 }
225 /// A text typed in a paragraph, as two updates: the second parks without
226 /// the first. Stands in for a replica or a server holding a parked update.
227 private func parkedReplica() async throws -> (paragraph: Data, typed: Data) {
228 let writer = CRDTReplica(guid: "offline-property")
229 _ = try await writer.open(update: Data())
230 let paragraph = try await writer.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")])
231 let typed = try await edit(writer, "Kept")
232 await writer.close()
233 return (paragraph, typed)
234 }
235 private func storeReplica(_ disk: BlobStore, account: DocsOfflineAccount, state: Data, sequence: Int64, parked: String? = nil) throws {
236 try account.saveMetadata(DocsOfflineMetadata(detail: DocumentDetail(sqid: "doc", title: "Document", guid: "offline-property", can_write: true, can_share: false)), key: "doc")
237 try disk.write(JSONEncoder().encode(PersistedReplica(format: 1, sequence: sequence, guid: "offline-property", savedAt: Date(), state: state, parked: parked)), to: "cache/docs/doc/replica")
238 }
239 private func stored(_ disk: BlobStore) throws -> PersistedReplica {
240 try JSONDecoder().decode(PersistedReplica.self, from: XCTUnwrap(disk.read("cache/docs/doc/replica")))
241 }
242 /// Opens the document, waits until it shows `text` and its replica has
243 /// no unaccepted parking, persists, and stops.
244 @discardableResult private func openUntilSettled(_ server: IntegratingServer, _ account: DocsOfflineAccount, _ network: NativeConnectivity, shows text: String) async throws -> CRDTProjection? {
245 let model = DocsModel(transport: { server }, connectivity: network, offlineAccount: account)
246 await model.open("doc")
247 let deadline = ContinuousClock.now.advanced(by: .seconds(5))
248 func settled() -> Bool { model.projection?.children.map(\.plainText).joined() == text && !model.unsettledParking }
249 while !settled() && .now < deadline { try await Task.sleep(for: .milliseconds(10)) }
250 let done = settled()
251 XCTAssertTrue(done, "the document never settled showing \(text)")
252 await model.persistReplica()
253 let shown = model.projection
254 await model.stop(); account.drainer.stop()
255 return shown
256 }
257 /// #145: a stored state that parks what it depends on, with a sequence
258 /// saying the server has nothing newer, catches up from the start once.
259 func testAStoredReplicaThatParksCatchesUpFromTheStartOnceAndStaysSettled() async throws {
260 let (paragraph, typed) = try await parkedReplica()
261 let server = IntegratingServer(); try await server.open(paragraph)
262 _ = try await server.responseDetails("/d/doc/updates", method: "POST", body: typed, contentType: "application/octet-stream", maxBytes: 1 << 20)
263 let disk = MemoryBlobStore()
264 let network = NativeConnectivity(source: ScriptedPathSource(.satisfied))
265 let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: network, transport: { server })
266 try storeReplica(disk, account: account, state: typed, sequence: 1)
267 let shown = try await openUntilSettled(server, account, network, shows: "Kept")
268 XCTAssertEqual(shown?.children.count, 1, "no first paragraph is added to an unsettled replica")
269 var downloads = await server.fullDownloadCount()
270 XCTAssertEqual(downloads, 1)
271 XCTAssertEqual(try stored(disk).sequence, 1)
272 try await openUntilSettled(server, account, network, shows: "Kept")
273 downloads = await server.fullDownloadCount()
274 XCTAssertEqual(downloads, 1, "a settled replica does not download the document again")
275 let serverText = try await server.text()
276 XCTAssertEqual(serverText, "Kept")
277 }
278 /// #147 finding 1: real damaged snapshots (native/crdt/tests/fixtures). The
279 /// server's state alone leaves most of them parking the damaged duplicate;
280 /// settling rebuilds the replica, so one download heals each for good.
281 func testRealDamagedSnapshotsHealWithOneDownload() async throws {
282 let directory = URL(fileURLWithPath: #filePath).deletingLastPathComponent()
283 .appendingPathComponent("../../../crdt/tests/fixtures/damaged-snapshots").standardized
284 let names = try FileManager.default.contentsOfDirectory(atPath: directory.path).filter { $0.hasPrefix("damaged-") }.sorted()
285 XCTAssertEqual(names.count, 29)
286 for name in names {
287 let damaged = try Data(contentsOf: directory.appendingPathComponent(name))
288 let good = try Data(contentsOf: directory.appendingPathComponent(name.replacingOccurrences(of: "damaged", with: "good")))
289 let server = IntegratingServer(); try await server.open(good); await server.advance(to: 5)
290 let expected = try await server.text()
291 let disk = MemoryBlobStore()
292 let network = NativeConnectivity(source: ScriptedPathSource(.satisfied))
293 let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: network, transport: { server })
294 try storeReplica(disk, account: account, state: damaged, sequence: 5)
295 try await openUntilSettled(server, account, network, shows: expected)
296 try await openUntilSettled(server, account, network, shows: expected)
297 let downloads = await server.fullDownloadCount()
298 XCTAssertEqual(downloads, 1, "\(name): downloads")
299 let record = try stored(disk)
300 XCTAssertEqual(record.sequence, 5, name)
301 // Accepted is only what the server itself parks, not the damage.
302 let serverParked = try await server.parked()
303 XCTAssertEqual(record.parked ?? "", serverParked, name)
304 let reopened = CRDTReplica(guid: "offline-property")
305 _ = try await reopened.open(update: record.state)
306 await reopened.acceptParking(record.parked ?? "")
307 let unsettled = try await reopened.hasUnacceptedParking()
308 XCTAssertFalse(unsettled, "\(name): the stored record parks the damage")
309 await reopened.close()
310 }
311 }
312 /// #147 re-review: typing before the replica settles. Each edit's update
313 /// carries the edit only, not the damaged duplicate the replica parks, so
314 /// the server never parks it and one download still heals.
315 func testTypingOnADamagedReplicaPostsOnlyTheEdit() async throws {
316 let directory = URL(fileURLWithPath: #filePath).deletingLastPathComponent()
317 .appendingPathComponent("../../../crdt/tests/fixtures/damaged-snapshots").standardized
318 let names = try FileManager.default.contentsOfDirectory(atPath: directory.path).filter { $0.hasPrefix("damaged-") }.sorted()
319 for name in names {
320 let damaged = try Data(contentsOf: directory.appendingPathComponent(name))
321 let good = try Data(contentsOf: directory.appendingPathComponent(name.replacingOccurrences(of: "damaged", with: "good")))
322 let server = IntegratingServer(); try await server.open(good); await server.advance(to: 5)
323 let serverParked = try await server.parked()
324 let disk = MemoryBlobStore()
325 let network = NativeConnectivity(source: ScriptedPathSource(.satisfied))
326 let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: network, transport: { server })
327 try storeReplica(disk, account: account, state: damaged, sequence: 5)
328 let model = DocsModel(transport: { server }, connectivity: network, offlineAccount: account)
329 await model.open("doc")
330 XCTAssertTrue(model.enqueue(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("LOCAL")]), name)
331 let deadline = ContinuousClock.now.advanced(by: .seconds(5))
332 func done() async throws -> Bool {
333 let serverText = try await server.text()
334 return !model.unsettledParking && !model.hasUnsavedChanges && serverText.contains("LOCAL")
335 && model.projection?.children.map(\.plainText).joined() == serverText
336 }
337 while try await !done() && .now < deadline { try await Task.sleep(for: .milliseconds(10)) }
338 let finished = try await done()
339 XCTAssertTrue(finished, "\(name): never settled with the edit sent")
340 let parkedNow = try await server.parked()
341 XCTAssertEqual(parkedNow, serverParked, "\(name): the server parks what an edit carried")
342 let downloads = await server.fullDownloadCount()
343 XCTAssertEqual(downloads, 1, name)
344 await model.stop(); account.drainer.stop()
345 }
346 }
347 /// #147 finding 2: when the server itself holds a parked update, every
348 /// replica parks it too. Accepted after one catch-up from the start, it
349 /// does not make every later open download the document again.
350 func testParkingTheServerHoldsIsAcceptedOnce() async throws {
351 let (_, typed) = try await parkedReplica()
352 let server = IntegratingServer(); try await server.open(Data())
353 _ = try await server.responseDetails("/d/doc/updates", method: "POST", body: typed, contentType: "application/octet-stream", maxBytes: 1 << 20)
354 let serverState = try await server.snapshot()
355 let disk = MemoryBlobStore()
356 let network = NativeConnectivity(source: ScriptedPathSource(.satisfied))
357 let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: network, transport: { server })
358 // A record written before #147, holding the server's state: nothing accepted yet.
359 try storeReplica(disk, account: account, state: serverState, sequence: 1)
360 for _ in 0..<3 { try await openUntilSettled(server, account, network, shows: "") }
361 let downloads = await server.fullDownloadCount()
362 XCTAssertEqual(downloads, 1)
363 XCTAssertFalse(try stored(disk).parked?.isEmpty ?? true)
364 // Opened with no record, from the server's state: accepted at once.
365 try disk.remove("cache/docs/doc/replica")
366 for _ in 0..<2 { try await openUntilSettled(server, account, network, shows: "") }
367 let later = await server.fullDownloadCount()
368 XCTAssertEqual(later, 2, "only the first open without a record downloads")
369 }
370 /// #147 re-review finding 3: a headless send that writes the document's
371 /// first record stores the server's state and accepts what it parks, as a
372 /// first open does, so the next open does not download it again.
373 func testAHeadlessSendWritingTheFirstRecordAcceptsTheServersParking() async throws {
374 let (_, typed) = try await parkedReplica()
375 let server = IntegratingServer(); try await server.open(Data())
376 _ = try await server.responseDetails("/d/doc/updates", method: "POST", body: typed, contentType: "application/octet-stream", maxBytes: 1 << 20)
377 let serverParked = try await server.parked()
378 XCTAssertFalse(serverParked.isEmpty)
379 let disk = MemoryBlobStore()
380 let network = NativeConnectivity(source: ScriptedPathSource(.satisfied))
381 while !network.isPathSatisfied { await Task.yield() }
382 let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: network, transport: { server })
383 try account.saveMetadata(DocsOfflineMetadata(detail: DocumentDetail(sqid: "doc", title: "Document", guid: "offline-property", can_write: true, can_share: false)), key: "doc")
384 let (other, _) = try await parkedReplica()
385 _ = try await account.outbox.enqueue(lane: "doc:doc", kind: "update", payload: other)
386 await account.drainer.drain()
387 let record = try stored(disk)
388 XCTAssertEqual(record.parked, serverParked)
389 try await openUntilSettled(server, account, network, shows: "")
390 let downloads = await server.fullDownloadCount()
391 XCTAssertEqual(downloads, 1, "only the headless send's first record downloads")
392 }
393 /// #147 re-review finding 4: accepted parking is compared as sets of id
394 /// ranges, so part of it integrating later leaves the rest accepted.
395 func testAcceptedParkingIsComparedByContainment() {
396 XCTAssertTrue(CRDTReplica.parking("", within: ""))
397 XCTAssertTrue(CRDTReplica.parking("7 3-5;", within: "7 0-10;9 0-2;"))
398 XCTAssertTrue(CRDTReplica.parking("7 3-5;|8 1-2;", within: "7 0-4 4-10;|8 0-3;"))
399 XCTAssertFalse(CRDTReplica.parking("7 3-12;", within: "7 0-10;"))
400 XCTAssertFalse(CRDTReplica.parking("9 0-1;", within: "7 0-10;"))
401 XCTAssertFalse(CRDTReplica.parking("|7 3-5;", within: "7 0-10;"), "a parked deletion is not a parked struct")
402 XCTAssertFalse(CRDTReplica.parking("7 0-1;", within: ""))
403 }
404 /// #147 re-review: a failed catch-up from the start is retried after the
405 /// backoff rows that would not apply get, not left to the next event.
406 func testAFailedCatchUpFromTheStartRetriesAfterABackoff() async throws {
407 let (paragraph, typed) = try await parkedReplica()
408 let server = IntegratingServer(); try await server.open(paragraph)
409 _ = try await server.responseDetails("/d/doc/updates", method: "POST", body: typed, contentType: "application/octet-stream", maxBytes: 1 << 20)
410 await server.failFullDownloads(1)
411 let disk = MemoryBlobStore()
412 let network = NativeConnectivity(source: ScriptedPathSource(.satisfied))
413 let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: network, transport: { server })
414 try storeReplica(disk, account: account, state: typed, sequence: 1)
415 let started = ContinuousClock.now
416 try await openUntilSettled(server, account, network, shows: "Kept")
417 let attempts = await server.fullDownloadAttemptCount()
418 XCTAssertEqual(attempts, 2)
419 XCTAssertGreaterThanOrEqual(ContinuousClock.now - started, .seconds(2), "retried before the backoff")
420 }
421 /// #147 finding 5: a headless send's merge can leave the record parking a
422 /// sent update typed against a change the record lacks. Its sequence is
423 /// kept; the next open's ordinary catch-up supplies the change.
424 func testAMergeThatParksKeepsTheSequence() async throws {
425 let (paragraph, typed) = try await parkedReplica()
426 let disk = MemoryBlobStore(), cache = DocsReplicaCache(store: disk)
427 try await cache.commit(PersistedReplica(format: 1, sequence: 9, guid: "offline-property", savedAt: Date(), state: typed), key: "doc", generation: 0)
428 XCTAssertEqual(try stored(disk).sequence, 9)
429 try await cache.commit(PersistedReplica(format: 1, sequence: 0, guid: "offline-property", savedAt: Date(), state: paragraph), key: "doc", generation: 0)
430 XCTAssertEqual(try stored(disk).sequence, 9)
431 }
432 func testReopenAppliesTheWholeLaneBeforePublishingAndDoesNotDuplicate() async throws {
433 let disk = MemoryBlobStore(), initial = try await initial()
434 let outbox = Outbox(store: disk, account: "a"), replica = CRDTReplica(guid: "offline-property")
435 let lane = DocsPersistence(store: disk, outbox: outbox, key: "draft-token", replica: replica)
436 try await lane.reopen(fallback: initial, sequence: 0)
437 try await lane.enqueue(edit(replica, "A"))
438 _ = try await lane.persist()
439 try await lane.enqueue(edit(replica, "B"))
440 for _ in 0..<2 {
441 let reopened = CRDTReplica(guid: "offline-property")
442 let next = DocsPersistence(store: disk, outbox: Outbox(store: disk, account: "a"), key: "draft-token", replica: reopened)
443 try await next.reopen(fallback: Data(), sequence: 0)
444 let text = try await reopened.projection().children.map(\.plainText).joined()
445 XCTAssertEqual(text, "AB", "I1b: replica contains A; lane contains A and B")
446 }
447 try await lane.discard()
448 XCTAssertTrue(replicaFiles(disk, "draft-token").isEmpty, "Discard cannot leave stranded local text in the replica")
449 let entries = await outbox.entries(lane: lane.lane)
450 XCTAssertTrue(entries.isEmpty)
451 }
452 /// Deterministic generated histories, plus an exhaustive crash sweep at
453 /// replacement's write and every delete. Every assertion reads committed
454 /// bytes through a fresh outbox/replica, not the live writer's memory.
455 func testGeneratedCrashHistoriesPreserveI1AndConverge() async throws {
456 let initial = try await initial()
457 for seed in 1...12 {
458 var random = OfflineRandom(seed: UInt64(seed))
459 var disk = FaultingBlobStore()
460 var outbox = Outbox(store: disk, account: "a")
461 var replica = CRDTReplica(guid: "offline-property")
462 var lane = DocsPersistence(store: disk, outbox: outbox, key: "doc", replica: replica)
463 try await lane.reopen(fallback: initial, sequence: 0)
464 let server = IntegratingServer(); try await server.open(initial)
465 var durableText = ""
466 var flying: [OutboxEntry] = []
467 var symbol = 0
468 for step in 0..<60 {
469 if step % 4 == 0 { disk.crash(after: Int.random(in: 0...10, using: &random)) }
470 do {
471 switch Int.random(in: 0..<8, using: &random) {
472 case 0, 1:
473 symbol += 1
474 let text = "[\(symbol)]"
475 let update = try await edit(replica, text)
476 let premature = try await lane.persist()
477 XCTAssertFalse(premature, "Writer tick between command and enqueue")
478 try await lane.enqueue(update); durableText += text
479 case 2: _ = try await lane.persist()
480 case 3, 4:
481 if flying.isEmpty { flying = try await outbox.beginSend(lane: lane.lane, maxBytes: 80) }
482 try await server.accept(flying)
483 if step % 2 == 0 {
484 for entry in flying { let has = await server.contains(entry.id); XCTAssertTrue(has) }
485 try await outbox.ack(flying.map(\.id))
486 } // otherwise the response is lost: server has it; disk keeps it
487 await outbox.endSend(flying.map(\.id)); flying = []
488 case 5:
489 let entries = await outbox.entries(lane: lane.lane)
490 if entries.count >= 2 {
491 if step % 2 == 0 {
492 flying = try await outbox.beginSend(lane: lane.lane, maxBytes: 1)
493 do { try await outbox.replace(entries.map(\.id), with: replica.mergeUpdates(entries.map(\.payload))); XCTFail("In-flight replacement must throw") }
494 catch OutboxError.inFlight {}
495 await outbox.endSend(flying.map(\.id)); flying = []
496 } else { try await lane.compact() }
497 }
498 case 6:
499 // A crash before any subsequent store op, including a
500 // writer tick or replacement's first/second step.
501 disk.crash(after: Int.random(in: 0...2, using: &random))
502 let entries = await outbox.entries(lane: lane.lane)
503 if entries.count >= 2 { try await outbox.replace(entries.map(\.id), with: replica.mergeUpdates(entries.map(\.payload))) }
504 else { _ = try await lane.persist() }
505 default:
506 for entry in try await outbox.beginSend(lane: lane.lane, maxBytes: nil) {
507 try await server.accept([entry]); try await outbox.ack([entry.id])
508 }
509 }
510 } catch is SimulatedCrash { }
511 // Reopen after *every* event. This simultaneously checks the
512 // missing-lane and duplicate-text cases at each crash boundary.
513 let frozen = disk.committed
514 let checked = CRDTReplica(guid: "offline-property")
515 let checkLane = DocsPersistence(store: frozen, outbox: Outbox(store: frozen, account: "a"), key: "doc", replica: checked)
516 try await checkLane.reopen(fallback: server.snapshot(), sequence: 0)
517 // Catch up with already acknowledged edits if the replica writer
518 // lagged behind ack; real reopen performs the same server catch-up.
519 _ = try await checked.apply(server.snapshot())
520 let recovered = try await checked.projection().children.map(\.plainText).joined()
521 XCTAssertEqual(recovered, durableText, "seed \(seed), event \(step): I1b / no duplicates")
522 if let stored = try DocsReplicaCache(store: frozen).load("doc") {
523 let proof = CRDTReplica(guid: "offline-property")
524 _ = try await proof.open(update: server.snapshot())
525 for entry in await Outbox(store: frozen, account: "a").entries(lane: lane.lane) { _ = try await proof.apply(entry.payload) }
526 let prior = try await proof.projection().children.map(\.plainText)
527 _ = try await proof.apply(stored.replica.state)
528 for segment in stored.segments { try await proof.apply(segment.update) }
529 let after = try await proof.projection().children.map(\.plainText)
530 XCTAssertEqual(prior, after, "I1a: replica contains no stranded local edit")
531 await proof.close()
532 }
533 await checked.close()
534 if disk.hasCrashed {
535 await replica.close()
536 disk = FaultingBlobStore(frozen); outbox = Outbox(store: disk, account: "a")
537 replica = CRDTReplica(guid: "offline-property")
538 lane = DocsPersistence(store: disk, outbox: outbox, key: "doc", replica: replica)
539 try await lane.reopen(fallback: server.snapshot(), sequence: 0)
540 _ = try await replica.apply(server.snapshot())
541 flying = []
542 }
543 }
544 // Reconnect and fully drain, with the real integrating replica.
545 let recovered = Outbox(store: disk.committed, account: "a")
546 let entries = await recovered.entries(lane: lane.lane)
547 try await server.accept(entries); try await recovered.ack(entries.map(\.id))
548 let text = try await server.text()
549 XCTAssertEqual(text, durableText, "seed \(seed): convergence after drain")
550 await replica.close()
551 }
552 }
553 func testEveryReplaceCrashBoundaryReopensWithoutLossOrDuplicateText() async throws {
554 let initial = try await initial()
555 let base = MemoryBlobStore(), source = CRDTReplica(guid: "offline-property")
556 let setup = DocsPersistence(store: base, outbox: Outbox(store: base, account: "a"), key: "doc", replica: source)
557 try await setup.reopen(fallback: initial, sequence: 0)
558 _ = try await setup.persist()
559 for text in ["A", "B", "C"] { try await setup.enqueue(edit(source, text)) }
560 for crashAfter in 0...3 {
561 let disk = FaultingBlobStore(MemoryBlobStore(base.contents))
562 let outbox = Outbox(store: disk, account: "a")
563 try await outbox.load()
564 let entries = await outbox.entries(lane: "doc:doc")
565 let merged = try await source.mergeUpdates(entries.map(\.payload))
566 disk.crash(after: crashAfter)
567 do { try await outbox.replace(entries.map(\.id), with: merged) }
568 catch is SimulatedCrash { }
569 let rebuilt = CRDTReplica(guid: "offline-property")
570 let frozen = disk.committed
571 let recovered = DocsPersistence(store: frozen, outbox: Outbox(store: frozen, account: "a"), key: "doc", replica: rebuilt)
572 try await recovered.reopen(fallback: Data(), sequence: 0)
573 let text = try await rebuilt.projection().children.map(\.plainText).joined()
574 XCTAssertEqual(text, "ABC", "Crash at replace operation \(crashAfter)")
575 await rebuilt.close()
576 }
577 await source.close()
578 }
579
580 func testModelReopensOfflineAndDrainsToIntegratingTransport() async throws {
581 let server = IntegratingServer(); try await server.open(initial())
582 let disk = FaultingBlobStore()
583 let connectivity = NativeConnectivity(source: ScriptedPathSource(.satisfied))
584 let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: connectivity, transport: { server })
585 let model = DocsModel(transport: { server }, connectivity: connectivity, offlineAccount: account)
586 await model.open("doc")
587 XCTAssertNotNil(model.projection)
588 await server.setOnline(false)
589 model.didRender(model.projectionGeneration)
590 XCTAssertTrue(model.enqueue(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("Offline edit")]))
591 while model.hasPendingInput { try await Task.sleep(for: .milliseconds(5)) }
592 XCTAssertTrue(model.hasUnsentChanges)
593 // Kill before the two-second writer. Freeze this process's store so
594 // its tasks cannot mutate the new process's committed view.
595 account.drainer.stop(); disk.crash(after: 0)
596 let frozen = disk.committed
597 let nextAccount = DocsOfflineAccount(store: frozen, accountID: "a", connectivity: connectivity, transport: { server })
598 let reopened = DocsModel(transport: { server }, connectivity: connectivity, offlineAccount: nextAccount)
599 await reopened.open("doc")
600 XCTAssertEqual(reopened.projection?.children.map(\.plainText).joined(), "Offline edit")
601 await server.setOnline(true)
602 await reopened.retry()
603 let deadline = ContinuousClock.now.advanced(by: .seconds(3))
604 while reopened.hasUnsavedChanges && .now < deadline { await reopened.flush(); try await Task.sleep(for: .milliseconds(10)) }
605 XCTAssertFalse(reopened.hasUnsavedChanges)
606 let text = try await server.text()
607 XCTAssertEqual(text, "Offline edit")
608 await reopened.stop(); nextAccount.drainer.stop()
609 }
610
611 func testUnlockRetriesFailedUpdateAndResumesAlreadyQueuedCommands() async throws {
612 let server = IntegratingServer(); try await server.open(initial())
613 let disk = FaultingBlobStore()
614 let connectivity = NativeConnectivity(source: ScriptedPathSource(.satisfied))
615 let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: connectivity, transport: { server })
616 let model = DocsModel(transport: { server }, connectivity: connectivity, offlineAccount: account)
617 await model.open("doc")
618 await server.setOnline(false)
619 disk.unavailable = true
620 for text in ["A", "B"] {
621 XCTAssertTrue(model.enqueue(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string(text)]))
622 }
623 let deadline = ContinuousClock.now.advanced(by: .seconds(2))
624 while !model.inputPaused && .now < deadline { try await Task.sleep(for: .milliseconds(5)) }
625 XCTAssertTrue(model.inputPaused)
626 disk.unavailable = false
627 await model.retry()
628 let resumed = ContinuousClock.now.advanced(by: .seconds(2))
629 while model.hasPendingInput && .now < resumed { try await Task.sleep(for: .milliseconds(5)) }
630 XCTAssertFalse(model.hasPendingInput, "Retry must resume the queued second command")
631 XCTAssertEqual(model.projection?.children.map(\.plainText).joined(), "BA")
632 await model.persistReplica()
633 XCTAssertFalse(model.hasUnpersistedInput)
634 await model.discardAll(); account.drainer.stop()
635 }
636
637 func testDurableTitleSurvivesReopenBeforeFirstReplicaWrite() async throws {
638 let server = IntegratingServer(); try await server.open(initial())
639 let disk = MemoryBlobStore()
640 let path = ScriptedPathSource(.unsatisfied)
641 let network = NativeConnectivity(source: path)
642 let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: network, transport: { server })
643 let detail = DocumentDetail(sqid: "doc", title: "Local title", guid: "offline-property", can_write: true, can_share: false)
644 try account.saveMetadata(DocsOfflineMetadata(detail: detail, pendingTitle: "Local title"), key: "doc")
645 let reopened = DocsModel(transport: { server }, connectivity: network, offlineAccount: account)
646 await reopened.open("doc")
647 XCTAssertEqual(reopened.detail?.title, "Local title")
648 XCTAssertEqual(try account.metadata("doc")?.pendingTitle, "Local title")
649 await reopened.discardAll(); account.drainer.stop()
650 }
651
652 func testTitleOnlyTransientFailureRetriesWithoutAnotherEdit() async throws {
653 let server = IntegratingServer(); try await server.open(initial())
654 let network = NativeConnectivity(source: ScriptedPathSource(.satisfied))
655 let account = DocsOfflineAccount(store: MemoryBlobStore(), accountID: "a", connectivity: network, transport: { server })
656 let model = DocsModel(transport: { server }, connectivity: network, offlineAccount: account)
657 await model.open("doc")
658 try await Task.sleep(for: .milliseconds(100))
659 await server.failTitles(1)
660 XCTAssertTrue(model.rename("Retry title"))
661 let deadline = ContinuousClock.now.advanced(by: .seconds(3))
662 while await server.savedTitle() != "Retry title", .now < deadline { try await Task.sleep(for: .milliseconds(10)) }
663 let title = await server.savedTitle()
664 XCTAssertEqual(title, "Retry title")
665 await model.discardAll(); account.drainer.stop()
666 }
667
668 func testHomeOnlyReplayPreservesAcknowledgedTextForOfflineReopen() async throws {
669 let seed = try await initial(), disk = MemoryBlobStore()
670 let server = IntegratingServer(); try await server.open(seed)
671 let network = NativeConnectivity(source: ScriptedPathSource(.satisfied))
672 let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: network, transport: { server })
673 let detail = DocumentDetail(sqid: "doc", title: "Document", guid: "offline-property", can_write: true, can_share: false)
674 try account.saveMetadata(DocsOfflineMetadata(detail: detail), key: "doc")
675 let replica = CRDTReplica(guid: detail.guid)
676 let lane = DocsPersistence(store: disk, outbox: account.outbox, key: "doc", replica: replica)
677 try await lane.reopen(fallback: seed, sequence: 0)
678 _ = try await lane.persist()
679 try await lane.enqueue(edit(replica, "Home replay"))
680 await replica.close()
681 // Home loads the list; it never opens the document's editor.
682 let home = DocsModel(transport: { server }, connectivity: network, offlineAccount: account)
683 await home.load()
684 let deadline = ContinuousClock.now.advanced(by: .seconds(3))
685 while !(await account.outbox.summary).isEmpty, .now < deadline { try await Task.sleep(for: .milliseconds(10)) }
686 let serverText = try await server.text()
687 XCTAssertEqual(serverText, "Home replay")
688 let summary = await account.outbox.summary
689 XCTAssertTrue(summary.isEmpty)
690 account.drainer.stop(); await server.setOnline(false)
691 let next = DocsOfflineAccount(store: disk, accountID: "a", connectivity: NativeConnectivity(source: ScriptedPathSource(.unsatisfied)), transport: { server })
692 let reopened = DocsModel(transport: { server }, offlineAccount: next)
693 await reopened.open("doc")
694 XCTAssertEqual(reopened.projection?.children.map(\.plainText).joined(), "Home replay")
695 await reopened.discardAll(); next.drainer.stop()
696 }
697
698 func testRenameDuringTitleRequestSendsTheLatestTitle() async throws {
699 let server = IntegratingServer(); try await server.open(initial())
700 let network = NativeConnectivity(source: ScriptedPathSource(.satisfied))
701 let account = DocsOfflineAccount(store: MemoryBlobStore(), accountID: "a", connectivity: network, transport: { server })
702 let model = DocsModel(transport: { server }, connectivity: network, offlineAccount: account)
703 await model.open("doc")
704 try await Task.sleep(for: .milliseconds(100))
705 await server.delayTitles()
706 XCTAssertTrue(model.rename("First"))
707 let started = ContinuousClock.now.advanced(by: .seconds(2))
708 while await server.titleRequestCount() == 0, .now < started { try await Task.sleep(for: .milliseconds(5)) }
709 XCTAssertTrue(model.rename("Latest"))
710 let deadline = ContinuousClock.now.advanced(by: .seconds(3))
711 while await server.savedTitle() != "Latest", .now < deadline { try await Task.sleep(for: .milliseconds(10)) }
712 let title = await server.savedTitle()
713 XCTAssertEqual(title, "Latest")
714 XCTAssertNil(try account.metadata("doc")?.pendingTitle)
715 await model.discardAll(); account.drainer.stop()
716 }
717
718 func testAttachedDraftMetadataRepairsMissingIndexAtEveryWriteBoundary() async throws {
719 let base = MemoryBlobStore()
720 let network = NativeConnectivity(source: ScriptedPathSource(.unsatisfied))
721 let original = DocsOfflineAccount(store: base, accountID: "a", connectivity: network, transport: { nil })
722 let draft = DocumentDetail(sqid: "draft-token", title: "Draft", guid: "g", can_write: true, can_share: false)
723 try original.saveMetadata(DocsOfflineMetadata(detail: draft, pendingTitle: "Renamed", draftToken: "token"), key: "draft-token")
724 let attached = DocumentDetail(sqid: "real", title: "Renamed", guid: "g", can_write: true, can_share: false)
725 for crashAfter in 0...8 {
726 let disk = FaultingBlobStore(MemoryBlobStore(base.contents))
727 let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: network, transport: { nil })
728 disk.crash(after: crashAfter)
729 do { try account.saveMetadata(DocsOfflineMetadata(detail: attached, pendingTitle: "Renamed"), key: "draft-token") }
730 catch is SimulatedCrash { }
731 let next = DocsOfflineAccount(store: disk.committed, accountID: "a", connectivity: network, transport: { nil })
732 let metadata = try XCTUnwrap(next.metadata("draft-token"))
733 if metadata.draftToken == nil {
734 XCTAssertEqual(try next.key(for: "real"), "draft-token", "Crash boundary \(crashAfter): discover attached bytes at their original sealed path")
735 }
736 XCTAssertEqual(metadata.pendingTitle, "Renamed")
737 }
738 }
739
740 func testConcurrentReplicaCommitsMergeAndDiscardInvalidatesOldCaptures() async throws {
741 let disk = MemoryBlobStore(), cache = DocsReplicaCache(store: disk), seed = try await initial()
742 let a = CRDTReplica(guid: "offline-property"), b = CRDTReplica(guid: "offline-property")
743 _ = try await a.open(update: seed); _ = try await b.open(update: seed)
744 let outbox = Outbox(store: disk, account: "a")
745 try await outbox.enqueue(lane: "doc:doc", kind: "update", payload: edit(a, "A"))
746 try await outbox.enqueue(lane: "doc:doc", kind: "update", payload: edit(b, "B"))
747 let first = PersistedReplica(format: 1, sequence: 2, guid: "offline-property", savedAt: Date(), state: try await a.persistentState().state)
748 let second = PersistedReplica(format: 1, sequence: 3, guid: "offline-property", savedAt: Date(), state: try await b.persistentState().state)
749 async let writeA = cache.commit(first, key: "doc", generation: 0)
750 async let writeB = cache.commit(second, key: "doc", generation: 0)
751 _ = try await (writeA, writeB)
752 // An older editor capture must not erase the headless sender's state.
753 try await cache.commit(first, key: "doc", generation: 0)
754 let stored = try await storedText(disk)
755 let text = try XCTUnwrap(stored)
756 XCTAssertEqual(text.count, 2); XCTAssertTrue(text.contains("A")); XCTAssertTrue(text.contains("B"))
757 XCTAssertEqual(try cache.load("doc")?.sequence, 3)
758 // Compaction folds the segments into the base without losing either.
759 try await cache.compact("doc", generation: 0)
760 XCTAssertEqual(try cache.load("doc")?.segments.count, 0)
761 XCTAssertEqual(try cache.load("doc")?.sequence, 3)
762 let compacted = try await storedText(disk)
763 XCTAssertEqual(compacted, text)
764 cache.invalidate("doc"); try cache.remove("doc")
765 do { try await cache.commit(first, key: "doc", generation: 0); XCTFail("A discarded capture must not write") }
766 catch is CancellationError { }
767 do { try cache.append(Data([0, 0]), sequence: 9, key: "doc", generation: 0); XCTFail("A discarded capture must not append") }
768 catch is CancellationError { }
769 XCTAssertTrue(replicaFiles(disk).isEmpty)
770 await a.close(); await b.close()
771 }
772
773 func testEveryDiscardCrashBoundaryLeavesNoStrandedReplica() async throws {
774 let base = MemoryBlobStore(), replica = CRDTReplica(guid: "offline-property")
775 let setup = DocsPersistence(store: base, outbox: Outbox(store: base, account: "a"), key: "doc", replica: replica)
776 try await setup.reopen(fallback: initial(), sequence: 0)
777 for text in ["A", "B"] { try await setup.enqueue(edit(replica, text)) }
778 _ = try await setup.persist()
779 for crashAfter in 0...6 {
780 let disk = FaultingBlobStore(MemoryBlobStore(base.contents))
781 let queue = Outbox(store: disk, account: "a")
782 try await queue.load()
783 let lane = DocsPersistence(store: disk, outbox: queue, key: "doc", replica: replica)
784 disk.crash(after: crashAfter)
785 do { try await lane.discard() } catch is SimulatedCrash { }
786 let frozen = disk.committed
787 let entries = await Outbox(store: frozen, account: "a").entries(lane: "doc:doc")
788 if !replicaFiles(frozen).isEmpty {
789 XCTAssertEqual(entries.count, 2, "Crash \(crashAfter): no unsent text may survive without its complete lane")
790 }
791 }
792 await replica.close()
793 }
794
795 func testLockedRenameIsRetriedBeforeLocalFailureClears() async throws {
796 let server = IntegratingServer(); try await server.open(initial())
797 let disk = FaultingBlobStore(), network = NativeConnectivity(source: ScriptedPathSource(.unsatisfied))
798 let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: network, transport: { server })
799 let model = DocsModel(transport: { server }, connectivity: network, offlineAccount: account)
800 await model.open("doc")
801 disk.unavailable = true
802 model.renameInput = "Keep this title"
803 XCTAssertFalse(model.commitRename())
804 XCTAssertFalse(model.commitRename(), "Equality with the failed in-memory title is not a durable commit")
805 disk.unavailable = false
806 await model.retry()
807 XCTAssertEqual(try account.metadata("doc")?.pendingTitle, "Keep this title")
808 XCTAssertTrue(model.commitRename())
809 await model.persistReplica()
810 XCTAssertEqual(try account.metadata("doc")?.pendingTitle, "Keep this title")
811 await model.discardAll(); account.drainer.stop()
812 }
813
814 func testRenameAfterTitlePOSTButBeforeBatchAckKeepsSuccessorTrigger() async throws {
815 let server = IntegratingServer(); try await server.open(initial())
816 let path = ScriptedPathSource(.unsatisfied), disk = MemoryBlobStore()
817 let network = NativeConnectivity(source: path)
818 let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: network, transport: { server })
819 let model = DocsModel(transport: { server }, connectivity: network, offlineAccount: account)
820 while network.path?.status != .unsatisfied { try await Task.sleep(for: .milliseconds(5)) }
821 await model.open("doc")
822 model.didRender(model.projectionGeneration)
823 XCTAssertTrue(model.enqueue(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("A")]))
824 while model.hasPendingInput { try await Task.sleep(for: .milliseconds(5)) }
825 var metadata = try XCTUnwrap(account.metadata("doc"))
826 metadata.pendingTitle = "First"
827 try account.saveMetadata(metadata, key: "doc")
828 try await account.ensureMetadataEntry("doc")
829 let queuedEntries = await account.outbox.entries(lane: "doc:doc")
830 XCTAssertEqual(queuedEntries.map(\.kind), ["update", "metadata"])
831 await server.delayUpdates(); path.send(.satisfied)
832 let started = ContinuousClock.now.advanced(by: .seconds(2))
833 while await server.updateRequestCount() == 0, .now < started { try await Task.sleep(for: .milliseconds(5)) }
834 let flying = await account.outbox.summary.inFlight
835 XCTAssertEqual(flying, 2)
836 metadata = try XCTUnwrap(account.metadata("doc"))
837 metadata.pendingTitle = "Successor"
838 try account.saveMetadata(metadata, key: "doc")
839 try await account.ensureMetadataEntry("doc")
840 let deadline = ContinuousClock.now.advanced(by: .seconds(3))
841 while await server.savedTitle() != "Successor", .now < deadline { try await Task.sleep(for: .milliseconds(10)) }
842 let title = await server.savedTitle(); XCTAssertEqual(title, "Successor")
843 await model.discardAll(); account.drainer.stop()
844 }
845
846 func testLostChangesNoticePersistsUntilDismissal() async throws {
847 let server = IntegratingServer(); try await server.open(initial())
848 let disk = MemoryBlobStore(["outbox/0000000000000001.entry": Data("corrupt".utf8)])
849 let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: NativeConnectivity(source: ScriptedPathSource(.unsatisfied)), transport: { server })
850 let home = DocsModel(transport: { server }, offlineAccount: account)
851 await home.load()
852 try await Task.sleep(for: .milliseconds(50))
853 XCTAssertEqual(home.lostChangesNotice, NativeSyncStrings.kit.unsentLost)
854 await home.load()
855 XCTAssertNotNil(home.lostChangesNotice, "A list refresh must not dismiss the notice")
856 await home.dismissLostChangesNotice()
857 try await Task.sleep(for: .milliseconds(50))
858 XCTAssertNil(home.lostChangesNotice)
859 account.drainer.stop()
860 }
861
862 func testLaneCapCannotBeBypassedAndClearsAfterDrain() async throws {
863 let server = IntegratingServer(); try await server.open(initial())
864 let network = NativeConnectivity(source: ScriptedPathSource(.unsatisfied))
865 let account = DocsOfflineAccount(store: MemoryBlobStore(), accountID: "a", connectivity: network, transport: { server })
866 let model = DocsModel(transport: { server }, connectivity: network, offlineAccount: account)
867 await model.open("doc")
868 try await account.outbox.enqueue(lane: "doc:doc", kind: "metadata", payload: Data(repeating: 0, count: 32 * 1024 * 1024 + 1))
869 try await Task.sleep(for: .milliseconds(50))
870 XCTAssertTrue(model.inputPaused)
871 XCTAssertEqual(model.syncStatus, .failed(pending: 1, reason: .tooManyUnsent))
872 await model.retry(); XCTAssertTrue(model.inputPaused)
873 let reopened = DocsModel(transport: { server }, connectivity: network, offlineAccount: account)
874 await reopened.open("doc")
875 XCTAssertTrue(reopened.inputPaused, "Reopening cannot bypass the byte ceiling")
876 try await account.outbox.discard(lane: "doc:doc")
877 try await Task.sleep(for: .milliseconds(50))
878 XCTAssertFalse(model.inputPaused)
879 XCTAssertEqual(model.syncStatus, .saved)
880 await reopened.discardAll(); await model.discardAll(); account.drainer.stop()
881 }
882
883 func testIntegratingServerStreamsSubsequentUpdates() async throws {
884 let server = IntegratingServer(), seed = try await initial()
885 try await server.open(seed)
886 let events = expectation(description: "Initial and subsequent sequence")
887 events.expectedFulfillmentCount = 2
888 let listener = Task { try await server.stream("/d/doc/stream", onOpen: {}) { _ in events.fulfill() } }
889 defer { listener.cancel() }
890 try await Task.sleep(for: .milliseconds(30))
891 let local = CRDTReplica(guid: "offline-property"); _ = try await local.open(update: seed)
892 let update = try await edit(local, "Remote")
893 _ = try await server.responseDetails("/d/doc/updates", method: "POST", body: update, contentType: "application/octet-stream", maxBytes: 1024)
894 await fulfillment(of: [events], timeout: 1)
895 await local.close()
896 }
897
898 func testDraftAttachmentReopensAfterEveryStoreOperation() async throws {
899 let seed = try await initial(), base = MemoryBlobStore()
900 let network = NativeConnectivity(source: ScriptedPathSource(.satisfied))
901 let original = DocsOfflineAccount(store: base, accountID: "a", connectivity: network, transport: { nil })
902 let detail = DocumentDetail(sqid: "draft-token", title: "Draft title", guid: "offline-property", can_write: true, can_share: false)
903 try original.saveMetadata(DocsOfflineMetadata(detail: detail, pendingTitle: "Draft title", draftToken: "token"), key: "draft-token")
904 let source = CRDTReplica(guid: detail.guid); _ = try await source.open(update: seed)
905 try await original.outbox.enqueue(lane: "doc:draft-token", kind: "update", payload: seed)
906 try await original.outbox.enqueue(lane: "doc:draft-token", kind: "update", payload: edit(source, "Draft content"))
907 await source.close()
908 // Discover the actual operation count, then crash before every one.
909 var limit = 0
910 for crashAfter in [-1] + Array(0...80) {
911 if crashAfter > limit && crashAfter >= 0 { break }
912 let server = IntegratingServer(); try await server.open(Data())
913 let disk = FaultingBlobStore(MemoryBlobStore(base.contents))
914 let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: network, transport: { server })
915 if crashAfter >= 0 { disk.crash(after: crashAfter) }
916 do { try await account.activate(); await account.drainer.drain() } catch is SimulatedCrash { }
917 account.drainer.stop()
918 if crashAfter == -1 { limit = disk.operationCount }
919 let frozen = disk.committed
920 let recovered = DocsOfflineAccount(store: frozen, accountID: "a", connectivity: network, transport: { server })
921 try await recovered.activate(); await recovered.drainer.drain()
922 XCTAssertEqual(try recovered.key(for: "doc"), "draft-token", "Boundary \(crashAfter)")
923 XCTAssertNil(try recovered.metadata("draft-token")?.draftToken)
924 let text = try await server.text(), count = await server.documentCount(), summary = await recovered.outbox.summary
925 XCTAssertEqual(text, "Draft content", "Boundary \(crashAfter)")
926 XCTAssertEqual(count, 1, "Creation-token retry cannot duplicate the document")
927 XCTAssertTrue(summary.isEmpty)
928 let reopened = CRDTReplica(guid: detail.guid)
929 let lane = DocsPersistence(store: frozen, outbox: recovered.outbox, key: "draft-token", replica: reopened)
930 try await lane.reopen(fallback: Data(), sequence: 0)
931 let offline = try await reopened.projection().children.map(\.plainText).joined()
932 XCTAssertEqual(offline, "Draft content")
933 await reopened.close(); recovered.drainer.stop()
934 }
935 XCTAssertLessThanOrEqual(limit, 80, "Expand the exhaustive sweep if attachment grows")
936 }
937
938 func testDirectDocumentOpenReportsLostKeyBeforeReadingItsIndex() async throws {
939 let server = IntegratingServer(); try await server.open(initial())
940 let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
941 defer { try? FileManager.default.removeItem(at: root) }
942 let keys = ScriptedKeyProvider(key: SymmetricKey(size: .bits256))
943 let disk = NativeSealedStore(root: root, accountID: "a", keys: keys)
944 let network = NativeConnectivity(source: ScriptedPathSource(.unsatisfied))
945 let old = DocsOfflineAccount(store: disk, accountID: "a", connectivity: network, transport: { server })
946 let detail = DocumentDetail(sqid: "doc", title: "Document", guid: "offline-property", can_write: true, can_share: false)
947 try old.saveMetadata(DocsOfflineMetadata(detail: detail), key: "doc")
948 try await old.outbox.enqueue(lane: "doc:doc", kind: "update", payload: Data([0]))
949 _ = keys.deleteKey()
950 // A process restart also drops NativeSealedStore's cached key/state.
951 // Reusing the old store would deliberately keep the still-usable key.
952 let reopened = NativeSealedStore(root: root, accountID: "a", keys: keys)
953 let next = DocsOfflineAccount(store: reopened, accountID: "a", connectivity: network, transport: { server })
954 let model = DocsModel(transport: { server }, connectivity: network, offlineAccount: next)
955 await model.open("doc")
956 try await Task.sleep(for: .milliseconds(50))
957 XCTAssertNotNil(model.projection)
958 XCTAssertEqual(model.lostChangesNotice, NativeSyncStrings.kit.unsentLost)
959 await model.discardAll(); next.drainer.stop()
960 }
961
962 func testDraftSeedSurvivesMetadataWriteFailureAndConvergesAfterUnlock() async throws {
963 let server = IntegratingServer(); try await server.open(Data())
964 let disk = MetadataLockStore(), network = NativeConnectivity(source: ScriptedPathSource(.satisfied))
965 let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: network, transport: { server })
966 let model = DocsModel(transport: { server }, connectivity: network, draft: true, offlineAccount: account)
967 await model.newDraft()
968 XCTAssertTrue(model.inputPaused)
969 disk.unlock(); await model.retry()
970 XCTAssertNotNil(model.projection)
971 model.didRender(model.projectionGeneration)
972 XCTAssertTrue(model.enqueue(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("Recovered draft")]))
973 while model.hasPendingInput { try await Task.sleep(for: .milliseconds(5)) }
974 let saved = await model.saveAll(); XCTAssertTrue(saved)
975 let text = try await server.text()
976 XCTAssertEqual(text, "Recovered draft", "The paragraph dependency must reach the server too")
977 await model.discardAll(); account.drainer.stop()
978 }
979
980}
981