oficina / docs Public

Docs native S1a: projection revisions and a dirty log in CRDTReplica

Spec 2026-11-22 §7 Design 1–2. The replica numbers every projection it
presents (presentedRevision, whoever asked) and logs, for the last 512,
the top-level ids each delta inserted or removed; a whole projection (the
`project` branch, for any reason: open, recovery, a reset, a delta that
would not apply) is logged as unknown.

presentation(…, since:) now returns a Presentation: the projection, its
revision and the blocks changed over exactly (since, revision], or nil
when the span is older than the log or crosses an unknown entry. One
call, so the main actor never asks the replica anything while applying.

CRDTNode and CRDTProjection become Equatable, for the full comparison.
ReplicaDirtyLogTests: revisions on every call, the exact span, Return,
overflow, recovery and delta.applied returning nil.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 24bd25d23034d6f640710a0a0f724238e3001838 parent 96fcd01
10 files changed, +232 −34
  • native/apple/Sources/DocsKit/CRDTProjection.swift +21 −3
  • native/apple/Sources/DocsKit/CRDTReplica.swift +67 −6
  • native/apple/Sources/DocsKit/DocsModel.swift +2 −2
  • native/apple/Tests/DocsKitTests/CRDTClipboardTests.swift +3 −2
  • native/apple/Tests/DocsKitTests/CRDTGenerationTests.swift +2 −2
  • native/apple/Tests/DocsKitTests/CRDTIncrementalTests.swift +3 −2
  • native/apple/Tests/DocsKitTests/CRDTSourceReuseTests.swift +10 −10
  • native/apple/Tests/DocsKitTests/DocumentListCommandTests.swift +2 −1
  • native/apple/Tests/DocsKitTests/RealtimeAuditTests.swift +6 −6
  • native/apple/Tests/DocsKitTests/ReplicaDirtyLogTests.swift +116 −0
diff --git a/native/apple/Sources/DocsKit/CRDTProjection.swift b/native/apple/Sources/DocsKit/CRDTProjection.swift
index d33c4b9..af9951e 100644
--- a/native/apple/Sources/DocsKit/CRDTProjection.swift
+++ b/native/apple/Sources/DocsKit/CRDTProjection.swift
@@ -1,6 +1,6 @@
import Foundation
-struct CRDTProjection: Decodable, Sendable {
+struct CRDTProjection: Decodable, Sendable, Equatable {
var children: [CRDTNode]
var canUndo: Bool
var canRedo: Bool
@@ -24,6 +24,22 @@ struct CRDTProjectionDelta: Decodable, Sendable {
let ops: [Operation]
let canUndo: Bool
let canRedo: Bool
+ /// The top-level block ids this delta inserts or removes from
+ /// `previous` (an edit in place is both, under one id).
+ func touched(in previous: CRDTProjection) -> Set<String> {
+ var ids = Set<String>(), at = 0
+ for operation in ops {
+ switch operation {
+ case .keep(let n): at += max(0, n)
+ case .remove(let n):
+ let end = min(previous.children.count, at + max(0, n))
+ if at < end { ids.formUnion(previous.children[at..<end].map(\.id)) }
+ at += max(0, n)
+ case .insert(let nodes): ids.formUnion(nodes.map(\.id))
+ }
+ }
+ return ids
+ }
/// nil unless it applies exactly to `previous`.
func applied(to previous: CRDTProjection) -> CRDTProjection? {
guard previous.children.count == base else { return nil }
@@ -45,7 +61,9 @@ struct CRDTProjectionDelta: Decodable, Sendable {
return CRDTProjection(children: children, canUndo: canUndo, canRedo: canRedo)
}
}
-struct CRDTNode: Decodable, Identifiable, Sendable {
+/// Equatable by structure, so a full comparison can tell which blocks of a
+/// new projection differ from the ones drawn (spec §7 Design 5).
+struct CRDTNode: Decodable, Identifiable, Sendable, Equatable {
let id: String
let type: String
var attrs: [String: String]?
@@ -53,7 +71,7 @@ struct CRDTNode: Decodable, Identifiable, Sendable {
var runs: [CRDTRun]?
var plainText: String { runs?.map(\.insert).joined() ?? children?.map(\.plainText).joined() ?? "" }
}
-struct CRDTRun: Decodable, Sendable {
+struct CRDTRun: Decodable, Sendable, Equatable {
var insert: String
var marks: [String: JSONValue]?
}
diff --git a/native/apple/Sources/DocsKit/CRDTReplica.swift b/native/apple/Sources/DocsKit/CRDTReplica.swift
index bd0cb7d..8a995d8 100644
--- a/native/apple/Sources/DocsKit/CRDTReplica.swift
+++ b/native/apple/Sources/DocsKit/CRDTReplica.swift
@@ -39,6 +39,39 @@ actor CRDTReplica {
/// 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?
+ /// Moves every time a projection becomes `presented`, whoever asked for
+ /// it (spec 2026-11-22 §7 Design 1). A text view that has drawn revision
+ /// r can ask what changed since r (`presentation(…, since:)`). Clearing
+ /// `presented` moves nothing: the next projection is then a whole one,
+ /// which the log records as unknown.
+ private(set) var presentedRevision: UInt64 = 0
+ /// For each recent revision, the top-level block ids its delta inserted
+ /// or removed (an edit in place is a remove and an insert of the same
+ /// id), or nil when it was a whole projection: then anything may have
+ /// changed. The last `dirtyLogLimit` revisions, oldest first.
+ private var dirtyLog: [(revision: UInt64, ids: Set<String>?)] = []
+ let dirtyLogLimit: Int
+ private func logPresented(_ ids: Set<String>?) {
+ presentedRevision &+= 1
+ dirtyLog.append((presentedRevision, ids))
+ // Drop the oldest half at once, so trimming is amortised O(1).
+ if dirtyLog.count > 2 * dirtyLogLimit { dirtyLog.removeFirst(dirtyLog.count - dirtyLogLimit) }
+ }
+ /// The blocks that changed over exactly the revisions (since, through]:
+ /// nil when that span reaches back past the log, or holds a whole
+ /// projection (open, a fresh source, recovery, a reset, a delta that
+ /// would not apply). Then only a full comparison can say.
+ func dirty(since: UInt64, through: UInt64) -> Set<String>? {
+ guard since < through else { return [] }
+ let kept = dirtyLog.suffix(dirtyLogLimit)
+ guard let oldest = kept.first?.revision, oldest <= since + 1 else { return nil }
+ var ids = Set<String>()
+ for entry in kept where entry.revision > since && entry.revision <= through {
+ guard let touched = entry.ids else { return nil }
+ ids.formUnion(touched)
+ }
+ return ids
+ }
private var sources: [UInt64: Sandbox] = [:]
/// Each source's state, to recreate it after it is retired or traps.
private var sourceStates: [UInt64: State] = [:]
@@ -82,7 +115,9 @@ actor CRDTReplica {
}
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 }
+ init(guid: String, unpersistedLimit: Int = 4 * 1024 * 1024, dirtyLogLimit: Int = 512) {
+ self.guid = guid; self.unpersistedLimit = unpersistedLimit; self.dirtyLogLimit = max(1, dirtyLogLimit)
+ }
struct PersistentState: Sendable {
let state: Data
let sequence: Int64
@@ -203,10 +238,14 @@ actor CRDTReplica {
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 }
+ if let next = delta.applied(to: presented) {
+ self.presented = next; logPresented(delta.touched(in: presented))
+ return next
+ }
}
+ // The whole document: an unknown entry, whatever the reason.
let projected = try JSONDecoder().decode(CRDTProjection.self, from: authority.invoke(["op": .string("project")]))
- presented = projected
+ presented = projected; logPresented(nil)
return projected
} catch { recover(); throw error }
}
@@ -281,12 +320,29 @@ actor CRDTReplica {
/// The replica settled without a rebuild (a catch-up integrated what it
/// parked): store it as the base on the next persist.
func markSettled() { settlements += 1 }
+ #if DEBUG
+ /// Tests only: change what the replica believes it last presented, so
+ /// the engine's next delta no longer applies to it.
+ func replacePresentedForTesting(_ transform: (CRDTProjection) -> CRDTProjection) { presented = presented.map(transform) }
+ #endif
func projection() throws -> CRDTProjection {
try authorityProjection(try currentAuthority())
}
+ /// A projection to publish, with what changed since the text view's
+ /// revision (spec §7 Design 2): `dirty` covers exactly
+ /// (`since`, `revision`], or is nil when only a full comparison can say.
+ /// Returned together, so the main actor never asks the replica anything
+ /// while it applies one.
+ struct Presentation: Sendable {
+ let generation: UInt64
+ let projection: CRDTProjection
+ let selection: NSRange
+ let revision: UInt64
+ let dirty: Set<String>?
+ }
/// 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)? {
+ func presentation(source generation: UInt64, selection: NSRange, allowReuse: Bool = false, since: UInt64 = 0) throws -> Presentation? {
let authority = try currentAuthority()
// Only the caller knows that this source has actually been rendered and
// has no pending candidate. An identical state is additionally required:
@@ -311,12 +367,17 @@ actor CRDTReplica {
throw error
}
}
- if reuse { return (generation, try authorityProjection(authority), resolved) }
+ func presented(_ generation: UInt64) throws -> Presentation {
+ let projection = try authorityProjection(authority)
+ return Presentation(generation: generation, projection: projection, selection: resolved,
+ revision: presentedRevision, dirty: dirty(since: since, through: presentedRevision))
+ }
+ if reuse { return try presented(generation) }
if lastGood.tail.count > 8 { try compact(authority) }
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)
+ return try presented(generation)
}
func retainGenerations(_ ids: Set<UInt64>) {
sources = sources.filter { ids.contains($0.key) }
diff --git a/native/apple/Sources/DocsKit/DocsModel.swift b/native/apple/Sources/DocsKit/DocsModel.swift
index 665603d..0bf7ee7 100644
--- a/native/apple/Sources/DocsKit/DocsModel.swift
+++ b/native/apple/Sources/DocsKit/DocsModel.swift
@@ -404,8 +404,8 @@ import RastrilloNative
guard documentEpoch == epoch, editing.isEmpty else { return }
do {
let source = renderedGeneration; let selected = selection
- if let (generation, projected, resolved) = try await replica.presentation(source: source, selection: selected, allowReuse: source == projectionGeneration), editing.isEmpty, source == renderedGeneration, selected == selection, !composing, documentEpoch == epoch, generation >= projectionGeneration {
- selection = resolved; projectionGeneration = generation; projection = projected
+ if let presented = try await replica.presentation(source: source, selection: selected, allowReuse: source == projectionGeneration), editing.isEmpty, source == renderedGeneration, selected == selection, !composing, documentEpoch == epoch, presented.generation >= projectionGeneration {
+ selection = presented.selection; projectionGeneration = presented.generation; projection = presented.projection
schedulePersistence()
}
} catch { if documentEpoch == epoch { errorKey = "native.recovered" } }
diff --git a/native/apple/Tests/DocsKitTests/CRDTClipboardTests.swift b/native/apple/Tests/DocsKitTests/CRDTClipboardTests.swift
index 408d490..cb4c398 100644
--- a/native/apple/Tests/DocsKitTests/CRDTClipboardTests.swift
+++ b/native/apple/Tests/DocsKitTests/CRDTClipboardTests.swift
@@ -9,7 +9,8 @@ final class CRDTClipboardTests: XCTestCase {
_ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")])
_ = try await replica.command(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("AB")])
let presentation = try await replica.presentation(source: 0, selection: NSRange(location: 1, length: 0))
- let (source, projection, _) = try XCTUnwrap(presentation)
+ let presented = try XCTUnwrap(presentation)
+ let (source, projection) = (presented.generation, presented.projection)
let content = NativeTextProjection.render(projection)
let blocks: [JSONValue] = [.object(["type": .string("paragraph"), "children": .array([.object(["type": .string("text"), "runs": .array([.object(["insert": .string("bold😀"), "marks": .object(["strong": .object([:])])])])])])])]
let pasted = try XCTUnwrap(DocumentClipboardInsertion.attributed(blocks: blocks, in: content, range: NSRange(location: 1, length: 0)))
@@ -33,7 +34,7 @@ final class CRDTClipboardTests: XCTestCase {
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)
+ let source = try XCTUnwrap(presentation?.generation)
for command: [String: JSONValue] in [
["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("-")],
["op": .string("display_autoformat"), "at": .number(0), "length": .number(1), "kind": .string("bullet_list"), "level": .number(0)],
diff --git a/native/apple/Tests/DocsKitTests/CRDTGenerationTests.swift b/native/apple/Tests/DocsKitTests/CRDTGenerationTests.swift
index 030601a..112791c 100644
--- a/native/apple/Tests/DocsKitTests/CRDTGenerationTests.swift
+++ b/native/apple/Tests/DocsKitTests/CRDTGenerationTests.swift
@@ -8,14 +8,14 @@ final class CRDTGenerationTests: XCTestCase {
_ = try await replica.open(update: Data())
_ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")])
let first = try await replica.presentation(source: 0, selection: NSRange(location: 0, length: 0))
- let source = try XCTUnwrap(first?.0)
+ let source = try XCTUnwrap(first?.generation)
var published = source
let characters = Array("Native text".unicodeScalars)
for (index, scalar) in characters.enumerated() {
_ = try await replica.command(["op": .string("display_edit"), "generation": .number(Double(source)), "at": .number(Double(index)), "length": .number(0), "text": .string(String(scalar))])
await replica.retainGenerations([source, published])
let candidate = try await replica.presentation(source: source, selection: NSRange(location: index + 1, length: 0))
- published = try XCTUnwrap(candidate?.0)
+ published = try XCTUnwrap(candidate?.generation)
// Deliberately withhold render acknowledgement: the next callback
// still belongs to the original displayed source, not this candidate.
}
diff --git a/native/apple/Tests/DocsKitTests/CRDTIncrementalTests.swift b/native/apple/Tests/DocsKitTests/CRDTIncrementalTests.swift
index 73b0a5a..349b910 100644
--- a/native/apple/Tests/DocsKitTests/CRDTIncrementalTests.swift
+++ b/native/apple/Tests/DocsKitTests/CRDTIncrementalTests.swift
@@ -35,7 +35,8 @@ import XCTest
_ = try await replica.command(paragraphs(40))
try await peer.open(update: try await replica.persistentState().state)
let first = try await replica.presentation(source: 0, selection: NSRange(location: 0, length: 0))
- var (source, projection, _) = try XCTUnwrap(first)
+ let opened = try XCTUnwrap(first)
+ var (source, projection) = (opened.generation, opened.projection)
var random = SystemRandomNumberGenerator()
var rendered = source
for step in 0..<120 {
@@ -54,7 +55,7 @@ import XCTest
}
await replica.retainGenerations([rendered, source])
guard let next = try await replica.presentation(source: rendered, selection: NSRange(location: at, length: 0), allowReuse: rendered == source) else { continue }
- (source, projection) = (next.0, next.1)
+ (source, projection) = (next.generation, next.projection)
// Acknowledge most renders, so both the reused and fresh paths run.
if step % 4 != 3 { rendered = source }
let expected = try await truth(replica)
diff --git a/native/apple/Tests/DocsKitTests/CRDTSourceReuseTests.swift b/native/apple/Tests/DocsKitTests/CRDTSourceReuseTests.swift
index c1a2175..a8d6b3b 100644
--- a/native/apple/Tests/DocsKitTests/CRDTSourceReuseTests.swift
+++ b/native/apple/Tests/DocsKitTests/CRDTSourceReuseTests.swift
@@ -8,13 +8,13 @@ final class CRDTSourceReuseTests: XCTestCase {
_ = try await replica.open(update: Data())
_ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")])
let initial = try await replica.presentation(source: 0, selection: NSRange(location: 0, length: 0))
- var source = try XCTUnwrap(initial?.0)
+ var source = try XCTUnwrap(initial?.generation)
let original = source
for index in 0..<100 {
_ = try await replica.command(["op": .string("display_edit"), "generation": .number(Double(source)), "at": .number(Double(index)), "length": .number(0), "text": .string("a")])
await replica.retainGenerations([source])
let next = try await replica.presentation(source: source, selection: NSRange(location: index + 1, length: 0), allowReuse: true)
- source = try XCTUnwrap(next?.0)
+ source = try XCTUnwrap(next?.generation)
}
XCTAssertEqual(source, original)
let clientData = try await replica.command(["op": .string("clients")])
@@ -25,7 +25,7 @@ final class CRDTSourceReuseTests: XCTestCase {
// A candidate without explicit rendered acknowledgement must remain fresh.
await replica.retainGenerations([source])
let unacknowledged = try await replica.presentation(source: source, selection: NSRange(location: 100, length: 0))
- XCTAssertNotEqual(unacknowledged?.0, source)
+ XCTAssertNotEqual(unacknowledged?.generation, source)
await replica.retainGenerations([source])
// A peer changes authority while displayed source stays at the old state.
@@ -35,21 +35,21 @@ final class CRDTSourceReuseTests: XCTestCase {
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)
+ let changed = try XCTUnwrap(divergent?.generation)
XCTAssertNotEqual(changed, source)
- XCTAssertEqual(divergent?.1.children.map(\.plainText).joined(), "peer " + String(repeating: "a", count: 100))
- XCTAssertEqual(divergent?.2.location, 105)
+ XCTAssertEqual(divergent?.projection.children.map(\.plainText).joined(), "peer " + String(repeating: "a", count: 100))
+ XCTAssertEqual(divergent?.selection.location, 105)
// Reusing the newly acknowledged live source does not merge undo ownership.
await replica.retainGenerations([changed])
_ = try await replica.command(["op": .string("display_edit"), "generation": .number(Double(changed)), "at": .number(105), "length": .number(0), "text": .string("!")])
let local = try await replica.presentation(source: changed, selection: NSRange(location: 106, length: 0), allowReuse: true)
- XCTAssertEqual(local?.0, changed)
+ XCTAssertEqual(local?.generation, changed)
_ = try await replica.command(["op": .string("undo")])
let undone = try await replica.presentation(source: changed, selection: NSRange(location: 106, length: 0), allowReuse: true)
- XCTAssertNotEqual(undone?.0, changed)
- XCTAssertFalse(undone?.1.children.map(\.plainText).joined().hasSuffix("!") ?? true)
- XCTAssertTrue(undone?.1.children.map(\.plainText).joined().hasPrefix("peer ") ?? false)
+ XCTAssertNotEqual(undone?.generation, changed)
+ XCTAssertFalse(undone?.projection.children.map(\.plainText).joined().hasSuffix("!") ?? true)
+ XCTAssertTrue(undone?.projection.children.map(\.plainText).joined().hasPrefix("peer ") ?? false)
await peer.close(); await replica.close()
}
}
diff --git a/native/apple/Tests/DocsKitTests/DocumentListCommandTests.swift b/native/apple/Tests/DocsKitTests/DocumentListCommandTests.swift
index 0eba3d3..737e27b 100644
--- a/native/apple/Tests/DocsKitTests/DocumentListCommandTests.swift
+++ b/native/apple/Tests/DocsKitTests/DocumentListCommandTests.swift
@@ -11,7 +11,8 @@ final class DocumentListCommandTests: XCTestCase {
_ = try await replica.command(JSONDecoder().decode([String: JSONValue].self, from: Data(paste.utf8)))
for type in ["ordered_list", "ordered_list"] {
let source = try await replica.presentation(source: 0, selection: NSRange(location: 0, length: 0))
- let (generation, projection, _) = try XCTUnwrap(source)
+ let presented = try XCTUnwrap(source)
+ let (generation, projection) = (presented.generation, presented.projection)
let paths = pathsToParagraphs(projection.children).filter { $0.contains { $0.type == "list_item" } }
let commands = DocumentCommands.listCommands(type: type, paths: paths)
_ = try await replica.command(["op": .string("batch"), "generation": .number(Double(generation)), "commands": .array(commands.map(JSONValue.object))])
diff --git a/native/apple/Tests/DocsKitTests/RealtimeAuditTests.swift b/native/apple/Tests/DocsKitTests/RealtimeAuditTests.swift
index fd84abd..8a06799 100644
--- a/native/apple/Tests/DocsKitTests/RealtimeAuditTests.swift
+++ b/native/apple/Tests/DocsKitTests/RealtimeAuditTests.swift
@@ -108,7 +108,7 @@ final class RealtimeAuditTests: XCTestCase {
do { _ = try await replica.open(update: bytes) } catch { Self.record(name, "local: open FAILED", [], note: "\(error)"); continue }
Self.record(name, "local: CRDTReplica.open", [Self.ms(t)], bytes: bytes.count)
guard let first = try await replica.presentation(source: 0, selection: NSRange(location: 0, length: 0)) else { XCTFail(); continue }
- var generation = first.0, projection = first.1
+ var generation = first.generation, projection = first.projection
t = .now
var rendered = NativeTextProjection.render(projection)
Self.record(name, "main: NativeTextProjection.render (cold)", [Self.ms(t)], note: "utf16=\(rendered.length)")
@@ -132,7 +132,7 @@ final class RealtimeAuditTests: XCTestCase {
t = .now
guard let next = try await replica.presentation(source: generation, selection: NSRange(location: at + 1, length: 0), allowReuse: true) else { failed = "presentation nil"; break }
present.append(Self.ms(t))
- generation = next.0; projection = next.1
+ generation = next.generation; projection = next.projection
} catch { failed = "\(error)"; break }
t = .now; let content = NativeTextProjection.render(projection); render.append(Self.ms(t))
t = .now; _ = rendered.isEqual(to: content); equal.append(Self.ms(t))
@@ -154,7 +154,7 @@ final class RealtimeAuditTests: XCTestCase {
await replica.retainGenerations([generation])
t = .now
guard let next = try await replica.presentation(source: generation, selection: NSRange(location: at, length: 0), allowReuse: false) else { break }
- fresh.append(Self.ms(t)); generation = next.0
+ fresh.append(Self.ms(t)); generation = next.generation
}
Self.record(name, "local: replica.presentation(fresh source)", fresh)
await replica.close()
@@ -170,7 +170,7 @@ final class RealtimeAuditTests: XCTestCase {
do { _ = try await replica.open(update: bytes); _ = try await peer.open(update: bytes) }
catch { Self.record(name, "remote: open FAILED", [], note: "\(error)"); continue }
guard let first = try await replica.presentation(source: 0, selection: NSRange(location: 0, length: 0)) else { continue }
- var generation = first.0, rendered = NativeTextProjection.render(first.1)
+ var generation = first.generation, rendered = NativeTextProjection.render(first.projection)
let storage = NSTextStorage(attributedString: rendered)
let peerText = NativeTextProjection.render(try await peer.projection())
var at = Self.middle(peerText) + 40
@@ -184,8 +184,8 @@ final class RealtimeAuditTests: XCTestCase {
await replica.retainGenerations([generation])
t = .now
guard let next = try await replica.presentation(source: generation, selection: NSRange(location: 10, length: 0), allowReuse: true) else { break }
- present.append(Self.ms(t)); generation = next.0
- t = .now; let content = NativeTextProjection.render(next.1); render.append(Self.ms(t))
+ present.append(Self.ms(t)); generation = next.generation
+ t = .now; let content = NativeTextProjection.render(next.projection); render.append(Self.ms(t))
t = .now; DocumentRenderReconciliation.apply(content, to: storage); reconcile.append(Self.ms(t))
rendered = content
} catch { Self.record(name, "remote: FAILED", [], note: "\(error)"); break }
diff --git a/native/apple/Tests/DocsKitTests/ReplicaDirtyLogTests.swift b/native/apple/Tests/DocsKitTests/ReplicaDirtyLogTests.swift
new file mode 100644
index 0000000..78c2a78
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/ReplicaDirtyLogTests.swift
@@ -0,0 +1,116 @@
+import Foundation
+import XCTest
+@testable import DocsKit
+
+/// The replica's revisions and dirty log (spec 2026-11-22 §7 Design 1–2,
+/// §11 "Replica dirty log").
+final class ReplicaDirtyLogTests: XCTestCase {
+ private func replica(limit: Int = 512) async throws -> CRDTReplica {
+ let replica = CRDTReplica(guid: "dirty-log", dirtyLogLimit: limit)
+ try await replica.open(update: Data())
+ _ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")])
+ let blocks: [JSONValue] = (0..<4).map { index in
+ .object(["type": .string("paragraph"), "children": .array([.object(["type": .string("text"), "runs": .array([.object(["insert": .string("Block \(index)"), "marks": .object([:])])])])])])
+ }
+ _ = try await replica.command(["op": .string("display_paste"), "at": .number(0), "length": .number(0), "blocks": .array(blocks)])
+ return replica
+ }
+ private func type(_ text: String, inBlock block: Int, of replica: CRDTReplica) async throws {
+ let projection = try await replica.projection()
+ let offset = projection.children.prefix(block).reduce(0) { $0 + $1.plainText.utf16.count + 1 }
+ _ = try await replica.command(["op": .string("display_edit"), "at": .number(Double(offset)), "length": .number(0), "text": .string(text)])
+ }
+
+ func testRevisionsAdvanceOnEveryProjectionWhoeverAsks() async throws {
+ let replica = try await replica()
+ let start = await replica.presentedRevision
+ _ = try await replica.projection()
+ _ = try await replica.projection()
+ let presented = try await XCTUnwrapAsync(try await replica.presentation(source: 0, selection: NSRange(location: 0, length: 0)))
+ let after = await replica.presentedRevision
+ XCTAssertEqual(after, start + 3)
+ XCTAssertEqual(presented.revision, after)
+ }
+
+ func testDirtyCoversExactlyTheRevisionsSince() async throws {
+ let replica = try await replica()
+ let opened = try await XCTUnwrapAsync(try await replica.presentation(source: 0, selection: NSRange(location: 0, length: 0)))
+ let ids = opened.projection.children.map(\.id)
+ // The first projection is a whole one: only a full comparison says.
+ XCTAssertNil(opened.dirty)
+ try await type("x", inBlock: 1, of: replica)
+ let first = try await XCTUnwrapAsync(try await replica.presentation(source: opened.generation, selection: NSRange(location: 0, length: 0), since: opened.revision))
+ XCTAssertEqual(first.dirty, [ids[1]])
+ try await type("y", inBlock: 3, of: replica)
+ // An extra projection between presentations: still in the log.
+ _ = try await replica.projection()
+ let second = try await XCTUnwrapAsync(try await replica.presentation(source: first.generation, selection: NSRange(location: 0, length: 0), since: first.revision))
+ XCTAssertEqual(second.dirty, [ids[3]])
+ // A text view still at the first revision gets the union.
+ let again = await replica.dirty(since: opened.revision, through: second.revision)
+ XCTAssertEqual(again, [ids[1], ids[3]])
+ // Nothing since the latest.
+ let none = await replica.dirty(since: second.revision, through: second.revision)
+ XCTAssertEqual(none, [])
+ // Spanning the whole projection at open: unknown.
+ let fromStart = await replica.dirty(since: 0, through: second.revision)
+ XCTAssertNil(fromStart)
+ }
+
+ func testStructuralEditsNameTheirBlocks() async throws {
+ let replica = try await replica()
+ let opened = try await XCTUnwrapAsync(try await replica.presentation(source: 0, selection: NSRange(location: 0, length: 0)))
+ let ids = opened.projection.children.map(\.id)
+ // A Return in block 1 splits it: block 1 changes and a new one appears.
+ let offset = opened.projection.children.prefix(1).reduce(0) { $0 + $1.plainText.utf16.count + 1 } + 3
+ _ = try await replica.command(["op": .string("display_edit"), "at": .number(Double(offset)), "length": .number(0), "text": .string("\n")])
+ let split = try await XCTUnwrapAsync(try await replica.presentation(source: opened.generation, selection: NSRange(location: 0, length: 0), since: opened.revision))
+ let inserted = Set(split.projection.children.map(\.id)).subtracting(ids)
+ XCTAssertEqual(inserted.count, 1)
+ XCTAssertEqual(split.dirty, Set([ids[1]]).union(inserted))
+ }
+
+ func testPastTheLogIsUnknown() async throws {
+ let replica = try await replica(limit: 4)
+ let opened = try await XCTUnwrapAsync(try await replica.presentation(source: 0, selection: NSRange(location: 0, length: 0)))
+ var latest = opened
+ for step in 0..<10 {
+ try await type("z", inBlock: step % 4, of: replica)
+ await replica.retainGenerations([latest.generation])
+ latest = try await XCTUnwrapAsync(try await replica.presentation(source: latest.generation, selection: NSRange(location: 0, length: 0), since: latest.revision))
+ XCTAssertNotNil(latest.dirty, "one revision back is always in the log")
+ }
+ let overflowed = await replica.dirty(since: opened.revision + 1, through: latest.revision)
+ XCTAssertNil(overflowed, "a span older than the log cannot be answered")
+ let recent = await replica.dirty(since: latest.revision - 2, through: latest.revision)
+ XCTAssertNotNil(recent)
+ }
+
+ func testAWholeProjectionIsUnknownWhateverTheReason() async throws {
+ // Recovery: an update that will not apply replaces the authority.
+ let replica = try await replica()
+ let opened = try await XCTUnwrapAsync(try await replica.presentation(source: 0, selection: NSRange(location: 0, length: 0)))
+ do { try await replica.apply(Data([0x01, 0xff, 0xff, 0xff, 0xff])); XCTFail("garbage applied") } catch {}
+ let recovered = try await XCTUnwrapAsync(try await replica.presentation(source: opened.generation, selection: NSRange(location: 0, length: 0), since: opened.revision))
+ XCTAssertNil(recovered.dirty, "after recovery the projection is whole")
+
+ // A delta that does not apply to what the replica presented.
+ try await type("q", inBlock: 2, of: replica)
+ await replica.retainGenerations([recovered.generation])
+ let before = try await XCTUnwrapAsync(try await replica.presentation(source: recovered.generation, selection: NSRange(location: 0, length: 0), since: recovered.revision))
+ XCTAssertNotNil(before.dirty)
+ await replica.replacePresentedForTesting { projection in
+ var changed = projection; changed.children.append(projection.children[0]); return changed
+ }
+ try await type("r", inBlock: 2, of: replica)
+ await replica.retainGenerations([before.generation])
+ let mismatched = try await XCTUnwrapAsync(try await replica.presentation(source: before.generation, selection: NSRange(location: 0, length: 0), since: before.revision))
+ XCTAssertNil(mismatched.dirty, "delta.applied returned nil: the full branch ran")
+ XCTAssertEqual(mismatched.projection.children.count, before.projection.children.count)
+ }
+}
+
+func XCTUnwrapAsync<T>(_ value: @autoclosure () async throws -> T?, file: StaticString = #filePath, line: UInt = #line) async throws -> T {
+ let unwrapped = try await value()
+ return try XCTUnwrap(unwrapped, file: file, line: line)
+}