oficina / docs Public

Docs native: persist the replica incrementally (append segments, compact now and then)

Audit finding 8. DocsReplicaCache.commit rewrote the whole replica after
every send and every incoming change: a new merger interpreter, open the
previous state, apply, snapshot, JSON/base64, seal and write; 57 ms at
10 pages, ~100 ms at 20, 0.9-1.4 s at 200.

A document's replica is now a base (`replica`, the same format 1 file)
plus segments in `replica-log/`, each one update with the sequence it
brings the state to ("DRL1", sequence, raw update bytes, sealed like
every file). The replica is their union.

- DocsPersistence.persist appends the updates applied since the last
  persist (CRDTReplica.persistentChanges/persisted) as one segment. The
  I1a watermark check is unchanged and still has no suspension before
  the write. With no base yet, or more than 1 MB of changes, it stores
  the whole state as before.
- Headless sends append the sent update instead of merging it into the
  base (still before the ack can remove the lane files).
- Every 32 segments, or after one of 256 KB, the segments are folded
  into the base: write base U segments, then remove exactly the merged
  segments. A crash between leaves segments the base already holds.
  Segments appended meanwhile stay; a base replaced meanwhile wins.
- reopen reads the base and every segment (sequence = the max). Segments
  without a base can only be left by an interrupted discard, so they are
  never read and are removed when a base is next written; discard
  removes segments before the base. A segment that fails to unseal drops
  the whole replica (as a corrupt base did): skipping it would leave a
  later segment's sequence claiming updates it no longer holds.

Measured on sealed disk (release): a persist after a keystroke or a
remote change is 1.8 ms at p1, p10, p10h and p20 (the full rewrite was
16, 55, 70 and 100 ms); the compaction every 32 appends is 10-28 ms.

Tests: ReplicaSegmentTests (appends never rewrite the base; compaction
keeps text and sequence; a crash at every operation of an append and of
the following compaction reopens with either the update and its
sequence or neither; orphan segments are never read; an unreadable
segment drops the replica and the outbox plus server restore it).
OfflineDurabilityTests now check I1a against base plus segments in the
generated crash histories, and discard against both.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 61fbce36cbd5783a226dcb98eb791703d0b35a4a parent 50cff9e
7 files changed, +387 −50
  • native/apple/Sources/DocsKit/CRDTReplica.swift +16 −5
  • native/apple/Sources/DocsKit/DocsModel.swift +1 −1
  • native/apple/Sources/DocsKit/DocsOfflineAccount.swift +17 −13
  • native/apple/Sources/DocsKit/DocsPersistence.swift +41 −10
  • native/apple/Sources/DocsKit/DocsReplicaCache.swift +128 −3
  • native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift +40 −18
  • native/apple/Tests/DocsKitTests/ReplicaSegmentTests.swift +144 −0
diff --git a/native/apple/Sources/DocsKit/CRDTReplica.swift b/native/apple/Sources/DocsKit/CRDTReplica.swift
index 3a76f35..734a4d9 100644
--- a/native/apple/Sources/DocsKit/CRDTReplica.swift
+++ b/native/apple/Sources/DocsKit/CRDTReplica.swift
@@ -77,15 +77,26 @@ actor CRDTReplica {
struct PersistentChanges: Sendable {
/// Every update applied since the last `persisted`, in order.
let updates: [Data]
+ /// The whole state, when asked for: taken at the same moment.
+ let whole: Data?
let sequence: Int64
let commandsApplied: Int
let guid: String
+ /// The parking accepted as the server's own when this was taken.
+ let parked: String
}
- /// What changed since the replica was last persisted: a writer appends
- /// these to the stored state instead of rewriting it.
- func persistentChanges() throws -> PersistentChanges {
- _ = try currentAuthority()
- return PersistentChanges(updates: unpersisted, sequence: durableSequence, commandsApplied: commandsApplied, guid: guid)
+ /// What changed since the replica was last persisted, so a writer can
+ /// append it instead of rewriting the whole state; and the whole state
+ /// too when those changes exceed `wholeAbove` bytes (-1: always).
+ func persistentChanges(wholeAbove limit: Int) throws -> PersistentChanges {
+ let authority = try currentAuthority()
+ let bytes = unpersisted.reduce(0) { $0 + $1.count }
+ var whole: Data?
+ if limit < 0 || bytes > limit {
+ if !lastGood.tail.isEmpty { try compact(authority) }
+ whole = lastGood.base
+ }
+ return PersistentChanges(updates: unpersisted, whole: whole, sequence: durableSequence, commandsApplied: commandsApplied, guid: guid, parked: acceptedParking)
}
/// The first `count` updates of the last `persistentChanges` are stored.
func persisted(_ count: Int) { unpersisted.removeFirst(min(count, unpersisted.count)) }
diff --git a/native/apple/Sources/DocsKit/DocsModel.swift b/native/apple/Sources/DocsKit/DocsModel.swift
index afd3503..5a4866d 100644
--- a/native/apple/Sources/DocsKit/DocsModel.swift
+++ b/native/apple/Sources/DocsKit/DocsModel.swift
@@ -284,7 +284,7 @@ import RastrilloNative
let detail: DocumentDetail
let initial: Data
let seq: Int64
- if let cached, try offlineAccount.store.read("cache/docs/\(key)/replica") != nil {
+ if let cached, try offlineAccount.replicaCache.hasBase(key) {
detail = cached.detail; pendingTitle = cached.pendingTitle; initial = Data(); seq = 0
} else {
let remote: DocumentDetail = try await client().request("/d/\(sqid)")
diff --git a/native/apple/Sources/DocsKit/DocsOfflineAccount.swift b/native/apple/Sources/DocsKit/DocsOfflineAccount.swift
index bf3f54f..c65478a 100644
--- a/native/apple/Sources/DocsKit/DocsOfflineAccount.swift
+++ b/native/apple/Sources/DocsKit/DocsOfflineAccount.swift
@@ -267,20 +267,24 @@ struct DocsSentUpdates: Sendable {
let assigned = (200..<300).contains(reply.status) ? Int64(reply.header("Docs-Seq") ?? "") : nil
posted(DocsSentUpdates(key: key, sequence: assigned, entries: Set(sending.map(\.id))))
try reply.requireSuccess()
- var state = update, sequence: Int64 = 0, parked: String? = nil
- 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
- // The server's whole state: what it parks is the server's own, and
- // the first record accepts it, as a first open does (#147).
- let reader = CRDTReplica(guid: metadata.detail.guid)
- do { _ = try await reader.open(update: state); parked = try await reader.parked(); await reader.close() }
- catch { await reader.close(); throw error }
- }
// 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, parked: parked), key: key, generation: generation)
+ if try replicaCache.hasBase(key), try replicaCache.append(update, sequence: 0, key: key, generation: generation) {
+ try? await replicaCache.compactIfNeeded(key, generation: generation, appended: update.count)
+ } else {
+ var state = update, sequence: Int64 = 0, parked: String? = nil
+ if try !replicaCache.hasBase(key) {
+ 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
+ // The server's whole state: what it parks is the server's own, and
+ // the first record accepts it, as a first open does (#147).
+ let reader = CRDTReplica(guid: metadata.detail.guid)
+ do { try await reader.open(update: state); parked = try await reader.parked(); await reader.close() }
+ catch { await reader.close(); throw error }
+ }
+ try await replicaCache.commit(PersistedReplica(format: 1, sequence: sequence, guid: metadata.detail.guid, savedAt: Date(), state: state, parked: parked), key: key, generation: generation)
+ }
// More of this lane is waiting (typed during this POST): hold the
// drainer until the next POST is allowed, then let it reserve
// everything typed by then in one batch.
diff --git a/native/apple/Sources/DocsKit/DocsPersistence.swift b/native/apple/Sources/DocsKit/DocsPersistence.swift
index 83b51a4..cfc87b4 100644
--- a/native/apple/Sources/DocsKit/DocsPersistence.swift
+++ b/native/apple/Sources/DocsKit/DocsPersistence.swift
@@ -31,6 +31,12 @@ struct PersistedReplica: Codable, Sendable {
/// from ever resending. DocsModel settles it (catching up, from the start if
/// need be) and adds no first paragraph to it meanwhile.
private(set) var unsettled = false
+ /// Whether this document has a stored base to append to, and the
+ /// sequence the stored replica has reached.
+ private var hasBase = false
+ private var storedSequence: Int64 = 0
+ /// Changes larger than this are stored as a whole state instead.
+ static let appendLimit = 1024 * 1024
let cache: DocsReplicaCache
private let generation: Int
var lane: String { "doc:" + key }
@@ -43,12 +49,13 @@ struct PersistedReplica: Codable, Sendable {
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)
+ let saved = try cache.load(key)
+ if let saved, saved.replica.format != 1 { throw BlobStoreError.unavailable }
+ try await replica.open(update: saved?.replica.state ?? fallback)
+ for segment in saved?.segments ?? [] { try await replica.apply(segment.update) }
await replica.setSequence(saved?.sequence ?? sequence)
if let saved {
- await replica.acceptParking(saved.parked ?? "")
+ await replica.acceptParking(saved.replica.parked ?? "")
unsettled = try await replica.hasUnacceptedParking()
} else {
// The server's whole state: whatever it parks is the server's own.
@@ -59,6 +66,10 @@ struct PersistedReplica: Codable, Sendable {
// here, even when it cannot currently send it.
for entry in entries where entry.kind == "update" { try await replica.apply(entry.payload); held.insert(entry.id) }
commandsDurable = 0
+ hasBase = saved != nil
+ storedSequence = saved?.sequence ?? 0
+ // Stored segments and replayed entries are already durable.
+ if saved != nil { await replica.persisted(Int.max) }
}
/// Entries the server has taken are acknowledged and never sent again.
func forget(_ entries: Set<UUID>) { held.subtract(entries) }
@@ -67,15 +78,35 @@ struct PersistedReplica: Codable, Sendable {
held.insert(entry.id)
commandsDurable += 1
}
+ /// Store what changed since the last persist: appended as one segment
+ /// (a few bytes per keystroke), or, with no base yet or a large change,
+ /// as the whole state.
@discardableResult func persist() async throws -> Bool {
- let captured = try await replica.persistentState()
+ let changes = try await replica.persistentChanges(wholeAbove: hasBase ? Self.appendLimit : -1)
// 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, parked: captured.parked)
- return try await cache.commit(saved, key: key, generation: generation) {
- self.active && captured.commandsApplied == self.commandsDurable
+ guard active, changes.commandsApplied == commandsDurable else { return false }
+ let valid = { self.active && changes.commandsApplied == self.commandsDurable }
+ if changes.updates.isEmpty && changes.sequence <= storedSequence && hasBase { return true }
+ if let whole = changes.whole {
+ let saved = PersistedReplica(format: 1, sequence: changes.sequence, guid: changes.guid, savedAt: Date(), state: whole, parked: changes.parked)
+ guard try await cache.commit(saved, key: key, generation: generation, valid: valid) else { return false }
+ } else {
+ let update = changes.updates.reduce(into: Data()) { $0.append($1) }
+ guard try cache.append(update, sequence: changes.sequence, key: key, generation: generation, valid: valid) else {
+ // The base is gone (or the capture is stale): store the whole state.
+ guard valid() else { return false }
+ hasBase = false
+ return try await persist()
+ }
}
+ hasBase = true
+ storedSequence = max(storedSequence, changes.sequence)
+ await replica.persisted(changes.updates.count)
+ // Folding segments into the base is upkeep, not durability: they are
+ // already stored, so a failure here is retried on a later persist.
+ try? await cache.compactIfNeeded(key, generation: generation, appended: changes.updates.reduce(0) { $0 + $1.count })
+ return true
}
func compact() async throws {
let entries = await outbox.sendable(lane: lane, maxBytes: nil)
@@ -105,7 +136,7 @@ struct PersistedReplica: Codable, Sendable {
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 cache.remove(key)
try await outbox.discard(lane: lane)
}
}
diff --git a/native/apple/Sources/DocsKit/DocsReplicaCache.swift b/native/apple/Sources/DocsKit/DocsReplicaCache.swift
index b3a8b2a..c4a1c40 100644
--- a/native/apple/Sources/DocsKit/DocsReplicaCache.swift
+++ b/native/apple/Sources/DocsKit/DocsReplicaCache.swift
@@ -1,17 +1,113 @@
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.
+/// A document's stored replica: a base (`replica`, the whole state when it
+/// was last compacted) plus segments in `replica-log/`, each an update
+/// appended since with the server sequence it brings the state to. The
+/// replica is their union; a CRDT applies them in any order, more than once.
+///
+/// Editor captures and headless sends both write here. Appending never
+/// rewrites what another writer stored, and a compaction removes only the
+/// segments it merged, so neither writer can erase an acknowledged batch.
@MainActor final class DocsReplicaCache {
let store: BlobStore
private var generations: [String: Int] = [:]
+ /// Compact once this many segments are waiting, or one large one is.
+ static let compactionSegments = 32
+ static let compactionBytes = 256 * 1024
init(store: BlobStore) { self.store = store }
func generation(_ key: String) -> Int { generations[key, default: 0] }
func invalidate(_ key: String) { generations[key, default: 0] += 1 }
+ static func basePath(_ key: String) -> String { "cache/docs/\(key)/replica" }
+ static func logPath(_ key: String) -> String { "cache/docs/\(key)/replica-log" }
+
+ struct Segment: Sendable {
+ let name: String
+ let sequence: Int64
+ let update: Data
+ private static let magic = Data("DRL1".utf8)
+ var encoded: Data {
+ var data = Self.magic
+ withUnsafeBytes(of: sequence.bigEndian) { data.append(contentsOf: $0) }
+ data.append(update)
+ return data
+ }
+ init(name: String, sequence: Int64, update: Data) { self.name = name; self.sequence = sequence; self.update = update }
+ init?(name: String, encoded data: Data) {
+ guard data.count >= 12, data.prefix(4) == Self.magic else { return nil }
+ let sequence = data.dropFirst(4).prefix(8).reduce(Int64(0)) { ($0 << 8) | Int64($1) }
+ self.init(name: name, sequence: sequence, update: Data(data.dropFirst(12)))
+ }
+ }
+ struct Stored: Sendable {
+ let replica: PersistedReplica
+ let segments: [Segment]
+ var sequence: Int64 { segments.reduce(replica.sequence) { max($0, $1.sequence) } }
+ }
+ /// Whether a base is stored, without reading (and unsealing) it.
+ func hasBase(_ key: String) throws -> Bool {
+ try store.list("cache/docs/\(key)").contains("replica")
+ }
+ /// The stored replica. A segment that fails to unseal makes the whole
+ /// replica untrustworthy (a later segment's sequence would claim updates
+ /// it no longer holds), so all of it is removed, as a corrupt base is,
+ /// and the next open starts again from the server and the outbox.
+ func load(_ key: String) throws -> Stored? {
+ guard let data = try store.read(Self.basePath(key)) else { return nil }
+ let replica = try JSONDecoder().decode(PersistedReplica.self, from: data)
+ var segments: [Segment] = []
+ do {
+ for name in try segmentNames(key) {
+ guard let data = try store.read(Self.logPath(key) + "/" + name) else { continue }
+ guard let segment = Segment(name: name, encoded: data) else { throw BlobStoreError.corrupt(Self.logPath(key) + "/" + name) }
+ segments.append(segment)
+ }
+ } catch BlobStoreError.corrupt(let path) {
+ try remove(key)
+ throw BlobStoreError.corrupt(path)
+ }
+ return Stored(replica: replica, segments: segments)
+ }
+ /// Segments first: an interrupted removal leaves the base alone (an
+ /// older state the outbox and server complete), never segments without it.
+ func remove(_ key: String) throws {
+ try store.remove(Self.logPath(key))
+ try store.remove(Self.basePath(key))
+ }
+ /// Only names this cache writes: anything else in the directory (a
+ /// file system's temporary file) is not a segment.
+ private func segmentNames(_ key: String) throws -> [String] {
+ try store.list(Self.logPath(key)).filter { name in
+ let parts = name.split(separator: "-", maxSplits: 2)
+ return parts.count == 3 && parts[0].count == 16 && parts[1].count == 8 && UUID(uuidString: String(parts[2])) != nil
+ }
+ }
+ private var counter: UInt64 = 0
+ private func segmentName() -> String {
+ counter &+= 1
+ return String(format: "%016llx-%08llx-", UInt64(Date().timeIntervalSince1970 * 1_000_000), counter) + UUID().uuidString
+ }
+ /// Store `update` as a new segment. Refuses (false) when there is no base
+ /// to append to, or when `valid` no longer holds; a discarded document
+ /// (a newer generation) throws.
+ @discardableResult func append(_ update: Data, sequence: Int64, key: String, generation: Int, valid: () -> Bool = { true }) throws -> Bool {
+ guard self.generation(key) == generation else { throw CancellationError() }
+ guard try hasBase(key), valid() else { return false }
+ let segment = Segment(name: segmentName(), sequence: sequence, update: update)
+ try store.write(segment.encoded, to: Self.logPath(key) + "/" + segment.name)
+ return true
+ }
+ /// Store a whole state. With a base already stored it is appended like
+ /// any update; otherwise it becomes the base, merged with any base a
+ /// concurrent writer stores first.
@discardableResult func commit(_ candidate: PersistedReplica, key: String, generation: Int, valid: () -> Bool = { true }) async throws -> Bool {
- let path = "cache/docs/\(key)/replica"
+ let path = Self.basePath(key)
while self.generation(key) == generation {
+ if try hasBase(key) {
+ guard valid() else { return false }
+ if try append(candidate.state, sequence: candidate.sequence, key: key, generation: generation) { return true }
+ continue
+ }
let before = try store.read(path)
let previous = try before.map { try JSONDecoder().decode(PersistedReplica.self, from: $0) }
let merger = CRDTReplica(guid: candidate.guid)
@@ -27,6 +123,9 @@ import RastrilloNative
let merged = PersistedReplica(format: 1, sequence: max(previous?.sequence ?? 0, candidate.sequence), guid: candidate.guid, savedAt: Date(), state: state,
parked: candidate.parked ?? previous?.parked)
guard valid() else { return false }
+ // Segments without a base are left by an interrupted removal:
+ // they belong to discarded state and must never be read again.
+ if previous == nil { try store.remove(Self.logPath(key)) }
try store.write(JSONEncoder().encode(merged), to: path)
return true
} catch {
@@ -36,4 +135,30 @@ import RastrilloNative
}
throw CancellationError()
}
+ /// Fold the segments into the base once enough of them are waiting.
+ func compactIfNeeded(_ key: String, generation: Int, appended bytes: Int = 0) async throws {
+ guard try bytes >= Self.compactionBytes || segmentNames(key).count >= Self.compactionSegments else { return }
+ try await compact(key, generation: generation)
+ }
+ /// Write base ∪ segments as the new base, then remove exactly the
+ /// segments merged. A crash between the two only leaves segments the base
+ /// already contains. Segments appended meanwhile stay.
+ func compact(_ key: String, generation: Int) async throws {
+ let path = Self.basePath(key)
+ guard let before = try store.read(path), let stored = try load(key), !stored.segments.isEmpty else { return }
+ let merger = CRDTReplica(guid: stored.replica.guid)
+ let state: Data
+ do {
+ try await merger.open(update: stored.replica.state)
+ for segment in stored.segments { try await merger.apply(segment.update) }
+ state = try await merger.persistentState().state
+ await merger.close()
+ } catch { await merger.close(); throw error }
+ guard self.generation(key) == generation else { throw CancellationError() }
+ // Another writer replaced the base meanwhile: leave the segments for it.
+ guard try store.read(path) == before else { return }
+ let merged = PersistedReplica(format: 1, sequence: stored.sequence, guid: stored.replica.guid, savedAt: Date(), state: state)
+ try store.write(JSONEncoder().encode(merged), to: path)
+ for segment in stored.segments { try store.remove(Self.logPath(key) + "/" + segment.name) }
+ }
}
diff --git a/native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift b/native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift
index 3e8d1ed..5045e43 100644
--- a/native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift
+++ b/native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift
@@ -118,6 +118,20 @@ private struct OfflineRandom: RandomNumberGenerator {
mutating func next() -> UInt64 { seed = seed &* 6364136223846793005 &+ 1442695040888963407; return seed }
}
@MainActor final class OfflineDurabilityTests: XCTestCase {
+ /// Every file the replica of `key` is stored in (base and segments).
+ private func replicaFiles(_ store: MemoryBlobStore, _ key: String = "doc") -> [String: Data] {
+ store.contents.filter { $0.key == DocsReplicaCache.basePath(key) || $0.key.hasPrefix(DocsReplicaCache.logPath(key) + "/") }
+ }
+ /// The stored replica's text: its base and every segment.
+ private func storedText(_ store: BlobStore, _ key: String = "doc") async throws -> String? {
+ guard let stored = try DocsReplicaCache(store: store).load(key) else { return nil }
+ let replica = CRDTReplica(guid: stored.replica.guid)
+ try await replica.open(update: stored.replica.state)
+ for segment in stored.segments { try await replica.apply(segment.update) }
+ let text = try await replica.projection().children.map(\.plainText).joined()
+ await replica.close()
+ return text
+ }
private func initial() async throws -> Data {
let seed = CRDTReplica(guid: "offline-property")
_ = try await seed.open(update: Data())
@@ -189,17 +203,19 @@ private struct OfflineRandom: RandomNumberGenerator {
try await lane.reopen(fallback: initial, sequence: 17)
let wroteInitial = try await lane.persist()
XCTAssertTrue(wroteInitial)
- let before = disk.contents[lane.path]
+ let before = replicaFiles(disk)
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)
+ XCTAssertEqual(replicaFiles(disk), 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)
+ let stored = try XCTUnwrap(DocsReplicaCache(store: disk).load("doc"))
+ XCTAssertEqual(stored.sequence, 17)
+ XCTAssertEqual(stored.segments.count, 1, "The edit is appended, not a rewrite of the replica")
+ let text = try await storedText(disk)
+ XCTAssertEqual(text, "A")
}
/// A text typed in a paragraph, as two updates: the second parks without
/// the first. Stands in for a replica or a server holding a parked update.
@@ -424,7 +440,7 @@ private struct OfflineRandom: RandomNumberGenerator {
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")
+ XCTAssertTrue(replicaFiles(disk, "draft-token").isEmpty, "Discard cannot leave stranded local text in the replica")
let entries = await outbox.entries(lane: lane.lane)
XCTAssertTrue(entries.isEmpty)
}
@@ -498,13 +514,13 @@ private struct OfflineRandom: RandomNumberGenerator {
_ = 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)
+ if let stored = try DocsReplicaCache(store: frozen).load("doc") {
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)
+ _ = try await proof.apply(stored.replica.state)
+ for segment in stored.segments { try await proof.apply(segment.update) }
let after = try await proof.projection().children.map(\.plainText)
XCTAssertEqual(prior, after, "I1a: replica contains no stranded local edit")
await proof.close()
@@ -730,17 +746,23 @@ private struct OfflineRandom: RandomNumberGenerator {
_ = 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")
- try await checked.open(update: saved.state)
- let text = try await checked.projection().children.map(\.plainText).joined()
+ let stored = try await storedText(disk)
+ let text = try XCTUnwrap(stored)
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")
+ XCTAssertEqual(try cache.load("doc")?.sequence, 3)
+ // Compaction folds the segments into the base without losing either.
+ try await cache.compact("doc", generation: 0)
+ XCTAssertEqual(try cache.load("doc")?.segments.count, 0)
+ XCTAssertEqual(try cache.load("doc")?.sequence, 3)
+ let compacted = try await storedText(disk)
+ XCTAssertEqual(compacted, text)
+ cache.invalidate("doc"); try cache.remove("doc")
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()
+ do { try cache.append(Data([0, 0]), sequence: 9, key: "doc", generation: 0); XCTFail("A discarded capture must not append") }
+ catch is CancellationError { }
+ XCTAssertTrue(replicaFiles(disk).isEmpty)
+ await a.close(); await b.close()
}
func testEveryDiscardCrashBoundaryLeavesNoStrandedReplica() async throws {
@@ -758,7 +780,7 @@ private struct OfflineRandom: RandomNumberGenerator {
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 {
+ if !replicaFiles(frozen).isEmpty {
XCTAssertEqual(entries.count, 2, "Crash \(crashAfter): no unsent text may survive without its complete lane")
}
}
diff --git a/native/apple/Tests/DocsKitTests/ReplicaSegmentTests.swift b/native/apple/Tests/DocsKitTests/ReplicaSegmentTests.swift
new file mode 100644
index 0000000..baa96e7
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/ReplicaSegmentTests.swift
@@ -0,0 +1,144 @@
+import Foundation
+import RastrilloNative
+import RastrilloTestSupport
+import XCTest
+@testable import DocsKit
+
+/// Audit finding 8: the replica is stored as a base plus appended segments,
+/// folded into the base now and then, instead of being rewritten whole after
+/// every send and every remote change. Each write boundary must keep I1 (no
+/// lost or duplicated text, no local edit without its outbox entry).
+@MainActor final class ReplicaSegmentTests: XCTestCase {
+ private let guid = "segments"
+ private func seed() async throws -> Data {
+ let replica = CRDTReplica(guid: guid)
+ try await replica.open(update: Data())
+ let update = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")])
+ await replica.close(); return update
+ }
+ private func type(_ replica: CRDTReplica, _ text: String) async throws -> Data {
+ let at = try await replica.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)])
+ }
+ private func reopenText(_ store: BlobStore, fallback: Data = Data()) async throws -> String {
+ let replica = CRDTReplica(guid: guid)
+ let lane = DocsPersistence(store: store, outbox: Outbox(store: store, account: "a"), key: "doc", replica: replica)
+ try await lane.reopen(fallback: fallback, sequence: 0)
+ let text = try await replica.projection().children.map(\.plainText).joined()
+ await replica.close()
+ return text
+ }
+ private func segments(_ store: MemoryBlobStore) -> Int {
+ store.contents.keys.filter { $0.hasPrefix(DocsReplicaCache.logPath("doc") + "/") }.count
+ }
+
+ func testPersistAppendsAndCompactsWithoutLosingAnything() async throws {
+ let disk = MemoryBlobStore(), replica = CRDTReplica(guid: guid)
+ let lane = DocsPersistence(store: disk, outbox: Outbox(store: disk, account: "a"), key: "doc", replica: replica)
+ try await lane.reopen(fallback: try await seed(), sequence: 4)
+ let first = try await lane.persist()
+ XCTAssertTrue(first, "the first persist stores a base")
+ let base = disk.contents[DocsReplicaCache.basePath("doc")]
+ var expected = ""
+ for index in 0..<(DocsReplicaCache.compactionSegments + 5) {
+ let text = "\(index),"
+ try await lane.enqueue(try await type(replica, text)); expected += text
+ await replica.setSequence(Int64(5 + index))
+ let wrote = try await lane.persist()
+ XCTAssertTrue(wrote)
+ if index < DocsReplicaCache.compactionSegments - 1 {
+ XCTAssertEqual(disk.contents[DocsReplicaCache.basePath("doc")], base, "appending never rewrites the base")
+ XCTAssertEqual(segments(disk), index + 1)
+ }
+ }
+ XCTAssertLessThan(segments(disk), DocsReplicaCache.compactionSegments, "segments were folded into the base")
+ XCTAssertNotEqual(disk.contents[DocsReplicaCache.basePath("doc")], base)
+ XCTAssertEqual(try DocsReplicaCache(store: disk).load("doc")?.sequence, Int64(4 + DocsReplicaCache.compactionSegments + 5))
+ let reopened = try await reopenText(disk)
+ XCTAssertEqual(reopened, expected)
+ // Nothing new: nothing written.
+ let files = disk.contents
+ let again = try await lane.persist()
+ XCTAssertTrue(again)
+ XCTAssertEqual(disk.contents, files)
+ await replica.close()
+ }
+
+ func testEveryAppendAndCompactionCrashBoundaryReopensWithEverything() async throws {
+ let base = MemoryBlobStore(), source = CRDTReplica(guid: guid)
+ let setup = DocsPersistence(store: base, outbox: Outbox(store: base, account: "a"), key: "doc", replica: source)
+ try await setup.reopen(fallback: try await seed(), sequence: 0)
+ _ = try await setup.persist()
+ var expected = ""
+ for text in ["A", "B", "C"] {
+ try await setup.enqueue(try await type(source, text)); expected += text
+ _ = try await setup.persist()
+ }
+ XCTAssertEqual(segments(base), 3)
+ // A remote update arrives and is appended; crash at every operation of
+ // that append and of the compaction after it.
+ let peer = CRDTReplica(guid: guid)
+ try await peer.open(update: try await source.persistentState().state)
+ let remote = try await type(peer, "R")
+ for crashAfter in 0...24 {
+ let disk = FaultingBlobStore(MemoryBlobStore(base.contents))
+ let replica = CRDTReplica(guid: guid)
+ let lane = DocsPersistence(store: disk, outbox: Outbox(store: disk, account: "a"), key: "doc", replica: replica)
+ try await lane.reopen(fallback: Data(), sequence: 0)
+ try await replica.apply(remote)
+ await replica.setSequence(9)
+ disk.crash(after: crashAfter)
+ do {
+ _ = try await lane.persist()
+ try await DocsReplicaCache(store: disk).compact("doc", generation: 0)
+ } catch is SimulatedCrash { }
+ let frozen = disk.committed
+ let text = try await reopenText(frozen)
+ let stored = try XCTUnwrap(DocsReplicaCache(store: frozen).load("doc"))
+ if stored.sequence == 9 { XCTAssertEqual(text, expected + "R", "crash \(crashAfter): the sequence moved with its update") }
+ else { XCTAssertEqual(text, expected, "crash \(crashAfter)"); XCTAssertEqual(stored.sequence, 0) }
+ await replica.close()
+ }
+ await source.close(); await peer.close()
+ }
+
+ func testSegmentsWithoutABaseAreDiscardedStateAndNeverRead() async throws {
+ let disk = MemoryBlobStore(), seed = try await seed()
+ // An interrupted discard left a segment holding discarded text.
+ let ghost = CRDTReplica(guid: guid)
+ try await ghost.open(update: seed)
+ let discarded = try await type(ghost, "discarded")
+ let segment = DocsReplicaCache.Segment(name: "0000000000000001-00000001-" + UUID().uuidString, sequence: 99, update: discarded)
+ try disk.write(segment.encoded, to: DocsReplicaCache.logPath("doc") + "/" + segment.name)
+ let replica = CRDTReplica(guid: guid)
+ let lane = DocsPersistence(store: disk, outbox: Outbox(store: disk, account: "a"), key: "doc", replica: replica)
+ try await lane.reopen(fallback: seed, sequence: 1)
+ let shown = try await replica.projection().children.map(\.plainText).joined()
+ XCTAssertEqual(shown, "")
+ _ = try await lane.persist()
+ XCTAssertEqual(segments(disk), 0, "writing a new base removes the orphaned segments")
+ let text = try await reopenText(disk)
+ XCTAssertEqual(text, "")
+ XCTAssertEqual(try DocsReplicaCache(store: disk).load("doc")?.sequence, 1)
+ await ghost.close(); await replica.close()
+ }
+
+ func testAnUnreadableSegmentDropsTheWholeReplicaNotPartOfIt() async throws {
+ let disk = MemoryBlobStore(), replica = CRDTReplica(guid: guid), server = try await seed()
+ let lane = DocsPersistence(store: disk, outbox: Outbox(store: disk, account: "a"), key: "doc", replica: replica)
+ try await lane.reopen(fallback: server, sequence: 0)
+ _ = try await lane.persist()
+ try await lane.enqueue(try await type(replica, "kept in the outbox"))
+ _ = try await lane.persist()
+ let name = try XCTUnwrap(disk.contents.keys.first { $0.hasPrefix(DocsReplicaCache.logPath("doc") + "/") })
+ try disk.write(Data("not a segment".utf8), to: name)
+ do { _ = try DocsReplicaCache(store: disk).load("doc"); XCTFail("An unreadable segment must not be skipped") }
+ catch BlobStoreError.corrupt { }
+ XCTAssertNil(disk.contents[DocsReplicaCache.basePath("doc")])
+ XCTAssertEqual(segments(disk), 0)
+ // The outbox still holds the edit; the server holds the rest.
+ let text = try await reopenText(disk, fallback: server)
+ XCTAssertEqual(text, "kept in the outbox")
+ await replica.close()
+ }
+}