oficina / docs Public

Keep Docs edits durably on the device (offline K3)

The Docs native app now writes every local edit to a per-account sealed
outbox (rastrillo/native K3: AES-GCM, Keychain key, never renamed after
sealing) before the replica, which persists only when everything applied
is durable. Reopening is the replica plus its lane, so a crash, a quit
or a lost network loses nothing and duplicates nothing. Proven by a
property test over crashes at every store op, and a SIGKILL mid-typing
test against the real server. Status shows Offline · N pending, or
Sign in to sync N when the session has ended.
Reviewed by Claude Fable 5.1 (#69, native #9).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from feat/k3-outbox-lane into main.
Paul Campbell pushed by claude agent, operated by paul@keymail.dev d40fbd154483bec6a56f0f82b1995220727069dd parent ee9ecb1
21 files changed, +1,680 −93
  • docs/testing/k3-evidence.md +163 −0
  • internal/docs/native_kill_test.go +85 −0
  • native/apple/Package.resolved +1 −1
  • native/apple/Package.swift +1 −1
  • native/apple/Sources/DocsApp/DocsAccountWindow.swift +2 −2
  • native/apple/Sources/DocsApp/DocsDocumentWindow.swift +1 −1
  • native/apple/Sources/DocsKit/CRDTReplica.swift +15 −0
  • native/apple/Sources/DocsKit/DocsModel.swift +187 −79
  • native/apple/Sources/DocsKit/DocsModels.swift +1 −1
  • native/apple/Sources/DocsKit/DocsOfflineAccount.swift +162 −0
  • native/apple/Sources/DocsKit/DocsPersistence.swift +82 −0
  • native/apple/Sources/DocsKit/DocsReplicaCache.swift +38 −0
  • native/apple/Sources/DocsKit/DocsWorkspace.swift +18 −4
  • native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift +733 −0
  • native/apple/Tests/DocsKitTests/OfflineKillTests.swift +80 −0
  • native/crdt/tests/snapshot.rs +28 −0
  • native/ios/project.yml +1 −1
  • native/macos/project.yml +1 −1
  • native/scripts/test-document-drafts.py +2 −1
  • native/scripts/test-offline-kill.py +78 −0
  • native/smoke/document-window/Package.resolved +1 −1

CI passed — run details

landed from feat/k3-outbox-lane

diff --git a/docs/testing/k3-evidence.md b/docs/testing/k3-evidence.md
new file mode 100644
index 0000000..8b68a4e
--- /dev/null
+++ b/docs/testing/k3-evidence.md
@@ -0,0 +1,163 @@
+# K3 offline durability evidence
+
+Continuation of native WIP 68a51d7, against reviewed spec 6049830 (§3.3–3.8,
+§4.3–4.4 and K3). Work/review records: rastrillo/native #9 and oficina/docs #69.
+Nothing has been merged or deployed.
+
+## Implementation and review
+
+- Account-owned sealed outbox, metadata and replicas; Home activates replay.
+- CommandsApplied is captured with snapshot/sequence. CommandsDurable advances
+ only after enqueue; the writer requires equality again immediately at commit.
+- Reopening captures the entire lane before reading its replica, applies update
+ entries in order, and publishes only after replay. Held updates remain visible.
+- Editor and headless senders merge with the latest durable replica using a
+ compare/retry. A shared generation invalidates writers on discard. Sent updates
+ are cached before ack, so Home replay preserves subsequent offline reopening.
+- Metadata keys are registered before metadata writes. Attached identity is
+ persisted before its repairable sqid alias; sealed paths never move. Creation
+ tokens survive failed attachment writes and retries remain idempotent.
+- Metadata-only outbox markers give titles/drafts the existing drainer's retries.
+ Activation reconciles the metadata/enqueue crash boundary. A newer rename gets
+ a successor marker behind an in-flight marker. Failed local title writes and
+ the draft's initial paragraph are retained for unlock/retry.
+- Account-level localized lost-content notice remains until dismissal. Opening a
+ document loads the outbox before touching the index, preserving key-loss notice.
+- Byte-cap pause is recomputed after queue changes and reopening; retry cannot
+ bypass it. Kit status preserves known state while storage is unavailable and
+ applies the spec's session-ended priority even for an empty outbox.
+- Highest-capability branch review: gpt-6-astra. Its metadata, cache, loss-notice,
+ cap and draft-seed findings were addressed with regressions. K4/K5/K6 features
+ remain in their specified slices; no merge approval is implied by code review.
+
+## Failing-first evidence
+
+All mutation controls below were restored before commits. Logs are local /tmp
+transcripts; this table records their observed assertions rather than merely
+claiming that a command failed.
+
+| Probe | Failing control / observed failure | Passing evidence |
+|---|---|---|
+| Original watermark, lane replay, generated history | DocsPersistence/snapshot stubs: 3 tests, 238 assertions (`k3-docs-red.log`) | `k3-docs-green.log` |
+| Replace crash boundaries and model reopen | Omit lane replay: 2 tests, 5 missing-text assertions (`k3-docs-integration-red.log`) | `k3-docs-integration-green.log` |
+| Unlock resumes queued commands | Existing defect: 3 assertions (`k3-unlock-red.log`) | Same integration green suite |
+| Title before replica, title retry, concurrent rename, attachment alias, Home replay | Prior implementation: 5 tests, 15 assertions (`k3-recovery-red.log`) | 15 durability/account tests (`k3-recovery-green.log`) |
+| Concurrent cache writes and discard ordering | Omit merge/invalidation; delete lane first: 2 tests, 6 assertions (`k3-cache-discard-red.log`) | 13 durability tests (`k3-cache-discard-green.log`) |
+| Locked title, loss notice, cap, live fake stream | Prior behavior / nil loss-notice stub: 4 tests fail (`k3-review-red.log`; the fifth timing probe initially missed its race and was corrected below) | 24 durability/account tests (`k3-review-green.log`) |
+| Rename after title POST, before batch ack | Assert both entries reserved; old marker suppresses successor: First != Successor (`k3-trigger-valid-red.log`) | Same 24-test green suite |
+| Draft attachment across store operations | Stub attachment sender; alias, token, content, count and empty-lane assertions fail (`k3-attachment-trigger-red.log`) | Same green suite, exhaustive sweep through actual operation count |
+| Direct sealed-key loss before index read | Prior code opens index first: no projection/no loss notice (`k3-attachment-trigger-red.log`) | Same green suite |
+| Draft paragraph survives metadata failure | Omit retained seed: server text empty instead of Recovered draft (`k3-seed-cap-red.log`) | Both tests pass (`k3-seed-cap-green.log`) |
+| Reopen cannot bypass lane cap | Prior unconditional input reset permits editing (`k3-seed-cap-red.log`) | Same green log |
+| Parked update snapshot | Replace only snapshot's encode_state_as_update_v1 with encode_diff_v1: healed text missing (`k3-parked-red.log`) | Existing snapshot passes native/crdt test (`k3-parked-green.log`) |
+
+The generated histories cover 12 deterministic seeds × 60 events. They place
+writer ticks between command and enqueue, inject crashes before arbitrary event
+store operations, reserve overlapping compaction candidates, integrate then lose
+responses, reopen and replay, and compare I1a/I1b and final server convergence.
+Separate sweeps cover every replacement/delete boundary, every discard boundary,
+and every actual store operation in draft attachment. The fake uses production
+WASM replicas, serves since-cursors and publishes subsequent stream sequences.
+
+## Real SIGKILL and draft integration
+
+`native/scripts/test-offline-kill.py` authenticates against actual Go handlers,
+opens the native model, verifies initial save, types 12 durable edits, and sends
+SIGKILL before the two-second replica writer. Recovery starts offline and checks
+exact text before reconnecting and comparing the real server's snapshot.
+
+The original fixture configured localhost:8080 despite using a random loopback
+port. A NativeHTTP-style Origin POST reproduced 403 (`k3-origin-red.log`). It now
+uses the listener's actual origin; CSRF is not bypassed. Failed initial-save or
+pre-kill typing assertions stop the harness.
+
+Negative control: omit only lane replay. Initial save and server convergence
+still pass, but offline reopen is empty instead of the 12 edits: exactly one
+assertion (`k3-kill-valid-red.log`). Restore replay: exact recovery/convergence,
+no duplicates (`k3-kill-valid-green.log`). Final-code rerun passed again
+(`/tmp/k3-kill-final.log`).
+
+Existing `test-document-drafts.py` also passed (`k3-draft-integration-green.log`).
+Its detail GET used to return Untitled permanently, even after an accepted rename;
+it now snapshots the current title at request start, preserving realistic delayed
+stale replies. The unchanged title assertion failed before this fixture correction.
+
+## Spec differences and slice boundaries
+
+- Discard removes the replica before the lane. The user accepted this ordering
+ with crash proof; the exhaustive sweep shows no stranded unsent replica text.
+- The index also registers immutable local keys, and the app uses metadata-kind
+ outbox markers. These minimal additions make metadata-only replay discoverable
+ after a crash; they introduce no kit update/retarget API.
+- Kit load/entries/beginSend/endSend express unavailable storage, held-entry
+ replay and atomic send reservations. Their rationale is recorded on native #9.
+- Equality is used for the durability watermark as explicitly requested by the
+ user (the spec allows <=). Existing snapshot is used; no new CRDT operation.
+- K4 offline library/draft presentation, K5 reauthentication/wipe, and K6 terminal
+ resolution, first-400 handling, relaxed close and iOS background task remain
+ outside K3. Existing close/signout protection remains in place.
+
+## Inherited WIP problems and gates
+
+The inherited kit was mostly no-op stubs. Tests included an unchecked empty-array
+index and an undeclared AppleTests → TestSupport dependency hidden by incremental
+builds. Further implementation checks caught rotation's /var versus /private path
+handling, retrying-lane starvation, and early idle from concurrent drain calls.
+Their red/green evidence is in the kit's docs/testing/k3-evidence.md.
+
+Final required gates are serial: native make ci; Docs .amadan/ci.d/10-gate; Docs
+native/scripts/check-native.sh. Use rustup cargo first, TMPDIR=/tmp, xcodegen before
+xcodebuild. Final head/results are recorded on discussions #9/#69, with logs
+`/tmp/k3-kit-release-ci.log`, `/tmp/k3-docs-final-gate.log`, and
+`/tmp/k3-docs-final-native.log`. Native hub CI lacks a macOS runner and fails on
+Sparkle extraction (missing unzip); the user directed reliance on local make ci.
+
+Disk is measured on /System/Volumes/Data, with a mandatory stop below 1.5 GiB.
+Only outputs created by this session are removed. The kit's inherited .build is
+moved aside for full gates, preserved, then restored; Docs targets, framework,
+.build and DerivedData created here are removed between stages.
+
+
+## Fable review follow-up (2026-09-24)
+
+- Missing, malformed-JSON, and tampered sealed metadata now hold only that lane with `rejected("metadata")`; genuine unavailable I/O still throws. The new test failed all three hold assertions against the inherited implementation, then passed while another document drained.
+- Held metadata markers are deduplicated using `entries(lane:excludingInFlight:)`. The new repeated-flush test first found five markers instead of one; it now passes, as does the existing rename-after-title-POST/in-flight-successor regression.
+- A durable offline lane uses SyncStatus without setting the generic errorKey. The new test first observed `native.pending` rather than nil, and now observes nil plus `.offline(pending: 1)`.
+- All 24 durability tests passed. Logs: `/tmp/k3-docs-review-{red,green}.log` (ephemeral); the red run had five expected assertions across three tests. The existing key-loss test was adjusted to create a fresh sealed store on simulated process restart: reusing the old instance now intentionally retains its cached key.
+- Native pins (all five) advance to `0ff1de9d542ce96430e158708e62be04d87d65a4`; native final-head local `make ci` passed (119 Swift tests and remaining platform/Go/Python gates). Its hub runner still fails before tests on missing unzip / absent macOS infrastructure.
+- Deferred as directed: review finding 4 (WASM decode per writer tick) belongs to K4/K7; finding 6 (sessionRestored on existing-account/window access) belongs to K5. No new K3 spec departure.
+
+
+Random SIGKILL mode: `native/scripts/test-offline-kill.py --random --seed 17`
+leaves typing unpaused and runs concurrent replica writer ticks. The controller
+kills after a seeded random delay, without a writer-side sleep/handshake. Recovery
+must contain the last atomically recorded durable text as a prefix, contain exactly
+the ordered k3 tokens (no gaps/duplicates/torn edits), then equal the real server.
+Failing-first control: stub the outbox write in DocsPersistence.enqueue while still
+advancing commandsDurable. Seed 17 killed at 0.260992 s; recovery was empty and
+failed the durable-prefix and ordered-token assertions (two failures). Restore the
+write: the same seed passed offline recovery and exact server convergence. Logs:
+`/tmp/k3-docs-review-kill-{red,green}.log`. The stub is not committed.
+
+Final-head gates and repeated kill runs are reported on #69; local logs use
+`/tmp/k3-docs-review-final-{gate,native,kill*}.log`. Build stages run serially,
+with rustup cargo first and TMPDIR=/tmp; xcodegen runs before xcodebuild.
+
+
+At 8f25e2f the full local Docs gates passed (82 XCTest cases, four fixture skips,
+16 Swift Testing cases, parked-update and wire checks); deterministic SIGKILL and
+random seeds 1/17/2 all passed. Final harness review moved the existing writer-log
+assertion check after process termination so random typing cannot emit an assertion
+between the check and SIGKILL without failing the script. Final-head reruns and
+cleanup are recorded on #69.
+
+Landing prep (2026-09-30): the native half merged, so all five native pins move
+from the K3 branch head `0ff1de9d542ce96430e158708e62be04d87d65a4` to rastrillo/native
+main `529f356f476e43174882361511032e0bdefa5317`, after merging fresh Docs origin/main.
+Gate results for this head are recorded on #69.
+Hub CI at de13d64 failed in the gate's wire-compatibility stage ("JS reads what
+Rust wrote": `verify-rust: empty update on stdin`). The runner log shows cargo
+stopping partway through replaying cached yrs warnings (40 of 67), then `error`,
+before emit_update ran. K3 does not touch core/, native/vendor/, scripts/ or
+fixtures/. A fresh clone of de13d64 passed `scripts/wire-gate.sh` locally, and
+the JS-reads-Rust pipe passed five times in a row.
diff --git a/internal/docs/native_kill_test.go b/internal/docs/native_kill_test.go
new file mode 100644
index 0000000..37439fd
--- /dev/null
+++ b/internal/docs/native_kill_test.go
@@ -0,0 +1,85 @@
+package docs_test
+
+import (
+ "encoding/json"
+ "github.com/carlosframework/docs/internal/docs"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "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")
+ }
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer listener.Close()
+ app, err := docs.NewForTestWith(t, docs.Config{AllowedAddresses: "kill@example.com", Origin: "http://" + listener.Addr().String()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ cookies := signInCookies(t, app, "kill@example.com")
+ create := httptest.NewRequest("POST", "/documents", strings.NewReader("title=Kill+recovery"))
+ create.Header.Set("Origin", "http://"+listener.Addr().String())
+ create.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ for _, cookie := range cookies {
+ create.AddCookie(cookie)
+ }
+ created := httptest.NewRecorder()
+ app.Handler().ServeHTTP(created, create)
+ if created.Code != http.StatusSeeOther {
+ t.Fatalf("create: status %d", created.Code)
+ }
+ sqid := strings.TrimPrefix(created.Header().Get("Location"), "/d/")
+ server := httptest.NewUnstartedServer(app.Handler())
+ server.Listener.Close()
+ server.Listener = listener
+ server.Start()
+ defer server.Close()
+ // Match NativeHTTP: Origin, without a browser's Sec-Fetch-Site shortcut.
+ request, err := http.NewRequest("POST", server.URL+"/d/"+sqid+"/title", strings.NewReader("title=Kill+recovery"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ request.Header.Set("Origin", server.URL)
+ request.Header.Set("Accept", "application/json")
+ request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ for _, cookie := range cookies {
+ request.AddCookie(cookie)
+ }
+ response, err := http.DefaultClient.Do(request)
+ if err != nil {
+ t.Fatal(err)
+ }
+ response.Body.Close()
+ if response.StatusCode < 200 || response.StatusCode >= 300 {
+ t.Fatalf("native-origin initial save: status %d, want 200", response.StatusCode)
+ }
+ 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(6 * 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..dba2208 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" : "529f356f476e43174882361511032e0bdefa5317"
}
},
{
diff --git a/native/apple/Package.swift b/native/apple/Package.swift
index b33e766..ef9ac89 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: "529f356f476e43174882361511032e0bdefa5317")
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..44c5836 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 }
@@ -22,6 +23,7 @@ import RastrilloApple
private(set) var draftToken: String?
private var creationTask: Task<Void, Never>?
private var pendingTitle: String?
+ private var metadataDirty = false
var renameInput: String?
private var titleRevision: UInt64 = 0
var isDraft: Bool { draftToken != nil }
@@ -31,7 +33,20 @@ 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 lostChangesNotice: String? { outboxSummary.lostUnsent ? NativeSyncStrings.kit.unsentLost : nil }
+ func dismissLostChangesNotice() async { await offlineAccount.outbox.acknowledgeLoss() }
+ 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 +63,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,8 +77,74 @@ 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 { metadataDirty || (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, 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.updateLaneSummary(summary.only("doc:" + key))
+ self.reloadMetadata()
+ }
+ }
+ }
+ private func updateLaneSummary(_ summary: OutboxSummary) {
+ laneSummary = summary
+ let tooLarge = summary.lanes.values.contains { $0.bytes > 32 * 1024 * 1024 }
+ if tooLarge, localFailure == nil || localFailure == .tooManyUnsent {
+ localFailure = .tooManyUnsent; inputPaused = true
+ } else if !tooLarge, localFailure == .tooManyUnsent {
+ localFailure = nil; inputPaused = detail?.can_write != true || summary.held > 0
+ }
+ }
+ private func reloadMetadata() {
+ guard !metadataDirty, 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 }
+ metadataDirty = true
+ try offlineAccount.saveMetadata(DocsOfflineMetadata(detail: detail, pendingTitle: pendingTitle, draftToken: draftToken), key: documentKey)
+ metadataDirty = false
+ }
+ 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 {
+ if try await !persistence.persist() { self.schedulePersistence() }
+ else if self.localFailure == .cannotSaveOnDevice, self.failedUpdate == nil, !self.metadataDirty {
+ 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
+ updateLaneSummary(await offlineAccount.outbox.summary.only(persistence.lane))
+ 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 {
@@ -88,15 +170,21 @@ import RastrilloApple
loading = true
defer { if documentEpoch == epoch { loading = false } }
do {
+ try await offlineAccount.outbox.load()
_ = 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)
+ failedUpdate = update
+ try saveMetadata()
+ try await durable(update)
await publish()
guard documentEpoch == epoch else { return }
+ offlineAccount.drainer.start()
startCreation()
- } catch { if documentEpoch == epoch { errorKey = "native.pending" } }
+ } catch { if documentEpoch == epoch { errorKey = "native.pending"; localFailure = .cannotSaveOnDevice; inputPaused = true } }
}
private func startCreation() {
guard creationTask == nil, draftToken != nil else { return }
@@ -108,33 +196,16 @@ import RastrilloApple
}
}
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)
+ try await offlineAccount.ensureMetadataEntry(key)
+ await offlineAccount.drainer.drain()
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
- // Do not publish while native callbacks are still in flight.
- if !hasPendingInput { await publish() }
- 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 {
- var form = URLComponents()
- form.queryItems = values.map { URLQueryItem(name: $0.key, value: $0.value) }
- return Data((form.percentEncodedQuery ?? "").replacingOccurrences(of: "+", with: "%2B").utf8)
- }
@discardableResult func commitRename() -> Bool {
guard let value = renameInput else { return true }
guard rename(value) else { return false }
@@ -146,10 +217,18 @@ import RastrilloApple
let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
let title = trimmed.isEmpty ? String(localized: "docs.document.untitled", bundle: DocsResources.bundle) : trimmed
guard title.utf8.count <= 1024 else { errorKey = "docs.error.generic"; return false }
- guard title != detail.title else { return true }
+ if title == detail.title {
+ guard metadataDirty else { return true }
+ do { try saveMetadata() } catch { localFailure = .cannotSaveOnDevice; inputPaused = true; return false }
+ }
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
- Task { await flush() }
+ do { try saveMetadata() } catch { localFailure = .cannotSaveOnDevice; inputPaused = true; return false }
+ Task {
+ do { if let documentKey { try await offlineAccount.ensureMetadataEntry(documentKey) } }
+ catch { localFailure = .cannotSaveOnDevice; inputPaused = true }
+ await flush()
+ }
return true
}
func open(_ sqid: String) async {
@@ -162,28 +241,52 @@ 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 }
+ try await offlineAccount.outbox.load()
+ 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 {
+ 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 }
+ 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
+ reloadMetadata()
+ sequence = try await replica.persistentState().sequence
+ laneSummary = await offlineAccount.outbox.summary.only("doc:" + key)
+ 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
+ updateLaneSummary(laneSummary)
await publish()
guard documentEpoch == epoch else { return }
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 +305,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 +337,38 @@ 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()
+ if metadataDirty { 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 }
+ await publish()
+ } catch { return }
+ }
+ if let persistence { updateLaneSummary(await offlineAccount.outbox.summary.only(persistence.lane)) }
+ if localFailure == .tooManyUnsent { return }
+ offlineAccount.drainer.start()
+ 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 +377,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
+ draftToken = nil; pendingTitle = nil; metadataDirty = false; 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,50 +413,21 @@ 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 !saving, detail != nil, 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 }
- 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
- }
- 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 }
- }
+ 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()
+ // SyncStatus presents a durable pending lane; it does not require
+ // keeping this document open. Preserve unrelated actionable errors.
if errorKey == "native.pending" || errorKey == "docs.editor.status.retrying" { errorKey = nil }
}
private func listen(_ sqid: String) async {
@@ -359,6 +465,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..b8faef2
--- /dev/null
+++ b/native/apple/Sources/DocsKit/DocsOfflineAccount.swift
@@ -0,0 +1,162 @@
+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
+ 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 {
+ 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)
+ 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() }
+ 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)
+ }
+ 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 {
+ 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 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, excludingInFlight: true)
+ 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)), generation = replicaCache.generation(String(lane.dropFirst(4)))
+ let saved: DocsOfflineMetadata?
+ do { saved = try metadata(key) }
+ catch BlobStoreError.corrupt { saved = nil }
+ catch is DecodingError { saved = nil }
+ // A missing/corrupt destination cannot be retried into existence. Keep
+ // its lane for resolution, without mistaking a locked store for loss.
+ guard lane.hasPrefix("doc:"), var metadata = saved else {
+ return Dictionary(uniqueKeysWithValues: entries.map { ($0.id, .hold(Hold(.rejected("metadata")))) })
+ }
+ 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)
+ }
+ 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)
+ let update: Data
+ 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()
+ 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).
+/// 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..dc0c8a0
--- /dev/null
+++ b/native/apple/Sources/DocsKit/DocsPersistence.swift
@@ -0,0 +1,82 @@
+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
+ 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, 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 entries where entry.kind == "update" { _ = 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)
+ 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
+ }
+ 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
+ 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)
+ try await outbox.discard(lane: lane)
+ }
+}
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 004cb35..ee4a520 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,10 +70,17 @@ 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)
}
+ .alert(NativeSyncStrings.kit.unsentLost, isPresented: Binding(
+ get: { model.lostChangesNotice != nil },
+ set: { showing in if !showing { Task { await model.dismissLostChangesNotice() } } }
+ )) {
+ Button { Task { await model.dismissLostChangesNotice() } } label: {
+ Text("native.close", bundle: DocsResources.bundle)
+ }
+ }
.onChange(of: model.documents.map { "\($0.sqid)\u{0}\($0.title)" }) {
if query.isEmpty { updateRecents?(model.documents.map { ($0.sqid, $0.title) }) }
}
@@ -88,6 +97,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 { 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) }
#endif
@@ -147,6 +160,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..d055b96
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift
@@ -0,0 +1,733 @@
+import Foundation
+import CryptoKit
+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 creationTokens: Set<String> = []
+ func documentCount() -> Int { creationTokens.count }
+ var online = true
+ var title = "Document"
+ var titleFailures = 0
+ var titleDelay = false
+ var updateDelay = false
+ var updateRequests = 0
+ func delayUpdates() { updateDelay = true }
+ func updateRequestCount() -> Int { updateRequests }
+ 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
+ var rows: [Int64: Data] = [:]
+ var listeners: [UUID: AsyncStream<Int64>.Continuation] = [:]
+ 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 == "/documents", let body {
+ let token = URLComponents(string: "?" + String(decoding: body, as: UTF8.self))?.queryItems?.first(where: { $0.name == "creation_token" })?.value ?? ""
+ creationTokens.insert(token)
+ return NativeResponse(data: Data(#"{"sqid":"doc","title":"Document"}"#.utf8), status: 201, headers: [:])
+ }
+ 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 {
+ updateRequests += 1
+ if updateDelay { try await Task.sleep(for: .milliseconds(300)) }
+ _ = try await replica.apply(body); sequence += 1
+ rows[sequence] = body
+ for listener in listeners.values { listener.yield(sequence) }
+ if loseNextResponse { loseNextResponse = false; throw NativeClientError.offline(.networkConnectionLost) }
+ return NativeResponse(data: Data(), status: 204, headers: [:])
+ }
+ if path.contains("/updates") {
+ let since = URLComponents(string: path)?.queryItems?.first(where: { $0.name == "since" })?.value.flatMap(Int64.init) ?? 0
+ let data: Data
+ if since > 0 {
+ let updates = rows.keys.sorted().filter { $0 > since }.compactMap { rows[$0] }
+ data = updates.isEmpty ? Data() : try await replica.mergeUpdates(updates)
+ } else { data = try await snapshot() }
+ return NativeResponse(data: data, status: 200, headers: ["Docs-Seq": String(sequence)])
+ }
+ 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 {
+ guard online else { throw NativeClientError.offline(.notConnectedToInternet) }
+ let id = UUID(), events = AsyncStream<Int64>.makeStream(bufferingPolicy: .bufferingNewest(1))
+ listeners[id] = events.continuation
+ defer { listeners.removeValue(forKey: id) }
+ try await onOpen(); try await onLine("data: \(sequence)")
+ for await sequence in events.stream { try Task.checkCancellation(); try await onLine("data: \(sequence)") }
+ }
+ func download(_ path: String, to destination: URL) async throws { throw NativeClientError.notFound }
+
+ func contains(_ id: UUID) -> Bool { accepted[id] != nil }
+}
+private final class MetadataLockStore: BlobStore, @unchecked Sendable {
+ let base = MemoryBlobStore()
+ private let lock = NSLock()
+ private var locked = true
+ func unlock() { lock.withLock { locked = false } }
+ func read(_ path: String) throws -> Data? { try base.read(path) }
+ func list(_ path: String) throws -> [String] { try base.list(path) }
+ func remove(_ path: String) throws { try base.remove(path) }
+ func write(_ bytes: Data, to path: String) throws {
+ if path.hasSuffix("/meta"), lock.withLock({ locked }) { throw BlobStoreError.unavailable }
+ try base.write(bytes, to: path)
+ }
+}
+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 testMissingOrCorruptMetadataHoldsOnlyItsLane() async throws {
+ for damage in 0..<3 {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let disk = NativeSealedStore(root: root, accountID: "a", keys: ScriptedKeyProvider())
+ let connectivity = NativeConnectivity(source: ScriptedPathSource(.satisfied))
+ while !connectivity.isPathSatisfied { await Task.yield() }
+ let transport = ScriptedTransport([])
+ let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: connectivity, transport: { transport })
+ if damage > 0 { try disk.write(Data("invalid metadata".utf8), to: "cache/docs/a/meta") }
+ if damage == 2 { try Data([0]).write(to: root.appendingPathComponent("cache/docs/a/meta")) }
+ try await account.outbox.enqueue(lane: "doc:a", kind: "metadata", payload: Data())
+ let detail = DocumentDetail(sqid: "b", title: "B", guid: "b", can_write: true, can_share: false)
+ try account.saveMetadata(DocsOfflineMetadata(detail: detail), key: "b")
+ try await account.outbox.enqueue(lane: "doc:b", kind: "metadata", payload: Data())
+ await account.drainer.drain()
+ let broken = await account.outbox.entries(lane: "doc:a")
+ let good = await account.outbox.entries(lane: "doc:b")
+ XCTAssertEqual(broken.first?.hold, Hold(.rejected("metadata")))
+ XCTAssertTrue(good.isEmpty, "Missing metadata must not block another document")
+ }
+ }
+
+ func testHeldMetadataMarkerDoesNotMultiplyOnFlush() async throws {
+ let account = DocsOfflineAccount(store: MemoryBlobStore(), accountID: "a", connectivity: NativeConnectivity(source: ScriptedPathSource(.unsatisfied)), transport: { ScriptedTransport([]) })
+ let detail = DocumentDetail(sqid: "doc", title: "Title", guid: "doc", can_write: true, can_share: false)
+ try account.saveMetadata(DocsOfflineMetadata(detail: detail, pendingTitle: "Rename"), key: "doc")
+ try await account.ensureMetadataEntry("doc")
+ let original = await account.outbox.entries(lane: "doc:doc")
+ try await account.outbox.hold(original.map(\.id), Hold(.accessLost))
+ for _ in 0..<4 { try await account.ensureMetadataEntry("doc") }
+ let entries = await account.outbox.entries(lane: "doc:doc")
+ XCTAssertEqual(entries.map(\.id), original.map(\.id))
+ }
+
+ func testDurableOfflineLaneUsesSyncStatusWithoutAnErrorMessage() async throws {
+ let server = IntegratingServer(); try await server.open(initial())
+ let path = ScriptedPathSource(.satisfied)
+ let connectivity = NativeConnectivity(source: path)
+ let account = DocsOfflineAccount(store: MemoryBlobStore(), accountID: "a", connectivity: connectivity, transport: { server })
+ let model = DocsModel(transport: { server }, connectivity: connectivity, offlineAccount: account)
+ await model.open("doc"); _ = await model.saveAll()
+ path.send(.unsatisfied)
+ while connectivity.isPathSatisfied { await Task.yield() }
+ model.didRender(model.projectionGeneration)
+ XCTAssertTrue(model.enqueue(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("Offline")]))
+ while model.hasPendingInput { await Task.yield() }
+ await model.flush()
+ XCTAssertNil(model.errorKey, "A durable pending lane does not require keeping this window open")
+ XCTAssertEqual(model.syncStatus, .offline(pending: 1))
+ await model.stop(); account.drainer.stop()
+ }
+
+ 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 {
+ 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:
+ 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()
+ }
+
+ 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()
+ }
+
+ func testLockedRenameIsRetriedBeforeLocalFailureClears() async throws {
+ let server = IntegratingServer(); try await server.open(initial())
+ let disk = FaultingBlobStore(), network = NativeConnectivity(source: ScriptedPathSource(.unsatisfied))
+ let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: network, transport: { server })
+ let model = DocsModel(transport: { server }, connectivity: network, offlineAccount: account)
+ await model.open("doc")
+ disk.unavailable = true
+ model.renameInput = "Keep this title"
+ XCTAssertFalse(model.commitRename())
+ XCTAssertFalse(model.commitRename(), "Equality with the failed in-memory title is not a durable commit")
+ disk.unavailable = false
+ await model.retry()
+ XCTAssertEqual(try account.metadata("doc")?.pendingTitle, "Keep this title")
+ XCTAssertTrue(model.commitRename())
+ await model.persistReplica()
+ XCTAssertEqual(try account.metadata("doc")?.pendingTitle, "Keep this title")
+ await model.discardAll(); account.drainer.stop()
+ }
+
+ func testRenameAfterTitlePOSTButBeforeBatchAckKeepsSuccessorTrigger() async throws {
+ let server = IntegratingServer(); try await server.open(initial())
+ let path = ScriptedPathSource(.unsatisfied), disk = MemoryBlobStore()
+ let network = NativeConnectivity(source: path)
+ let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: network, transport: { server })
+ let model = DocsModel(transport: { server }, connectivity: network, offlineAccount: account)
+ while network.path?.status != .unsatisfied { try await Task.sleep(for: .milliseconds(5)) }
+ await model.open("doc")
+ model.didRender(model.projectionGeneration)
+ XCTAssertTrue(model.enqueue(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("A")]))
+ while model.hasPendingInput { try await Task.sleep(for: .milliseconds(5)) }
+ var metadata = try XCTUnwrap(account.metadata("doc"))
+ metadata.pendingTitle = "First"
+ try account.saveMetadata(metadata, key: "doc")
+ try await account.ensureMetadataEntry("doc")
+ let queuedEntries = await account.outbox.entries(lane: "doc:doc")
+ XCTAssertEqual(queuedEntries.map(\.kind), ["update", "metadata"])
+ await server.delayUpdates(); path.send(.satisfied)
+ let started = ContinuousClock.now.advanced(by: .seconds(2))
+ while await server.updateRequestCount() == 0, .now < started { try await Task.sleep(for: .milliseconds(5)) }
+ let flying = await account.outbox.summary.inFlight
+ XCTAssertEqual(flying, 2)
+ metadata = try XCTUnwrap(account.metadata("doc"))
+ metadata.pendingTitle = "Successor"
+ try account.saveMetadata(metadata, key: "doc")
+ try await account.ensureMetadataEntry("doc")
+ let deadline = ContinuousClock.now.advanced(by: .seconds(3))
+ while await server.savedTitle() != "Successor", .now < deadline { try await Task.sleep(for: .milliseconds(10)) }
+ let title = await server.savedTitle(); XCTAssertEqual(title, "Successor")
+ await model.discardAll(); account.drainer.stop()
+ }
+
+ func testLostChangesNoticePersistsUntilDismissal() async throws {
+ let server = IntegratingServer(); try await server.open(initial())
+ let disk = MemoryBlobStore(["outbox/0000000000000001.entry": Data("corrupt".utf8)])
+ let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: NativeConnectivity(source: ScriptedPathSource(.unsatisfied)), transport: { server })
+ let home = DocsModel(transport: { server }, offlineAccount: account)
+ await home.load()
+ try await Task.sleep(for: .milliseconds(50))
+ XCTAssertEqual(home.lostChangesNotice, NativeSyncStrings.kit.unsentLost)
+ await home.load()
+ XCTAssertNotNil(home.lostChangesNotice, "A list refresh must not dismiss the notice")
+ await home.dismissLostChangesNotice()
+ try await Task.sleep(for: .milliseconds(50))
+ XCTAssertNil(home.lostChangesNotice)
+ account.drainer.stop()
+ }
+
+ func testLaneCapCannotBeBypassedAndClearsAfterDrain() async throws {
+ let server = IntegratingServer(); try await server.open(initial())
+ let network = NativeConnectivity(source: ScriptedPathSource(.unsatisfied))
+ 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 account.outbox.enqueue(lane: "doc:doc", kind: "metadata", payload: Data(repeating: 0, count: 32 * 1024 * 1024 + 1))
+ try await Task.sleep(for: .milliseconds(50))
+ XCTAssertTrue(model.inputPaused)
+ XCTAssertEqual(model.syncStatus, .failed(pending: 1, reason: .tooManyUnsent))
+ await model.retry(); XCTAssertTrue(model.inputPaused)
+ let reopened = DocsModel(transport: { server }, connectivity: network, offlineAccount: account)
+ await reopened.open("doc")
+ XCTAssertTrue(reopened.inputPaused, "Reopening cannot bypass the byte ceiling")
+ try await account.outbox.discard(lane: "doc:doc")
+ try await Task.sleep(for: .milliseconds(50))
+ XCTAssertFalse(model.inputPaused)
+ XCTAssertEqual(model.syncStatus, .saved)
+ await reopened.discardAll(); await model.discardAll(); account.drainer.stop()
+ }
+
+ func testIntegratingServerStreamsSubsequentUpdates() async throws {
+ let server = IntegratingServer(), seed = try await initial()
+ try await server.open(seed)
+ let events = expectation(description: "Initial and subsequent sequence")
+ events.expectedFulfillmentCount = 2
+ let listener = Task { try await server.stream("/d/doc/stream", onOpen: {}) { _ in events.fulfill() } }
+ defer { listener.cancel() }
+ try await Task.sleep(for: .milliseconds(30))
+ let local = CRDTReplica(guid: "offline-property"); _ = try await local.open(update: seed)
+ let update = try await edit(local, "Remote")
+ _ = try await server.responseDetails("/d/doc/updates", method: "POST", body: update, contentType: "application/octet-stream", maxBytes: 1024)
+ await fulfillment(of: [events], timeout: 1)
+ await local.close()
+ }
+
+ func testDraftAttachmentReopensAfterEveryStoreOperation() async throws {
+ let seed = try await initial(), base = MemoryBlobStore()
+ let network = NativeConnectivity(source: ScriptedPathSource(.satisfied))
+ let original = DocsOfflineAccount(store: base, accountID: "a", connectivity: network, transport: { nil })
+ let detail = DocumentDetail(sqid: "draft-token", title: "Draft title", guid: "offline-property", can_write: true, can_share: false)
+ try original.saveMetadata(DocsOfflineMetadata(detail: detail, pendingTitle: "Draft title", draftToken: "token"), key: "draft-token")
+ let source = CRDTReplica(guid: detail.guid); _ = try await source.open(update: seed)
+ try await original.outbox.enqueue(lane: "doc:draft-token", kind: "update", payload: seed)
+ try await original.outbox.enqueue(lane: "doc:draft-token", kind: "update", payload: edit(source, "Draft content"))
+ await source.close()
+ // Discover the actual operation count, then crash before every one.
+ var limit = 0
+ for crashAfter in [-1] + Array(0...80) {
+ if crashAfter > limit && crashAfter >= 0 { break }
+ let server = IntegratingServer(); try await server.open(Data())
+ let disk = FaultingBlobStore(MemoryBlobStore(base.contents))
+ let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: network, transport: { server })
+ if crashAfter >= 0 { disk.crash(after: crashAfter) }
+ do { try await account.activate(); await account.drainer.drain() } catch is SimulatedCrash { }
+ account.drainer.stop()
+ if crashAfter == -1 { limit = disk.operationCount }
+ let frozen = disk.committed
+ let recovered = DocsOfflineAccount(store: frozen, accountID: "a", connectivity: network, transport: { server })
+ try await recovered.activate(); await recovered.drainer.drain()
+ XCTAssertEqual(try recovered.key(for: "doc"), "draft-token", "Boundary \(crashAfter)")
+ XCTAssertNil(try recovered.metadata("draft-token")?.draftToken)
+ let text = try await server.text(), count = await server.documentCount(), summary = await recovered.outbox.summary
+ XCTAssertEqual(text, "Draft content", "Boundary \(crashAfter)")
+ XCTAssertEqual(count, 1, "Creation-token retry cannot duplicate the document")
+ XCTAssertTrue(summary.isEmpty)
+ let reopened = CRDTReplica(guid: detail.guid)
+ let lane = DocsPersistence(store: frozen, outbox: recovered.outbox, key: "draft-token", replica: reopened)
+ try await lane.reopen(fallback: Data(), sequence: 0)
+ let offline = try await reopened.projection().children.map(\.plainText).joined()
+ XCTAssertEqual(offline, "Draft content")
+ await reopened.close(); recovered.drainer.stop()
+ }
+ XCTAssertLessThanOrEqual(limit, 80, "Expand the exhaustive sweep if attachment grows")
+ }
+
+ func testDirectDocumentOpenReportsLostKeyBeforeReadingItsIndex() async throws {
+ let server = IntegratingServer(); try await server.open(initial())
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let keys = ScriptedKeyProvider(key: SymmetricKey(size: .bits256))
+ let disk = NativeSealedStore(root: root, accountID: "a", keys: keys)
+ let network = NativeConnectivity(source: ScriptedPathSource(.unsatisfied))
+ let old = 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 old.saveMetadata(DocsOfflineMetadata(detail: detail), key: "doc")
+ try await old.outbox.enqueue(lane: "doc:doc", kind: "update", payload: Data([0]))
+ _ = keys.deleteKey()
+ // A process restart also drops NativeSealedStore's cached key/state.
+ // Reusing the old store would deliberately keep the still-usable key.
+ let reopened = NativeSealedStore(root: root, accountID: "a", keys: keys)
+ let next = DocsOfflineAccount(store: reopened, accountID: "a", connectivity: network, transport: { server })
+ let model = DocsModel(transport: { server }, connectivity: network, offlineAccount: next)
+ await model.open("doc")
+ try await Task.sleep(for: .milliseconds(50))
+ XCTAssertNotNil(model.projection)
+ XCTAssertEqual(model.lostChangesNotice, NativeSyncStrings.kit.unsentLost)
+ await model.discardAll(); next.drainer.stop()
+ }
+
+ func testDraftSeedSurvivesMetadataWriteFailureAndConvergesAfterUnlock() async throws {
+ let server = IntegratingServer(); try await server.open(Data())
+ let disk = MetadataLockStore(), network = NativeConnectivity(source: ScriptedPathSource(.satisfied))
+ let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: network, transport: { server })
+ let model = DocsModel(transport: { server }, connectivity: network, draft: true, offlineAccount: account)
+ await model.newDraft()
+ XCTAssertTrue(model.inputPaused)
+ disk.unlock(); await model.retry()
+ XCTAssertNotNil(model.projection)
+ model.didRender(model.projectionGeneration)
+ XCTAssertTrue(model.enqueue(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("Recovered draft")]))
+ while model.hasPendingInput { try await Task.sleep(for: .milliseconds(5)) }
+ let saved = await model.saveAll(); XCTAssertTrue(saved)
+ let text = try await server.text()
+ XCTAssertEqual(text, "Recovered draft", "The paragraph dependency must reach the server too")
+ 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..89fd585
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/OfflineKillTests.swift
@@ -0,0 +1,80 @@
+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 randomKill = env["DOCS_KILL_RANDOM"] == "1"
+ 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" {
+ guard await model.saveAll() else {
+ XCTFail("Initial save failed: \(model.syncStatus)"); return
+ }
+ 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)
+ // Exercise I1a with writer ticks racing command/enqueue. No sleep
+ // or handshake freezes the typing process in random mode.
+ let writer: Task<Void, Never>? = randomKill ? Task {
+ while !Task.isCancelled { await model.persistReplica(); await Task.yield() }
+ } : nil
+ defer { writer?.cancel() }
+ for index in 1...(randomKill ? 10_000 : 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 { await Task.yield() }
+ if randomKill || 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.
+ if !randomKill { try await Task.sleep(for: .seconds(1)) }
+ }
+ if !randomKill { 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)
+ let reopened = model.projection?.children.map(\.plainText).joined() ?? ""
+ if randomKill {
+ XCTAssertFalse(expected.isEmpty, "The controller must observe durable typing before killing")
+ XCTAssertTrue(reopened.hasPrefix(expected), "Offline reopen must preserve the last recorded durable prefix")
+ let tokens = reopened.split(separator: ";")
+ XCTAssertEqual(reopened, (1...max(1, tokens.count)).map { "k3-\($0);" }.joined(), "Recovered text must have no gaps, torn edits, or duplicates")
+ } else {
+ XCTAssertEqual(reopened, 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(), reopened, "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..7c317f1 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: 529f356f476e43174882361511032e0bdefa5317
settings:
base:
SWIFT_VERSION: '6.0'
diff --git a/native/macos/project.yml b/native/macos/project.yml
index 81fd871..2ff784f 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: 529f356f476e43174882361511032e0bdefa5317
settings:
base:
SWIFT_VERSION: '6.0'
diff --git a/native/scripts/test-document-drafts.py b/native/scripts/test-document-drafts.py
index bb25747..d5dcf7e 100644
--- a/native/scripts/test-document-drafts.py
+++ b/native/scripts/test-document-drafts.py
@@ -67,8 +67,9 @@ class Handler(http.server.BaseHTTPRequestHandler):
self.reply(200, **{"Docs-Seq": "0"})
else:
cls.metadata += 1
+ title = cls.title or "Untitled document"
if cls.metadata == 2: time.sleep(0.9) # Old title arrives after rename acknowledgement.
- self.reply(200, json.dumps(dict(sqid=self.path.split("/")[-1], title="Untitled document", guid="server-guid", can_write=True, can_share=True)).encode())
+ self.reply(200, json.dumps(dict(sqid=self.path.split("/")[-1], title=title, guid="server-guid", can_write=True, can_share=True)).encode())
def log_message(self, *_): pass
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
threading.Thread(target=server.serve_forever, daemon=True).start()
diff --git a/native/scripts/test-offline-kill.py b/native/scripts/test-offline-kill.py
new file mode 100755
index 0000000..4bbfd0d
--- /dev/null
+++ b/native/scripts/test-offline-kill.py
@@ -0,0 +1,78 @@
+#!/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 argparse
+import random
+import os
+from pathlib import Path
+import signal
+import subprocess
+import tempfile
+import time
+
+parser = argparse.ArgumentParser(description=__doc__)
+parser.add_argument("--random", action="store_true", help="kill during unpaused typing and concurrent replica writes")
+parser.add_argument("--seed", type=int, default=None, help="reproduce the controller's random delay")
+args = parser.parse_args()
+seed = args.seed if args.seed is not None else random.SystemRandom().randrange(2**32)
+kill_delay = random.Random(seed).uniform(0, .5)
+root = Path(__file__).resolve().parents[2]
+
+def wait_for(path, process, timeout=300):
+ 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, DOCS_KILL_RANDOM="1" if args.random else "0", TMPDIR="/tmp")
+ server_log = (scratch / "server.log").open("w")
+ server = subprocess.Popen(["go", "test", "./internal/docs", "-run", "^TestNativeKillServer$", "-count=1", "-timeout=8m"], 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)
+ if args.random:
+ # Only the controller waits; the editing process never pauses
+ # for us and can die during a command, enqueue, or writer tick.
+ time.sleep(kill_delay)
+ pid = int((scratch / "pid").read_text())
+ os.kill(pid, signal.SIGKILL)
+ result = writer.wait(timeout=20)
+ assert result != 0, "typing process unexpectedly succeeded"
+ # Include assertions emitted during the controller’s random delay.
+ assert ": error:" not in (scratch / "writer.log").read_text(), "typing assertions failed before kill"
+ if args.random:
+ print(f"SIGKILL during unpaused typing + writer ticks (seed={seed}, delay={kill_delay:.6f}s)", flush=True)
+ else:
+ 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 preserves recorded prefix; real server equals reopened replica; no gaps or 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..ab01631 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" : "529f356f476e43174882361511032e0bdefa5317"
}
},
{