oficina / docs Public

Docs native: settle a parked replica with at most one full download

Replaces d2f16cb's rule, which distrusted any stored replica that was
not whole (#147 findings 1, 2 and 5):
- Finding 1: most real damaged replicas stayed "not whole" after the
  catch-up from 0, so healing took two full downloads.
- Finding 2: when the server itself holds a parked update, every open
  became a full download, forever.
- Finding 5: a headless send could store sequence 0 for a healthy
  replica.

Now a replica records the parking it has accepted (`PersistedReplica
.parked`, the engine's `parked` description). Only parking it has not
accepted unsettles it:
- Reopen keeps the stored sequence and notes whether the replica is
  unsettled. A replica opened from the server's state accepts what that
  parks at once.
- DocsModel settles after every catch-up. If unaccepted parking remains
  after an ordinary catch-up, it catches up from the start once. After
  that, CRDTReplica rebuilds the authority from its own snapshot, which
  drops a damaged duplicate, and accepts what still parks: the server's
  own.
- With nothing newer on the server, an unsettled replica goes straight
  to the catch-up from the start.
- No first paragraph is added while unsettled.
- DocsReplicaCache stores the sequence as main did, and carries the
  accepted parking.

Tests, in OfflineDurabilityTests:
- A parked stored replica heals with one full download and stays
  settled.
- All 29 real damaged snapshots heal with one download each, and the
  record accepts only the server's own parking; without the rebuild,
  21 fail.
- A server that holds a parked update costs one full download, not one
  per open.
- A merge that parks keeps its sequence.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev f21fdd5297bea547c196e3bddabbe23d0c6b75f6 parent b7b4650
5 files changed, +192 −63
  • native/apple/Sources/DocsKit/CRDTReplica.swift +35 −5
  • native/apple/Sources/DocsKit/DocsModel.swift +30 −4
  • native/apple/Sources/DocsKit/DocsPersistence.swift +19 −12
  • native/apple/Sources/DocsKit/DocsReplicaCache.swift +2 −4
  • native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift +106 −38
diff --git a/native/apple/Sources/DocsKit/CRDTReplica.swift b/native/apple/Sources/DocsKit/CRDTReplica.swift
index f9df826..e11be20 100644
--- a/native/apple/Sources/DocsKit/CRDTReplica.swift
+++ b/native/apple/Sources/DocsKit/CRDTReplica.swift
@@ -34,6 +34,8 @@ actor CRDTReplica {
private var lastGood = Data()
private var commandsApplied = 0
private var durableSequence: Int64 = 0
+ /// Parking this replica has accepted as the server's own (#147).
+ private var acceptedParking = ""
private let guid: String
enum Failure: Error { case unavailable, rejected, invalidProjection, generationLimit }
init(guid: String) { self.guid = guid }
@@ -42,10 +44,11 @@ actor CRDTReplica {
let sequence: Int64
let commandsApplied: Int
let guid: String
+ let parked: String
}
func persistentState() throws -> PersistentState {
_ = try currentAuthority()
- return PersistentState(state: lastGood, sequence: durableSequence, commandsApplied: commandsApplied, guid: guid)
+ return PersistentState(state: lastGood, sequence: durableSequence, commandsApplied: commandsApplied, guid: guid, parked: acceptedParking)
}
func setSequence(_ sequence: Int64) { durableSequence = max(durableSequence, sequence) }
func close() { opened = false; authority = nil; merger = nil; sources.removeAll(); sourceSnapshots.removeAll(); lastGood = Data() }
@@ -64,7 +67,7 @@ actor CRDTReplica {
}
func open(update: Data) throws -> CRDTProjection {
sources.removeAll(); sourceSnapshots.removeAll()
- commandsApplied = 0; durableSequence = 0
+ commandsApplied = 0; durableSequence = 0; acceptedParking = ""
authority = try fresh(update: update).1
opened = true
lastGood = try authority!.invoke(["op": .string("snapshot")])
@@ -81,12 +84,39 @@ actor CRDTReplica {
return try authority.projection()
}
/// False when the replica parks structs or deletions it cannot integrate
- /// (their dependency never arrived): it shows less than it holds, and a
- /// sequence stored with it would stop the server from ever resending what
- /// is missing (#145).
+ /// (their dependency never arrived): it shows less than it holds (#145).
func isWhole() throws -> Bool {
try JSONDecoder().decode(Bool.self, from: currentAuthority().invoke(["op": .string("whole")]))
}
+ /// What the replica parks, described canonically ("" when whole).
+ func parked() throws -> String {
+ try JSONDecoder().decode(String.self, from: currentAuthority().invoke(["op": .string("parked")]))
+ }
+ func acceptParking(_ parked: String) { acceptedParking = parked }
+ /// Accept whatever is parked now; call only once caught up from the start.
+ func acceptCurrentParking() throws { acceptedParking = try parked() }
+ /// True when the replica parks something it has not accepted: damage, or
+ /// something the server has that this replica lacks.
+ func hasUnacceptedParking() throws -> Bool {
+ let parked = try parked()
+ return !parked.isEmpty && parked != acceptedParking
+ }
+ /// Once caught up from the start: rebuild the authority from its own
+ /// snapshot and accept what still parks. Applying the server's state does
+ /// 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`.
+ 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")])
+ }
+ acceptedParking = try parked()
+ }
/// 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)? {
diff --git a/native/apple/Sources/DocsKit/DocsModel.swift b/native/apple/Sources/DocsKit/DocsModel.swift
index 3527898..80e1e74 100644
--- a/native/apple/Sources/DocsKit/DocsModel.swift
+++ b/native/apple/Sources/DocsKit/DocsModel.swift
@@ -56,6 +56,9 @@ import RastrilloNative
@ObservationIgnored private var refusedRemote: (since: Int64, attempts: Int, notBefore: ContinuousClock.Instant)?
@ObservationIgnored private var refusedRetryTask: Task<Void, Never>?
@ObservationIgnored private var latestAnnounced: Int64 = 0
+ /// The replica parks something it has not accepted (#145, #147): catch up,
+ /// and from the start if that does not settle it. See `settleParking`.
+ @ObservationIgnored private(set) var unsettledParking = false
/// The iPhone app is in the background: no stream may start.
@ObservationIgnored private var liveUpdatesSuspended = false
var syncStatus: SyncStatus { offlineAccount.drainer.status(lane: documentKey.map { "doc:" + $0 }, localFailure: localFailure) }
@@ -312,9 +315,10 @@ import RastrilloNative
updateLaneSummary(laneSummary)
await publish()
guard documentEpoch == epoch else { return }
- // Not while catching up from the start: an incomplete replica may
- // show nothing of a document that has content.
- if projection.children.isEmpty && detail.can_write && persistence?.catchingUpFromStart != true {
+ unsettledParking = persistence?.unsettled == true
+ // Not while unsettled: such a replica may show nothing of a
+ // document that has content.
+ if projection.children.isEmpty && detail.can_write && !unsettledParking {
enqueue(["op":.string("insert_element"), "at":.number(0), "type":.string("paragraph")])
}
await persistReplica()
@@ -502,7 +506,10 @@ import RastrilloNative
let epoch = documentEpoch
guard detail?.sqid == sqid else { return }
latestAnnounced = max(latestAnnounced, remoteSequence)
- guard remoteSequence > sequence, let replica else { return }
+ guard remoteSequence > sequence || unsettledParking, let replica else { return }
+ // Unsettled with nothing newer to fetch: only a catch-up from the
+ // start can supply what the replica's parked structs wait for.
+ if unsettledParking && remoteSequence <= sequence { sequence = 0 }
// Rows that would not apply are fetched again only after a backoff,
// and the editor keeps saying it is retrying meanwhile.
if let refused = refusedRemote, refused.since == sequence, refused.notBefore > .now {
@@ -548,11 +555,29 @@ import RastrilloNative
}
sequence = max(sequence, seq)
await replica.setSequence(sequence)
+ try await settleParking(sqid, caughtUpFrom: since)
await persistReplica()
if editing.isEmpty && editingTask == nil { await publish() }
await flush()
} catch { if documentEpoch == epoch, !Task.isCancelled { errorKey = "docs.editor.status.retrying" } }
}
+ /// After a catch-up: if the replica parks something it has not accepted,
+ /// a catch-up from `since` > 0 did not supply it, so catch up from the
+ /// start once. After a catch-up from the start the replica holds the
+ /// server's whole state: rebuilt from its own snapshot it drops a damaged
+ /// duplicate (#145), and what still parks is the server's own, accepted
+ /// and stored with it so no later open downloads it again (#147).
+ private func settleParking(_ sqid: String, caughtUpFrom since: Int64) async throws {
+ guard let replica else { return }
+ guard try await replica.hasUnacceptedParking() else { unsettledParking = false; return }
+ if since > 0 {
+ unsettledParking = true
+ Task { [weak self] in await self?.refresh(sqid, remoteSequence: self?.latestAnnounced ?? 0, holding: false) }
+ } else {
+ try await replica.settleAfterCatchingUpFromStart()
+ unsettledParking = false
+ }
+ }
/// An update POST came back. The web's rule (live-updates.mjs
/// `noteOwnSeq`): adopt the server's sequence for it only when it is
/// exactly the next row, so nothing anyone else wrote can be skipped, and
@@ -588,6 +613,7 @@ import RastrilloNative
heldRemoteTask?.cancel(); heldRemoteTask = nil; heldRemoteSequence = nil
refusedRetryTask?.cancel(); refusedRetryTask = nil; refusedRemote = nil
latestAnnounced = 0
+ unsettledParking = false
}
private func stopObservingSends() {
if let sendObserver { offlineAccount.stopObservingSends(sendObserver) }
diff --git a/native/apple/Sources/DocsKit/DocsPersistence.swift b/native/apple/Sources/DocsKit/DocsPersistence.swift
index 9bab0e9..c56a2de 100644
--- a/native/apple/Sources/DocsKit/DocsPersistence.swift
+++ b/native/apple/Sources/DocsKit/DocsPersistence.swift
@@ -7,6 +7,10 @@ struct PersistedReplica: Codable, Sendable {
let guid: String
let savedAt: Date
let state: Data
+ /// What this state was known to park once caught up from the start (the
+ /// engine's `parked` description): the server's own parked updates, not
+ /// damage. Absent in records written before #147, and when nothing was.
+ var parked: String? = nil
}
/// One document's durability boundary. The writer and editor share this
@@ -22,10 +26,11 @@ struct PersistedReplica: Codable, Sendable {
/// of the same document writes entries this replica has not seen.
private(set) var held: Set<UUID> = []
private var active = true
- /// The stored replica did not integrate whole, so its sequence was not
- /// trusted and the document catches up from the start. What it shows
- /// until then is incomplete (DocsModel adds no first paragraph to it).
- private(set) var catchingUpFromStart = false
+ /// The stored replica parks something it has not accepted: possibly damage
+ /// from before the #145 fix, which its stored sequence would keep the server
+ /// 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
let cache: DocsReplicaCache
private let generation: Int
var lane: String { "doc:" + key }
@@ -41,13 +46,15 @@ struct PersistedReplica: Codable, Sendable {
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)
- // A stored state that parks structs or deletions has lost what they
- // depend on; before the #145 fix yrs could write such a snapshot. Its
- // sequence would keep the server from resending it, so catch up from
- // the start: the server's whole state supplies what is missing.
- catchingUpFromStart = false
- if saved != nil { catchingUpFromStart = try await !replica.isWhole() }
- await replica.setSequence(catchingUpFromStart ? 0 : saved?.sequence ?? sequence)
+ await replica.setSequence(saved?.sequence ?? sequence)
+ if let saved {
+ await replica.acceptParking(saved.parked ?? "")
+ unsettled = try await replica.hasUnacceptedParking()
+ } else {
+ // The server's whole state: whatever it parks is the server's own.
+ try await replica.acceptCurrentParking()
+ unsettled = false
+ }
// 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) }
@@ -65,7 +72,7 @@ struct PersistedReplica: Codable, Sendable {
// 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)
+ 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
}
diff --git a/native/apple/Sources/DocsKit/DocsReplicaCache.swift b/native/apple/Sources/DocsKit/DocsReplicaCache.swift
index bce93e2..e168eb5 100644
--- a/native/apple/Sources/DocsKit/DocsReplicaCache.swift
+++ b/native/apple/Sources/DocsKit/DocsReplicaCache.swift
@@ -19,15 +19,13 @@ import RastrilloNative
_ = try await merger.open(update: previous?.state ?? Data())
_ = try await merger.apply(candidate.state)
let state = try await merger.persistentState().state
- // A state that does not integrate whole is kept, but never with
- // a sequence that says the server has nothing more for it (#145).
- let whole = try await merger.isWhole()
await merger.close()
guard self.generation(key) == generation else { throw CancellationError() }
// No suspension between the compare and write. A concurrent
// editor or headless writer forces a fresh merge, never a loss.
guard try store.read(path) == before else { continue }
- let merged = PersistedReplica(format: 1, sequence: whole ? max(previous?.sequence ?? 0, candidate.sequence) : 0, guid: candidate.guid, savedAt: Date(), state: state)
+ 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 }
try store.write(JSONEncoder().encode(merged), to: path)
return true
diff --git a/native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift b/native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift
index 265f6f9..59f2a67 100644
--- a/native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift
+++ b/native/apple/Tests/DocsKitTests/OfflineDurabilityTests.swift
@@ -28,6 +28,11 @@ private actor IntegratingServer: NativeTransport {
var loseNextResponse = false
var sequence: Int64 = 0
var rows: [Int64: Data] = [:]
+ /// Replies carrying the whole state (no `since`, or `since=0`).
+ var fullDownloads = 0
+ func fullDownloadCount() -> Int { fullDownloads }
+ func advance(to sequence: Int64) { self.sequence = sequence }
+ func parked() async throws -> String { try await replica.parked() }
var listeners: [UUID: AsyncStream<Int64>.Continuation] = [:]
func setOnline(_ value: Bool) { online = value }
let replica = CRDTReplica(guid: "offline-property")
@@ -70,7 +75,7 @@ private actor IntegratingServer: NativeTransport {
if since > 0 {
let updates = rows.keys.sorted().filter { $0 > since }.compactMap { rows[$0] }
data = updates.isEmpty ? Data() : try await replica.mergeUpdates(updates)
- } else { data = try await snapshot() }
+ } else { fullDownloads += 1; data = try await snapshot() }
return NativeResponse(data: data, status: 200, headers: ["Docs-Seq": String(sequence)])
}
let detail = DocumentDetail(sqid: "doc", title: title, guid: "offline-property", can_write: true, can_share: false)
@@ -189,10 +194,8 @@ private struct OfflineRandom: RandomNumberGenerator {
XCTAssertEqual(saved.sequence, 17)
XCTAssertFalse(saved.state.isEmpty)
}
- /// #145: before the yrs GC fix a stored snapshot could hold a struct a
- /// fresh document cannot integrate, parking everything after it, while
- /// its sequence told the server nothing was missing. Modelled by a stored
- /// state that parks its text for want of the paragraph it was typed in.
+ /// 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.
private func parkedReplica() async throws -> (paragraph: Data, typed: Data) {
let writer = CRDTReplica(guid: "offline-property")
_ = try await writer.open(update: Data())
@@ -201,51 +204,116 @@ private struct OfflineRandom: RandomNumberGenerator {
await writer.close()
return (paragraph, typed)
}
- func testAStoredReplicaThatDoesNotIntegrateWholeIsNotTrustedAndHealsFromTheServer() async throws {
+ private func storeReplica(_ disk: BlobStore, account: DocsOfflineAccount, state: Data, sequence: Int64, parked: String? = nil) throws {
+ try account.saveMetadata(DocsOfflineMetadata(detail: DocumentDetail(sqid: "doc", title: "Document", guid: "offline-property", can_write: true, can_share: false)), key: "doc")
+ try disk.write(JSONEncoder().encode(PersistedReplica(format: 1, sequence: sequence, guid: "offline-property", savedAt: Date(), state: state, parked: parked)), to: "cache/docs/doc/replica")
+ }
+ private func stored(_ disk: BlobStore) throws -> PersistedReplica {
+ try JSONDecoder().decode(PersistedReplica.self, from: XCTUnwrap(disk.read("cache/docs/doc/replica")))
+ }
+ /// Opens the document, waits until it shows `text` and its replica has
+ /// no unaccepted parking, persists, and stops.
+ @discardableResult private func openUntilSettled(_ server: IntegratingServer, _ account: DocsOfflineAccount, _ network: NativeConnectivity, shows text: String) async throws -> CRDTProjection? {
+ let model = DocsModel(transport: { server }, connectivity: network, offlineAccount: account)
+ await model.open("doc")
+ let deadline = ContinuousClock.now.advanced(by: .seconds(5))
+ func settled() -> Bool { model.projection?.children.map(\.plainText).joined() == text && !model.unsettledParking }
+ while !settled() && .now < deadline { try await Task.sleep(for: .milliseconds(10)) }
+ let done = settled()
+ XCTAssertTrue(done, "the document never settled showing \(text)")
+ await model.persistReplica()
+ let shown = model.projection
+ await model.stop(); account.drainer.stop()
+ return shown
+ }
+ /// #145: a stored state that parks what it depends on, with a sequence
+ /// saying the server has nothing newer, catches up from the start once.
+ func testAStoredReplicaThatParksCatchesUpFromTheStartOnceAndStaysSettled() async throws {
let (paragraph, typed) = try await parkedReplica()
let server = IntegratingServer(); try await server.open(paragraph)
_ = try await server.responseDetails("/d/doc/updates", method: "POST", body: typed, contentType: "application/octet-stream", maxBytes: 1 << 20)
let disk = MemoryBlobStore()
let network = NativeConnectivity(source: ScriptedPathSource(.satisfied))
let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: network, transport: { server })
- try account.saveMetadata(DocsOfflineMetadata(detail: DocumentDetail(sqid: "doc", title: "Document", guid: "offline-property", can_write: true, can_share: false)), key: "doc")
- let stored = PersistedReplica(format: 1, sequence: 1, guid: "offline-property", savedAt: Date(), state: typed)
- try disk.write(JSONEncoder().encode(stored), to: "cache/docs/doc/replica")
-
- let lane = DocsPersistence(store: disk, outbox: Outbox(store: disk, account: "a"), key: "doc", replica: CRDTReplica(guid: "offline-property"))
- try await lane.reopen(fallback: Data(), sequence: 0)
- XCTAssertTrue(lane.catchingUpFromStart)
- let distrusted = try await lane.replica.persistentState().sequence
- XCTAssertEqual(distrusted, 0, "an incomplete replica's stored sequence is not trusted")
- await lane.replica.close()
-
- let model = DocsModel(transport: { server }, connectivity: network, offlineAccount: account)
- await model.open("doc")
- let deadline = ContinuousClock.now.advanced(by: .seconds(3))
- while model.projection?.children.map(\.plainText).joined() != "Kept" && .now < deadline { try await Task.sleep(for: .milliseconds(10)) }
- XCTAssertEqual(model.projection?.children.map(\.plainText).joined(), "Kept", "catching up from the start heals the replica")
- XCTAssertEqual(model.projection?.children.count, 1, "no first paragraph is added to an incomplete replica")
- await model.persistReplica()
- let healed = try JSONDecoder().decode(PersistedReplica.self, from: XCTUnwrap(disk.read("cache/docs/doc/replica")))
- XCTAssertEqual(healed.sequence, 1)
- let reopened = CRDTReplica(guid: "offline-property")
- _ = try await reopened.open(update: healed.state)
- let whole = try await reopened.isWhole()
- XCTAssertTrue(whole)
- await reopened.close()
+ try storeReplica(disk, account: account, state: typed, sequence: 1)
+ let shown = try await openUntilSettled(server, account, network, shows: "Kept")
+ XCTAssertEqual(shown?.children.count, 1, "no first paragraph is added to an unsettled replica")
+ var downloads = await server.fullDownloadCount()
+ XCTAssertEqual(downloads, 1)
+ XCTAssertEqual(try stored(disk).sequence, 1)
+ try await openUntilSettled(server, account, network, shows: "Kept")
+ downloads = await server.fullDownloadCount()
+ XCTAssertEqual(downloads, 1, "a settled replica does not download the document again")
let serverText = try await server.text()
XCTAssertEqual(serverText, "Kept")
- await model.stop(); account.drainer.stop()
}
- func testAStateThatDoesNotIntegrateWholeIsStoredWithoutASequence() async throws {
+ /// #147 finding 1: real damaged snapshots (native/crdt/tests/fixtures). The
+ /// server's state alone leaves most of them parking the damaged duplicate;
+ /// settling rebuilds the replica, so one download heals each for good.
+ func testRealDamagedSnapshotsHealWithOneDownload() async throws {
+ let directory = URL(fileURLWithPath: #filePath).deletingLastPathComponent()
+ .appendingPathComponent("../../../crdt/tests/fixtures/damaged-snapshots").standardized
+ let names = try FileManager.default.contentsOfDirectory(atPath: directory.path).filter { $0.hasPrefix("damaged-") }.sorted()
+ XCTAssertEqual(names.count, 29)
+ for name in names {
+ let damaged = try Data(contentsOf: directory.appendingPathComponent(name))
+ let good = try Data(contentsOf: directory.appendingPathComponent(name.replacingOccurrences(of: "damaged", with: "good")))
+ let server = IntegratingServer(); try await server.open(good); await server.advance(to: 5)
+ let expected = try await server.text()
+ let disk = MemoryBlobStore()
+ let network = NativeConnectivity(source: ScriptedPathSource(.satisfied))
+ let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: network, transport: { server })
+ try storeReplica(disk, account: account, state: damaged, sequence: 5)
+ try await openUntilSettled(server, account, network, shows: expected)
+ try await openUntilSettled(server, account, network, shows: expected)
+ let downloads = await server.fullDownloadCount()
+ XCTAssertEqual(downloads, 1, "\(name): downloads")
+ let record = try stored(disk)
+ XCTAssertEqual(record.sequence, 5, name)
+ // Accepted is only what the server itself parks, not the damage.
+ let serverParked = try await server.parked()
+ XCTAssertEqual(record.parked ?? "", serverParked, name)
+ let reopened = CRDTReplica(guid: "offline-property")
+ _ = try await reopened.open(update: record.state)
+ await reopened.acceptParking(record.parked ?? "")
+ let unsettled = try await reopened.hasUnacceptedParking()
+ XCTAssertFalse(unsettled, "\(name): the stored record parks the damage")
+ await reopened.close()
+ }
+ }
+ /// #147 finding 2: when the server itself holds a parked update, every
+ /// replica parks it too. Accepted after one catch-up from the start, it
+ /// does not make every later open download the document again.
+ func testParkingTheServerHoldsIsAcceptedOnce() async throws {
+ let (_, typed) = try await parkedReplica()
+ let server = IntegratingServer(); try await server.open(Data())
+ _ = try await server.responseDetails("/d/doc/updates", method: "POST", body: typed, contentType: "application/octet-stream", maxBytes: 1 << 20)
+ let serverState = try await server.snapshot()
+ let disk = MemoryBlobStore()
+ let network = NativeConnectivity(source: ScriptedPathSource(.satisfied))
+ let account = DocsOfflineAccount(store: disk, accountID: "a", connectivity: network, transport: { server })
+ // A record written before #147, holding the server's state: nothing accepted yet.
+ try storeReplica(disk, account: account, state: serverState, sequence: 1)
+ for _ in 0..<3 { try await openUntilSettled(server, account, network, shows: "") }
+ let downloads = await server.fullDownloadCount()
+ XCTAssertEqual(downloads, 1)
+ XCTAssertFalse(try stored(disk).parked?.isEmpty ?? true)
+ // Opened with no record, from the server's state: accepted at once.
+ try disk.remove("cache/docs/doc/replica")
+ for _ in 0..<2 { try await openUntilSettled(server, account, network, shows: "") }
+ let later = await server.fullDownloadCount()
+ XCTAssertEqual(later, 2, "only the first open without a record downloads")
+ }
+ /// #147 finding 5: a headless send's merge can leave the record parking a
+ /// sent update typed against a change the record lacks. Its sequence is
+ /// kept; the next open's ordinary catch-up supplies the change.
+ func testAMergeThatParksKeepsTheSequence() async throws {
let (paragraph, typed) = try await parkedReplica()
let disk = MemoryBlobStore(), cache = DocsReplicaCache(store: disk)
try await cache.commit(PersistedReplica(format: 1, sequence: 9, guid: "offline-property", savedAt: Date(), state: typed), key: "doc", generation: 0)
- var saved = try JSONDecoder().decode(PersistedReplica.self, from: XCTUnwrap(disk.read("cache/docs/doc/replica")))
- XCTAssertEqual(saved.sequence, 0)
- try await cache.commit(PersistedReplica(format: 1, sequence: 9, guid: "offline-property", savedAt: Date(), state: paragraph), key: "doc", generation: 0)
- saved = try JSONDecoder().decode(PersistedReplica.self, from: XCTUnwrap(disk.read("cache/docs/doc/replica")))
- XCTAssertEqual(saved.sequence, 9, "whole again: the sequence is kept")
+ XCTAssertEqual(try stored(disk).sequence, 9)
+ try await cache.commit(PersistedReplica(format: 1, sequence: 0, guid: "offline-property", savedAt: Date(), state: paragraph), key: "doc", generation: 0)
+ XCTAssertEqual(try stored(disk).sequence, 9)
}
func testReopenAppliesTheWholeLaneBeforePublishingAndDoesNotDuplicate() async throws {
let disk = MemoryBlobStore(), initial = try await initial()