oficina / docs Public

Docs native: replica bookkeeping fixes from review (findings 4-7)

Fable's review on #145:
- 4: a whole state stored as a segment (after the 4 MB overflow) now
  counts toward compaction, so whole-state segments do not pile up.
- 5: `persisted` marks updates by position in the epoch, not "the
  first n", so overlapping or out-of-order captures can never mark an
  update they did not store. Test: two overlapping captures, both
  orders, and a stale capture after both.
- 6: `command` refuses `apply` as it does projections: an import there
  would bypass lastGood, the sources' states and the unstored record.
- 7: a sandbox is built from a state's base, then its tail in envelopes
  of its own (at most 4 MB each), so a base near the bridge's 8 MiB
  limit still imports with a tail behind it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 4c8881b4832504bf038e729ca66f3efa38b97178 parent 20448f6
3 files changed, +82 −22
  • native/apple/Sources/DocsKit/CRDTReplica.swift +43 −20
  • native/apple/Sources/DocsKit/DocsPersistence.swift +3 −1
  • native/apple/Tests/DocsKitTests/CRDTIncrementalTests.swift +36 −1
diff --git a/native/apple/Sources/DocsKit/CRDTReplica.swift b/native/apple/Sources/DocsKit/CRDTReplica.swift
index a2bce5c..386e77a 100644
--- a/native/apple/Sources/DocsKit/CRDTReplica.swift
+++ b/native/apple/Sources/DocsKit/CRDTReplica.swift
@@ -22,13 +22,12 @@ actor CRDTReplica {
}
/// A replica's state as bytes without encoding it: a base update and the
/// updates applied since, in order. Their concatenation is one input for
- /// the 255 envelope, which applies each update in turn.
+ /// the 255 envelope, which applies each update in turn (see `fresh(state:)`).
struct State: Sendable {
private(set) var base = Data()
private(set) var tail: [Data] = []
private(set) var tailBytes = 0
init(base: Data = Data()) { self.base = base }
- var data: Data { tail.isEmpty ? base : tail.reduce(into: base) { $0.append($1) } }
mutating func append(_ update: Data) { tail.append(update); tailBytes += update.count }
/// Re-encode as one snapshot once the tail costs more to replay or
/// keep than a snapshot does to take.
@@ -59,6 +58,9 @@ actor CRDTReplica {
/// Updates applied to the authority since the replica was last persisted.
private var unpersisted: [Data] = []
private var unpersistedBytes = 0
+ /// The position of `unpersisted[0]` among every update recorded in this
+ /// epoch, so a capture marks exactly what it covered as stored.
+ private var unpersistedStart = 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.
@@ -68,9 +70,12 @@ actor CRDTReplica {
private func recordUnpersisted(_ update: Data) {
unpersisted.append(update); unpersistedBytes += update.count
if unpersistedBytes > unpersistedLimit {
- unpersisted.removeAll(); unpersistedBytes = 0; unpersistedEpoch &+= 1; needsWhole = true
+ resetUnpersisted(); needsWhole = true
}
}
+ private func resetUnpersisted() {
+ unpersisted.removeAll(); unpersistedBytes = 0; unpersistedStart = 0; unpersistedEpoch &+= 1
+ }
private let guid: String
enum Failure: Error { case unavailable, rejected, invalidProjection, generationLimit }
init(guid: String, unpersistedLimit: Int = 4 * 1024 * 1024) { self.guid = guid; self.unpersistedLimit = unpersistedLimit }
@@ -98,6 +103,8 @@ actor CRDTReplica {
/// The parking accepted as the server's own when this was taken.
let parked: String
let epoch: UInt64
+ /// The position after the last update captured.
+ let end: Int
}
/// What changed since the replica was last persisted, so a writer can
/// append it instead of rewriting the whole state; and the whole state
@@ -109,43 +116,57 @@ actor CRDTReplica {
if !lastGood.tail.isEmpty { try compact(authority) }
whole = lastGood.base
}
- return PersistentChanges(updates: unpersisted, whole: whole, sequence: durableSequence, commandsApplied: commandsApplied, guid: guid, parked: acceptedParking, epoch: unpersistedEpoch)
+ return PersistentChanges(updates: unpersisted, whole: whole, sequence: durableSequence, commandsApplied: commandsApplied, guid: guid,
+ parked: acceptedParking, epoch: unpersistedEpoch, end: unpersistedStart + unpersisted.count)
}
- /// The first `count` updates of the last `persistentChanges` are stored.
- /// `changes` (or, with `count`, that many first updates) are stored.
+ /// Everything `changes` captured is stored. By position, not count: a
+ /// capture that overlaps one already marked (or arrives after a later
+ /// one) marks nothing twice and never an update it did not cover.
func persisted(_ changes: PersistentChanges) {
guard changes.epoch == unpersistedEpoch else { return }
- let count = min(changes.updates.count, unpersisted.count)
+ let count = min(max(0, changes.end - unpersistedStart), unpersisted.count)
unpersistedBytes -= unpersisted.prefix(count).reduce(0) { $0 + $1.count }
- unpersisted.removeFirst(count)
+ unpersisted.removeFirst(count); unpersistedStart += 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 persistedAll() { resetUnpersisted(); 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(); unpersistedBytes = 0; unpersistedEpoch &+= 1
+ lastGood = State(); resetUnpersisted()
+ }
+ /// A sandbox from a state, imported as its base and then its tail in
+ /// envelopes of their own, so a base near the bridge's 8 MiB limit still
+ /// imports with a tail behind it.
+ private func fresh(state: State) throws -> (UInt64, Sandbox) {
+ try fresh(update: state.base, then: state.tail)
}
- private func fresh(update: Data) throws -> (UInt64, Sandbox) {
+ private func fresh(update: Data, then tail: [Data] = []) throws -> (UInt64, Sandbox) {
let sandbox = try Sandbox()
var client = UInt64(UInt32.random(in: 1...UInt32.max))
while reserved.contains(client) { client = UInt64(UInt32.random(in: 1...UInt32.max)) }
reserved.insert(client)
_ = try sandbox.invoke(["op": .string("open"), "guid": .string(guid), "client": .number(Double(client))])
if !update.isEmpty { _ = try sandbox.invoke(Data([255]) + update) }
+ var chunk = Data([255])
+ for part in tail {
+ if chunk.count > 1, chunk.count + part.count > 4 * 1024 * 1024 { _ = try sandbox.invoke(chunk); chunk = Data([255]) }
+ chunk.append(part)
+ }
+ if chunk.count > 1 { _ = try sandbox.invoke(chunk) }
let used = try JSONDecoder().decode([UInt64].self, from: sandbox.invoke(["op": .string("clients")]))
reserved.formUnion(used)
// Imported state may already contain the proposed ID. Never write it.
- if used.contains(client) { return try fresh(update: update) }
+ if used.contains(client) { return try fresh(update: update, then: tail) }
return (client, sandbox)
}
func open(update: Data) throws {
sources.removeAll(); sourceStates.removeAll(); sourceVersions.removeAll()
commandsApplied = 0; durableSequence = 0; presented = nil; acceptedParking = ""
- unpersisted.removeAll(); unpersistedBytes = 0; unpersistedEpoch &+= 1; needsWhole = false
+ resetUnpersisted(); needsWhole = false
authority = try fresh(update: update).1
opened = true
lastGood = State(base: try authority!.invoke(["op": .string("snapshot")]))
@@ -153,7 +174,7 @@ actor CRDTReplica {
}
private func currentAuthority() throws -> Sandbox {
guard opened else { throw Failure.unavailable }
- if authority == nil { presented = nil; authority = try fresh(update: lastGood.data).1 }
+ if authority == nil { presented = nil; authority = try fresh(state: lastGood).1 }
guard let authority else { throw Failure.unavailable }
return authority
}
@@ -269,7 +290,7 @@ actor CRDTReplica {
let start = try endpoint(selection.location), end = try endpoint(NSMaxRange(selection))
resolved = NSRange(location: min(start, end), length: abs(end - start))
} catch {
- if let state = sourceStates[generation] { sources[generation] = try? fresh(update: state.data).1 }
+ if let state = sourceStates[generation] { sources[generation] = try? fresh(state: state).1 }
else { sources.removeValue(forKey: generation) }
recover()
throw error
@@ -277,7 +298,7 @@ actor CRDTReplica {
}
if reuse { return (generation, try authorityProjection(authority), resolved) }
if lastGood.tail.count > 8 { try compact(authority) }
- let (_, source) = try fresh(update: lastGood.data)
+ let (_, source) = try fresh(state: lastGood)
let generation = nextGeneration; nextGeneration += 1
sources[generation] = source; sourceStates[generation] = lastGood; sourceVersions[generation] = version
return (generation, try authorityProjection(authority), resolved)
@@ -291,7 +312,7 @@ actor CRDTReplica {
// No invalid interpreter is reused. A new authority ID cannot reuse
// clocks from a partially executed command. UI reports undo loss.
presented = nil
- authority = try? fresh(update: lastGood.data).1
+ authority = try? fresh(state: lastGood).1
}
func mergeUpdates(_ updates: [Data]) throws -> Data {
guard let first = updates.first else { throw Failure.rejected }
@@ -319,13 +340,15 @@ actor CRDTReplica {
let generation: UInt64? = if case .number(let value) = command["generation"] { UInt64(exactly: value) } else { nil }
let op: String? = if case .string(let value) = command["op"] { value } else { nil }
// Projections go through `projection()` only: it owns the delta base.
- if op == "project" || op == "project_delta" || op == "open" { throw Failure.rejected }
+ // So do imports: an `apply` here would bypass lastGood, the sources'
+ // states and the record of unstored changes.
+ if op == "project" || op == "project_delta" || op == "open" || op == "apply" { throw Failure.rejected }
let isHistory = op == "undo" || op == "redo"
let writer: Sandbox
if isHistory || generation == nil { writer = authority }
else {
let generation = generation!
- if sources[generation] == nil, let state = sourceStates[generation] { sources[generation] = try fresh(update: state.data).1 }
+ if sources[generation] == nil, let state = sourceStates[generation] { sources[generation] = try fresh(state: state).1 }
guard let source = sources[generation] else { throw Failure.unavailable }
writer = source
}
@@ -350,7 +373,7 @@ actor CRDTReplica {
compactIfWanted(authority)
return update
} catch {
- if writer !== authority, let generation { sources[generation] = try? fresh(update: (sourceStates[generation] ?? lastGood).data).1 }
+ if writer !== authority, let generation { sources[generation] = try? fresh(state: sourceStates[generation] ?? lastGood).1 }
if authorityTouched { recover() }
throw error
}
diff --git a/native/apple/Sources/DocsKit/DocsPersistence.swift b/native/apple/Sources/DocsKit/DocsPersistence.swift
index ae6ed7e..4fd2428 100644
--- a/native/apple/Sources/DocsKit/DocsPersistence.swift
+++ b/native/apple/Sources/DocsKit/DocsPersistence.swift
@@ -105,7 +105,9 @@ struct PersistedReplica: Codable, Sendable {
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 })
+ // A whole state stored as a segment counts too, so it is folded in.
+ let appended = changes.updates.reduce(changes.whole?.count ?? 0) { $0 + $1.count }
+ try? await cache.compactIfNeeded(key, generation: generation, appended: appended)
return true
}
func compact() async throws {
diff --git a/native/apple/Tests/DocsKitTests/CRDTIncrementalTests.swift b/native/apple/Tests/DocsKitTests/CRDTIncrementalTests.swift
index 047c256..73b0a5a 100644
--- a/native/apple/Tests/DocsKitTests/CRDTIncrementalTests.swift
+++ b/native/apple/Tests/DocsKitTests/CRDTIncrementalTests.swift
@@ -92,11 +92,46 @@ import XCTest
func testProjectionsCannotBeRequestedAsCommands() async throws {
let replica = CRDTReplica(guid: "incremental")
try await replica.open(update: Data())
- for op in ["project", "project_delta", "open"] {
+ for op in ["project", "project_delta", "open", "apply"] {
do { _ = try await replica.command(["op": .string(op)]); XCTFail(op) } catch { }
}
let snapshot = try await replica.command(["op": .string("snapshot")])
XCTAssertFalse(snapshot.isEmpty)
await replica.close()
}
+
+ /// Review finding 5: a capture marks exactly the updates it covered, even
+ /// when two captures overlap or are marked out of order.
+ func testOverlappingCapturesNeverMarkAnUncapturedUpdate() async throws {
+ let replica = CRDTReplica(guid: "incremental")
+ try await replica.open(update: Data())
+ _ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")])
+ func type(_ text: String) async throws {
+ _ = try await replica.command(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string(text)])
+ }
+ try await type("a"); try await type("b")
+ let first = try await replica.persistentChanges(wholeAbove: .max)
+ try await type("c")
+ let second = try await replica.persistentChanges(wholeAbove: .max)
+ try await type("d")
+ XCTAssertEqual(first.updates.count, 3); XCTAssertEqual(second.updates.count, 4)
+ // The later capture is stored first; the earlier one then marks nothing.
+ await replica.persisted(second)
+ await replica.persisted(first)
+ var left = try await replica.persistentChanges(wholeAbove: .max)
+ XCTAssertEqual(left.updates.count, 1, "only d is unstored")
+ // In order: the first marks its three, the second only its fourth.
+ try await type("e")
+ left = try await replica.persistentChanges(wholeAbove: .max)
+ try await type("f")
+ let wider = try await replica.persistentChanges(wholeAbove: .max)
+ await replica.persisted(left); await replica.persisted(wider)
+ let rest = try await replica.persistentChanges(wholeAbove: .max)
+ XCTAssertTrue(rest.updates.isEmpty)
+ try await type("g")
+ await replica.persisted(left)
+ let last = try await replica.persistentChanges(wholeAbove: .max)
+ XCTAssertEqual(last.updates.count, 1, "a stale capture cannot mark g")
+ await replica.close()
+ }
}