oficina / docs Public

Docs native: no projection or snapshot per command; presentations patch only changed blocks

Audit finding 2 (Swift half). CRDTReplica.command took a source
snapshot, applied the update to the authority, projected the whole
document (which DocsModel threw away) and snapshotted the authority,
after every keystroke; apply projected and snapshotted after every
remote change; every presentation projected the whole document.

- command returns the update only; apply returns nothing. Neither
  projects nor snapshots.
- lastGood is now "a base update plus the updates applied since"
  (CRDTReplica.State). Recovery and new sources replay it; it is
  re-encoded as one snapshot only when its tail is long or large, when
  a new source is opened from a long tail, or for persistentState.
- Source reuse used to need byte-identical snapshots of source and
  authority. It now tracks the authority version each source is known
  to equal (made from the authority's state then, every change since
  applied to both), and each source's own state for recreation.
- The authority's last projection is kept; presentations ask for
  project_delta and patch it (CRDTProjectionDelta), re-projecting only
  touched blocks. Any mismatch, decode failure or replaced authority
  falls back to a whole projection. Projections can no longer be asked
  for through command (they own the delta base); a failed projection
  recovers the authority instead of leaving it poisoned.
- DocsModel.refresh publishes before persisting, and open reads the
  sequence without a snapshot.

Audit probes (release, production fuel), before -> after:
  command(display_edit): p1 5.35 -> 0.76 ms, p10 43.4 -> 1.09,
    p10h 47.8 -> 1.25, p20 88.4 -> 1.55
  presentation (reused source): p1 7.11 -> 2.26, p10 61.1 -> 3.28,
    p10h 63.6 -> 3.57, p20 120.8 -> 4.05
  remote apply: p10 18.9 -> 0.22, p20 37.2 -> 0.23
  presentation after a remote change (fresh source): p10 72.8 -> 9.1,
    p20 143.4 -> 14.7
  new host: 6.9 -> 0.04 ms (module cache)
swift test: 133 tests, 0 failures.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev d0ec3d79c350b025b162cec59d17d0e9e14eb00d parent dfa43a6
12 files changed, +196 −67
  • native/apple/Sources/DocsKit/CRDTProjection.swift +40 −0
  • native/apple/Sources/DocsKit/CRDTReplica.swift +128 −45
  • native/apple/Sources/DocsKit/DocsModel.swift +7 −5
  • native/apple/Sources/DocsKit/DocsOfflineAccount.swift +1 −1
  • native/apple/Sources/DocsKit/DocsPersistence.swift +1 −1
  • native/apple/Sources/DocsKit/DocsReplicaCache.swift +2 −2
  • native/apple/Tests/DocsKitTests/CRDTClipboardTests.swift +2 −2
  • native/apple/Tests/DocsKitTests/CRDTSourceReuseTests.swift +4 −3
  • native/apple/Tests/DocsKitTests/DocumentSyncIntegrationTests.swift +3 −2
  • native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift +5 −4
  • native/apple/Tests/DocsKitTests/OfflineKillTests.swift +2 −1
  • native/apple/Tests/DocsKitTests/RealtimeSyncTests.swift +1 −1
diff --git a/native/apple/Sources/DocsKit/CRDTProjection.swift b/native/apple/Sources/DocsKit/CRDTProjection.swift
index 26ce3c5..d33c4b9 100644
--- a/native/apple/Sources/DocsKit/CRDTProjection.swift
+++ b/native/apple/Sources/DocsKit/CRDTProjection.swift
@@ -5,6 +5,46 @@ struct CRDTProjection: Decodable, Sendable {
var canUndo: Bool
var canRedo: Bool
}
+/// The engine's `project_delta`: edits to the previous projection's list of
+/// top-level blocks. Only blocks a transaction touched arrive re-projected;
+/// every other block is the previous value, unchanged.
+struct CRDTProjectionDelta: Decodable, Sendable {
+ enum Operation: Decodable, Sendable {
+ case keep(Int), remove(Int), insert([CRDTNode])
+ private enum Key: String, CodingKey { case keep, remove, insert }
+ init(from decoder: any Decoder) throws {
+ let container = try decoder.container(keyedBy: Key.self)
+ if let count = try container.decodeIfPresent(Int.self, forKey: .keep) { self = .keep(count) }
+ else if let count = try container.decodeIfPresent(Int.self, forKey: .remove) { self = .remove(count) }
+ else { self = .insert(try container.decode([CRDTNode].self, forKey: .insert)) }
+ }
+ }
+ let base: Int
+ let count: Int
+ let ops: [Operation]
+ let canUndo: Bool
+ let canRedo: Bool
+ /// nil unless it applies exactly to `previous`.
+ func applied(to previous: CRDTProjection) -> CRDTProjection? {
+ guard previous.children.count == base else { return nil }
+ var children: [CRDTNode] = []
+ children.reserveCapacity(count)
+ var at = 0
+ for operation in ops {
+ switch operation {
+ case .keep(let n):
+ guard n >= 0, at + n <= base else { return nil }
+ children.append(contentsOf: previous.children[at..<(at + n)]); at += n
+ case .remove(let n):
+ guard n >= 0, at + n <= base else { return nil }
+ at += n
+ case .insert(let nodes): children.append(contentsOf: nodes)
+ }
+ }
+ guard at == base, children.count == count else { return nil }
+ return CRDTProjection(children: children, canUndo: canUndo, canRedo: canRedo)
+ }
+}
struct CRDTNode: Decodable, Identifiable, Sendable {
let id: String
let type: String
diff --git a/native/apple/Sources/DocsKit/CRDTReplica.swift b/native/apple/Sources/DocsKit/CRDTReplica.swift
index b7b62fd..3a76f35 100644
--- a/native/apple/Sources/DocsKit/CRDTReplica.swift
+++ b/native/apple/Sources/DocsKit/CRDTReplica.swift
@@ -19,23 +19,45 @@ actor CRDTReplica {
output.count = Int(count); return output
}
func invoke(_ command: [String: JSONValue]) throws -> Data { try invoke(JSONEncoder().encode(command)) }
- func projection() throws -> CRDTProjection {
- try JSONDecoder().decode(CRDTProjection.self, from: invoke(["op": .string("project")]))
- }
+ }
+ /// 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.
+ 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.
+ var wantsCompaction: Bool { tail.count > 128 || tailBytes > 256 * 1024 || (tailBytes > 16 * 1024 && tailBytes > base.count / 2) }
}
private var authority: Sandbox?
private var merger: Sandbox?
private var opened = false
+ /// The authority's last projection, which is also the base its deltas
+ /// are reported against. nil whenever the authority is replaced.
+ private var presented: CRDTProjection?
private var sources: [UInt64: Sandbox] = [:]
- private var sourceSnapshots: [UInt64: Data] = [:]
+ /// Each source's state, to recreate it after it is retired or traps.
+ private var sourceStates: [UInt64: State] = [:]
+ /// The authority version each source is known to equal: it was made
+ /// from the authority's state then, and every change since went to both.
+ private var sourceVersions: [UInt64: UInt64] = [:]
private var nextGeneration: UInt64 = 1
// IDs remain reserved for this session even when a source is retired or traps.
private var reserved: Set<UInt64> = []
- private var lastGood = Data()
+ private var lastGood = State()
+ /// Moves on every change to the authority's state.
+ private var version: UInt64 = 0
private var commandsApplied = 0
private var durableSequence: Int64 = 0
/// Parking this replica has accepted as the server's own (#147).
private var acceptedParking = ""
+ /// Updates applied to the authority since the replica was last persisted.
+ private var unpersisted: [Data] = []
private let guid: String
enum Failure: Error { case unavailable, rejected, invalidProjection, generationLimit }
init(guid: String) { self.guid = guid }
@@ -46,12 +68,34 @@ actor CRDTReplica {
let guid: String
let parked: String
}
+ /// The whole state as one snapshot.
func persistentState() throws -> PersistentState {
+ let authority = try currentAuthority()
+ if !lastGood.tail.isEmpty { try compact(authority) }
+ return PersistentState(state: lastGood.base, sequence: durableSequence, commandsApplied: commandsApplied, guid: guid, parked: acceptedParking)
+ }
+ struct PersistentChanges: Sendable {
+ /// Every update applied since the last `persisted`, in order.
+ let updates: [Data]
+ let sequence: Int64
+ let commandsApplied: Int
+ let guid: 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 PersistentState(state: lastGood, sequence: durableSequence, commandsApplied: commandsApplied, guid: guid, parked: acceptedParking)
+ return PersistentChanges(updates: unpersisted, sequence: durableSequence, commandsApplied: commandsApplied, guid: guid)
}
+ /// The first `count` updates of the last `persistentChanges` are stored.
+ func persisted(_ count: Int) { unpersisted.removeFirst(min(count, unpersisted.count)) }
+ func currentSequence() -> Int64 { durableSequence }
func setSequence(_ sequence: Int64) { durableSequence = max(durableSequence, sequence) }
- func close() { opened = false; authority = nil; merger = nil; sources.removeAll(); sourceSnapshots.removeAll(); lastGood = Data() }
+ func close() {
+ opened = false; authority = nil; merger = nil; presented = nil
+ sources.removeAll(); sourceStates.removeAll(); sourceVersions.removeAll()
+ lastGood = State(); unpersisted.removeAll()
+ }
private func fresh(update: Data) throws -> (UInt64, Sandbox) {
let sandbox = try Sandbox()
var client = UInt64(UInt32.random(in: 1...UInt32.max))
@@ -65,23 +109,40 @@ actor CRDTReplica {
if used.contains(client) { return try fresh(update: update) }
return (client, sandbox)
}
- func open(update: Data) throws -> CRDTProjection {
- sources.removeAll(); sourceSnapshots.removeAll()
- commandsApplied = 0; durableSequence = 0; acceptedParking = ""
+ func open(update: Data) throws {
+ sources.removeAll(); sourceStates.removeAll(); sourceVersions.removeAll()
+ commandsApplied = 0; durableSequence = 0; unpersisted.removeAll(); presented = nil; acceptedParking = ""
authority = try fresh(update: update).1
opened = true
- lastGood = try authority!.invoke(["op": .string("snapshot")])
- return try projection()
+ lastGood = State(base: try authority!.invoke(["op": .string("snapshot")]))
+ version &+= 1
}
private func currentAuthority() throws -> Sandbox {
guard opened else { throw Failure.unavailable }
- if authority == nil { authority = try fresh(update: lastGood).1 }
+ if authority == nil { presented = nil; authority = try fresh(update: lastGood.data).1 }
guard let authority else { throw Failure.unavailable }
return authority
}
- func projection() throws -> CRDTProjection {
- let authority = try currentAuthority()
- return try authority.projection()
+ /// Snapshot the authority so its state is one update again.
+ private func compact(_ authority: Sandbox) throws {
+ do { lastGood = State(base: try authority.invoke(["op": .string("snapshot")])) }
+ catch { recover(); throw error }
+ }
+ private func compactIfWanted(_ authority: Sandbox) {
+ if lastGood.wantsCompaction { try? compact(authority) }
+ }
+ /// The authority's projection: the changed blocks patched into the last
+ /// one, or the whole document when there is no last one.
+ private func authorityProjection(_ authority: Sandbox) throws -> CRDTProjection {
+ do {
+ if let presented {
+ let delta = try JSONDecoder().decode(CRDTProjectionDelta.self, from: authority.invoke(["op": .string("project_delta")]))
+ if let next = delta.applied(to: presented) { self.presented = next; return next }
+ }
+ let projected = try JSONDecoder().decode(CRDTProjection.self, from: authority.invoke(["op": .string("project")]))
+ presented = projected
+ return projected
+ } catch { recover(); throw error }
}
/// False when the replica parks structs or deletions it cannot integrate
/// (their dependency never arrived): it shows less than it holds (#145).
@@ -137,26 +198,31 @@ actor CRDTReplica {
/// not unpark a damaged duplicate (yrs checks a parked struct's
/// dependencies before noticing it is integrated); a snapshot merges
/// parked structs with integrated ones and drops it. What parks after
- /// that is the server's own. Undo history goes, as in `recover`.
+ /// that is the server's own. Undo history goes, as in `recover`; every
+ /// source is out of date, and the state becomes that one snapshot.
func settleAfterCatchingUpFromStart() throws {
let authority = try currentAuthority()
if !(try parked()).isEmpty {
let snapshot = try authority.invoke(["op": .string("snapshot")])
let rebuilt = try fresh(update: snapshot).1
- self.authority = rebuilt
- lastGood = try rebuilt.invoke(["op": .string("snapshot")])
+ self.authority = rebuilt; presented = nil
+ lastGood = State(base: try rebuilt.invoke(["op": .string("snapshot")]))
+ version &+= 1
}
acceptedParking = try parked()
}
+ func projection() throws -> CRDTProjection {
+ try authorityProjection(try currentAuthority())
+ }
/// Bound retained WASM memories. The caller defers publication until render
/// acknowledgement and queued-callback drainage allow old sources to retire.
func presentation(source generation: UInt64, selection: NSRange, allowReuse: Bool = false) throws -> (UInt64, CRDTProjection, NSRange)? {
let authority = try currentAuthority()
// Only the caller knows that this source has actually been rendered and
- // has no pending candidate. Byte-identical state is additionally required:
+ // has no pending candidate. An identical state is additionally required:
// peers, undo, and divergent queued edits must still publish a fresh source.
// Never reconstruct or transfer a client ID to enable this fast path.
- let reuse = allowReuse && sources[generation] != nil && sourceSnapshots[generation] == lastGood
+ let reuse = allowReuse && sources[generation] != nil && sourceVersions[generation] == version
guard reuse || sources.count < 3 else { return nil }
var resolved = selection
if let displayed = sources[generation] {
@@ -169,26 +235,29 @@ 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 snapshot = sourceSnapshots[generation] { sources[generation] = try? fresh(update: snapshot).1 }
+ if let state = sourceStates[generation] { sources[generation] = try? fresh(update: state.data).1 }
else { sources.removeValue(forKey: generation) }
recover()
throw error
}
}
- if reuse { return (generation, try authority.projection(), resolved) }
- let (_, source) = try fresh(update: lastGood)
+ if reuse { return (generation, try authorityProjection(authority), resolved) }
+ if lastGood.tail.count > 8 { try compact(authority) }
+ let (_, source) = try fresh(update: lastGood.data)
let generation = nextGeneration; nextGeneration += 1
- sources[generation] = source; sourceSnapshots[generation] = lastGood
- return (generation, try authority.projection(), resolved)
+ sources[generation] = source; sourceStates[generation] = lastGood; sourceVersions[generation] = version
+ return (generation, try authorityProjection(authority), resolved)
}
func retainGenerations(_ ids: Set<UInt64>) {
sources = sources.filter { ids.contains($0.key) }
- sourceSnapshots = sourceSnapshots.filter { ids.contains($0.key) }
+ sourceStates = sourceStates.filter { ids.contains($0.key) }
+ sourceVersions = sourceVersions.filter { ids.contains($0.key) }
}
private func recover() {
// No invalid interpreter is reused. A new authority ID cannot reuse
// clocks from a partially executed command. UI reports undo loss.
- authority = try? fresh(update: lastGood).1
+ presented = nil
+ authority = try? fresh(update: lastGood.data).1
}
func mergeUpdates(_ updates: [Data]) throws -> Data {
guard let first = updates.first else { throw Failure.rejected }
@@ -200,40 +269,54 @@ actor CRDTReplica {
do { return try merger!.invoke(envelope) }
catch { merger = nil; throw error }
}
- func apply(_ update: Data) throws -> CRDTProjection {
+ func apply(_ update: Data) throws {
let authority = try currentAuthority()
- do {
- _ = try authority.invoke(Data([255]) + update)
- let projected = try authority.projection()
- lastGood = try authority.invoke(["op": .string("snapshot")])
- return projected
- } catch { recover(); throw error }
+ do { _ = try authority.invoke(Data([255]) + update) }
+ catch { recover(); throw error }
+ lastGood.append(update); version &+= 1; unpersisted.append(update)
+ compactIfWanted(authority)
}
- func command(_ command: [String: JSONValue]) throws -> (Data, CRDTProjection) {
+ /// Reads that change nothing; any other command is an edit.
+ private static let reads: Set<String> = ["snapshot", "clients", "anchor", "resolve"]
+ /// Runs one command and returns the update it made: only what its own
+ /// transactions changed. No projection and no snapshot are taken.
+ func command(_ command: [String: JSONValue]) throws -> Data {
let authority = try currentAuthority()
let generation: UInt64? = if case .number(let value) = command["generation"] { UInt64(exactly: value) } else { nil }
- let isHistory = command["op"] == .string("undo") || command["op"] == .string("redo")
+ 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 }
+ let isHistory = op == "undo" || op == "redo"
let writer: Sandbox
if isHistory || generation == nil { writer = authority }
else {
let generation = generation!
- if sources[generation] == nil, let snapshot = sourceSnapshots[generation] { sources[generation] = try fresh(update: snapshot).1 }
+ if sources[generation] == nil, let state = sourceStates[generation] { sources[generation] = try fresh(update: state.data).1 }
guard let source = sources[generation] else { throw Failure.unavailable }
writer = source
}
- let sourceBefore = writer === authority ? lastGood : (generation.flatMap { sourceSnapshots[$0] } ?? lastGood)
+ if let op, Self.reads.contains(op) { return try writer.invoke(command) }
var authorityTouched = writer === authority
do {
let update = try writer.invoke(command)
- let sourceAfter = try writer.invoke(["op": .string("snapshot")])
if writer !== authority { authorityTouched = true; _ = try authority.invoke(Data([254]) + update) }
- let projected = try authority.projection()
- lastGood = try authority.invoke(["op": .string("snapshot")])
- if writer !== authority, let generation { sourceSnapshots[generation] = sourceAfter }
+ let wasInSync = generation.map { sourceVersions[$0] == version } ?? false
+ lastGood.append(update); version &+= 1; unpersisted.append(update)
+ if writer !== authority, let generation {
+ if wasInSync { sourceStates[generation] = lastGood; sourceVersions[generation] = version }
+ else {
+ sourceVersions.removeValue(forKey: generation)
+ sourceStates[generation]?.append(update)
+ if sourceStates[generation]?.wantsCompaction == true, let state = try? writer.invoke(["op": .string("snapshot")]) {
+ sourceStates[generation] = State(base: state)
+ }
+ }
+ }
commandsApplied += 1
- return (update, projected)
+ compactIfWanted(authority)
+ return update
} catch {
- if writer !== authority, let generation { sources[generation] = try? fresh(update: sourceBefore).1 }
+ if writer !== authority, let generation { sources[generation] = try? fresh(update: (sourceStates[generation] ?? lastGood).data).1 }
if authorityTouched { recover() }
throw error
}
diff --git a/native/apple/Sources/DocsKit/DocsModel.swift b/native/apple/Sources/DocsKit/DocsModel.swift
index 0070126..afd3503 100644
--- a/native/apple/Sources/DocsKit/DocsModel.swift
+++ b/native/apple/Sources/DocsKit/DocsModel.swift
@@ -202,7 +202,7 @@ import RastrilloNative
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")])
+ let update = try await local.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")])
guard documentEpoch == epoch else { await local.close(); return }
// A model is reused across documents: never compare a draft's
// rows with the cursor of the document open before it, nor its
@@ -299,7 +299,7 @@ import RastrilloNative
configurePersistence(key: key, replica: replica)
try await persistence!.reopen(fallback: initial, sequence: seq)
let projection = try await replica.projection()
- let persisted = try await replica.persistentState().sequence
+ let persisted = await replica.currentSequence()
guard documentEpoch == epoch else { await replica.close(); return }
// The cursor is this document's before the replica is published:
// a POST answer (`sent`) is compared with it as soon as it is.
@@ -345,7 +345,7 @@ import RastrilloNative
while documentEpoch == epoch, !editing.isEmpty, let replica {
let command = editing.removeFirst()
do {
- let (update, _) = try await replica.command(command)
+ let update = try await replica.command(command)
guard documentEpoch == epoch else { return }
do { try await durable(update) }
catch { localFailure = .cannotSaveOnDevice; inputPaused = true; break }
@@ -549,7 +549,7 @@ import RastrilloNative
throw error
}
guard self.detail?.sqid == sqid, self.replica === replica else { return }
- do { _ = try await replica.apply(reply.data) }
+ do { try await replica.apply(reply.data) }
catch {
guard self.detail?.sqid == sqid, self.replica === replica else { return }
backOff(sqid, since: since)
@@ -563,8 +563,10 @@ import RastrilloNative
sequence = max(sequence, seq)
await replica.setSequence(sequence)
try await settleParking(sqid, caughtUpFrom: since)
- await persistReplica()
+ // Show the change first: storing it is not what makes it durable
+ // (the server has it, and `sequence` is stored with the state).
if editing.isEmpty && editingTask == nil { await publish() }
+ await persistReplica()
await flush()
} catch { if documentEpoch == epoch, !Task.isCancelled { errorKey = "docs.editor.status.retrying" } }
}
diff --git a/native/apple/Sources/DocsKit/DocsOfflineAccount.swift b/native/apple/Sources/DocsKit/DocsOfflineAccount.swift
index af23c9e..bf3f54f 100644
--- a/native/apple/Sources/DocsKit/DocsOfflineAccount.swift
+++ b/native/apple/Sources/DocsKit/DocsOfflineAccount.swift
@@ -251,7 +251,7 @@ struct DocsSentUpdates: Sendable {
let update: Data
var sending = updates
do {
- _ = try await merger.open(update: Data())
+ try await merger.open(update: Data())
do { update = try await merger.mergeUpdates(updates.map(\.payload)) }
catch { sending = Array(updates.prefix(1)); update = sending[0].payload }
await merger.close()
diff --git a/native/apple/Sources/DocsKit/DocsPersistence.swift b/native/apple/Sources/DocsKit/DocsPersistence.swift
index c56a2de..83b51a4 100644
--- a/native/apple/Sources/DocsKit/DocsPersistence.swift
+++ b/native/apple/Sources/DocsKit/DocsPersistence.swift
@@ -57,7 +57,7 @@ struct PersistedReplica: Codable, Sendable {
}
// Replay includes held entries: the editor must show everything kept
// here, even when it cannot currently send it.
- for entry in entries where entry.kind == "update" { _ = try await replica.apply(entry.payload); held.insert(entry.id) }
+ for entry in entries where entry.kind == "update" { try await replica.apply(entry.payload); held.insert(entry.id) }
commandsDurable = 0
}
/// Entries the server has taken are acknowledged and never sent again.
diff --git a/native/apple/Sources/DocsKit/DocsReplicaCache.swift b/native/apple/Sources/DocsKit/DocsReplicaCache.swift
index e168eb5..b3a8b2a 100644
--- a/native/apple/Sources/DocsKit/DocsReplicaCache.swift
+++ b/native/apple/Sources/DocsKit/DocsReplicaCache.swift
@@ -16,8 +16,8 @@ import RastrilloNative
let previous = try before.map { try JSONDecoder().decode(PersistedReplica.self, from: $0) }
let merger = CRDTReplica(guid: candidate.guid)
do {
- _ = try await merger.open(update: previous?.state ?? Data())
- _ = try await merger.apply(candidate.state)
+ try await merger.open(update: previous?.state ?? Data())
+ try await merger.apply(candidate.state)
let state = try await merger.persistentState().state
await merger.close()
guard self.generation(key) == generation else { throw CancellationError() }
diff --git a/native/apple/Tests/DocsKitTests/CRDTClipboardTests.swift b/native/apple/Tests/DocsKitTests/CRDTClipboardTests.swift
index d36cfaa..408d490 100644
--- a/native/apple/Tests/DocsKitTests/CRDTClipboardTests.swift
+++ b/native/apple/Tests/DocsKitTests/CRDTClipboardTests.swift
@@ -30,7 +30,7 @@ final class CRDTClipboardTests: XCTestCase {
_ = try await replica.open(update: Data())
let receiver = CRDTReplica(guid: "rules-typeahead")
_ = try await receiver.open(update: Data())
- let (initial, _) = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")])
+ let initial = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")])
_ = try await receiver.apply(initial)
let presentation = try await replica.presentation(source: 0, selection: NSRange(location: 0, length: 0))
let source = try XCTUnwrap(presentation?.0)
@@ -42,7 +42,7 @@ final class CRDTClipboardTests: XCTestCase {
["op": .string("display_edit"), "at": .number(6), "length": .number(0), "text": .string("two😀")]
] {
var command = command; command["generation"] = .number(Double(source))
- let (update, _) = try await replica.command(command)
+ let update = try await replica.command(command)
_ = try await receiver.apply(update)
let local = try await replica.projection(); let remote = try await receiver.projection()
XCTAssertEqual(local.children.map(\.id), remote.children.map(\.id))
diff --git a/native/apple/Tests/DocsKitTests/CRDTSourceReuseTests.swift b/native/apple/Tests/DocsKitTests/CRDTSourceReuseTests.swift
index 57805ba..c1a2175 100644
--- a/native/apple/Tests/DocsKitTests/CRDTSourceReuseTests.swift
+++ b/native/apple/Tests/DocsKitTests/CRDTSourceReuseTests.swift
@@ -17,7 +17,8 @@ final class CRDTSourceReuseTests: XCTestCase {
source = try XCTUnwrap(next?.0)
}
XCTAssertEqual(source, original)
- let (clientData, typed) = try await replica.command(["op": .string("clients")])
+ let clientData = try await replica.command(["op": .string("clients")])
+ let typed = try await replica.projection()
XCTAssertEqual(try JSONDecoder().decode([UInt64].self, from: clientData).count, 2)
XCTAssertEqual(typed.children.map(\.plainText).joined(), String(repeating: "a", count: 100))
@@ -28,10 +29,10 @@ final class CRDTSourceReuseTests: XCTestCase {
await replica.retainGenerations([source])
// A peer changes authority while displayed source stays at the old state.
- let (snapshot, _) = try await replica.command(["op": .string("snapshot")])
+ let snapshot = try await replica.command(["op": .string("snapshot")])
let peer = CRDTReplica(guid: "source-reuse-test")
_ = try await peer.open(update: snapshot)
- let (peerUpdate, _) = try await peer.command(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("peer ")])
+ let peerUpdate = try await peer.command(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("peer ")])
_ = try await replica.apply(peerUpdate)
let divergent = try await replica.presentation(source: source, selection: NSRange(location: 100, length: 0), allowReuse: true)
let changed = try XCTUnwrap(divergent?.0)
diff --git a/native/apple/Tests/DocsKitTests/DocumentSyncIntegrationTests.swift b/native/apple/Tests/DocsKitTests/DocumentSyncIntegrationTests.swift
index a8c9ddf..e03d618 100644
--- a/native/apple/Tests/DocsKitTests/DocumentSyncIntegrationTests.swift
+++ b/native/apple/Tests/DocsKitTests/DocumentSyncIntegrationTests.swift
@@ -13,8 +13,9 @@ final class DocumentSyncIntegrationTests: XCTestCase {
XCTFail("Malformed updates must fail")
} catch { }
_ = try await replica.projection()
- let (first, _) = try await replica.command(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("a")])
- let (second, projection) = try await replica.command(["op": .string("display_edit"), "at": .number(1), "length": .number(0), "text": .string("b")])
+ let first = try await replica.command(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("a")])
+ let second = try await replica.command(["op": .string("display_edit"), "at": .number(1), "length": .number(0), "text": .string("b")])
+ let projection = try await replica.projection()
let merged = try await replica.mergeUpdates([first, second])
XCTAssertFalse(merged.isEmpty)
let after = try await replica.projection()
diff --git a/native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift b/native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift
index 5f01e9d..3e8d1ed 100644
--- a/native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift
+++ b/native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift
@@ -121,13 +121,13 @@ private struct OfflineRandom: RandomNumberGenerator {
private func initial() async throws -> Data {
let seed = CRDTReplica(guid: "offline-property")
_ = try await seed.open(update: Data())
- let (update, _) = try await seed.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")])
+ let update = try await seed.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")])
await seed.close(); return update
}
private func edit(_ replica: CRDTReplica, _ text: String) async throws -> Data {
let projection = try await replica.projection()
let at = projection.children.map(\.plainText).joined().utf16.count
- return try await replica.command(["op": .string("display_edit"), "at": .number(Double(at)), "length": .number(0), "text": .string(text)]).0
+ return try await replica.command(["op": .string("display_edit"), "at": .number(Double(at)), "length": .number(0), "text": .string(text)])
}
func testMissingOrCorruptMetadataHoldsOnlyItsLane() async throws {
for damage in 0..<3 {
@@ -206,7 +206,7 @@ private struct OfflineRandom: RandomNumberGenerator {
private func parkedReplica() async throws -> (paragraph: Data, typed: Data) {
let writer = CRDTReplica(guid: "offline-property")
_ = try await writer.open(update: Data())
- let (paragraph, _) = try await writer.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")])
+ let paragraph = try await writer.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")])
let typed = try await edit(writer, "Kept")
await writer.close()
return (paragraph, typed)
@@ -732,7 +732,8 @@ private struct OfflineRandom: RandomNumberGenerator {
try await cache.commit(first, key: "doc", generation: 0)
let saved = try JSONDecoder().decode(PersistedReplica.self, from: XCTUnwrap(disk.contents["cache/docs/doc/replica"]))
let checked = CRDTReplica(guid: "offline-property")
- let text = try await checked.open(update: saved.state).children.map(\.plainText).joined()
+ try await checked.open(update: saved.state)
+ let text = try await checked.projection().children.map(\.plainText).joined()
XCTAssertEqual(text.count, 2); XCTAssertTrue(text.contains("A")); XCTAssertTrue(text.contains("B"))
XCTAssertEqual(saved.sequence, 3)
cache.invalidate("doc"); try disk.remove("cache/docs/doc/replica")
diff --git a/native/apple/Tests/DocsKitTests/OfflineKillTests.swift b/native/apple/Tests/DocsKitTests/OfflineKillTests.swift
index 89fd585..6f5c1d4 100644
--- a/native/apple/Tests/DocsKitTests/OfflineKillTests.swift
+++ b/native/apple/Tests/DocsKitTests/OfflineKillTests.swift
@@ -72,7 +72,8 @@ final class OfflineKillTests: XCTestCase {
let reply = try await client.responseDetails("/d/\(config["sqid"]!)/updates", maxBytes: 8 * 1024 * 1024)
try reply.requireSuccess()
let server = CRDTReplica(guid: model.detail!.guid)
- let projected = try await server.open(update: reply.data)
+ try await server.open(update: reply.data)
+ let projected = try await server.projection()
XCTAssertEqual(projected.children.map(\.plainText).joined(), reopened, "Real server converges after the killed client's lane drains")
await server.close(); await model.stop(); account.drainer.stop()
}
diff --git a/native/apple/Tests/DocsKitTests/RealtimeSyncTests.swift b/native/apple/Tests/DocsKitTests/RealtimeSyncTests.swift
index 37d0dfe..5b419c7 100644
--- a/native/apple/Tests/DocsKitTests/RealtimeSyncTests.swift
+++ b/native/apple/Tests/DocsKitTests/RealtimeSyncTests.swift
@@ -126,7 +126,7 @@ private final class MetadataReadCounter: BlobStore, @unchecked Sendable {
let peer = CRDTReplica(guid: "realtime-sync")
let state = try await server.responseDetails("/d/\(sqid)/updates", method: "GET", body: nil, contentType: "", maxBytes: 1 << 20).data
_ = try await peer.open(update: state)
- let (update, _) = try await peer.command(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string(text)])
+ let update = try await peer.command(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string(text)])
await peer.close()
return update
}