oficina / docs Public

Close metadata retry and loss-reporting gaps with crash regressions

Paul Campbell pushed by paul@keymail.dev ced4f54be782bbb7dde589521f2498312ee1d017 parent b14105c
6 files changed, +391 −173
  • docs/testing/k3-evidence.md +117 −152
  • native/apple/Sources/DocsKit/DocsModel.swift +39 −17
  • native/apple/Sources/DocsKit/DocsOfflineAccount.swift +1 −1
  • native/apple/Sources/DocsKit/DocsWorkspace.swift +8 −0
  • native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift +224 −2
  • native/scripts/test-document-drafts.py +2 −1

CI passed — run details

diff --git a/docs/testing/k3-evidence.md b/docs/testing/k3-evidence.md
index 00f2f91..b804796 100644
--- a/docs/testing/k3-evidence.md
+++ b/docs/testing/k3-evidence.md
@@ -1,153 +1,118 @@
-# K3 continuation: evidence and disk-stop handoff
-
-**WIP, not mergeable.** Work stopped on 2026-09-24 when free disk space
-reached 1.2 GiB, below the user's mandatory 1.5 GiB stop threshold.
-No merge or deployment occurred. Discussion: oficina/docs #69; kit: #9.
-The kit pin is 6b6b19814c8df182954db36f1f4637bd0cda181a on feat/k3-outbox.
-
-## Implemented, with partial validation
-
-- Per-account shared Outbox/OutboxDrainer and sealed metadata/replicas.
-- CRDTReplica atomically captures state, server sequence and commandsApplied
- using existing snapshot. DocsPersistence advances commandsDurable only after
- enqueue and writes only when commandsApplied == commandsDurable.
-- Reopen applies the persisted replica and the entire lane before publication.
-- Coalesced two-second writer, server catch-up/background/close flush hooks.
-- Compaction threshold and byte batching; queued input separated from unsent
- changes; visible local-storage failure and 32 MiB input stop.
-- Native status/banner adoption and app account IDs passed to the sealed store.
-- Ported parked-update test (NOT YET EXECUTED).
-- Integrating WASM fake, generated crash histories, exhaustive replacement
- boundaries, model reopen/transport test, storage-unlock regression.
-- A real authenticated Go-handler loopback server and SIGKILL harness.
-
-## Observed tests
-
-| Test | Failing-first evidence | Subsequent evidence |
+# 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 |
|---|---|---|
-| Watermark, lane reopen, generated history | No-op DocsPersistence + snapshot capture: 3 tests, 238 failures; /tmp/k3-docs-red.log | 3 tests passed; /tmp/k3-docs-green.log |
-| Each replace crash boundary + actual model reopen | Remove only lane replay: 2 tests, 5 failures on missing text; /tmp/k3-docs-integration-red.log | Included in 6 durability tests passing below |
-| Unlock resumes already queued commands | Current defect: 1 test, 3 failures; /tmp/k3-unlock-red.log | Passed after retry fixes |
-| Durability + account boundaries | Earlier full Swift run found 2 assertions failing in account-switch retry | 10 focused tests passed (6 durability, 4 account), /tmp/k3-docs-integration-green.log |
-| Seal count/rotation (kit) | Rotation call stubbed: both new tests failed | All 14 sealed-store tests passed; /tmp/k3-rotation-green-2.log |
-| Independent app retry (kit) | Retrying first lane prevented second sending | All 15 drainer tests passed; /tmp/k3-lane-retry-green.log |
-
-The initial full Docs Swift run executed 60 XCTest tests (3 skipped), with
-2 failed account-switch assertions, plus 16 passing Swift Testing tests.
-The focused rerun fixed those assertions, but a final full rerun remains.
-
-**Kill test is not a passing proof.** /tmp/k3-kill-red.log records a real
-SIGKILL after 12 durable typing edits with lane replay deliberately omitted.
-Recovery correctly failed its missing-text assertion, but the writer also
-failed its initial save assertion and server convergence failed independently.
-Investigate the initial save/server request path before claiming a valid
-negative control. The mutation was restored before saving this WIP. Run both
-red and green controls again. The test script should also refuse to proceed
-if its writer logged any assertion failure before the kill marker.
-
-The new native/crdt parked-update test still needs a failing run with
-Editor.snapshot using encode_diff_v1, then a passing run with the existing
-encode_state_as_update_v1. No new snapshot operation was added.
-
-## Remaining review findings (gpt-6-astra, read-only review)
-
-1. Preserve cached pendingTitle when metadata exists but replica is absent.
- The fallback fetch currently overwrites that durable rename with server data.
-2. Repair the draft attachment crash boundary between writing sqid index and
- attached metadata: stale draft metadata can leave the lane retrying forever.
-3. Serialize/retry title sends centrally. The current single model sender fixed
- competing account/model POSTs, but it sends pendingTitle only once: a second
- rename arriving during the first request can remain unsent indefinitely.
- Title-only transient errors also need an automatic retry/reopen owner.
-4. Start account replay when selecting an account into Home, without racing
- document reopen against ack/removal. Current starts cover open/newDraft,
- but Home itself does not start pending replay after a relaunch.
-5. Extend regression tests for the above before fixing, and rerun review.
-6. Audit draft/error recovery, local cap/hold semantics, unavailable-store
- status preservation and the once-only lost-content notice: incomplete UI
- recovery remains possible. The integrating fake's stream currently emits
- only its initial sequence; it still needs ongoing server-change delivery.
-
-Earlier review findings fixed: discard writer invalidation, storage unlock
-resuming queued commands, successful persistence clearing local failure,
-account-return retry, and independent lanes after an app-level retry. A
-competing title sender was removed. The latest draft-worker start placement
-has not had its own full rerun.
-
-## Spec differences and incomplete items
-
-- Discard removes the replica *before* its lane, rather than the textual order
- in §4.3. This deliberately prevents a process kill leaving a replica whose
- unsent lane was already deleted. A captured writer is invalidated first.
-- Empty/session-ended status currently resolves to saved, as the inherited
- kit tests expect; the spec's priority table lists session-ended before saved.
- Reconcile this explicitly instead of silently calling it exact conformance.
-- Kit adds load/entries/beginSend/endSend APIs to express replay and in-flight
- reservations. No update or retarget operation was introduced.
-- K5 reauthentication, subject migration, signout wipe and K6 first-400,
- terminal-hold UI, relaxed close guard/background send task remain deferred
- per their slice rows. Existing close/signout protection is still in place.
-- All unimplemented/review items above remain gaps, not approved deviations.
-
-## Remaining gates
-
-- rastrillo/native make ci: an earlier full pass predates the latest rotation
- and retry fixes. Run again at final head. Hub has no macOS runner and failed
- extracting Sparkle because unzip was absent; use local macOS make ci.
-- Docs .amadan/ci.d/10-gate: NOT RUN in this continuation.
-- Docs native/scripts/check-native.sh: NOT RUN as the full gate. Framework
- preparation, xcodegen and focused/full Swift runs were performed separately.
-- Run xcodegen before every xcodebuild. Put ~/.cargo/bin first on PATH;
- TMPDIR=/tmp. Run only one gate at a time.
-- Repeat real SIGKILL red/green controls after correcting its setup failure.
-- Full branch review, branch discussion updates, and current CI status.
-
-## Disk ownership
-
-At start, native-k3-outbox/.build already existed: it was not deleted.
-This session created, then removed companion build/, Docs native/apple/.build,
-native/crdt/target, native/host/target, native/build, and the generated
-DocsCRDT.xcframework. The generated Xcode projects remain ignored. No other
-session's outputs were removed. Cleanup briefly restored 1.7 GiB, then free
-space continued falling; do not restart builds without sufficient headroom.
-
-## Resume: SIGKILL proof (2026-09-24)
-
-The fixture configured localhost:8080 while NativeHTTP used its random loopback
-origin. A native-style title POST failed 403 (`/tmp/k3-origin-red.log`).
-Configure the server's actual listener origin; do not bypass CSRF. The script
-now refuses a failed initial save or pre-kill typing assertion.
-
-With only lane replay omitted, offline reopen failed with empty text instead of
-all 12 edits; initial save and server convergence passed (one assertion failure,
-`/tmp/k3-kill-valid-red.log`). Restore replay: SIGKILL after 12 durable edits,
-exact offline recovery, real authenticated server convergence, no duplicate text
-all passed (`/tmp/k3-kill-valid-green.log`).
-
-Parked-update port executed: `cargo test --manifest-path native/crdt/Cargo.toml
---locked --test snapshot`. Switching only Editor.snapshot to encode_diff_v1
-failed the healed-text equality (`/tmp/k3-parked-red.log`). Restoring existing
-encode_state_as_update_v1 passed (`/tmp/k3-parked-green.log`). No new op.
-
-## Resume: durable metadata and Home replay
-
-Five focused regressions failed on the prior implementation (15 assertions,
-/tmp/k3-recovery-red.log): title before first replica write, title-only transient
-retry, rename during an in-flight title POST, attached draft index crash repair,
-and Home-only replay. Account-owned metadata sends through the existing drainer,
-registered immutable metadata keys, repairable aliases, and shared monotonic
-replica commits passed those plus all existing durability/account tests (15
-passing, /tmp/k3-recovery-green.log).
-
-Replica cache merge/invalidation and replica-before-lane discard were deliberately
-broken: two tests failed with six assertions (/tmp/k3-cache-discard-red.log).
-Restore the implementations: all 13 durability tests pass, including generated
-crashes scheduled before arbitrary event store operations and exhaustive discard
-boundaries (/tmp/k3-cache-discard-green.log). Replica-first deletion therefore
-cannot leave local text stranded after removal of its lane.
-
-A metadata marker is an app-owned outbox kind, not a kit API. CRDT replay and
-compaction use only update entries. A kill after metadata but before enqueue is
-reconciled from registered keys on activation. Both editor and headless writers
-merge the latest durable cache under a compare/retry and shared discard generation;
-the editor also checks commandsApplied == commandsDurable immediately at commit.
+| 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.
diff --git a/native/apple/Sources/DocsKit/DocsModel.swift b/native/apple/Sources/DocsKit/DocsModel.swift
index d1e4de9..7721307 100644
--- a/native/apple/Sources/DocsKit/DocsModel.swift
+++ b/native/apple/Sources/DocsKit/DocsModel.swift
@@ -23,6 +23,7 @@ import RastrilloNative
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 }
@@ -42,6 +43,8 @@ import RastrilloNative
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]] = []
@@ -74,7 +77,7 @@ import RastrilloNative
return current
}
var hasPendingInput: Bool { !editing.isEmpty || editingTask != nil }
- var hasUnpersistedInput: Bool { (renameInput != nil && renameInput != detail?.title) || composing || !editing.isEmpty || editingTask != nil || failedUpdate != nil || localFailure == .cannotSaveOnDevice }
+ 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 }
@@ -85,13 +88,22 @@ import RastrilloNative
summaryTask = Task { [weak self, outbox = offlineAccount.outbox] in
for await summary in await outbox.changes {
guard let self, self.documentKey == key else { return }
- self.laneSummary = summary.only("doc:" + key)
+ self.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 let key = documentKey, let stored = try? offlineAccount.metadata(key) else { return }
+ 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 {
@@ -100,7 +112,9 @@ import RastrilloNative
}
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()
@@ -114,7 +128,7 @@ import RastrilloNative
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 {
+ else if self.localFailure == .cannotSaveOnDevice, self.failedUpdate == nil, !self.metadataDirty {
self.localFailure = nil
if self.detail?.can_write == true { self.inputPaused = false }
}
@@ -126,10 +140,7 @@ import RastrilloNative
failedUpdate = update
try await persistence.enqueue(update)
failedUpdate = nil
- laneSummary = await offlineAccount.outbox.summary.only(persistence.lane)
- if (laneSummary.lanes[persistence.lane]?.bytes ?? 0) > 32 * 1024 * 1024 {
- localFailure = .tooManyUnsent; inputPaused = true
- }
+ updateLaneSummary(await offlineAccount.outbox.summary.only(persistence.lane))
try await persistence.compact()
}
func load(query: String = "") async {
@@ -159,19 +170,21 @@ import RastrilloNative
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
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 }
@@ -193,11 +206,6 @@ import RastrilloNative
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 }
@@ -209,11 +217,18 @@ import RastrilloNative
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
do { try saveMetadata() } catch { localFailure = .cannotSaveOnDevice; inputPaused = true; return false }
- Task { await flush() }
+ Task {
+ do { if let documentKey { try await offlineAccount.ensureMetadataEntry(documentKey) } }
+ catch { localFailure = .cannotSaveOnDevice; inputPaused = true }
+ await flush()
+ }
return true
}
func open(_ sqid: String) async {
@@ -226,6 +241,7 @@ import RastrilloNative
guard documentEpoch == epoch else { return }
defer { if documentEpoch == epoch { loading = false } }
do {
+ try await offlineAccount.outbox.load()
let key = try offlineAccount.key(for: sqid)
let cached = try offlineAccount.metadata(key)
pendingTitle = cached?.pendingTitle; draftToken = cached?.draftToken
@@ -257,6 +273,7 @@ import RastrilloNative
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 {
@@ -329,13 +346,18 @@ import RastrilloNative
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() }
}
@@ -375,7 +397,7 @@ import RastrilloNative
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
editing.removeAll(); saving = false
diff --git a/native/apple/Sources/DocsKit/DocsOfflineAccount.swift b/native/apple/Sources/DocsKit/DocsOfflineAccount.swift
index 746af36..b6e2432 100644
--- a/native/apple/Sources/DocsKit/DocsOfflineAccount.swift
+++ b/native/apple/Sources/DocsKit/DocsOfflineAccount.swift
@@ -73,7 +73,7 @@ struct DocsOfflineMetadata: Codable {
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)
+ let entries = await outbox.sendable(lane: "doc:" + key, maxBytes: nil)
guard replicaCache.generation(key) == generation, !entries.contains(where: { $0.kind == "metadata" }) else { return }
try await outbox.enqueue(lane: "doc:" + key, kind: "metadata", payload: Data())
}
diff --git a/native/apple/Sources/DocsKit/DocsWorkspace.swift b/native/apple/Sources/DocsKit/DocsWorkspace.swift
index ce8f840..ee4a520 100644
--- a/native/apple/Sources/DocsKit/DocsWorkspace.swift
+++ b/native/apple/Sources/DocsKit/DocsWorkspace.swift
@@ -73,6 +73,14 @@ import SwiftUI
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) }) }
}
diff --git a/native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift b/native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift
index a6ab4dc..81f8d9b 100644
--- a/native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift
+++ b/native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift
@@ -1,4 +1,5 @@
import Foundation
+import CryptoKit
import RastrilloApple
import RastrilloNative
import RastrilloTestSupport
@@ -8,10 +9,16 @@ import XCTest
/// 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 }
@@ -20,6 +27,8 @@ private actor IntegratingServer: NativeTransport {
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] = [:]
@@ -31,6 +40,11 @@ private actor IntegratingServer: NativeTransport {
func text() async throws -> String { try await replica.projection().children.map(\.plainText).joined() }
func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse {
guard online else { throw NativeClientError.offline(.notConnectedToInternet) }
+ if method == "POST", path == "/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)) }
@@ -42,25 +56,51 @@ private actor IntegratingServer: NativeTransport {
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") {
- return NativeResponse(data: try await snapshot(), status: 200, headers: ["Docs-Seq": String(sequence)])
+ 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)")
- try await Task.sleep(for: .seconds(3600))
+ 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 }
@@ -452,4 +492,186 @@ private struct OfflineRandom: RandomNumberGenerator {
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()
+ let next = DocsOfflineAccount(store: disk, 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/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()