oficina / docs Public

Docs native: bound the replica's record of unstored changes

If nothing can be stored for a long time (a locked device) the updates
awaiting persistence would grow without bound. Past 4 MB they are
dropped and the next persist stores the whole state instead; an epoch
keeps a capture taken before the drop from marking later updates
stored. Test: ReplicaSegmentTests.testChangesTooLargeToKeepInMemory...
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev e8f52cee49a652dfa8b6f8701f060ef84d66cc22 parent 61fbce3
3 files changed, +56 −12
  • native/apple/Sources/DocsKit/CRDTReplica.swift +32 −9
  • native/apple/Sources/DocsKit/DocsPersistence.swift +3 −3
  • native/apple/Tests/DocsKitTests/ReplicaSegmentTests.swift +21 −0
diff --git a/native/apple/Sources/DocsKit/CRDTReplica.swift b/native/apple/Sources/DocsKit/CRDTReplica.swift
index 734a4d9..a2bce5c 100644
--- a/native/apple/Sources/DocsKit/CRDTReplica.swift
+++ b/native/apple/Sources/DocsKit/CRDTReplica.swift
@@ -58,9 +58,22 @@ actor CRDTReplica {
private var acceptedParking = ""
/// Updates applied to the authority since the replica was last persisted.
private var unpersisted: [Data] = []
+ private var unpersistedBytes = 0
+ /// Moves when `unpersisted` stops being a record of every change (it
+ /// grew past `unpersistedLimit` while nothing could be stored, or the
+ /// replica reopened): only a whole state can be stored after that.
+ private var unpersistedEpoch: UInt64 = 0
+ private var needsWhole = false
+ let unpersistedLimit: Int
+ private func recordUnpersisted(_ update: Data) {
+ unpersisted.append(update); unpersistedBytes += update.count
+ if unpersistedBytes > unpersistedLimit {
+ unpersisted.removeAll(); unpersistedBytes = 0; unpersistedEpoch &+= 1; needsWhole = true
+ }
+ }
private let guid: String
enum Failure: Error { case unavailable, rejected, invalidProjection, generationLimit }
- init(guid: String) { self.guid = guid }
+ init(guid: String, unpersistedLimit: Int = 4 * 1024 * 1024) { self.guid = guid; self.unpersistedLimit = unpersistedLimit }
struct PersistentState: Sendable {
let state: Data
let sequence: Int64
@@ -84,28 +97,37 @@ actor CRDTReplica {
let guid: String
/// The parking accepted as the server's own when this was taken.
let parked: String
+ let epoch: UInt64
}
/// 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 limit < 0 || unpersistedBytes > limit || needsWhole {
if !lastGood.tail.isEmpty { try compact(authority) }
whole = lastGood.base
}
- return PersistentChanges(updates: unpersisted, whole: whole, sequence: durableSequence, commandsApplied: commandsApplied, guid: guid, parked: acceptedParking)
+ return PersistentChanges(updates: unpersisted, whole: whole, sequence: durableSequence, commandsApplied: commandsApplied, guid: guid, parked: acceptedParking, epoch: unpersistedEpoch)
}
/// The first `count` updates of the last `persistentChanges` are stored.
- func persisted(_ count: Int) { unpersisted.removeFirst(min(count, unpersisted.count)) }
+ /// `changes` (or, with `count`, that many first updates) are stored.
+ func persisted(_ changes: PersistentChanges) {
+ guard changes.epoch == unpersistedEpoch else { return }
+ let count = min(changes.updates.count, unpersisted.count)
+ unpersistedBytes -= unpersisted.prefix(count).reduce(0) { $0 + $1.count }
+ unpersisted.removeFirst(count)
+ if changes.whole != nil { needsWhole = false }
+ }
+ /// Everything applied so far is already stored elsewhere (on reopen).
+ func persistedAll() { unpersisted.removeAll(); unpersistedBytes = 0; unpersistedEpoch &+= 1; needsWhole = false }
func currentSequence() -> Int64 { durableSequence }
func setSequence(_ sequence: Int64) { durableSequence = max(durableSequence, sequence) }
func close() {
opened = false; authority = nil; merger = nil; presented = nil
sources.removeAll(); sourceStates.removeAll(); sourceVersions.removeAll()
- lastGood = State(); unpersisted.removeAll()
+ lastGood = State(); unpersisted.removeAll(); unpersistedBytes = 0; unpersistedEpoch &+= 1
}
private func fresh(update: Data) throws -> (UInt64, Sandbox) {
let sandbox = try Sandbox()
@@ -122,7 +144,8 @@ actor CRDTReplica {
}
func open(update: Data) throws {
sources.removeAll(); sourceStates.removeAll(); sourceVersions.removeAll()
- commandsApplied = 0; durableSequence = 0; unpersisted.removeAll(); presented = nil; acceptedParking = ""
+ commandsApplied = 0; durableSequence = 0; presented = nil; acceptedParking = ""
+ unpersisted.removeAll(); unpersistedBytes = 0; unpersistedEpoch &+= 1; needsWhole = false
authority = try fresh(update: update).1
opened = true
lastGood = State(base: try authority!.invoke(["op": .string("snapshot")]))
@@ -284,7 +307,7 @@ actor CRDTReplica {
let authority = try currentAuthority()
do { _ = try authority.invoke(Data([255]) + update) }
catch { recover(); throw error }
- lastGood.append(update); version &+= 1; unpersisted.append(update)
+ lastGood.append(update); version &+= 1; recordUnpersisted(update)
compactIfWanted(authority)
}
/// Reads that change nothing; any other command is an edit.
@@ -312,7 +335,7 @@ actor CRDTReplica {
let update = try writer.invoke(command)
if writer !== authority { authorityTouched = true; _ = try authority.invoke(Data([254]) + update) }
let wasInSync = generation.map { sourceVersions[$0] == version } ?? false
- lastGood.append(update); version &+= 1; unpersisted.append(update)
+ lastGood.append(update); version &+= 1; recordUnpersisted(update)
if writer !== authority, let generation {
if wasInSync { sourceStates[generation] = lastGood; sourceVersions[generation] = version }
else {
diff --git a/native/apple/Sources/DocsKit/DocsPersistence.swift b/native/apple/Sources/DocsKit/DocsPersistence.swift
index cfc87b4..ae6ed7e 100644
--- a/native/apple/Sources/DocsKit/DocsPersistence.swift
+++ b/native/apple/Sources/DocsKit/DocsPersistence.swift
@@ -69,7 +69,7 @@ struct PersistedReplica: Codable, Sendable {
hasBase = saved != nil
storedSequence = saved?.sequence ?? 0
// Stored segments and replayed entries are already durable.
- if saved != nil { await replica.persisted(Int.max) }
+ if saved != nil { await replica.persistedAll() }
}
/// Entries the server has taken are acknowledged and never sent again.
func forget(_ entries: Set<UUID>) { held.subtract(entries) }
@@ -87,7 +87,7 @@ struct PersistedReplica: Codable, Sendable {
// A writer running between command and enqueue must defer its capture.
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 changes.whole == nil, 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 }
@@ -102,7 +102,7 @@ struct PersistedReplica: Codable, Sendable {
}
hasBase = true
storedSequence = max(storedSequence, changes.sequence)
- await replica.persisted(changes.updates.count)
+ await replica.persisted(changes)
// 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 })
diff --git a/native/apple/Tests/DocsKitTests/ReplicaSegmentTests.swift b/native/apple/Tests/DocsKitTests/ReplicaSegmentTests.swift
index baa96e7..49ec823 100644
--- a/native/apple/Tests/DocsKitTests/ReplicaSegmentTests.swift
+++ b/native/apple/Tests/DocsKitTests/ReplicaSegmentTests.swift
@@ -141,4 +141,25 @@ import XCTest
XCTAssertEqual(text, "kept in the outbox")
await replica.close()
}
+
+ func testChangesTooLargeToKeepInMemoryAreStoredAsAWholeState() async throws {
+ let disk = MemoryBlobStore(), replica = CRDTReplica(guid: guid, unpersistedLimit: 64 * 1024)
+ let lane = DocsPersistence(store: disk, outbox: Outbox(store: disk, account: "a"), key: "doc", replica: replica)
+ try await lane.reopen(fallback: try await seed(), sequence: 0)
+ _ = try await lane.persist()
+ // Remote changes pile up while the store cannot be written.
+ let peer = CRDTReplica(guid: guid)
+ try await peer.open(update: try await replica.persistentState().state)
+ let chunk = String(repeating: "r", count: 8 * 1024)
+ for _ in 0..<10 { try await replica.apply(try await type(peer, chunk)) }
+ await replica.setSequence(8)
+ let changes = try await replica.persistentChanges(wholeAbove: DocsPersistence.appendLimit)
+ XCTAssertLessThan(changes.updates.reduce(0) { $0 + $1.count }, 64 * 1024, "memory stays bounded")
+ XCTAssertNotNil(changes.whole, "the dropped changes are stored as the whole state")
+ _ = try await lane.persist()
+ let text = try await reopenText(disk)
+ XCTAssertEqual(text.count, chunk.count * 10)
+ XCTAssertEqual(try DocsReplicaCache(store: disk).load("doc")?.sequence, 8)
+ await replica.close(); await peer.close()
+ }
}