oficina / docs Public

Docs native: number replica segments without gaps; a gap drops the replica

Review finding 3 (Fable, #145). A missing segment was silent: if the
removal after a corrupt read failed, or a power loss dropped one file,
the next load succeeded with a hole that a later segment's sequence
hid, and the server was never asked for what it held.

Segments are now numbered from the base's `segmentsFrom` (a new
optional field; absent means 0). The number is in the name and in the
sealed bytes ("DRL2": index, sequence, update), checked against each
other. Load requires the numbers from `segmentsFrom` to run without a
gap; a gap is treated like an unreadable segment: the whole replica is
removed and the outbox plus the server restore it. Compaction writes
the base with `segmentsFrom` one past the last segment it merged, then
removes everything below it, so segments it already holds (left by an
interrupted compaction) are skipped on load. Appends take one past the
highest stored number, or the base's start when none is.

Tests: a removed middle segment fails the load, drops the replica and
reopens with every edit from the outbox; an interrupted compaction's
leftovers are skipped and new segments continue the numbering.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 6f95eb9f2da41d871a32c8e6c3a538708ef6a194 parent 4c8881b
3 files changed, +105 −21
  • native/apple/Sources/DocsKit/DocsPersistence.swift +3 −0
  • native/apple/Sources/DocsKit/DocsReplicaCache.swift +47 −20
  • native/apple/Tests/DocsKitTests/ReplicaSegmentTests.swift +55 −1
diff --git a/native/apple/Sources/DocsKit/DocsPersistence.swift b/native/apple/Sources/DocsKit/DocsPersistence.swift
index 4fd2428..b71e4df 100644
--- a/native/apple/Sources/DocsKit/DocsPersistence.swift
+++ b/native/apple/Sources/DocsKit/DocsPersistence.swift
@@ -11,6 +11,9 @@ struct PersistedReplica: Codable, Sendable {
/// 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
+ /// The index of the first replica segment not folded into `state`;
+ /// segments must follow it without a gap (absent: 0).
+ var segmentsFrom: Int64? = nil
}
/// One document's durability boundary. The writer and editor share this
diff --git a/native/apple/Sources/DocsKit/DocsReplicaCache.swift b/native/apple/Sources/DocsKit/DocsReplicaCache.swift
index c4a1c40..cae2909 100644
--- a/native/apple/Sources/DocsKit/DocsReplicaCache.swift
+++ b/native/apple/Sources/DocsKit/DocsReplicaCache.swift
@@ -21,22 +21,30 @@ import RastrilloNative
static func basePath(_ key: String) -> String { "cache/docs/\(key)/replica" }
static func logPath(_ key: String) -> String { "cache/docs/\(key)/replica-log" }
+ /// One appended update. Segments are numbered without gaps from the
+ /// base's `segmentsFrom`; the number is in the name and, sealed, in the
+ /// bytes, so a missing or substituted segment is seen on load.
struct Segment: Sendable {
let name: String
+ let index: Int64
let sequence: Int64
let update: Data
- private static let magic = Data("DRL1".utf8)
+ private static let magic = Data("DRL2".utf8)
var encoded: Data {
var data = Self.magic
+ withUnsafeBytes(of: index.bigEndian) { data.append(contentsOf: $0) }
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 }
+ static func name(_ index: Int64) -> String { String(format: "%016llx-%08x-", index, UInt32.random(in: 0...UInt32.max)) + UUID().uuidString }
+ static func index(of name: String) -> Int64? { Int64(name.prefix(16), radix: 16) }
+ init(index: Int64, sequence: Int64, update: Data) { self.name = Self.name(index); self.index = index; 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)))
+ guard data.count >= 20, data.prefix(4) == Self.magic else { return nil }
+ func number(_ at: Int) -> Int64 { data.dropFirst(at).prefix(8).reduce(Int64(0)) { ($0 << 8) | Int64($1) } }
+ guard number(4) == Self.index(of: name) else { return nil }
+ self.name = name; index = number(4); sequence = number(12); update = Data(data.dropFirst(20))
}
}
struct Stored: Sendable {
@@ -48,24 +56,34 @@ import RastrilloNative
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.
+ /// The stored replica. A segment that fails to unseal, or a gap in the
+ /// numbering (a segment removed after a failed read, or lost), 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.
+ /// Segments numbered below the base's `segmentsFrom` are already in it
+ /// (a compaction stopped before removing them) and are skipped.
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)
+ let first = replica.segmentsFrom ?? 0
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) }
+ let path = Self.logPath(key) + "/" + name
+ guard let index = Segment.index(of: name), index >= first else { continue }
+ guard let data = try store.read(path), let segment = Segment(name: name, encoded: data) else { throw BlobStoreError.corrupt(path) }
segments.append(segment)
}
+ segments.sort { $0.index < $1.index }
+ for (offset, segment) in segments.enumerated() where segment.index != first + Int64(offset) {
+ throw BlobStoreError.corrupt(Self.logPath(key) + "/" + segment.name)
+ }
} catch BlobStoreError.corrupt(let path) {
try remove(key)
throw BlobStoreError.corrupt(path)
}
+ nextIndex[key] = first + Int64(segments.count)
return Stored(replica: replica, segments: segments)
}
/// Segments first: an interrupted removal leaves the base alone (an
@@ -82,10 +100,15 @@ import RastrilloNative
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
+ /// The next segment number per document, once known in this process.
+ private var nextIndex: [String: Int64] = [:]
+ /// The number the next segment takes: one past the highest stored, or
+ /// the base's `segmentsFrom` when none is.
+ private func nextSegment(_ key: String) throws -> Int64 {
+ if let highest = try segmentNames(key).compactMap(Segment.index(of:)).max() { return highest + 1 }
+ if let known = nextIndex[key] { return known }
+ guard let data = try store.read(Self.basePath(key)) else { return 0 }
+ return try JSONDecoder().decode(PersistedReplica.self, from: data).segmentsFrom ?? 0
}
/// 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
@@ -93,8 +116,9 @@ import RastrilloNative
@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)
+ let segment = Segment(index: try nextSegment(key), sequence: sequence, update: update)
try store.write(segment.encoded, to: Self.logPath(key) + "/" + segment.name)
+ nextIndex[key] = segment.index + 1
return true
}
/// Store a whole state. With a base already stored it is appended like
@@ -121,11 +145,11 @@ import RastrilloNative
// 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: max(previous?.sequence ?? 0, candidate.sequence), guid: candidate.guid, savedAt: Date(), state: state,
- parked: candidate.parked ?? previous?.parked)
+ parked: candidate.parked ?? previous?.parked, segmentsFrom: previous?.segmentsFrom)
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)) }
+ if previous == nil { try store.remove(Self.logPath(key)); nextIndex[key] = 0 }
try store.write(JSONEncoder().encode(merged), to: path)
return true
} catch {
@@ -157,8 +181,11 @@ import RastrilloNative
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)
+ let next = (stored.segments.last?.index ?? 0) + 1
+ let merged = PersistedReplica(format: 1, sequence: stored.sequence, guid: stored.replica.guid, savedAt: Date(), state: state, segmentsFrom: next)
try store.write(JSONEncoder().encode(merged), to: path)
- for segment in stored.segments { try store.remove(Self.logPath(key) + "/" + segment.name) }
+ // Remove what the new base holds: the merged segments, and any left
+ // below the old base's start by an earlier interrupted compaction.
+ for name in try segmentNames(key) where (Segment.index(of: name) ?? next) < next { try store.remove(Self.logPath(key) + "/" + name) }
}
}
diff --git a/native/apple/Tests/DocsKitTests/ReplicaSegmentTests.swift b/native/apple/Tests/DocsKitTests/ReplicaSegmentTests.swift
index 49ec823..55b0f63 100644
--- a/native/apple/Tests/DocsKitTests/ReplicaSegmentTests.swift
+++ b/native/apple/Tests/DocsKitTests/ReplicaSegmentTests.swift
@@ -108,7 +108,7 @@ import XCTest
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)
+ let segment = DocsReplicaCache.Segment(index: 0, 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)
@@ -162,4 +162,58 @@ import XCTest
XCTAssertEqual(try DocsReplicaCache(store: disk).load("doc")?.sequence, 8)
await replica.close(); await peer.close()
}
+
+ /// Review finding 3: segments are numbered without gaps from the base. A
+ /// missing one (removed after a failed read, or lost) is not silently
+ /// skipped while a later segment's sequence claims its updates: the
+ /// replica is dropped and the outbox plus the server restore it.
+ func testAMissingSegmentDropsTheReplicaLikeACorruptOne() 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()
+ for (index, text) in ["A", "B", "C"].enumerated() {
+ try await lane.enqueue(try await type(replica, text))
+ await replica.setSequence(Int64(index + 1))
+ _ = try await lane.persist()
+ }
+ let names = disk.contents.keys.filter { $0.hasPrefix(DocsReplicaCache.logPath("doc") + "/") }.sorted()
+ XCTAssertEqual(names.count, 3)
+ XCTAssertEqual(names.map { DocsReplicaCache.Segment.index(of: String($0.split(separator: "/").last!)) }, [0, 1, 2])
+ try disk.remove(names[1])
+ do { _ = try DocsReplicaCache(store: disk).load("doc"); XCTFail("A gap must not load") }
+ catch BlobStoreError.corrupt { }
+ XCTAssertTrue(disk.contents.keys.filter { $0.contains("/replica") }.isEmpty, "the whole replica is dropped")
+ let text = try await reopenText(disk, fallback: server)
+ XCTAssertEqual(text, "ABC", "the outbox restores every edit")
+ await replica.close()
+ }
+
+ func testCompactionContinuesTheNumberingAndSkipsWhatTheBaseHolds() 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: 0)
+ _ = try await lane.persist()
+ for text in ["A", "B"] { try await lane.enqueue(try await type(replica, text)); _ = try await lane.persist() }
+ // A compaction that stops after writing the base leaves its segments.
+ let before = disk.contents
+ let cache = DocsReplicaCache(store: disk)
+ try await cache.compact("doc", generation: 0)
+ let base = try XCTUnwrap(disk.contents[DocsReplicaCache.basePath("doc")])
+ let interrupted = MemoryBlobStore(before.merging([DocsReplicaCache.basePath("doc"): base]) { $1 })
+ let stored = try XCTUnwrap(DocsReplicaCache(store: interrupted).load("doc"))
+ XCTAssertEqual(stored.replica.segmentsFrom, 2)
+ XCTAssertTrue(stored.segments.isEmpty, "segments the base holds are skipped")
+ // New segments continue from the base, in both stores.
+ for store in [disk, interrupted] {
+ let next = DocsReplicaCache(store: store)
+ XCTAssertTrue(try next.append(Data([0, 0]), sequence: 5, key: "doc", generation: 0))
+ let loaded = try XCTUnwrap(next.load("doc"))
+ XCTAssertEqual(loaded.segments.map(\.index), [2])
+ XCTAssertEqual(loaded.sequence, 5)
+ }
+ let text = try await reopenText(interrupted)
+ XCTAssertEqual(text, "AB")
+ await replica.close()
+ }
}