Native: an edit is never sent to, or stuck on, a sheet it was not made on
Review #72 finding 1. open() awaited the new page while write() no longer checked busy, so a cell committed meanwhile was sent against the old sheet; both grid-changed exits in the sender then left the batch .sending for ever: a phantom value on the new sheet and Close, Quit and open() refusing until a force quit. write() now refuses while a sheet is opening, open() clears pending edits and the draft as it replaces the page, and a send that finds its sheet gone drops its edits instead of leaving them sending. Tests: anEditDuringASheetSwitchIsNotSentToEitherSheet and aSendForASheetNoLongerShownIsDroppedNotStuck fail without this.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4 files changed,
+107
−10
native/apple/Sources/SheetsKit/SheetModel.swift+8 −1native/apple/Sources/SheetsKit/SheetWrites.swift+14 −2native/apple/Tests/SheetsKitTests/OptimisticEditTests.swift+38 −0native/apple/Tests/SheetsKitTests/SheetServerFixture.swift+47 −7
diff --git a/native/apple/Sources/SheetsKit/SheetModel.swift b/native/apple/Sources/SheetsKit/SheetModel.swift| index ad0624e..bd9653b 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetModel.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetModel.swift |
| @@ -22,6 +22,8 @@ import RastrilloApple |
| var pending: [Coordinate: PendingEdit] = [:] |
| @ObservationIgnored var editGeneration: UInt64 = 0 |
| @ObservationIgnored var sender: Task<Void, Never>? |
| + /// True while `open` replaces the sheet: no edit may start against either. |
| + @ObservationIgnored var opening = false |
| /// An edit being typed, or one not yet acknowledged by the server. |
| var hasUnconfirmedChanges: Bool { dirty || !pending.isEmpty } |
| var busy = false |
| @@ -72,10 +74,15 @@ import RastrilloApple |
| return |
| } |
| busy = true |
| - defer { busy = false } |
| + opening = true |
| + defer { busy = false; opening = false } |
| do { |
| let value: SheetPage = try await client.request("/sheets/\(sheet.ID)") |
| clearCopyProvenance() |
| + // Pending edits belong to the sheet they were made on; none survive it. |
| + pending = [:] |
| + originalDraft = "" |
| + draft = "" |
| page = value |
| version = 0 |
| cells = [:] |
diff --git a/native/apple/Sources/SheetsKit/SheetWrites.swift b/native/apple/Sources/SheetsKit/SheetWrites.swift| index 290574a..4e3984c 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetWrites.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetWrites.swift |
| @@ -33,6 +33,8 @@ struct PendingEdit: Sendable, Equatable { |
| /// the answer from the server arrives later and never blocks editing. |
| @discardableResult func write(_ writes: [CellWrite]) -> Bool { |
| guard mayWrite else { return false } |
| + // Mid-switch, an edit could only be sent to the sheet being left. |
| + guard !opening else { return false } |
| guard writes.allSatisfy({ $0.raw.utf8.count <= 8192 }) else { |
| error = "A cell exceeds the input size limit. Nothing was changed." |
| return false |
| @@ -121,7 +123,7 @@ struct PendingEdit: Sendable, Equatable { |
| throw NativeClientError.message(sheetsMacString("Not saved")) |
| } |
| let response = try await wire.decode(bytes) |
| - guard grid == source else { return } |
| + guard grid == source else { return abandon(batch) } |
| await accept(response) |
| resolve(batch[offset..<(offset + chunk.count)], failed: false) |
| offset += chunk.count |
| @@ -130,13 +132,23 @@ struct PendingEdit: Sendable, Equatable { |
| notice = "Saved" |
| if showTable { await loadTable() } |
| } catch { |
| - guard grid == source else { return } |
| + guard grid == source else { return abandon(batch) } |
| // The cells say so themselves, with Retry and Revert; editing goes on. |
| resolve(batch[offset...], failed: true) |
| } |
| } |
| } |
| + /// The sheet changed under a send: its edits were for the old sheet, and |
| + /// must neither paint on the new one nor stay "sending" for ever. |
| + private func abandon(_ batch: [PendingEdit]) { |
| + var next = pending |
| + for edit in batch where next[edit.write.coordinate]?.generation == edit.generation { |
| + next[edit.write.coordinate] = nil |
| + } |
| + pending = next |
| + } |
| + |
| /// Settles the edits a send carried, unless the person edited the cell again |
| /// while it was in flight: that newer edit is still queued and stays. |
| private func resolve(_ sent: ArraySlice<PendingEdit>, failed: Bool) { |
diff --git a/native/apple/Tests/SheetsKitTests/OptimisticEditTests.swift b/native/apple/Tests/SheetsKitTests/OptimisticEditTests.swift| index 5c44b24..901df57 100644 |
| --- a/native/apple/Tests/SheetsKitTests/OptimisticEditTests.swift |
| +++ b/native/apple/Tests/SheetsKitTests/OptimisticEditTests.swift |
| @@ -205,3 +205,41 @@ private let b1 = Coordinate(r: 0, c: 1) |
| let order = server.requests.filter { $0.hasSuffix("/undo") || $0.hasSuffix("/cells/batch") } |
| #expect(order.last?.hasSuffix("/undo") == true, "\(order)") |
| } |
| + |
| +// Review #72, finding 1: an edit must never be sent to, or painted on, a |
| +// sheet it was not made on, and a send must never be left "sending". |
| +@MainActor @Test func anEditDuringASheetSwitchIsNotSentToEitherSheet() async { |
| + let server = SheetServerFixture() |
| + server.holdPages() |
| + let model = fixtureModel(server) |
| + let opening = Task { await model.open(SheetSummary(ID: 2, Title: "", TabID: 0, TabName: "")) } |
| + #expect(await eventually { server.requests.contains("GET /sheets/2") }) |
| + model.select(a1) |
| + model.draft = "typed mid-switch" |
| + model.commit() |
| + #expect(model.pending.isEmpty, "an edit started while the sheet is being replaced") |
| + server.releasePages() |
| + await opening.value |
| + #expect(model.page?.Sheet.ID == 2) |
| + #expect(model.displayCell(a1) == nil, "no phantom value on the new sheet") |
| + #expect(!model.hasUnconfirmedChanges, "close, quit and open would refuse for ever") |
| + #expect(server.batches.isEmpty) |
| +} |
| + |
| +@MainActor @Test func aSendForASheetNoLongerShownIsDroppedNotStuck() async { |
| + let server = SheetServerFixture() |
| + server.hold() |
| + let model = fixtureModel(server) |
| + type(model, a1, "old sheet") |
| + #expect(await eventually { server.heldCount == 1 }) |
| + // The page is replaced while the send is in flight. |
| + model.page = SheetPage( |
| + Sheet: SheetSummary(ID: 2, Title: "Other", TabID: 2, TabName: "Tab"), Rows: 6, Cols: 4, Truncated: false, |
| + MayWrite: true, MayComment: true, MayShare: false, FillSwatches: [], InkSwatches: [], NumberFormats: [], |
| + Warned: nil) |
| + server.release(stopHolding: true) |
| + await model.settle() |
| + #expect(model.pending.isEmpty, "left .sending for ever") |
| + #expect(model.displayCell(a1) == nil) |
| + #expect(!model.hasUnconfirmedChanges) |
| +} |
diff --git a/native/apple/Tests/SheetsKitTests/SheetServerFixture.swift b/native/apple/Tests/SheetsKitTests/SheetServerFixture.swift| index 99719b5..110f2e3 100644 |
| --- a/native/apple/Tests/SheetsKitTests/SheetServerFixture.swift |
| +++ b/native/apple/Tests/SheetsKitTests/SheetServerFixture.swift |
| @@ -16,6 +16,10 @@ final class SheetServerFixture: NativeTransport, @unchecked Sendable { |
| private var holding = false |
| private var waiting: [CheckedContinuation<Void, Never>] = [] |
| private var refusals = 0 |
| + private var unauthorized = 0 |
| + private var losses = 0 |
| + private var holdingPages = false |
| + private var waitingPages: [CheckedContinuation<Void, Never>] = [] |
| private var stamp: UInt64 = 0 |
| private var sent: [[Sent]] = [] |
| private var requested: [String] = [] |
| @@ -39,6 +43,20 @@ final class SheetServerFixture: NativeTransport, @unchecked Sendable { |
| next?.resume() |
| } |
| func refuseNext(_ count: Int = 1) { lock.withLock { refusals = count } } |
| + /// The next batches meet an ended session: 401, applied nowhere. |
| + func unauthorizeNext(_ count: Int = 1) { lock.withLock { unauthorized = count } } |
| + /// The next batch is applied, then its answer is lost on the way back. |
| + func loseNextResponse() { lock.withLock { losses = 1 } } |
| + /// Opening a sheet (GET /sheets/<id>) waits for `releasePages`. |
| + func holdPages() { lock.withLock { holdingPages = true } } |
| + func releasePages() { |
| + let all: [CheckedContinuation<Void, Never>] = lock.withLock { |
| + holdingPages = false |
| + defer { waitingPages = [] } |
| + return waitingPages |
| + } |
| + all.forEach { $0.resume() } |
| + } |
| static func display(_ raw: String) -> String { raw.hasPrefix("=") ? "computed" : raw } |
| @@ -56,6 +74,17 @@ final class SheetServerFixture: NativeTransport, @unchecked Sendable { |
| -> NativeResponse |
| { |
| lock.withLock { requested.append(method + " " + (path.split(separator: "?").first.map(String.init) ?? path)) } |
| + if method == "GET", path.hasPrefix("/sheets/"), let id = UInt64(path.dropFirst("/sheets/".count)) { |
| + await withCheckedContinuation { continuation in |
| + let wait = lock.withLock { () -> Bool in |
| + if holdingPages { waitingPages.append(continuation) } |
| + return holdingPages |
| + } |
| + if !wait { continuation.resume() } |
| + } |
| + let page = #"{"Sheet":{"ID":\#(id),"Title":"Sheet \#(id)","TabID":\#(id),"TabName":"Tab"},"Rows":6,"Cols":4,"Truncated":false,"MayWrite":true,"MayComment":true,"MayShare":false,"FillSwatches":[],"InkSwatches":[],"NumberFormats":[]}"# |
| + return NativeResponse(data: Data(page.utf8), status: 200) |
| + } |
| if method == "GET", path.contains("/cells?") { |
| // A snapshot, as a refetch after a version gap reads it. |
| return lock.withLock { |
| @@ -71,14 +100,19 @@ final class SheetServerFixture: NativeTransport, @unchecked Sendable { |
| struct Batch: Decodable { let cells: [Wire] } |
| struct Wire: Decodable { let r: Int; let c: Int; let raw: String } |
| let batch = try JSONDecoder().decode(Batch.self, from: body).cells.map { Sent(r: $0.r, c: $0.c, raw: $0.raw) } |
| - let mustWait = lock.withLock { () -> Bool in |
| - sent.append(batch) |
| - return holding |
| - } |
| - if mustWait { |
| - await withCheckedContinuation { continuation in lock.withLock { waiting.append(continuation) } } |
| + await withCheckedContinuation { continuation in |
| + let wait = lock.withLock { () -> Bool in |
| + sent.append(batch) |
| + if holding { waiting.append(continuation) } |
| + return holding |
| + } |
| + if !wait { continuation.resume() } |
| } |
| - return lock.withLock { |
| + let outcome = lock.withLock { () -> NativeResponse? in |
| + if unauthorized > 0 { |
| + unauthorized -= 1 |
| + return NativeResponse(data: Data(), status: 401) |
| + } |
| if refusals > 0 { |
| refusals -= 1 |
| return NativeResponse(data: Data(), status: 503) |
| @@ -88,9 +122,15 @@ final class SheetServerFixture: NativeTransport, @unchecked Sendable { |
| let changed = batch.map { |
| #"{"r":\#($0.r),"c":\#($0.c),"raw":"\#($0.raw)","display":"\#(Self.display($0.raw))"}"# |
| }.joined(separator: ",") |
| + if losses > 0 { |
| + losses -= 1 |
| + return nil |
| + } |
| return NativeResponse( |
| data: Data(#"{"version":\#(stamp),"stamps":\#(batch.count),"cells":[\#(changed)]}"#.utf8), status: 200) |
| } |
| + guard let outcome else { throw NativeClientError.offline(.networkConnectionLost) } |
| + return outcome |
| } |
| func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) |
| async throws |