WIP: save K3 durable Docs lane and crash tests at the mandatory disk stop
19 files changed,
+930
−63
docs/testing/k3-evidence.md+112 −0internal/docs/native_kill_test.go+40 −0native/apple/Package.resolved+1 −1native/apple/Package.swift+1 −1native/apple/Sources/DocsApp/DocsAccountWindow.swift+2 −2native/apple/Sources/DocsApp/DocsDocumentWindow.swift+1 −1native/apple/Sources/DocsKit/CRDTReplica.swift+15 −0native/apple/Sources/DocsKit/DocsModel.swift+147 −50native/apple/Sources/DocsKit/DocsModels.swift+1 −1native/apple/Sources/DocsKit/DocsOfflineAccount.swift+87 −0native/apple/Sources/DocsKit/DocsPersistence.swift+74 −0native/apple/Sources/DocsKit/DocsWorkspace.swift+10 −4native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift+284 −0native/apple/Tests/DocsKitTests/OfflineKillTests.swift+63 −0native/crdt/tests/snapshot.rs+28 −0native/ios/project.yml+1 −1native/macos/project.yml+1 −1native/scripts/test-offline-kill.py+61 −0native/smoke/document-window/Package.resolved+1 −1
CI passed — run details
diff --git a/docs/testing/k3-evidence.md b/docs/testing/k3-evidence.md| new file mode 100644 |
| index 0000000..7f99e8a |
| --- /dev/null |
| +++ b/docs/testing/k3-evidence.md |
| @@ -0,0 +1,112 @@ |
| +# K3 continuation: evidence and disk-stop handoff |
| + |
| +**WIP, not mergeable.** Work stopped on 2026-09-24 when free disk space |
| +reached 1.2 GiB, below the user's mandatory 1.5 GiB stop threshold. |
| +No merge or deployment occurred. Discussion: oficina/docs #69; kit: #9. |
| +The kit pin is 6b6b19814c8df182954db36f1f4637bd0cda181a on feat/k3-outbox. |
| + |
| +## Implemented, with partial validation |
| + |
| +- Per-account shared Outbox/OutboxDrainer and sealed metadata/replicas. |
| +- CRDTReplica atomically captures state, server sequence and commandsApplied |
| + using existing snapshot. DocsPersistence advances commandsDurable only after |
| + enqueue and writes only when commandsApplied == commandsDurable. |
| +- Reopen applies the persisted replica and the entire lane before publication. |
| +- Coalesced two-second writer, server catch-up/background/close flush hooks. |
| +- Compaction threshold and byte batching; queued input separated from unsent |
| + changes; visible local-storage failure and 32 MiB input stop. |
| +- Native status/banner adoption and app account IDs passed to the sealed store. |
| +- Ported parked-update test (NOT YET EXECUTED). |
| +- Integrating WASM fake, generated crash histories, exhaustive replacement |
| + boundaries, model reopen/transport test, storage-unlock regression. |
| +- A real authenticated Go-handler loopback server and SIGKILL harness. |
| + |
| +## Observed tests |
| + |
| +| Test | Failing-first evidence | Subsequent evidence | |
| +|---|---|---| |
| +| Watermark, lane reopen, generated history | No-op DocsPersistence + snapshot capture: 3 tests, 238 failures; /tmp/k3-docs-red.log | 3 tests passed; /tmp/k3-docs-green.log | |
| +| Each replace crash boundary + actual model reopen | Remove only lane replay: 2 tests, 5 failures on missing text; /tmp/k3-docs-integration-red.log | Included in 6 durability tests passing below | |
| +| Unlock resumes already queued commands | Current defect: 1 test, 3 failures; /tmp/k3-unlock-red.log | Passed after retry fixes | |
| +| Durability + account boundaries | Earlier full Swift run found 2 assertions failing in account-switch retry | 10 focused tests passed (6 durability, 4 account), /tmp/k3-docs-integration-green.log | |
| +| Seal count/rotation (kit) | Rotation call stubbed: both new tests failed | All 14 sealed-store tests passed; /tmp/k3-rotation-green-2.log | |
| +| Independent app retry (kit) | Retrying first lane prevented second sending | All 15 drainer tests passed; /tmp/k3-lane-retry-green.log | |
| + |
| +The initial full Docs Swift run executed 60 XCTest tests (3 skipped), with |
| +2 failed account-switch assertions, plus 16 passing Swift Testing tests. |
| +The focused rerun fixed those assertions, but a final full rerun remains. |
| + |
| +**Kill test is not a passing proof.** /tmp/k3-kill-red.log records a real |
| +SIGKILL after 12 durable typing edits with lane replay deliberately omitted. |
| +Recovery correctly failed its missing-text assertion, but the writer also |
| +failed its initial save assertion and server convergence failed independently. |
| +Investigate the initial save/server request path before claiming a valid |
| +negative control. The mutation was restored before saving this WIP. Run both |
| +red and green controls again. The test script should also refuse to proceed |
| +if its writer logged any assertion failure before the kill marker. |
| + |
| +The new native/crdt parked-update test still needs a failing run with |
| +Editor.snapshot using encode_diff_v1, then a passing run with the existing |
| +encode_state_as_update_v1. No new snapshot operation was added. |
| + |
| +## Remaining review findings (gpt-6-astra, read-only review) |
| + |
| +1. Preserve cached pendingTitle when metadata exists but replica is absent. |
| + The fallback fetch currently overwrites that durable rename with server data. |
| +2. Repair the draft attachment crash boundary between writing sqid index and |
| + attached metadata: stale draft metadata can leave the lane retrying forever. |
| +3. Serialize/retry title sends centrally. The current single model sender fixed |
| + competing account/model POSTs, but it sends pendingTitle only once: a second |
| + rename arriving during the first request can remain unsent indefinitely. |
| + Title-only transient errors also need an automatic retry/reopen owner. |
| +4. Start account replay when selecting an account into Home, without racing |
| + document reopen against ack/removal. Current starts cover open/newDraft, |
| + but Home itself does not start pending replay after a relaunch. |
| +5. Extend regression tests for the above before fixing, and rerun review. |
| +6. Audit draft/error recovery, local cap/hold semantics, unavailable-store |
| + status preservation and the once-only lost-content notice: incomplete UI |
| + recovery remains possible. The integrating fake's stream currently emits |
| + only its initial sequence; it still needs ongoing server-change delivery. |
| + |
| +Earlier review findings fixed: discard writer invalidation, storage unlock |
| +resuming queued commands, successful persistence clearing local failure, |
| +account-return retry, and independent lanes after an app-level retry. A |
| +competing title sender was removed. The latest draft-worker start placement |
| +has not had its own full rerun. |
| + |
| +## Spec differences and incomplete items |
| + |
| +- Discard removes the replica *before* its lane, rather than the textual order |
| + in §4.3. This deliberately prevents a process kill leaving a replica whose |
| + unsent lane was already deleted. A captured writer is invalidated first. |
| +- Empty/session-ended status currently resolves to saved, as the inherited |
| + kit tests expect; the spec's priority table lists session-ended before saved. |
| + Reconcile this explicitly instead of silently calling it exact conformance. |
| +- Kit adds load/entries/beginSend/endSend APIs to express replay and in-flight |
| + reservations. No update or retarget operation was introduced. |
| +- K5 reauthentication, subject migration, signout wipe and K6 first-400, |
| + terminal-hold UI, relaxed close guard/background send task remain deferred |
| + per their slice rows. Existing close/signout protection is still in place. |
| +- All unimplemented/review items above remain gaps, not approved deviations. |
| + |
| +## Remaining gates |
| + |
| +- rastrillo/native make ci: an earlier full pass predates the latest rotation |
| + and retry fixes. Run again at final head. Hub has no macOS runner and failed |
| + extracting Sparkle because unzip was absent; use local macOS make ci. |
| +- Docs .amadan/ci.d/10-gate: NOT RUN in this continuation. |
| +- Docs native/scripts/check-native.sh: NOT RUN as the full gate. Framework |
| + preparation, xcodegen and focused/full Swift runs were performed separately. |
| +- Run xcodegen before every xcodebuild. Put ~/.cargo/bin first on PATH; |
| + TMPDIR=/tmp. Run only one gate at a time. |
| +- Repeat real SIGKILL red/green controls after correcting its setup failure. |
| +- Full branch review, branch discussion updates, and current CI status. |
| + |
| +## Disk ownership |
| + |
| +At start, native-k3-outbox/.build already existed: it was not deleted. |
| +This session created, then removed companion build/, Docs native/apple/.build, |
| +native/crdt/target, native/host/target, native/build, and the generated |
| +DocsCRDT.xcframework. The generated Xcode projects remain ignored. No other |
| +session's outputs were removed. Cleanup briefly restored 1.7 GiB, then free |
| +space continued falling; do not restart builds without sufficient headroom. |
diff --git a/internal/docs/native_kill_test.go b/internal/docs/native_kill_test.go| new file mode 100644 |
| index 0000000..24bb3fc |
| --- /dev/null |
| +++ b/internal/docs/native_kill_test.go |
| @@ -0,0 +1,40 @@ |
| +package docs_test |
| + |
| +import ( |
| + "encoding/json" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// The kill script uses the actual authenticated application, update log and |
| +// snapshot handlers on loopback. No substitute server accepts the updates. |
| +func TestNativeKillServer(t *testing.T) { |
| + dir := os.Getenv("DOCS_KILL_DIR") |
| + if dir == "" { |
| + t.Skip("Run native/scripts/test-offline-kill.py") |
| + } |
| + app := members(t, "kill@example.com") |
| + cookies := signInCookies(t, app, "kill@example.com") |
| + sqid := createDoc(t, app, cookies, "Kill recovery") |
| + server := httptest.NewServer(app.Handler()) |
| + defer server.Close() |
| + config := map[string]string{"origin": server.URL, "sqid": sqid, "name": cookies[0].Name, "value": cookies[0].Value} |
| + data, err := json.Marshal(config) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(filepath.Join(dir, "connection.json"), data, 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + deadline := time.Now().Add(3 * time.Minute) |
| + for time.Now().Before(deadline) { |
| + if _, err := os.Stat(filepath.Join(dir, "done")); err == nil { |
| + return |
| + } |
| + time.Sleep(20 * time.Millisecond) |
| + } |
| + t.Fatal("kill script never completed") |
| +} |
diff --git a/native/apple/Package.resolved b/native/apple/Package.resolved| index 8032174..c33ea15 100644 |
| --- a/native/apple/Package.resolved |
| +++ b/native/apple/Package.resolved |
| @@ -6,7 +6,7 @@ |
| "kind" : "remoteSourceControl", |
| "location" : "https://amadan.net/rastrillo/native", |
| "state" : { |
| - "revision" : "14ee567be2e1816002c7db4274acaf2926983b4c" |
| + "revision" : "6b6b19814c8df182954db36f1f4637bd0cda181a" |
| } |
| }, |
| { |
diff --git a/native/apple/Package.swift b/native/apple/Package.swift| index b33e766..cf4f7e2 100644 |
| --- a/native/apple/Package.swift |
| +++ b/native/apple/Package.swift |
| @@ -3,7 +3,7 @@ import PackageDescription |
| import Foundation |
| let sharedNative: Package.Dependency = ProcessInfo.processInfo.environment["OFICINA_NATIVE_PACKAGE_PATH"].map { .package(name: "native", path: $0) } |
| - ?? .package(url: "https://amadan.net/rastrillo/native", revision: "14ee567be2e1816002c7db4274acaf2926983b4c") |
| + ?? .package(url: "https://amadan.net/rastrillo/native", revision: "6b6b19814c8df182954db36f1f4637bd0cda181a") |
| let package = Package(name: "DocsNative", defaultLocalization: "en", platforms: [.macOS(.v26), .iOS(.v26)], |
| products: [.library(name: "DocsKit", targets: ["DocsKit"]), .executable(name: "DocsMac", targets: ["DocsMac"])], |
diff --git a/native/apple/Sources/DocsApp/DocsAccountWindow.swift b/native/apple/Sources/DocsApp/DocsAccountWindow.swift| index 6f33d51..9a3c92b 100644 |
| --- a/native/apple/Sources/DocsApp/DocsAccountWindow.swift |
| +++ b/native/apple/Sources/DocsApp/DocsAccountWindow.swift |
| @@ -22,7 +22,7 @@ struct DocsAccountWindow: View { |
| if let client = connection.client { |
| #if os(macOS) |
| if let account = connection.activeAccountID { |
| - DocsWorkspace(client: client, transport: transport(for: account), accounts: connection.showAccounts, signOut: { |
| + DocsWorkspace(client: client, accountID: account, transport: transport(for: account), accounts: connection.showAccounts, signOut: { |
| guard connection.activeAccountID == account, windows.canSignOut(account) else { return } |
| windows.entries.removeAll { $0.account == account } |
| connection.signOut() |
| @@ -41,7 +41,7 @@ struct DocsAccountWindow: View { |
| .id(account) |
| } |
| #else |
| - DocsWorkspace(client: client, transport: transport(for: connection.activeAccountID), accounts: connection.showAccounts, signOut: connection.signOut) |
| + DocsWorkspace(client: client, accountID: connection.activeAccountID, transport: transport(for: connection.activeAccountID), accounts: connection.showAccounts, signOut: connection.signOut) |
| .id(connection.activeAccountID) |
| #endif |
| } else { |
diff --git a/native/apple/Sources/DocsApp/DocsDocumentWindow.swift b/native/apple/Sources/DocsApp/DocsDocumentWindow.swift| index 0fdf391..941e00d 100644 |
| --- a/native/apple/Sources/DocsApp/DocsDocumentWindow.swift |
| +++ b/native/apple/Sources/DocsApp/DocsDocumentWindow.swift |
| @@ -8,7 +8,7 @@ struct DocsDocumentWindow: View { |
| @Environment(\.openWindow) private var openWindow |
| var body: some View { |
| if let entry = windows.entries.first(where: { $0.id == id }) { |
| - DocsWorkspace(client: entry.client, signOut: {}, documentID: entry.document, newDocument: entry.isDraft, documentChanged: { document, title in windows.attach(entry.id, document: document, title: title) }) |
| + DocsWorkspace(client: entry.client, accountID: entry.account, signOut: {}, documentID: entry.document, newDocument: entry.isDraft, documentChanged: { document, title in windows.attach(entry.id, document: document, title: title) }) |
| .id(entry.id) |
| .focusedSceneValue(\.docsWindowAccount, entry.account) |
| .onAppear { windows.setOpen(entry.id, true) } |
diff --git a/native/apple/Sources/DocsKit/CRDTReplica.swift b/native/apple/Sources/DocsKit/CRDTReplica.swift| index f9b987e..07b9bce 100644 |
| --- a/native/apple/Sources/DocsKit/CRDTReplica.swift |
| +++ b/native/apple/Sources/DocsKit/CRDTReplica.swift |
| @@ -32,9 +32,22 @@ actor CRDTReplica { |
| // IDs remain reserved for this session even when a source is retired or traps. |
| private var reserved: Set<UInt64> = [] |
| private var lastGood = Data() |
| + private var commandsApplied = 0 |
| + private var durableSequence: Int64 = 0 |
| private let guid: String |
| enum Failure: Error { case unavailable, rejected, invalidProjection, generationLimit } |
| init(guid: String) { self.guid = guid } |
| + struct PersistentState: Sendable { |
| + let state: Data |
| + let sequence: Int64 |
| + let commandsApplied: Int |
| + let guid: String |
| + } |
| + func persistentState() throws -> PersistentState { |
| + _ = try currentAuthority() |
| + return PersistentState(state: lastGood, sequence: durableSequence, commandsApplied: commandsApplied, guid: guid) |
| + } |
| + func setSequence(_ sequence: Int64) { durableSequence = max(durableSequence, sequence) } |
| func close() { opened = false; authority = nil; merger = nil; sources.removeAll(); sourceSnapshots.removeAll(); lastGood = Data() } |
| private func fresh(update: Data) throws -> (UInt64, Sandbox) { |
| let sandbox = try Sandbox() |
| @@ -51,6 +64,7 @@ actor CRDTReplica { |
| } |
| func open(update: Data) throws -> CRDTProjection { |
| sources.removeAll(); sourceSnapshots.removeAll() |
| + commandsApplied = 0; durableSequence = 0 |
| authority = try fresh(update: update).1 |
| opened = true |
| lastGood = try authority!.invoke(["op": .string("snapshot")]) |
| @@ -148,6 +162,7 @@ actor CRDTReplica { |
| let projected = try authority.projection() |
| lastGood = try authority.invoke(["op": .string("snapshot")]) |
| if writer !== authority, let generation { sourceSnapshots[generation] = sourceAfter } |
| + commandsApplied += 1 |
| return (update, projected) |
| } catch { |
| if writer !== authority, let generation { sources[generation] = try? fresh(update: sourceBefore).1 } |
diff --git a/native/apple/Sources/DocsKit/DocsModel.swift b/native/apple/Sources/DocsKit/DocsModel.swift| index 1121011..d6ed5e8 100644 |
| --- a/native/apple/Sources/DocsKit/DocsModel.swift |
| +++ b/native/apple/Sources/DocsKit/DocsModel.swift |
| @@ -1,6 +1,7 @@ |
| import Foundation |
| import Observation |
| import RastrilloApple |
| +import RastrilloNative |
| @MainActor @Observable final class DocsModel { |
| enum ListState { case loading, loaded, failed } |
| @@ -31,7 +32,18 @@ import RastrilloApple |
| var typingMarks: [String: JSONValue]? |
| private var replica: CRDTReplica? |
| private var sequence: Int64 = 0 |
| - private var pending: [Data] = [] |
| + let offlineAccount: DocsOfflineAccount |
| + private var persistence: DocsPersistence? |
| + private var documentKey: String? |
| + private var failedUpdate: Data? |
| + private var localFailure: SyncFailure? |
| + private var writerTask: Task<Void, Never>? |
| + private let writer = CoalescedRunner() |
| + private var laneSummary = OutboxSummary() |
| + private var summaryTask: Task<Void, Never>? |
| + var syncStatus: SyncStatus { offlineAccount.drainer.status(lane: documentKey.map { "doc:" + $0 }, localFailure: localFailure) } |
| + var outboxSummary: OutboxSummary { offlineAccount.drainer.summary } |
| + |
| private var editing: [[String: JSONValue]] = [] |
| private var editingTask: Task<Void, Never>? |
| private var streamTask: Task<Void, Never>? |
| @@ -48,9 +60,10 @@ import RastrilloApple |
| let connectivity: NativeConnectivity |
| /// Monotonic seconds for the stream loop's pacing; tests substitute a fake. |
| var reconnectClock: @MainActor () -> TimeInterval = { ProcessInfo.processInfo.systemUptime } |
| - init(transport: @escaping @MainActor () -> NativeTransport?, connectivity: NativeConnectivity? = nil, draft: Bool = false) { |
| + init(transport: @escaping @MainActor () -> NativeTransport?, connectivity: NativeConnectivity? = nil, draft: Bool = false, offlineAccount: DocsOfflineAccount? = nil) { |
| self.transport = transport |
| self.connectivity = connectivity ?? .shared |
| + self.offlineAccount = offlineAccount ?? DocsOfflineAccount(store: EphemeralDocsStore(), accountID: UUID().uuidString, connectivity: connectivity ?? .shared, transport: transport) |
| if draft { draftToken = UUID().uuidString } |
| } |
| convenience init(client: NativeTransport, connectivity: NativeConnectivity? = nil, draft: Bool = false) { |
| @@ -61,7 +74,56 @@ import RastrilloApple |
| return current |
| } |
| var hasPendingInput: Bool { !editing.isEmpty || editingTask != nil } |
| - var hasUnsavedChanges: Bool { (renameInput != nil && renameInput != detail?.title) || isDraft || pendingTitle != nil || composing || !pending.isEmpty || !editing.isEmpty || editingTask != nil } |
| + var hasUnpersistedInput: Bool { (renameInput != nil && renameInput != detail?.title) || composing || !editing.isEmpty || editingTask != nil || failedUpdate != nil || localFailure == .cannotSaveOnDevice } |
| + var hasUnsentChanges: Bool { !laneSummary.isEmpty || pendingTitle != nil || isDraft } |
| + // K6 relaxes the close guard; K3 exposes the split without bypassing it. |
| + 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) |
| + 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) |
| + } |
| + } |
| + } |
| + private func saveMetadata() throws { |
| + guard let documentKey, let detail else { return } |
| + try offlineAccount.saveMetadata(DocsOfflineMetadata(detail: detail, pendingTitle: pendingTitle, draftToken: draftToken), key: documentKey) |
| + } |
| + private func schedulePersistence() { |
| + writerTask?.cancel() |
| + writerTask = Task { [weak self] in |
| + do { try await Task.sleep(for: .seconds(2)) } catch { return } |
| + await self?.persistReplica() |
| + } |
| + } |
| + func persistReplica() async { |
| + 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 |
| + if self.detail?.can_write == true { self.inputPaused = false } |
| + } |
| + } catch { self.localFailure = .cannotSaveOnDevice; self.inputPaused = true } |
| + } |
| + } |
| + private func durable(_ update: Data) async throws { |
| + guard let persistence else { throw BlobStoreError.unavailable } |
| + failedUpdate = update |
| + try await persistence.enqueue(update) |
| + failedUpdate = nil |
| + laneSummary = await offlineAccount.outbox.summary.only(persistence.lane) |
| + if (laneSummary.lanes[persistence.lane]?.bytes ?? 0) > 32 * 1024 * 1024 { |
| + localFailure = .tooManyUnsent; inputPaused = true |
| + } |
| + try await persistence.compact() |
| + } |
| func load(query: String = "") async { |
| let request = UUID(); listRequest = request |
| listState = .loading |
| @@ -91,10 +153,14 @@ import RastrilloApple |
| _ = try await local.open(update: Data()) |
| let (update, _) = try await local.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")]) |
| guard documentEpoch == epoch else { await local.close(); return } |
| - replica = local; pending.append(update) |
| + replica = local |
| + configurePersistence(key: "draft-" + draftToken!, replica: local) |
| detail = DocumentDetail(sqid: "draft-" + draftToken!, title: String(localized: "docs.document.untitled", bundle: DocsResources.bundle), guid: guid, can_write: true, can_share: false) |
| + try saveMetadata() |
| + try await durable(update) |
| await publish() |
| guard documentEpoch == epoch else { return } |
| + offlineAccount.drainer.start() |
| startCreation() |
| } catch { if documentEpoch == epoch { errorKey = "native.pending" } } |
| } |
| @@ -123,6 +189,10 @@ import RastrilloApple |
| 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() } |
| guard documentEpoch == epoch else { return } |
| @@ -149,6 +219,7 @@ import RastrilloApple |
| guard title != detail.title else { return true } |
| self.detail = DocumentDetail(sqid: detail.sqid, title: title, guid: detail.guid, can_write: detail.can_write, can_share: detail.can_share) |
| pendingTitle = title; titleRevision &+= 1 |
| + do { try saveMetadata() } catch { localFailure = .cannotSaveOnDevice; inputPaused = true; return false } |
| Task { await flush() } |
| return true |
| } |
| @@ -162,14 +233,30 @@ import RastrilloApple |
| guard documentEpoch == epoch else { return } |
| defer { if documentEpoch == epoch { loading = false } } |
| do { |
| - let detail: DocumentDetail = try await client().request("/d/\(sqid)") |
| - let reply = try await client().responseDetails("/d/\(sqid)/updates", maxBytes: 8 * 1024 * 1024) |
| - guard reply.status == 200, let seq = Int64(reply.header("Docs-Seq") ?? "") else { throw CRDTReplica.Failure.rejected } |
| + let key = try offlineAccount.key(for: sqid) |
| + let cached = try offlineAccount.metadata(key) |
| + 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 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 } |
| + initial = reply.data; seq = cursor |
| + } |
| guard documentEpoch == epoch else { return } |
| let replica = CRDTReplica(guid: detail.guid) |
| - let projection = try await replica.open(update: reply.data) |
| + configurePersistence(key: key, replica: replica) |
| + try await persistence!.reopen(fallback: initial, sequence: seq) |
| + let projection = try await replica.projection() |
| guard documentEpoch == epoch else { await replica.close(); return } |
| - self.replica = replica; self.detail = detail; sequence = seq |
| + self.replica = replica; self.detail = detail |
| + sequence = try await replica.persistentState().sequence |
| + laneSummary = await offlineAccount.outbox.summary.only("doc:" + key) |
| + try saveMetadata() |
| projectionGeneration = 0; renderedGeneration = 0 |
| selection = NSRange(location: 0, length: 0); typingMarks = nil |
| composing = false; inputPaused = false |
| @@ -178,12 +265,14 @@ import RastrilloApple |
| if projection.children.isEmpty && detail.can_write { |
| enqueue(["op":.string("insert_element"), "at":.number(0), "type":.string("paragraph")]) |
| } |
| + await persistReplica() |
| + offlineAccount.drainer.start() |
| streamTask = Task { [weak self] in await self?.listen(sqid) } |
| } catch { if documentEpoch == epoch { errorKey = "docs.error.generic"; detail = nil; projection = nil } } |
| } |
| @discardableResult func enqueue(_ command: [String: JSONValue]) -> Bool { |
| guard !inputPaused, detail?.can_write == true else { return false } |
| - let buffered = pending.reduce(0) { $0 + $1.count } + editing.reduce(0) { $0 + ((try? JSONEncoder().encode($1).count) ?? 0) } |
| + let buffered = editing.reduce(0) { $0 + ((try? JSONEncoder().encode($1).count) ?? 0) } |
| guard let incoming = try? JSONEncoder().encode(command).count, incoming <= 2 * 1024 * 1024 - buffered else { errorKey = "native.pending"; return false } |
| var command = command |
| if case .number(let generation) = command["generation"], let value = UInt64(exactly: generation) { didRender(value) } |
| @@ -202,7 +291,8 @@ import RastrilloApple |
| do { |
| let (update, _) = try await replica.command(command) |
| guard documentEpoch == epoch else { return } |
| - pending.append(update) |
| + do { try await durable(update) } |
| + catch { localFailure = .cannotSaveOnDevice; inputPaused = true; break } |
| if editing.isEmpty { await publish() } |
| } catch { |
| guard documentEpoch == epoch else { return } |
| @@ -233,17 +323,34 @@ import RastrilloApple |
| let source = renderedGeneration; let selected = selection |
| if let (generation, projected, resolved) = try await replica.presentation(source: source, selection: selected, allowReuse: source == projectionGeneration), editing.isEmpty, source == renderedGeneration, selected == selection, !composing, documentEpoch == epoch, generation >= projectionGeneration { |
| selection = resolved; projectionGeneration = generation; projection = projected |
| + schedulePersistence() |
| } |
| } catch { if documentEpoch == epoch { errorKey = "native.recovered" } } |
| } |
| func retry() async { |
| + let epoch = documentEpoch |
| + 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 |
| + await persistReplica() |
| + guard localFailure == nil else { return } |
| + } catch { return } |
| + } |
| + if editingTask == nil, !editing.isEmpty, !inputPaused { |
| + editingTask = Task { await drainEdits() } |
| + } |
| if isDraft { |
| if replica == nil { await newDraft() } else { startCreation() } |
| await creationTask?.value |
| return |
| } |
| + if transport() != nil { offlineAccount.drainer.sessionRestored() } |
| + offlineAccount.drainer.retryNow() |
| if inputPaused { |
| - let epoch = documentEpoch |
| if let detail { await refreshAccess(detail.sqid, epoch: epoch) } |
| guard documentEpoch == epoch, detail?.can_write == true else { return } |
| inputPaused = false; errorKey = nil |
| @@ -252,20 +359,30 @@ import RastrilloApple |
| } |
| func stop() async { |
| lifetime = UUID() |
| + await persistReplica() |
| guard !hasUnsavedChanges else { return } |
| documentEpoch = UUID(); streamTask?.cancel(); streamTask = nil |
| + writerTask?.cancel(); summaryTask?.cancel() |
| let previous = replica; replica = nil; detail = nil; projection = nil |
| if let previous { await previous.close() } |
| } |
| /// Discard only unsent local draft state. An already acknowledged network |
| /// update remains part of the shared document, as in the web editor. |
| func discardAll() async { |
| + documentEpoch = UUID() |
| + writerTask?.cancel(); editingTask?.cancel(); streamTask?.cancel() |
| + do { |
| + try await persistence?.discard() |
| + if let documentKey { try offlineAccount.store.remove("cache/docs/\(documentKey)/meta") } |
| + } catch { localFailure = .cannotSaveOnDevice; return } |
| + writerTask?.cancel(); summaryTask?.cancel(); persistence = nil; documentKey = nil |
| + laneSummary = OutboxSummary(); failedUpdate = nil; localFailure = nil |
| documentEpoch = UUID() |
| creationTask?.cancel(); creationTask = nil; creatingDocument = false |
| draftToken = nil; pendingTitle = nil; renameInput = nil |
| streamTask?.cancel(); streamTask = nil |
| editingTask?.cancel(); editingTask = nil |
| - pending.removeAll(); editing.removeAll(); saving = false |
| + editing.removeAll(); saving = false |
| composing = false; inputPaused = false; typingMarks = nil |
| selection = NSRange(location: 0, length: 0) |
| let previous = replica; replica = nil; detail = nil; projection = nil |
| @@ -278,51 +395,29 @@ import RastrilloApple |
| if let editingTask { await editingTask.value } |
| while saving { try? await Task.sleep(for: .milliseconds(20)) } |
| await flush() |
| + await persistReplica() |
| return !hasUnsavedChanges |
| } |
| func flush() async { |
| - guard !isDraft, !saving, let detail, let replica else { return }; saving = true |
| + guard !isDraft, !saving, let detail, let persistence else { return }; saving = true |
| let epoch = documentEpoch |
| defer { if documentEpoch == epoch { saving = false } } |
| - while !pending.isEmpty || pendingTitle != nil { |
| - if let title = pendingTitle { |
| - do { |
| - let (_, status) = try await client().response("/d/\(detail.sqid)/title", method: "POST", body: Self.form(["title": title]), contentType: "application/x-www-form-urlencoded") |
| - guard documentEpoch == epoch else { return } |
| - guard status == 204 else { throw CRDTReplica.Failure.rejected } |
| - if pendingTitle == title { pendingTitle = nil } |
| - } catch { if documentEpoch == epoch { errorKey = "native.pending" }; return } |
| - } |
| - if pending.isEmpty { continue } |
| + // Titles are metadata rather than CRDT updates. Send them first even |
| + // when this lane contains no text updates. |
| + if let title = pendingTitle { |
| do { |
| - // A slow request must not leave one full round trip per keypress. |
| - // Keep the captured prefix until acknowledgement; edits appended |
| - // during either await belong to the next batch. |
| - var bytes = 0 |
| - let batch = pending.prefix { update in |
| - guard bytes == 0 || bytes + update.count <= 512 * 1024 else { return false } |
| - bytes += update.count |
| - return true |
| - } |
| - var count = batch.count |
| - let update: Data |
| - do { update = try await replica.mergeUpdates(Array(batch)) } |
| - catch { |
| - // An optimization hitting its sandbox limit must not block saving. |
| - update = batch.first! |
| - count = 1 |
| - } |
| + 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 } |
| - let (_, status) = try await client().response("/d/\(detail.sqid)/updates", method: "POST", body: update, contentType: "application/octet-stream") |
| - guard documentEpoch == epoch else { return } |
| - guard status == 204 else { |
| - if status == 401 || status == 403 || status == 404 { await refreshAccess(detail.sqid, epoch: epoch) } |
| - throw CRDTReplica.Failure.rejected |
| - } |
| - pending.removeFirst(count) |
| - } catch { if documentEpoch == epoch { errorKey = "native.pending" }; return } |
| + if pendingTitle == title { pendingTitle = nil; try saveMetadata() } |
| + } catch { errorKey = "native.pending"; return } |
| } |
| - if errorKey == "native.pending" || errorKey == "docs.editor.status.retrying" { errorKey = nil } |
| + await offlineAccount.drainer.drain() |
| + guard documentEpoch == epoch else { return } |
| + laneSummary = await offlineAccount.outbox.summary.only(persistence.lane) |
| + if laneSummary.isEmpty { |
| + if errorKey == "native.pending" || errorKey == "docs.editor.status.retrying" { errorKey = nil } |
| + } else { errorKey = "native.pending" } |
| } |
| private func listen(_ sqid: String) async { |
| let epoch = documentEpoch |
| @@ -359,6 +454,8 @@ import RastrilloApple |
| _ = try await replica.apply(reply.data) |
| guard self.detail?.sqid == sqid, self.replica === replica else { return } |
| sequence = max(sequence, seq) |
| + await replica.setSequence(sequence) |
| + await persistReplica() |
| if editing.isEmpty && editingTask == nil { await publish() } |
| await flush() |
| } catch { if documentEpoch == epoch { errorKey = "docs.editor.status.retrying" } } |
diff --git a/native/apple/Sources/DocsKit/DocsModels.swift b/native/apple/Sources/DocsKit/DocsModels.swift| index 26f70d4..4585b32 100644 |
| --- a/native/apple/Sources/DocsKit/DocsModels.swift |
| +++ b/native/apple/Sources/DocsKit/DocsModels.swift |
| @@ -8,7 +8,7 @@ struct DocumentSummary: Decodable, Identifiable, Sendable { |
| var id: String { sqid } |
| } |
| struct DocumentList: Decodable, Sendable { let documents: [DocumentSummary]; let can_create: Bool } |
| -struct DocumentDetail: Decodable, Sendable { |
| +struct DocumentDetail: Codable, Sendable { |
| let sqid: String |
| let title: String |
| let guid: String |
diff --git a/native/apple/Sources/DocsKit/DocsOfflineAccount.swift b/native/apple/Sources/DocsKit/DocsOfflineAccount.swift| new file mode 100644 |
| index 0000000..54586b9 |
| --- /dev/null |
| +++ b/native/apple/Sources/DocsKit/DocsOfflineAccount.swift |
| @@ -0,0 +1,87 @@ |
| +import Foundation |
| +import Observation |
| +import RastrilloApple |
| +import RastrilloNative |
| + |
| +struct DocsOfflineMetadata: Codable { |
| + var detail: DocumentDetail |
| + var pendingTitle: String? |
| + var draftToken: String? |
| +} |
| + |
| +/// All windows for an account share the same outbox and send reservation. |
| +@MainActor @Observable final class DocsOfflineAccount { |
| + private static var accounts: [String: DocsOfflineAccount] = [:] |
| + let store: BlobStore |
| + let outbox: Outbox |
| + let connectivity: NativeConnectivity |
| + private var supplier: @MainActor () -> NativeTransport? |
| + private(set) var drainer: OutboxDrainer! |
| + static func account(_ id: String, origin: URL, fallback: NativeTransport, transport: (@MainActor () -> NativeTransport?)?) -> DocsOfflineAccount { |
| + if let existing = accounts[id] { if let transport { existing.supplier = transport; existing.drainer.sessionRestored() }; return existing } |
| + let root = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] |
| + .appendingPathComponent(Bundle.main.bundleIdentifier ?? "works.oficina.docs") |
| + .appendingPathComponent("accounts").appendingPathComponent(id) |
| + let store = NativeSealedStore(root: root, accountID: id, keys: KeychainKeyProvider(accountID: id, origin: origin)) |
| + let account = DocsOfflineAccount(store: store, accountID: id, connectivity: .shared, transport: transport ?? { fallback }) |
| + accounts[id] = account; return account |
| + } |
| + init(store: BlobStore, accountID: String, connectivity: NativeConnectivity, transport: @escaping @MainActor () -> NativeTransport?) { |
| + self.store = store; outbox = Outbox(store: store, account: accountID) |
| + 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() } |
| + return try await self.send(lane, entries: entries, transport: transport) |
| + } |
| + } |
| + func metadata(_ key: String) throws -> DocsOfflineMetadata? { |
| + guard let bytes = try store.read("cache/docs/\(key)/meta") else { return nil } |
| + return try JSONDecoder().decode(DocsOfflineMetadata.self, from: bytes) |
| + } |
| + func saveMetadata(_ metadata: DocsOfflineMetadata, key: String) throws { |
| + try store.write(JSONEncoder().encode(metadata), to: "cache/docs/\(key)/meta") |
| + } |
| + 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 |
| + } |
| + 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") |
| + } |
| + 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) }) |
| + } |
| + // 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) }) |
| + } |
| + 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() |
| + 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) }) |
| + } |
| +} |
| + |
| +/// Used only by previews and callers that have no NativeAccount (unit tests). |
| +/// The application always supplies its per-account sealed store. |
| +final class EphemeralDocsStore: BlobStore, @unchecked Sendable { |
| + private let lock = NSLock() |
| + private var files: [String: Data] = [:] |
| + func read(_ path: String) throws -> Data? { lock.withLock { files[path] } } |
| + func write(_ data: Data, to path: String) throws { lock.withLock { files[path] = data } } |
| + func remove(_ path: String) throws { lock.withLock { files = files.filter { $0.key != path && !$0.key.hasPrefix(path + "/") } } } |
| + func list(_ directory: String) throws -> [String] { lock.withLock { |
| + files.keys.filter { $0.hasPrefix(directory + "/") }.map { String($0.dropFirst(directory.count + 1)) }.filter { !$0.contains("/") }.sorted() |
| + } } |
| +} |
diff --git a/native/apple/Sources/DocsKit/DocsPersistence.swift b/native/apple/Sources/DocsKit/DocsPersistence.swift| new file mode 100644 |
| index 0000000..08e7000 |
| --- /dev/null |
| +++ b/native/apple/Sources/DocsKit/DocsPersistence.swift |
| @@ -0,0 +1,74 @@ |
| +import Foundation |
| +import RastrilloNative |
| + |
| +struct PersistedReplica: Codable, Sendable { |
| + let format: Int |
| + let sequence: Int64 |
| + let guid: String |
| + let savedAt: Date |
| + let state: Data |
| +} |
| + |
| +/// One document's durability boundary. The writer and editor share this |
| +/// watermark, but only a successful outbox write may advance it. |
| +@MainActor final class DocsPersistence { |
| + let store: BlobStore |
| + let outbox: Outbox |
| + let key: String |
| + let replica: CRDTReplica |
| + private(set) var commandsDurable = 0 |
| + private var active = true |
| + var lane: String { "doc:" + key } |
| + var path: String { "cache/docs/" + key + "/replica" } |
| + init(store: BlobStore, outbox: Outbox, key: String, replica: CRDTReplica) { |
| + self.store = store; self.outbox = outbox; self.key = key; self.replica = replica |
| + } |
| + func reopen(fallback: Data, sequence: Int64) async throws { |
| + try await outbox.load() |
| + 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) } |
| + commandsDurable = 0 |
| + } |
| + func enqueue(_ update: Data) async throws { |
| + try await outbox.enqueue(lane: lane, kind: "update", payload: update) |
| + commandsDurable += 1 |
| + } |
| + @discardableResult func persist() async throws -> Bool { |
| + let captured = try await replica.persistentState() |
| + // No suspension between checking the watermark and the atomic write. |
| + // 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 |
| + } |
| + 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 !batch.isEmpty && bytes + entry.payload.count > 512 * 1024 { break } |
| + batch.append(entry); bytes += entry.payload.count |
| + } |
| + guard batch.count > 1 else { return } |
| + let merged = try await replica.mergeUpdates(batch.map(\.payload)) |
| + guard merged.count <= 512 * 1024 else { return } |
| + // A send can reserve the batch while mergeUpdates suspends. Refusing |
| + // that compaction is expected; it must never delete the reservation. |
| + do { try await outbox.replace(batch.map(\.id), with: merged) } |
| + catch OutboxError.inFlight { } |
| + catch OutboxError.unknownEntry { } |
| + } |
| + func discard() async throws { |
| + active = false |
| + // 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) |
| + try await outbox.discard(lane: lane) |
| + } |
| +} |
diff --git a/native/apple/Sources/DocsKit/DocsWorkspace.swift b/native/apple/Sources/DocsKit/DocsWorkspace.swift| index 004cb35..256a6d8 100644 |
| --- a/native/apple/Sources/DocsKit/DocsWorkspace.swift |
| +++ b/native/apple/Sources/DocsKit/DocsWorkspace.swift |
| @@ -12,6 +12,7 @@ import SwiftUI |
| @State private var sharing = false |
| @State private var exportRequest: String? |
| @Environment(\.openWindow) private var openWindow |
| + @Environment(\.scenePhase) private var scenePhase |
| @State private var jumping = false |
| @State private var discarding = false |
| @State private var images = DocsImageStore() |
| @@ -29,10 +30,11 @@ import SwiftUI |
| private let client: NativeHTTP |
| /// `transport` supplies the account's current session to the model on every |
| /// request; without one the model keeps `client` for its whole lifetime. |
| - public init(client: NativeHTTP, transport: (@MainActor () -> NativeTransport?)? = nil, accounts: (() -> Void)? = nil, signOut: @escaping () -> Void, documentID: String? = nil, newDocument: Bool = false, createDocument: (() -> Void)? = nil, documentChanged: ((String, String) -> Void)? = nil, canSignOut: Bool = true, createRequested: Binding<Bool> = .constant(false), accountsRequested: Binding<Bool> = .constant(false), openDocument: ((String, String) -> Void)? = nil, updateRecents: (([(String, String)]) -> Void)? = nil) { |
| + public init(client: NativeHTTP, accountID: String? = nil, transport: (@MainActor () -> NativeTransport?)? = nil, accounts: (() -> Void)? = nil, signOut: @escaping () -> Void, documentID: String? = nil, newDocument: Bool = false, createDocument: (() -> Void)? = nil, documentChanged: ((String, String) -> Void)? = nil, canSignOut: Bool = true, createRequested: Binding<Bool> = .constant(false), accountsRequested: Binding<Bool> = .constant(false), openDocument: ((String, String) -> Void)? = nil, updateRecents: (([(String, String)]) -> Void)? = nil) { |
| self.updateRecents = updateRecents; self.canSignOut = canSignOut; self._createRequested = createRequested; self._accountsRequested = accountsRequested; self.documentID = documentID; self.openDocument = openDocument |
| self.newDocument = newDocument; self.createDocument = createDocument; self.documentChanged = documentChanged |
| - _model = State(initialValue: transport.map { DocsModel(transport: $0, draft: newDocument) } ?? DocsModel(client: client, draft: newDocument)); self.signOut = signOut; self.accounts = accounts; self.client = client |
| + let offline = accountID.map { DocsOfflineAccount.account($0, origin: client.origin, fallback: client, transport: transport) } |
| + _model = State(initialValue: DocsModel(transport: transport ?? { client }, draft: newDocument, offlineAccount: offline)); self.signOut = signOut; self.accounts = accounts; self.client = client |
| } |
| private var library: some View { |
| List { |
| @@ -68,8 +70,7 @@ import SwiftUI |
| #endif |
| } |
| .safeAreaInset(edge: .top, spacing: 0) { |
| - NativeOfflineBanner(connectivity: model.connectivity, origin: client.origin, |
| - message: String(localized: "docs.offline.banner", defaultValue: "You’re offline. Waiting for a connection.", bundle: DocsResources.bundle)) |
| + NativeOfflineBanner(connectivity: model.connectivity, origin: client.origin, summary: model.outboxSummary) |
| } |
| .onChange(of: model.documents.map { "\($0.sqid)\u{0}\($0.title)" }) { |
| @@ -88,6 +89,10 @@ import SwiftUI |
| } |
| .sheet(isPresented: $jumping) { DocsJumpSheet(model: model, client: client) } |
| .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 os(macOS) |
| .background { DocsCloseGuard(hasUnsaved: { model.hasUnsavedChanges }, save: { await model.saveAll() }, discard: { await model.discardAll() }).frame(width: 0, height: 0) } |
| #endif |
| @@ -147,6 +152,7 @@ import SwiftUI |
| } |
| private var editor: some View { |
| VStack(spacing: 0) { |
| + NativeSyncStatusView(status: model.syncStatus) |
| if let key = model.errorKey { |
| HStack { |
| Text(LocalizedStringKey(key), bundle: DocsResources.bundle) |
diff --git a/native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift b/native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift| new file mode 100644 |
| index 0000000..f90eb62 |
| --- /dev/null |
| +++ b/native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift |
| @@ -0,0 +1,284 @@ |
| +import Foundation |
| +import RastrilloApple |
| +import RastrilloNative |
| +import RastrilloTestSupport |
| +import XCTest |
| +@testable import DocsKit |
| + |
| +/// Uses the production WASM replica: a lost response really integrates bytes. |
| +private actor IntegratingServer: NativeTransport { |
| + nonisolated let origin = URL(string: "http://localhost:8099")! |
| + var online = true |
| + var loseNextResponse = false |
| + var sequence: Int64 = 0 |
| + func setOnline(_ value: Bool) { online = value } |
| + let replica = CRDTReplica(guid: "offline-property") |
| + var accepted: [UUID: Data] = [:] |
| + func open(_ initial: Data) async throws { _ = try await replica.open(update: initial) } |
| + func accept(_ entries: [OutboxEntry]) async throws { |
| + for entry in entries { _ = try await replica.apply(entry.payload); accepted[entry.id] = entry.payload } |
| + } |
| + func snapshot() async throws -> Data { try await replica.persistentState().state } |
| + 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("/updates"), let body { |
| + _ = try await replica.apply(body); sequence += 1 |
| + if loseNextResponse { loseNextResponse = false; throw NativeClientError.offline(.networkConnectionLost) } |
| + return NativeResponse(data: Data(), status: 204, headers: [:]) |
| + } |
| + 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) |
| + 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 { |
| + guard online else { throw NativeClientError.offline(.notConnectedToInternet) } |
| + try await onOpen(); try await onLine("data: \(sequence)") |
| + try await Task.sleep(for: .seconds(3600)) |
| + } |
| + func download(_ path: String, to destination: URL) async throws { throw NativeClientError.notFound } |
| + |
| + func contains(_ id: UUID) -> Bool { accepted[id] != nil } |
| +} |
| +private struct OfflineRandom: RandomNumberGenerator { |
| + var seed: UInt64 |
| + mutating func next() -> UInt64 { seed = seed &* 6364136223846793005 &+ 1442695040888963407; return seed } |
| +} |
| +@MainActor final class OfflineDurabilityTests: XCTestCase { |
| + private func initial() async throws -> Data { |
| + let seed = CRDTReplica(guid: "offline-property") |
| + _ = try await seed.open(update: Data()) |
| + let (update, _) = try await seed.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")]) |
| + await seed.close(); return update |
| + } |
| + private func edit(_ replica: CRDTReplica, _ text: String) async throws -> Data { |
| + let projection = try await replica.projection() |
| + let at = projection.children.map(\.plainText).joined().utf16.count |
| + return try await replica.command(["op": .string("display_edit"), "at": .number(Double(at)), "length": .number(0), "text": .string(text)]).0 |
| + } |
| + func testWriterBetweenCommandAndEnqueueCannotPersistTheCommand() async throws { |
| + let disk = MemoryBlobStore(), initial = try await initial() |
| + let replica = CRDTReplica(guid: "offline-property") |
| + let lane = DocsPersistence(store: disk, outbox: Outbox(store: disk, account: "a"), key: "doc", replica: replica) |
| + try await lane.reopen(fallback: initial, sequence: 17) |
| + let wroteInitial = try await lane.persist() |
| + XCTAssertTrue(wroteInitial) |
| + let before = disk.contents[lane.path] |
| + let update = try await edit(replica, "A") |
| + let premature = try await lane.persist() |
| + XCTAssertFalse(premature, "I1a: command returned, but enqueue has not") |
| + XCTAssertEqual(disk.contents[lane.path], before) |
| + try await lane.enqueue(update) |
| + let wrote = try await lane.persist() |
| + XCTAssertTrue(wrote) |
| + let saved = try JSONDecoder().decode(PersistedReplica.self, from: XCTUnwrap(disk.contents[lane.path])) |
| + XCTAssertEqual(saved.sequence, 17) |
| + XCTAssertFalse(saved.state.isEmpty) |
| + } |
| + func testReopenAppliesTheWholeLaneBeforePublishingAndDoesNotDuplicate() async throws { |
| + let disk = MemoryBlobStore(), initial = try await initial() |
| + let outbox = Outbox(store: disk, account: "a"), replica = CRDTReplica(guid: "offline-property") |
| + let lane = DocsPersistence(store: disk, outbox: outbox, key: "draft-token", replica: replica) |
| + try await lane.reopen(fallback: initial, sequence: 0) |
| + try await lane.enqueue(edit(replica, "A")) |
| + _ = try await lane.persist() |
| + try await lane.enqueue(edit(replica, "B")) |
| + for _ in 0..<2 { |
| + let reopened = CRDTReplica(guid: "offline-property") |
| + let next = DocsPersistence(store: disk, outbox: Outbox(store: disk, account: "a"), key: "draft-token", replica: reopened) |
| + try await next.reopen(fallback: Data(), sequence: 0) |
| + let text = try await reopened.projection().children.map(\.plainText).joined() |
| + XCTAssertEqual(text, "AB", "I1b: replica contains A; lane contains A and B") |
| + } |
| + try await lane.discard() |
| + XCTAssertNil(disk.contents[lane.path], "Discard cannot leave stranded local text in the replica") |
| + let entries = await outbox.entries(lane: lane.lane) |
| + XCTAssertTrue(entries.isEmpty) |
| + } |
| + /// Deterministic generated histories, plus an exhaustive crash sweep at |
| + /// replacement's write and every delete. Every assertion reads committed |
| + /// bytes through a fresh outbox/replica, not the live writer's memory. |
| + func testGeneratedCrashHistoriesPreserveI1AndConverge() async throws { |
| + let initial = try await initial() |
| + for seed in 1...12 { |
| + var random = OfflineRandom(seed: UInt64(seed)) |
| + var disk = FaultingBlobStore() |
| + var outbox = Outbox(store: disk, account: "a") |
| + var replica = CRDTReplica(guid: "offline-property") |
| + var lane = DocsPersistence(store: disk, outbox: outbox, key: "doc", replica: replica) |
| + try await lane.reopen(fallback: initial, sequence: 0) |
| + let server = IntegratingServer(); try await server.open(initial) |
| + var durableText = "" |
| + var flying: [OutboxEntry] = [] |
| + var symbol = 0 |
| + for step in 0..<60 { |
| + do { |
| + switch Int.random(in: 0..<8, using: &random) { |
| + case 0, 1: |
| + symbol += 1 |
| + let text = "[\(symbol)]" |
| + let update = try await edit(replica, text) |
| + let premature = try await lane.persist() |
| + XCTAssertFalse(premature, "Writer tick between command and enqueue") |
| + try await lane.enqueue(update); durableText += text |
| + case 2: _ = try await lane.persist() |
| + case 3, 4: |
| + if flying.isEmpty { flying = try await outbox.beginSend(lane: lane.lane, maxBytes: 80) } |
| + try await server.accept(flying) |
| + if step % 2 == 0 { |
| + for entry in flying { let has = await server.contains(entry.id); XCTAssertTrue(has) } |
| + try await outbox.ack(flying.map(\.id)) |
| + } // otherwise the response is lost: server has it; disk keeps it |
| + await outbox.endSend(flying.map(\.id)); flying = [] |
| + case 5: |
| + let entries = await outbox.entries(lane: lane.lane) |
| + if entries.count >= 2 { |
| + if step % 2 == 0 { |
| + flying = try await outbox.beginSend(lane: lane.lane, maxBytes: 1) |
| + do { try await outbox.replace(entries.map(\.id), with: replica.mergeUpdates(entries.map(\.payload))); XCTFail("In-flight replacement must throw") } |
| + catch OutboxError.inFlight {} |
| + await outbox.endSend(flying.map(\.id)); flying = [] |
| + } else { try await lane.compact() } |
| + } |
| + case 6: |
| + // A crash before any subsequent store op, including a |
| + // writer tick or replacement's first/second step. |
| + disk.crash(after: Int.random(in: 0...2, using: &random)) |
| + let entries = await outbox.entries(lane: lane.lane) |
| + if entries.count >= 2 { try await outbox.replace(entries.map(\.id), with: replica.mergeUpdates(entries.map(\.payload))) } |
| + else { _ = try await lane.persist() } |
| + default: |
| + for entry in try await outbox.beginSend(lane: lane.lane, maxBytes: nil) { |
| + try await server.accept([entry]); try await outbox.ack([entry.id]) |
| + } |
| + } |
| + } catch is SimulatedCrash { } |
| + // Reopen after *every* event. This simultaneously checks the |
| + // missing-lane and duplicate-text cases at each crash boundary. |
| + let frozen = disk.committed |
| + let checked = CRDTReplica(guid: "offline-property") |
| + let checkLane = DocsPersistence(store: frozen, outbox: Outbox(store: frozen, account: "a"), key: "doc", replica: checked) |
| + try await checkLane.reopen(fallback: server.snapshot(), sequence: 0) |
| + // Catch up with already acknowledged edits if the replica writer |
| + // lagged behind ack; real reopen performs the same server catch-up. |
| + _ = try await checked.apply(server.snapshot()) |
| + let recovered = try await checked.projection().children.map(\.plainText).joined() |
| + XCTAssertEqual(recovered, durableText, "seed \(seed), event \(step): I1b / no duplicates") |
| + if let data = frozen.contents[lane.path] { |
| + let saved = try JSONDecoder().decode(PersistedReplica.self, from: data) |
| + let proof = CRDTReplica(guid: "offline-property") |
| + _ = try await proof.open(update: server.snapshot()) |
| + for entry in await Outbox(store: frozen, account: "a").entries(lane: lane.lane) { _ = try await proof.apply(entry.payload) } |
| + let prior = try await proof.projection().children.map(\.plainText) |
| + _ = try await proof.apply(saved.state) |
| + let after = try await proof.projection().children.map(\.plainText) |
| + XCTAssertEqual(prior, after, "I1a: replica contains no stranded local edit") |
| + await proof.close() |
| + } |
| + await checked.close() |
| + if disk.hasCrashed { |
| + await replica.close() |
| + disk = FaultingBlobStore(frozen); outbox = Outbox(store: disk, account: "a") |
| + replica = CRDTReplica(guid: "offline-property") |
| + lane = DocsPersistence(store: disk, outbox: outbox, key: "doc", replica: replica) |
| + try await lane.reopen(fallback: server.snapshot(), sequence: 0) |
| + _ = try await replica.apply(server.snapshot()) |
| + flying = [] |
| + } |
| + } |
| + // Reconnect and fully drain, with the real integrating replica. |
| + let recovered = Outbox(store: disk.committed, account: "a") |
| + let entries = await recovered.entries(lane: lane.lane) |
| + try await server.accept(entries); try await recovered.ack(entries.map(\.id)) |
| + let text = try await server.text() |
| + XCTAssertEqual(text, durableText, "seed \(seed): convergence after drain") |
| + await replica.close() |
| + } |
| + } |
| + func testEveryReplaceCrashBoundaryReopensWithoutLossOrDuplicateText() async throws { |
| + let initial = try await initial() |
| + let base = MemoryBlobStore(), source = CRDTReplica(guid: "offline-property") |
| + let setup = DocsPersistence(store: base, outbox: Outbox(store: base, account: "a"), key: "doc", replica: source) |
| + try await setup.reopen(fallback: initial, sequence: 0) |
| + _ = try await setup.persist() |
| + for text in ["A", "B", "C"] { try await setup.enqueue(edit(source, text)) } |
| + for crashAfter in 0...3 { |
| + let disk = FaultingBlobStore(MemoryBlobStore(base.contents)) |
| + let outbox = Outbox(store: disk, account: "a") |
| + try await outbox.load() |
| + let entries = await outbox.entries(lane: "doc:doc") |
| + let merged = try await source.mergeUpdates(entries.map(\.payload)) |
| + disk.crash(after: crashAfter) |
| + do { try await outbox.replace(entries.map(\.id), with: merged) } |
| + catch is SimulatedCrash { } |
| + let rebuilt = CRDTReplica(guid: "offline-property") |
| + let frozen = disk.committed |
| + let recovered = DocsPersistence(store: frozen, outbox: Outbox(store: frozen, account: "a"), key: "doc", replica: rebuilt) |
| + try await recovered.reopen(fallback: Data(), sequence: 0) |
| + let text = try await rebuilt.projection().children.map(\.plainText).joined() |
| + XCTAssertEqual(text, "ABC", "Crash at replace operation \(crashAfter)") |
| + await rebuilt.close() |
| + } |
| + await source.close() |
| + } |
| + |
| + func testModelReopensOfflineAndDrainsToIntegratingTransport() async throws { |
| + let server = IntegratingServer(); try await server.open(initial()) |
| + let disk = FaultingBlobStore() |
| + let connectivity = NativeConnectivity(source: ScriptedPathSource(.satisfied)) |
| + let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: connectivity, transport: { server }) |
| + let model = DocsModel(transport: { server }, connectivity: connectivity, offlineAccount: account) |
| + await model.open("doc") |
| + XCTAssertNotNil(model.projection) |
| + await server.setOnline(false) |
| + model.didRender(model.projectionGeneration) |
| + XCTAssertTrue(model.enqueue(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("Offline edit")])) |
| + while model.hasPendingInput { try await Task.sleep(for: .milliseconds(5)) } |
| + XCTAssertTrue(model.hasUnsentChanges) |
| + // Kill before the two-second writer. Freeze this process's store so |
| + // its tasks cannot mutate the new process's committed view. |
| + account.drainer.stop(); disk.crash(after: 0) |
| + let frozen = disk.committed |
| + let nextAccount = DocsOfflineAccount(store: frozen, accountID: "a", connectivity: connectivity, transport: { server }) |
| + let reopened = DocsModel(transport: { server }, connectivity: connectivity, offlineAccount: nextAccount) |
| + await reopened.open("doc") |
| + XCTAssertEqual(reopened.projection?.children.map(\.plainText).joined(), "Offline edit") |
| + await server.setOnline(true) |
| + await reopened.retry() |
| + let deadline = ContinuousClock.now.advanced(by: .seconds(3)) |
| + while reopened.hasUnsavedChanges && .now < deadline { await reopened.flush(); try await Task.sleep(for: .milliseconds(10)) } |
| + XCTAssertFalse(reopened.hasUnsavedChanges) |
| + let text = try await server.text() |
| + XCTAssertEqual(text, "Offline edit") |
| + await reopened.stop(); nextAccount.drainer.stop() |
| + } |
| + |
| + func testUnlockRetriesFailedUpdateAndResumesAlreadyQueuedCommands() async throws { |
| + let server = IntegratingServer(); try await server.open(initial()) |
| + let disk = FaultingBlobStore() |
| + let connectivity = NativeConnectivity(source: ScriptedPathSource(.satisfied)) |
| + let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: connectivity, transport: { server }) |
| + let model = DocsModel(transport: { server }, connectivity: connectivity, offlineAccount: account) |
| + await model.open("doc") |
| + await server.setOnline(false) |
| + disk.unavailable = true |
| + for text in ["A", "B"] { |
| + XCTAssertTrue(model.enqueue(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string(text)])) |
| + } |
| + let deadline = ContinuousClock.now.advanced(by: .seconds(2)) |
| + while !model.inputPaused && .now < deadline { try await Task.sleep(for: .milliseconds(5)) } |
| + XCTAssertTrue(model.inputPaused) |
| + disk.unavailable = false |
| + await model.retry() |
| + let resumed = ContinuousClock.now.advanced(by: .seconds(2)) |
| + while model.hasPendingInput && .now < resumed { try await Task.sleep(for: .milliseconds(5)) } |
| + XCTAssertFalse(model.hasPendingInput, "Retry must resume the queued second command") |
| + XCTAssertEqual(model.projection?.children.map(\.plainText).joined(), "BA") |
| + await model.persistReplica() |
| + XCTAssertFalse(model.hasUnpersistedInput) |
| + await model.discardAll(); account.drainer.stop() |
| + } |
| + |
| +} |
diff --git a/native/apple/Tests/DocsKitTests/OfflineKillTests.swift b/native/apple/Tests/DocsKitTests/OfflineKillTests.swift| new file mode 100644 |
| index 0000000..6fb096e |
| --- /dev/null |
| +++ b/native/apple/Tests/DocsKitTests/OfflineKillTests.swift |
| @@ -0,0 +1,63 @@ |
| +import CryptoKit |
| +import Foundation |
| +import RastrilloApple |
| +import RastrilloTestSupport |
| +import XCTest |
| +@testable import DocsKit |
| + |
| +final class OfflineKillTests: XCTestCase { |
| + @MainActor func testTypingProcessAndRecovery() async throws { |
| + let env = ProcessInfo.processInfo.environment |
| + guard let directory = env["DOCS_KILL_DIR"], let mode = env["DOCS_KILL_MODE"] else { |
| + throw XCTSkip("Run native/scripts/test-offline-kill.py") |
| + } |
| + let root = URL(fileURLWithPath: directory) |
| + let config = try JSONDecoder().decode([String: String].self, from: Data(contentsOf: root.appendingPathComponent("connection.json"))) |
| + let client = NativeHTTP(origin: URL(string: config["origin"]!)!, credential: NativeSession(name: config["name"]!, value: config["value"]!)) |
| + let path = ScriptedPathSource(mode == "write" ? .satisfied : .unsatisfied) |
| + let connectivity = NativeConnectivity(source: path) |
| + let keys = ScriptedKeyProvider(key: SymmetricKey(data: Data(repeating: 73, count: 32))) |
| + let store = NativeSealedStore(root: root.appendingPathComponent("account"), accountID: "kill-test", keys: keys) |
| + let account = DocsOfflineAccount(store: store, accountID: "kill-test", connectivity: connectivity, transport: { client }) |
| + let model = DocsModel(transport: { client }, connectivity: connectivity, offlineAccount: account) |
| + await model.open(config["sqid"]!) |
| + XCTAssertNotNil(model.projection) |
| + if mode == "write" { |
| + let saved = await model.saveAll(); XCTAssertTrue(saved) |
| + path.send(.unsatisfied) |
| + while connectivity.isPathSatisfied { try await Task.sleep(for: .milliseconds(5)) } |
| + try String(ProcessInfo.processInfo.processIdentifier).write(to: root.appendingPathComponent("pid"), atomically: true, encoding: .utf8) |
| + for index in 1...200 { |
| + model.didRender(model.projectionGeneration) |
| + let text = model.projection?.children.map(\.plainText).joined() ?? "" |
| + XCTAssertTrue(model.enqueue(["op": .string("display_edit"), "at": .number(Double(text.utf16.count)), "length": .number(0), "text": .string("k3-\(index);")])) |
| + while model.hasPendingInput { try await Task.sleep(for: .milliseconds(2)) } |
| + if index == 12 { |
| + let expected = model.projection?.children.map(\.plainText).joined() ?? "" |
| + try expected.write(to: root.appendingPathComponent("expected"), atomically: true, encoding: .utf8) |
| + try Data().write(to: root.appendingPathComponent("kill-now"), options: .atomic) |
| + // The controller kills us in the middle of this typing run, |
| + // before the two-second replica writer can run. |
| + try await Task.sleep(for: .seconds(1)) |
| + } |
| + try await Task.sleep(for: .milliseconds(15)) |
| + } |
| + XCTFail("The controller did not kill the typing process") |
| + } else { |
| + let expected = try String(contentsOf: root.appendingPathComponent("expected"), encoding: .utf8) |
| + XCTAssertEqual(model.projection?.children.map(\.plainText).joined(), expected, "Offline reopen must include every durable keystroke exactly once") |
| + path.send(.satisfied) |
| + while !connectivity.isPathSatisfied { try await Task.sleep(for: .milliseconds(5)) } |
| + await model.retry() |
| + let deadline = ContinuousClock.now.advanced(by: .seconds(10)) |
| + while model.hasUnsavedChanges && .now < deadline { await model.flush(); try await Task.sleep(for: .milliseconds(10)) } |
| + XCTAssertFalse(model.hasUnsavedChanges) |
| + let reply = try await client.responseDetails("/d/\(config["sqid"]!)/updates", maxBytes: 8 * 1024 * 1024) |
| + try reply.requireSuccess() |
| + let server = CRDTReplica(guid: model.detail!.guid) |
| + let projected = try await server.open(update: reply.data) |
| + XCTAssertEqual(projected.children.map(\.plainText).joined(), expected, "Real server converges after the killed client's lane drains") |
| + await server.close(); await model.stop(); account.drainer.stop() |
| + } |
| + } |
| +} |
diff --git a/native/crdt/tests/snapshot.rs b/native/crdt/tests/snapshot.rs| new file mode 100644 |
| index 0000000..01422fb |
| --- /dev/null |
| +++ b/native/crdt/tests/snapshot.rs |
| @@ -0,0 +1,28 @@ |
| +use docs_native_crdt::Editor; |
| +use serde_json::{json, Value}; |
| + |
| +fn plain(value: &Value) -> String { |
| + if let Some(runs) = value["runs"].as_array() { |
| + return runs.iter().filter_map(|run| run["insert"].as_str()).collect(); |
| + } |
| + value["children"].as_array().map(|children| children.iter().map(plain).collect()).unwrap_or_default() |
| +} |
| + |
| +// Port of core/tests/snapshot.rs:121, through the native Editor's actual |
| +// snapshot operation and vendored yrs. encode_diff_v1 drops this pending data. |
| +#[test] |
| +fn a_snapshot_with_a_parked_update_heals_once_its_dependency_arrives() { |
| + let mut origin = Editor::new("parked", 1); |
| + let dependency = origin.command(&json!({"op":"insert_element","at":0,"type":"paragraph"})).unwrap(); |
| + let dependent = origin.command(&json!({"op":"display_edit","at":0,"length":0,"text":"hello world"})).unwrap(); |
| + let parked = Editor::new("parked", 2); |
| + parked.apply(&dependent).unwrap(); |
| + assert_eq!(plain(&parked.projection()), ""); |
| + let rebuilt = Editor::new("parked", 3); |
| + rebuilt.apply(&parked.snapshot()).unwrap(); |
| + assert_eq!(plain(&rebuilt.projection()), ""); |
| + parked.apply(&dependency).unwrap(); |
| + rebuilt.apply(&dependency).unwrap(); |
| + assert_eq!(plain(&parked.projection()), "hello world"); |
| + assert_eq!(plain(&rebuilt.projection()), plain(&parked.projection())); |
| +} |
diff --git a/native/ios/project.yml b/native/ios/project.yml| index 28ec608..a10e2d2 100644 |
| --- a/native/ios/project.yml |
| +++ b/native/ios/project.yml |
| @@ -8,7 +8,7 @@ packages: |
| path: ../apple |
| RastrilloNative: |
| url: https://amadan.net/rastrillo/native |
| - revision: 14ee567be2e1816002c7db4274acaf2926983b4c |
| + revision: 6b6b19814c8df182954db36f1f4637bd0cda181a |
| settings: |
| base: |
| SWIFT_VERSION: '6.0' |
diff --git a/native/macos/project.yml b/native/macos/project.yml| index 81fd871..d278c2b 100644 |
| --- a/native/macos/project.yml |
| +++ b/native/macos/project.yml |
| @@ -7,7 +7,7 @@ packages: |
| path: ../apple |
| RastrilloNative: |
| url: https://amadan.net/rastrillo/native |
| - revision: 14ee567be2e1816002c7db4274acaf2926983b4c |
| + revision: 6b6b19814c8df182954db36f1f4637bd0cda181a |
| settings: |
| base: |
| SWIFT_VERSION: '6.0' |
diff --git a/native/scripts/test-offline-kill.py b/native/scripts/test-offline-kill.py| new file mode 100755 |
| index 0000000..645f66c |
| --- /dev/null |
| +++ b/native/scripts/test-offline-kill.py |
| @@ -0,0 +1,61 @@ |
| +#!/usr/bin/env python3 |
| +"""SIGKILL an actual native editing process mid-typing, reopen offline, drain |
| +against real authenticated Docs handlers, and compare the server snapshot. |
| +Requires the CRDT framework built by check-native.sh; never touches user data. |
| +""" |
| +import os |
| +from pathlib import Path |
| +import signal |
| +import subprocess |
| +import tempfile |
| +import time |
| + |
| +root = Path(__file__).resolve().parents[2] |
| + |
| +def wait_for(path, process, timeout=120): |
| + deadline = time.monotonic() + timeout |
| + while not path.exists(): |
| + if process.poll() is not None: |
| + raise RuntimeError(f"process exited {process.returncode} before {path.name}") |
| + if time.monotonic() > deadline: |
| + raise TimeoutError(path.name) |
| + time.sleep(.02) |
| + |
| +with tempfile.TemporaryDirectory(prefix="docs-k3-kill-", dir="/tmp") as tmp: |
| + scratch = Path(tmp) |
| + env = dict(os.environ, DOCS_KILL_DIR=tmp, TMPDIR="/tmp") |
| + server_log = (scratch / "server.log").open("w") |
| + server = subprocess.Popen(["go", "test", "./internal/docs", "-run", "^TestNativeKillServer$", "-count=1", "-timeout=4m"], cwd=root, env=env, stdout=server_log, stderr=subprocess.STDOUT, start_new_session=True) |
| + writer = None |
| + try: |
| + wait_for(scratch / "connection.json", server) |
| + command = ["swift", "test", "--package-path", "native/apple", "--filter", "OfflineKillTests"] |
| + with (scratch / "writer.log").open("w") as log: |
| + writer = subprocess.Popen(command, cwd=root, env=dict(env, DOCS_KILL_MODE="write"), stdout=log, stderr=subprocess.STDOUT, start_new_session=True) |
| + wait_for(scratch / "kill-now", writer) |
| + pid = int((scratch / "pid").read_text()) |
| + os.kill(pid, signal.SIGKILL) |
| + result = writer.wait(timeout=20) |
| + assert result != 0, "typing process unexpectedly succeeded" |
| + print("SIGKILL delivered after 12 durable edits, before coalesced replica write", flush=True) |
| + recovered = subprocess.run(command, cwd=root, env=dict(env, DOCS_KILL_MODE="recover"), capture_output=True, text=True, timeout=120) |
| + if recovered.returncode: |
| + print(recovered.stdout) |
| + print(recovered.stderr) |
| + raise RuntimeError("offline recovery / real server convergence failed") |
| + (scratch / "done").touch() |
| + assert server.wait(timeout=15) == 0, "real server fixture failed" |
| + print("PASS: offline reopen exact; real server converged; no duplicate text", flush=True) |
| + except Exception: |
| + # Logs contain only test-generated state. Never print connection.json. |
| + for name in ("server.log", "writer.log"): |
| + path = scratch / name |
| + if path.exists(): |
| + print(path.read_text()[-12000:]) |
| + raise |
| + finally: |
| + for process in (writer, server): |
| + if process is not None and process.poll() is None: |
| + os.killpg(process.pid, signal.SIGTERM) |
| + process.wait(timeout=10) |
| + server_log.close() |
diff --git a/native/smoke/document-window/Package.resolved b/native/smoke/document-window/Package.resolved| index 0e15d8a..c453853 100644 |
| --- a/native/smoke/document-window/Package.resolved |
| +++ b/native/smoke/document-window/Package.resolved |
| @@ -6,7 +6,7 @@ |
| "kind" : "remoteSourceControl", |
| "location" : "https://amadan.net/rastrillo/native", |
| "state" : { |
| - "revision" : "14ee567be2e1816002c7db4274acaf2926983b4c" |
| + "revision" : "6b6b19814c8df182954db36f1f4637bd0cda181a" |
| } |
| }, |
| { |