Recover metadata and replay account lanes from Home without losing cached edits
7 files changed,
+364
−63
docs/testing/k3-evidence.md+28 −0native/apple/Sources/DocsKit/DocsModel.swift+27 −38native/apple/Sources/DocsKit/DocsOfflineAccount.swift+86 −19native/apple/Sources/DocsKit/DocsPersistence.swift+12 −4native/apple/Sources/DocsKit/DocsReplicaCache.swift+38 −0native/apple/Sources/DocsKit/DocsWorkspace.swift+1 −1native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift+172 −1
CI passed — run details
diff --git a/docs/testing/k3-evidence.md b/docs/testing/k3-evidence.md| index 206f619..00f2f91 100644 |
| --- a/docs/testing/k3-evidence.md |
| +++ b/docs/testing/k3-evidence.md |
| @@ -123,3 +123,31 @@ all 12 edits; initial save and server convergence passed (one assertion failure, |
| `/tmp/k3-kill-valid-red.log`). Restore replay: SIGKILL after 12 durable edits, |
| exact offline recovery, real authenticated server convergence, no duplicate text |
| all passed (`/tmp/k3-kill-valid-green.log`). |
| + |
| +Parked-update port executed: `cargo test --manifest-path native/crdt/Cargo.toml |
| +--locked --test snapshot`. Switching only Editor.snapshot to encode_diff_v1 |
| +failed the healed-text equality (`/tmp/k3-parked-red.log`). Restoring existing |
| +encode_state_as_update_v1 passed (`/tmp/k3-parked-green.log`). No new op. |
| + |
| +## Resume: durable metadata and Home replay |
| + |
| +Five focused regressions failed on the prior implementation (15 assertions, |
| +/tmp/k3-recovery-red.log): title before first replica write, title-only transient |
| +retry, rename during an in-flight title POST, attached draft index crash repair, |
| +and Home-only replay. Account-owned metadata sends through the existing drainer, |
| +registered immutable metadata keys, repairable aliases, and shared monotonic |
| +replica commits passed those plus all existing durability/account tests (15 |
| +passing, /tmp/k3-recovery-green.log). |
| + |
| +Replica cache merge/invalidation and replica-before-lane discard were deliberately |
| +broken: two tests failed with six assertions (/tmp/k3-cache-discard-red.log). |
| +Restore the implementations: all 13 durability tests pass, including generated |
| +crashes scheduled before arbitrary event store operations and exhaustive discard |
| +boundaries (/tmp/k3-cache-discard-green.log). Replica-first deletion therefore |
| +cannot leave local text stranded after removal of its lane. |
| + |
| +A metadata marker is an app-owned outbox kind, not a kit API. CRDT replay and |
| +compaction use only update entries. A kill after metadata but before enqueue is |
| +reconciled from registered keys on activation. Both editor and headless writers |
| +merge the latest durable cache under a compare/retry and shared discard generation; |
| +the editor also checks commandsApplied == commandsDurable immediately at commit. |
diff --git a/native/apple/Sources/DocsKit/DocsModel.swift b/native/apple/Sources/DocsKit/DocsModel.swift| index d6ed5e8..d1e4de9 100644 |
| --- a/native/apple/Sources/DocsKit/DocsModel.swift |
| +++ b/native/apple/Sources/DocsKit/DocsModel.swift |
| @@ -80,15 +80,24 @@ import RastrilloNative |
| var hasUnsavedChanges: Bool { hasUnpersistedInput || hasUnsentChanges } |
| private func configurePersistence(key: String, replica: CRDTReplica) { |
| documentKey = key |
| - persistence = DocsPersistence(store: offlineAccount.store, outbox: offlineAccount.outbox, key: key, replica: replica) |
| + persistence = DocsPersistence(store: offlineAccount.store, outbox: offlineAccount.outbox, key: key, replica: replica, cache: offlineAccount.replicaCache) |
| summaryTask?.cancel() |
| summaryTask = Task { [weak self, outbox = offlineAccount.outbox] in |
| for await summary in await outbox.changes { |
| guard let self, self.documentKey == key else { return } |
| self.laneSummary = summary.only("doc:" + key) |
| + self.reloadMetadata() |
| } |
| } |
| } |
| + private func reloadMetadata() { |
| + guard let key = documentKey, let stored = try? offlineAccount.metadata(key) else { return } |
| + let attached = draftToken != nil && stored.draftToken == nil |
| + detail = stored.detail; pendingTitle = stored.pendingTitle; draftToken = stored.draftToken |
| + if attached, streamTask == nil { |
| + streamTask = Task { [weak self] in await self?.listen(stored.detail.sqid) } |
| + } |
| + } |
| private func saveMetadata() throws { |
| guard let documentKey, let detail else { return } |
| try offlineAccount.saveMetadata(DocsOfflineMetadata(detail: detail, pendingTitle: pendingTitle, draftToken: draftToken), key: documentKey) |
| @@ -104,7 +113,6 @@ import RastrilloNative |
| await writer.run { [weak self] in |
| guard let self, let persistence = self.persistence else { return } |
| do { |
| - try self.saveMetadata() |
| if try await !persistence.persist() { self.schedulePersistence() } |
| else if self.localFailure == .cannotSaveOnDevice, self.failedUpdate == nil { |
| self.localFailure = nil |
| @@ -125,6 +133,7 @@ import RastrilloNative |
| try await persistence.compact() |
| } |
| func load(query: String = "") async { |
| + do { try await offlineAccount.activate() } catch { localFailure = .cannotSaveOnDevice } |
| let request = UUID(); listRequest = request |
| listState = .loading |
| do { |
| @@ -174,30 +183,14 @@ import RastrilloNative |
| } |
| } |
| private func attachDraft(epoch: UUID) async { |
| - guard let token = draftToken, let local = replica else { return } |
| + guard let key = documentKey else { return } |
| do { |
| - let body = Self.form(["title": detail?.title ?? "", "creation_token": token]) |
| - let (data, status) = try await client().response("/documents", method: "POST", body: body, contentType: "application/x-www-form-urlencoded") |
| - guard status == 201 else { throw CRDTReplica.Failure.rejected } |
| - let item = try JSONDecoder().decode(DocumentSummary.self, from: data) |
| - guard documentEpoch == epoch else { return } |
| - let attached: DocumentDetail = try await client().request("/d/\(item.sqid)") |
| - let reply = try await client().responseDetails("/d/\(item.sqid)/updates", maxBytes: 8 * 1024 * 1024) |
| - guard reply.status == 200, let seq = Int64(reply.header("Docs-Seq") ?? ""), attached.can_write else { throw CRDTReplica.Failure.rejected } |
| - guard documentEpoch == epoch else { return } |
| - if !reply.data.isEmpty { _ = try await local.apply(reply.data) } |
| - guard documentEpoch == epoch else { return } |
| - detail = DocumentDetail(sqid: attached.sqid, title: pendingTitle ?? attached.title, guid: attached.guid, can_write: attached.can_write, can_share: attached.can_share) |
| - draftToken = nil; sequence = seq; errorKey = nil |
| - await local.setSequence(seq) |
| - if let documentKey { try offlineAccount.attach(attached.sqid, key: documentKey) } |
| - try saveMetadata() |
| - await persistReplica() |
| - // Do not publish while native callbacks are still in flight. |
| - if !hasPendingInput { await publish() } |
| + try await offlineAccount.ensureMetadataEntry(key) |
| + await offlineAccount.drainer.drain() |
| guard documentEpoch == epoch else { return } |
| - streamTask = Task { [weak self] in await self?.listen(item.sqid) } |
| - await flush() |
| + reloadMetadata() |
| + if isDraft { errorKey = "native.pending" } |
| + else { await persistReplica(); await flush() } |
| } catch { if documentEpoch == epoch { errorKey = "native.pending" } } |
| } |
| private static func form(_ values: [String: String]) -> Data { |
| @@ -235,13 +228,15 @@ import RastrilloNative |
| do { |
| let key = try offlineAccount.key(for: sqid) |
| let cached = try offlineAccount.metadata(key) |
| + pendingTitle = cached?.pendingTitle; draftToken = cached?.draftToken |
| let detail: DocumentDetail |
| let initial: Data |
| let seq: Int64 |
| if let cached, try offlineAccount.store.read("cache/docs/\(key)/replica") != nil { |
| detail = cached.detail; pendingTitle = cached.pendingTitle; initial = Data(); seq = 0 |
| } else { |
| - detail = try await client().request("/d/\(sqid)") |
| + let remote: DocumentDetail = try await client().request("/d/\(sqid)") |
| + detail = DocumentDetail(sqid: remote.sqid, title: cached?.pendingTitle ?? remote.title, guid: remote.guid, can_write: remote.can_write, can_share: remote.can_share) |
| let reply = try await client().responseDetails("/d/\(sqid)/updates", maxBytes: 8 * 1024 * 1024) |
| try reply.requireSuccess() |
| guard let cursor = Int64(reply.header("Docs-Seq") ?? "") else { throw CRDTReplica.Failure.rejected } |
| @@ -254,9 +249,11 @@ import RastrilloNative |
| let projection = try await replica.projection() |
| guard documentEpoch == epoch else { await replica.close(); return } |
| self.replica = replica; self.detail = detail |
| + reloadMetadata() |
| sequence = try await replica.persistentState().sequence |
| laneSummary = await offlineAccount.outbox.summary.only("doc:" + key) |
| - try saveMetadata() |
| + if cached == nil { try saveMetadata() } |
| + try await offlineAccount.ensureMetadataEntry(key) |
| projectionGeneration = 0; renderedGeneration = 0 |
| selection = NSRange(location: 0, length: 0); typingMarks = nil |
| composing = false; inputPaused = false |
| @@ -332,7 +329,6 @@ import RastrilloNative |
| if localFailure == .cannotSaveOnDevice || failedUpdate != nil { |
| do { |
| try await offlineAccount.outbox.load() |
| - try saveMetadata() |
| if let failedUpdate { try await durable(failedUpdate) } |
| guard documentEpoch == epoch else { return } |
| localFailure = nil; inputPaused = false |
| @@ -399,22 +395,15 @@ import RastrilloNative |
| return !hasUnsavedChanges |
| } |
| func flush() async { |
| - guard !isDraft, !saving, let detail, let persistence else { return }; saving = true |
| + guard !saving, detail != nil, let persistence else { return }; saving = true |
| let epoch = documentEpoch |
| defer { if documentEpoch == epoch { saving = false } } |
| - // Titles are metadata rather than CRDT updates. Send them first even |
| - // when this lane contains no text updates. |
| - if let title = pendingTitle { |
| - do { |
| - let reply = try await client().responseDetails("/d/\(detail.sqid)/title", method: "POST", body: Self.form(["title": title]), contentType: "application/x-www-form-urlencoded") |
| - try reply.requireSuccess() |
| - guard documentEpoch == epoch else { return } |
| - if pendingTitle == title { pendingTitle = nil; try saveMetadata() } |
| - } catch { errorKey = "native.pending"; return } |
| - } |
| + do { try await offlineAccount.ensureMetadataEntry(persistence.key) } |
| + catch { localFailure = .cannotSaveOnDevice; inputPaused = true; return } |
| await offlineAccount.drainer.drain() |
| guard documentEpoch == epoch else { return } |
| laneSummary = await offlineAccount.outbox.summary.only(persistence.lane) |
| + reloadMetadata() |
| if laneSummary.isEmpty { |
| if errorKey == "native.pending" || errorKey == "docs.editor.status.retrying" { errorKey = nil } |
| } else { errorKey = "native.pending" } |
diff --git a/native/apple/Sources/DocsKit/DocsOfflineAccount.swift b/native/apple/Sources/DocsKit/DocsOfflineAccount.swift| index 54586b9..746af36 100644 |
| --- a/native/apple/Sources/DocsKit/DocsOfflineAccount.swift |
| +++ b/native/apple/Sources/DocsKit/DocsOfflineAccount.swift |
| @@ -15,6 +15,7 @@ struct DocsOfflineMetadata: Codable { |
| let store: BlobStore |
| let outbox: Outbox |
| let connectivity: NativeConnectivity |
| + let replicaCache: DocsReplicaCache |
| private var supplier: @MainActor () -> NativeTransport? |
| private(set) var drainer: OutboxDrainer! |
| static func account(_ id: String, origin: URL, fallback: NativeTransport, transport: (@MainActor () -> NativeTransport?)?) -> DocsOfflineAccount { |
| @@ -28,6 +29,7 @@ struct DocsOfflineMetadata: Codable { |
| } |
| init(store: BlobStore, accountID: String, connectivity: NativeConnectivity, transport: @escaping @MainActor () -> NativeTransport?) { |
| self.store = store; outbox = Outbox(store: store, account: accountID) |
| + replicaCache = DocsReplicaCache(store: store) |
| self.connectivity = connectivity; supplier = transport |
| drainer = OutboxDrainer(outbox: outbox, transport: { [weak self] in self?.supplier() }, connectivity: connectivity, maxBatchBytes: 512 * 1024) { [weak self] lane, entries, transport in |
| guard let self else { throw CancellationError() } |
| @@ -38,39 +40,104 @@ struct DocsOfflineMetadata: Codable { |
| guard let bytes = try store.read("cache/docs/\(key)/meta") else { return nil } |
| return try JSONDecoder().decode(DocsOfflineMetadata.self, from: bytes) |
| } |
| + private func index() throws -> [String: String] { |
| + try store.read("cache/docs/index").map { try JSONDecoder().decode([String: String].self, from: $0) } ?? [:] |
| + } |
| func saveMetadata(_ metadata: DocsOfflineMetadata, key: String) throws { |
| + // Register the immutable key first. A crash may leave an empty slot, |
| + // never undiscoverable metadata or a rename that Home cannot replay. |
| + var index = try index() |
| + if index[key] == nil { |
| + index[key] = key |
| + try store.write(JSONEncoder().encode(index), to: "cache/docs/index") |
| + } |
| try store.write(JSONEncoder().encode(metadata), to: "cache/docs/\(key)/meta") |
| + if metadata.draftToken == nil, index[metadata.detail.sqid] != key { |
| + index[metadata.detail.sqid] = key |
| + try store.write(JSONEncoder().encode(index), to: "cache/docs/index") |
| + } |
| } |
| func key(for sqid: String) throws -> String { |
| - guard let bytes = try store.read("cache/docs/index") else { return sqid } |
| - return try JSONDecoder().decode([String: String].self, from: bytes)[sqid] ?? sqid |
| + let index = try index() |
| + if let key = index[sqid] { return key } |
| + // The alias is derived state. Attachment metadata is committed first, |
| + // so scanning registered keys heals a kill before the alias write. |
| + for key in Set(index.values).sorted() { |
| + if let metadata = try metadata(key), metadata.detail.sqid == sqid { |
| + try saveMetadata(metadata, key: key) |
| + return key |
| + } |
| + } |
| + return sqid |
| } |
| - func attach(_ sqid: String, key: String) throws { |
| - var index = try store.read("cache/docs/index").map { try JSONDecoder().decode([String: String].self, from: $0) } ?? [:] |
| - index[sqid] = key |
| - try store.write(JSONEncoder().encode(index), to: "cache/docs/index") |
| + func ensureMetadataEntry(_ key: String) async throws { |
| + let generation = replicaCache.generation(key) |
| + guard let metadata = try metadata(key), metadata.pendingTitle != nil || metadata.draftToken != nil else { return } |
| + let entries = await outbox.entries(lane: "doc:" + key) |
| + guard replicaCache.generation(key) == generation, !entries.contains(where: { $0.kind == "metadata" }) else { return } |
| + try await outbox.enqueue(lane: "doc:" + key, kind: "metadata", payload: Data()) |
| + } |
| + func activate() async throws { |
| + try await outbox.load() |
| + // Older K3 records can also be discovered from their durable lane. |
| + let lanes = await outbox.summary.lanes.keys |
| + let keys = Set(try index().values).union(lanes.filter { $0.hasPrefix("doc:") }.map { String($0.dropFirst(4)) }) |
| + for key in keys.sorted() { try await ensureMetadataEntry(key) } |
| + drainer.start(); drainer.kick() |
| + } |
| + private static func form(_ values: [String: String]) -> Data { |
| + var form = URLComponents(); form.queryItems = values.map { URLQueryItem(name: $0.key, value: $0.value) } |
| + return Data((form.percentEncodedQuery ?? "").replacingOccurrences(of: "+", with: "%2B").utf8) |
| } |
| private func send(_ lane: String, entries: [OutboxEntry], transport: NativeTransport) async throws -> [UUID: OutboxDrainer.Disposition] { |
| - let key = String(lane.dropFirst(4)) |
| - guard lane.hasPrefix("doc:"), let metadata = try metadata(key), metadata.draftToken == nil else { |
| - return Dictionary(uniqueKeysWithValues: entries.map { ($0.id, .retry) }) |
| + let key = String(lane.dropFirst(4)), generation = replicaCache.generation(String(lane.dropFirst(4))) |
| + guard lane.hasPrefix("doc:"), var metadata = try metadata(key) else { throw BlobStoreError.unavailable } |
| + if let token = metadata.draftToken { |
| + let reply = try await transport.responseDetails("/documents", method: "POST", body: Self.form(["title": metadata.detail.title, "creation_token": token]), contentType: "application/x-www-form-urlencoded") |
| + try reply.requireSuccess() |
| + let item = try JSONDecoder().decode(DocumentSummary.self, from: reply.data) |
| + let attached: DocumentDetail = try await transport.request("/d/\(item.sqid)") |
| + guard replicaCache.generation(key) == generation, let latest = try self.metadata(key) else { throw CancellationError() } |
| + metadata = latest |
| + metadata.detail = DocumentDetail(sqid: attached.sqid, title: latest.pendingTitle ?? attached.title, guid: attached.guid, can_write: attached.can_write, can_share: attached.can_share) |
| + metadata.draftToken = nil |
| + // Commit identity before publishing it or attempting text sends. |
| + try saveMetadata(metadata, key: key) |
| } |
| - // The model serializes title requests, including title-only edits. |
| - // Its durable metadata blocks text replay until that title is accepted. |
| - if metadata.pendingTitle != nil { |
| - return Dictionary(uniqueKeysWithValues: entries.map { ($0.id, .retry) }) |
| + while let title = metadata.pendingTitle { |
| + let reply = try await transport.responseDetails("/d/\(metadata.detail.sqid)/title", method: "POST", body: Self.form(["title": title]), contentType: "application/x-www-form-urlencoded") |
| + try reply.requireSuccess() |
| + guard replicaCache.generation(key) == generation, var latest = try self.metadata(key) else { throw CancellationError() } |
| + if latest.pendingTitle == title { latest.pendingTitle = nil; try saveMetadata(latest, key: key) } |
| + metadata = latest // A rename during this POST must also be sent. |
| } |
| + let updates = entries.filter { $0.kind == "update" } |
| + var dispositions = Dictionary(uniqueKeysWithValues: entries.filter { $0.kind == "metadata" }.map { ($0.id, OutboxDrainer.Disposition.sent) }) |
| + guard !updates.isEmpty else { return dispositions } |
| let merger = CRDTReplica(guid: metadata.detail.guid) |
| - _ = try await merger.open(update: Data()) |
| - var sending = entries |
| let update: Data |
| - do { update = try await merger.mergeUpdates(entries.map(\.payload)) } |
| - catch { sending = Array(entries.prefix(1)); update = sending[0].payload } |
| - await merger.close() |
| + var sending = updates |
| + do { |
| + _ = try await merger.open(update: Data()) |
| + do { update = try await merger.mergeUpdates(updates.map(\.payload)) } |
| + catch { sending = Array(updates.prefix(1)); update = sending[0].payload } |
| + await merger.close() |
| + } catch { await merger.close(); throw error } |
| let reply = try await transport.responseDetails("/d/\(metadata.detail.sqid)/updates", method: "POST", body: update, contentType: "application/octet-stream") |
| try reply.requireSuccess() |
| - return Dictionary(uniqueKeysWithValues: sending.map { ($0.id, .sent) }) |
| + var state = update, sequence: Int64 = 0 |
| + if try store.read("cache/docs/\(key)/replica") == nil { |
| + let initial = try await transport.responseDetails("/d/\(metadata.detail.sqid)/updates", maxBytes: 8 * 1024 * 1024) |
| + try initial.requireSuccess() |
| + guard let cursor = Int64(initial.header("Docs-Seq") ?? "") else { throw NativeClientError.invalidResponse } |
| + state = initial.data; sequence = cursor |
| + } |
| + // Keep sent bytes locally before ack can remove their lane files. |
| + try await replicaCache.commit(PersistedReplica(format: 1, sequence: sequence, guid: metadata.detail.guid, savedAt: Date(), state: state), key: key, generation: generation) |
| + for entry in sending { dispositions[entry.id] = .sent } |
| + return dispositions |
| } |
| + |
| } |
| /// Used only by previews and callers that have no NativeAccount (unit tests). |
diff --git a/native/apple/Sources/DocsKit/DocsPersistence.swift b/native/apple/Sources/DocsKit/DocsPersistence.swift| index 08e7000..dc0c8a0 100644 |
| --- a/native/apple/Sources/DocsKit/DocsPersistence.swift |
| +++ b/native/apple/Sources/DocsKit/DocsPersistence.swift |
| @@ -18,20 +18,25 @@ struct PersistedReplica: Codable, Sendable { |
| let replica: CRDTReplica |
| private(set) var commandsDurable = 0 |
| private var active = true |
| + let cache: DocsReplicaCache |
| + private let generation: Int |
| var lane: String { "doc:" + key } |
| var path: String { "cache/docs/" + key + "/replica" } |
| - init(store: BlobStore, outbox: Outbox, key: String, replica: CRDTReplica) { |
| + init(store: BlobStore, outbox: Outbox, key: String, replica: CRDTReplica, cache: DocsReplicaCache? = nil) { |
| self.store = store; self.outbox = outbox; self.key = key; self.replica = replica |
| + self.cache = cache ?? DocsReplicaCache(store: store) |
| + generation = self.cache.generation(key) |
| } |
| func reopen(fallback: Data, sequence: Int64) async throws { |
| try await outbox.load() |
| + let entries = await outbox.entries(lane: lane) |
| let saved = try store.read(path).map { try JSONDecoder().decode(PersistedReplica.self, from: $0) } |
| if let saved, saved.format != 1 { throw BlobStoreError.unavailable } |
| _ = try await replica.open(update: saved?.state ?? fallback) |
| await replica.setSequence(saved?.sequence ?? sequence) |
| // Replay includes held entries: the editor must show everything kept |
| // here, even when it cannot currently send it. |
| - for entry in await outbox.entries(lane: lane) { _ = try await replica.apply(entry.payload) } |
| + for entry in entries where entry.kind == "update" { _ = try await replica.apply(entry.payload) } |
| commandsDurable = 0 |
| } |
| func enqueue(_ update: Data) async throws { |
| @@ -44,14 +49,16 @@ struct PersistedReplica: Codable, Sendable { |
| // A writer running between command and enqueue must defer its capture. |
| guard active, captured.commandsApplied == commandsDurable else { return false } |
| let saved = PersistedReplica(format: 1, sequence: captured.sequence, guid: captured.guid, savedAt: Date(), state: captured.state) |
| - try store.write(JSONEncoder().encode(saved), to: path) |
| - return true |
| + return try await cache.commit(saved, key: key, generation: generation) { |
| + self.active && captured.commandsApplied == self.commandsDurable |
| + } |
| } |
| func compact() async throws { |
| let entries = await outbox.sendable(lane: lane, maxBytes: nil) |
| guard entries.count > 256 || entries.reduce(0, { $0 + $1.payload.count }) > 1024 * 1024 else { return } |
| var batch: [OutboxEntry] = []; var bytes = 0 |
| for entry in entries { |
| + if entry.kind != "update" { if batch.isEmpty { continue }; break } |
| if !batch.isEmpty && bytes + entry.payload.count > 512 * 1024 { break } |
| batch.append(entry); bytes += entry.payload.count |
| } |
| @@ -66,6 +73,7 @@ struct PersistedReplica: Codable, Sendable { |
| } |
| func discard() async throws { |
| active = false |
| + cache.invalidate(key) |
| // Remove the replica first: a crash may replay lane entries again, |
| // but can never leave local text whose lane has already been removed. |
| try store.remove(path) |
diff --git a/native/apple/Sources/DocsKit/DocsReplicaCache.swift b/native/apple/Sources/DocsKit/DocsReplicaCache.swift| new file mode 100644 |
| index 0000000..bcccf18 |
| --- /dev/null |
| +++ b/native/apple/Sources/DocsKit/DocsReplicaCache.swift |
| @@ -0,0 +1,38 @@ |
| +import Foundation |
| +import RastrilloNative |
| + |
| +/// Editor captures and headless sends both commit here. Merging with the latest |
| +/// durable state prevents either writer from erasing an acknowledged batch. |
| +@MainActor final class DocsReplicaCache { |
| + let store: BlobStore |
| + private var generations: [String: Int] = [:] |
| + init(store: BlobStore) { self.store = store } |
| + func generation(_ key: String) -> Int { generations[key, default: 0] } |
| + func invalidate(_ key: String) { generations[key, default: 0] += 1 } |
| + @discardableResult func commit(_ candidate: PersistedReplica, key: String, generation: Int, valid: () -> Bool = { true }) async throws -> Bool { |
| + let path = "cache/docs/\(key)/replica" |
| + while self.generation(key) == generation { |
| + let before = try store.read(path) |
| + let previous = try before.map { try JSONDecoder().decode(PersistedReplica.self, from: $0) } |
| + let merger = CRDTReplica(guid: candidate.guid) |
| + do { |
| + _ = try await merger.open(update: previous?.state ?? Data()) |
| + _ = try await merger.apply(candidate.state) |
| + let state = try await merger.persistentState().state |
| + await merger.close() |
| + guard self.generation(key) == generation else { throw CancellationError() } |
| + // No suspension between the compare and write. A concurrent |
| + // editor or headless writer forces a fresh merge, never a loss. |
| + guard try store.read(path) == before else { continue } |
| + let merged = PersistedReplica(format: 1, sequence: max(previous?.sequence ?? 0, candidate.sequence), guid: candidate.guid, savedAt: Date(), state: state) |
| + guard valid() else { return false } |
| + try store.write(JSONEncoder().encode(merged), to: path) |
| + return true |
| + } catch { |
| + await merger.close() |
| + throw error |
| + } |
| + } |
| + throw CancellationError() |
| + } |
| +} |
diff --git a/native/apple/Sources/DocsKit/DocsWorkspace.swift b/native/apple/Sources/DocsKit/DocsWorkspace.swift| index 256a6d8..ce8f840 100644 |
| --- a/native/apple/Sources/DocsKit/DocsWorkspace.swift |
| +++ b/native/apple/Sources/DocsKit/DocsWorkspace.swift |
| @@ -91,7 +91,7 @@ import SwiftUI |
| .onDisappear { Task { await model.stop() } } |
| .onChange(of: scenePhase) { _, phase in |
| if phase == .background { Task { await model.persistReplica() } } |
| - if phase == .active { model.offlineAccount.drainer.kick() } |
| + if phase == .active { Task { try? await model.offlineAccount.activate() } } |
| } |
| #if os(macOS) |
| .background { DocsCloseGuard(hasUnsaved: { model.hasUnsavedChanges }, save: { await model.saveAll() }, discard: { await model.discardAll() }).frame(width: 0, height: 0) } |
diff --git a/native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift b/native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift| index f90eb62..a6ab4dc 100644 |
| --- a/native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift |
| +++ b/native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift |
| @@ -9,6 +9,15 @@ import XCTest |
| private actor IntegratingServer: NativeTransport { |
| nonisolated let origin = URL(string: "http://localhost:8099")! |
| var online = true |
| + var title = "Document" |
| + var titleFailures = 0 |
| + var titleDelay = false |
| + var titleRequests = 0 |
| + func delayTitles() { titleDelay = true } |
| + func titleRequestCount() -> Int { titleRequests } |
| + func failTitles(_ count: Int) { titleFailures = count } |
| + func savedTitle() -> String { title } |
| + |
| var loseNextResponse = false |
| var sequence: Int64 = 0 |
| func setOnline(_ value: Bool) { online = value } |
| @@ -22,6 +31,16 @@ private actor IntegratingServer: NativeTransport { |
| func text() async throws -> String { try await replica.projection().children.map(\.plainText).joined() } |
| func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { |
| guard online else { throw NativeClientError.offline(.notConnectedToInternet) } |
| + if method == "POST", path.hasSuffix("/title"), let body { |
| + titleRequests += 1 |
| + if titleDelay { try await Task.sleep(for: .milliseconds(200)) } |
| + if titleFailures > 0 { titleFailures -= 1; throw NativeClientError.server(status: 503) } |
| + title = URLComponents(string: "?" + String(decoding: body, as: UTF8.self))?.queryItems?.first(where: { $0.name == "title" })?.value ?? "" |
| + return NativeResponse(data: Data(), status: 200, headers: [:]) |
| + } |
| + if path.hasPrefix("/?") { |
| + return NativeResponse(data: Data(#"{"documents":[],"can_create":true}"#.utf8), status: 200, headers: [:]) |
| + } |
| if method == "POST", path.hasSuffix("/updates"), let body { |
| _ = try await replica.apply(body); sequence += 1 |
| if loseNextResponse { loseNextResponse = false; throw NativeClientError.offline(.networkConnectionLost) } |
| @@ -30,7 +49,7 @@ private actor IntegratingServer: NativeTransport { |
| if path.contains("/updates") { |
| return NativeResponse(data: try await snapshot(), status: 200, headers: ["Docs-Seq": String(sequence)]) |
| } |
| - let detail = DocumentDetail(sqid: "doc", title: "Document", guid: "offline-property", can_write: true, can_share: false) |
| + let detail = DocumentDetail(sqid: "doc", title: title, guid: "offline-property", can_write: true, can_share: false) |
| return NativeResponse(data: try JSONEncoder().encode(detail), status: 200, headers: [:]) |
| } |
| func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws { |
| @@ -114,6 +133,7 @@ private struct OfflineRandom: RandomNumberGenerator { |
| var flying: [OutboxEntry] = [] |
| var symbol = 0 |
| for step in 0..<60 { |
| + if step % 4 == 0 { disk.crash(after: Int.random(in: 0...10, using: &random)) } |
| do { |
| switch Int.random(in: 0..<8, using: &random) { |
| case 0, 1: |
| @@ -281,4 +301,155 @@ private struct OfflineRandom: RandomNumberGenerator { |
| await model.discardAll(); account.drainer.stop() |
| } |
| + func testDurableTitleSurvivesReopenBeforeFirstReplicaWrite() async throws { |
| + let server = IntegratingServer(); try await server.open(initial()) |
| + let disk = MemoryBlobStore() |
| + let path = ScriptedPathSource(.unsatisfied) |
| + let network = NativeConnectivity(source: path) |
| + let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: network, transport: { server }) |
| + let detail = DocumentDetail(sqid: "doc", title: "Local title", guid: "offline-property", can_write: true, can_share: false) |
| + try account.saveMetadata(DocsOfflineMetadata(detail: detail, pendingTitle: "Local title"), key: "doc") |
| + let reopened = DocsModel(transport: { server }, connectivity: network, offlineAccount: account) |
| + await reopened.open("doc") |
| + XCTAssertEqual(reopened.detail?.title, "Local title") |
| + XCTAssertEqual(try account.metadata("doc")?.pendingTitle, "Local title") |
| + await reopened.discardAll(); account.drainer.stop() |
| + } |
| + |
| + func testTitleOnlyTransientFailureRetriesWithoutAnotherEdit() async throws { |
| + let server = IntegratingServer(); try await server.open(initial()) |
| + let network = NativeConnectivity(source: ScriptedPathSource(.satisfied)) |
| + let account = DocsOfflineAccount(store: MemoryBlobStore(), accountID: "a", connectivity: network, transport: { server }) |
| + let model = DocsModel(transport: { server }, connectivity: network, offlineAccount: account) |
| + await model.open("doc") |
| + try await Task.sleep(for: .milliseconds(100)) |
| + await server.failTitles(1) |
| + XCTAssertTrue(model.rename("Retry title")) |
| + let deadline = ContinuousClock.now.advanced(by: .seconds(3)) |
| + while await server.savedTitle() != "Retry title", .now < deadline { try await Task.sleep(for: .milliseconds(10)) } |
| + let title = await server.savedTitle() |
| + XCTAssertEqual(title, "Retry title") |
| + await model.discardAll(); account.drainer.stop() |
| + } |
| + |
| + func testHomeOnlyReplayPreservesAcknowledgedTextForOfflineReopen() async throws { |
| + let seed = try await initial(), disk = MemoryBlobStore() |
| + let server = IntegratingServer(); try await server.open(seed) |
| + let network = NativeConnectivity(source: ScriptedPathSource(.satisfied)) |
| + let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: network, transport: { server }) |
| + let detail = DocumentDetail(sqid: "doc", title: "Document", guid: "offline-property", can_write: true, can_share: false) |
| + try account.saveMetadata(DocsOfflineMetadata(detail: detail), key: "doc") |
| + let replica = CRDTReplica(guid: detail.guid) |
| + let lane = DocsPersistence(store: disk, outbox: account.outbox, key: "doc", replica: replica) |
| + try await lane.reopen(fallback: seed, sequence: 0) |
| + _ = try await lane.persist() |
| + try await lane.enqueue(edit(replica, "Home replay")) |
| + await replica.close() |
| + // Home loads the list; it never opens the document's editor. |
| + let home = DocsModel(transport: { server }, connectivity: network, offlineAccount: account) |
| + await home.load() |
| + let deadline = ContinuousClock.now.advanced(by: .seconds(3)) |
| + while !(await account.outbox.summary).isEmpty, .now < deadline { try await Task.sleep(for: .milliseconds(10)) } |
| + let serverText = try await server.text() |
| + XCTAssertEqual(serverText, "Home replay") |
| + let summary = await account.outbox.summary |
| + XCTAssertTrue(summary.isEmpty) |
| + account.drainer.stop(); await server.setOnline(false) |
| + let next = DocsOfflineAccount(store: disk, accountID: "a", connectivity: NativeConnectivity(source: ScriptedPathSource(.unsatisfied)), transport: { server }) |
| + let reopened = DocsModel(transport: { server }, offlineAccount: next) |
| + await reopened.open("doc") |
| + XCTAssertEqual(reopened.projection?.children.map(\.plainText).joined(), "Home replay") |
| + await reopened.discardAll(); next.drainer.stop() |
| + } |
| + |
| + func testRenameDuringTitleRequestSendsTheLatestTitle() async throws { |
| + let server = IntegratingServer(); try await server.open(initial()) |
| + let network = NativeConnectivity(source: ScriptedPathSource(.satisfied)) |
| + let account = DocsOfflineAccount(store: MemoryBlobStore(), accountID: "a", connectivity: network, transport: { server }) |
| + let model = DocsModel(transport: { server }, connectivity: network, offlineAccount: account) |
| + await model.open("doc") |
| + try await Task.sleep(for: .milliseconds(100)) |
| + await server.delayTitles() |
| + XCTAssertTrue(model.rename("First")) |
| + let started = ContinuousClock.now.advanced(by: .seconds(2)) |
| + while await server.titleRequestCount() == 0, .now < started { try await Task.sleep(for: .milliseconds(5)) } |
| + XCTAssertTrue(model.rename("Latest")) |
| + let deadline = ContinuousClock.now.advanced(by: .seconds(3)) |
| + while await server.savedTitle() != "Latest", .now < deadline { try await Task.sleep(for: .milliseconds(10)) } |
| + let title = await server.savedTitle() |
| + XCTAssertEqual(title, "Latest") |
| + XCTAssertNil(try account.metadata("doc")?.pendingTitle) |
| + await model.discardAll(); account.drainer.stop() |
| + } |
| + |
| + func testAttachedDraftMetadataRepairsMissingIndexAtEveryWriteBoundary() async throws { |
| + let base = MemoryBlobStore() |
| + let network = NativeConnectivity(source: ScriptedPathSource(.unsatisfied)) |
| + let original = DocsOfflineAccount(store: base, accountID: "a", connectivity: network, transport: { nil }) |
| + let draft = DocumentDetail(sqid: "draft-token", title: "Draft", guid: "g", can_write: true, can_share: false) |
| + try original.saveMetadata(DocsOfflineMetadata(detail: draft, pendingTitle: "Renamed", draftToken: "token"), key: "draft-token") |
| + let attached = DocumentDetail(sqid: "real", title: "Renamed", guid: "g", can_write: true, can_share: false) |
| + for crashAfter in 0...8 { |
| + let disk = FaultingBlobStore(MemoryBlobStore(base.contents)) |
| + let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: network, transport: { nil }) |
| + disk.crash(after: crashAfter) |
| + do { try account.saveMetadata(DocsOfflineMetadata(detail: attached, pendingTitle: "Renamed"), key: "draft-token") } |
| + catch is SimulatedCrash { } |
| + let next = DocsOfflineAccount(store: disk.committed, accountID: "a", connectivity: network, transport: { nil }) |
| + let metadata = try XCTUnwrap(next.metadata("draft-token")) |
| + if metadata.draftToken == nil { |
| + XCTAssertEqual(try next.key(for: "real"), "draft-token", "Crash boundary \(crashAfter): discover attached bytes at their original sealed path") |
| + } |
| + XCTAssertEqual(metadata.pendingTitle, "Renamed") |
| + } |
| + } |
| + |
| + func testConcurrentReplicaCommitsMergeAndDiscardInvalidatesOldCaptures() async throws { |
| + let disk = MemoryBlobStore(), cache = DocsReplicaCache(store: disk), seed = try await initial() |
| + let a = CRDTReplica(guid: "offline-property"), b = CRDTReplica(guid: "offline-property") |
| + _ = try await a.open(update: seed); _ = try await b.open(update: seed) |
| + let outbox = Outbox(store: disk, account: "a") |
| + try await outbox.enqueue(lane: "doc:doc", kind: "update", payload: edit(a, "A")) |
| + try await outbox.enqueue(lane: "doc:doc", kind: "update", payload: edit(b, "B")) |
| + let first = PersistedReplica(format: 1, sequence: 2, guid: "offline-property", savedAt: Date(), state: try await a.persistentState().state) |
| + let second = PersistedReplica(format: 1, sequence: 3, guid: "offline-property", savedAt: Date(), state: try await b.persistentState().state) |
| + async let writeA = cache.commit(first, key: "doc", generation: 0) |
| + async let writeB = cache.commit(second, key: "doc", generation: 0) |
| + _ = try await (writeA, writeB) |
| + // An older editor capture must not erase the headless sender's state. |
| + try await cache.commit(first, key: "doc", generation: 0) |
| + let saved = try JSONDecoder().decode(PersistedReplica.self, from: XCTUnwrap(disk.contents["cache/docs/doc/replica"])) |
| + let checked = CRDTReplica(guid: "offline-property") |
| + let text = try await checked.open(update: saved.state).children.map(\.plainText).joined() |
| + XCTAssertEqual(text.count, 2); XCTAssertTrue(text.contains("A")); XCTAssertTrue(text.contains("B")) |
| + XCTAssertEqual(saved.sequence, 3) |
| + cache.invalidate("doc"); try disk.remove("cache/docs/doc/replica") |
| + do { try await cache.commit(first, key: "doc", generation: 0); XCTFail("A discarded capture must not write") } |
| + catch is CancellationError { } |
| + XCTAssertNil(disk.contents["cache/docs/doc/replica"]) |
| + await a.close(); await b.close(); await checked.close() |
| + } |
| + |
| + func testEveryDiscardCrashBoundaryLeavesNoStrandedReplica() async throws { |
| + let base = MemoryBlobStore(), replica = CRDTReplica(guid: "offline-property") |
| + let setup = DocsPersistence(store: base, outbox: Outbox(store: base, account: "a"), key: "doc", replica: replica) |
| + try await setup.reopen(fallback: initial(), sequence: 0) |
| + for text in ["A", "B"] { try await setup.enqueue(edit(replica, text)) } |
| + _ = try await setup.persist() |
| + for crashAfter in 0...6 { |
| + let disk = FaultingBlobStore(MemoryBlobStore(base.contents)) |
| + let queue = Outbox(store: disk, account: "a") |
| + try await queue.load() |
| + let lane = DocsPersistence(store: disk, outbox: queue, key: "doc", replica: replica) |
| + disk.crash(after: crashAfter) |
| + do { try await lane.discard() } catch is SimulatedCrash { } |
| + let frozen = disk.committed |
| + let entries = await Outbox(store: frozen, account: "a").entries(lane: "doc:doc") |
| + if frozen.contents[lane.path] != nil { |
| + XCTAssertEqual(entries.count, 2, "Crash \(crashAfter): no unsent text may survive without its complete lane") |
| + } |
| + } |
| + await replica.close() |
| + } |
| + |
| } |