oficina / sheets Public

Native: an ended session holds the edit queue and resends, instead of marking edits refused

Review #72 finding 5. A 401, the 303 to sign-in, or the guards' "Sign in
first." 403 (which the Oficina ID transport reports as 401) starts a
silent re-mint, but the batch was marked failed at once, the next queued
batch failed the same way before the re-mint landed, and nothing retried.

Now an ended session requeues the batch (it stays pending: Saving…) and
waits, 0.5 s doubling to 30 s, about a minute in all since Oficina ID
re-mints at most once a minute per team, then sends again with whatever
was queued meanwhile. Only a session that never comes back marks the
edits as not saved. Real refusals are marked at once, as before.

Tests: anEndedSessionHoldsTheQueueAndResends,
aSessionThatNeverReturnsIsMarkedInTheEnd.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 5e441f4a43ebd09a7ffb0910ead5ac7520ddc545 parent 7ad778d
3 files changed, +56 −0
  • native/apple/Sources/SheetsKit/SheetModel.swift +6 −0
  • native/apple/Sources/SheetsKit/SheetWrites.swift +22 −0
  • native/apple/Tests/SheetsKitTests/OptimisticEditTests.swift +28 −0
diff --git a/native/apple/Sources/SheetsKit/SheetModel.swift b/native/apple/Sources/SheetsKit/SheetModel.swift
index cf3b1d6..4d189dc 100644
--- a/native/apple/Sources/SheetsKit/SheetModel.swift
+++ b/native/apple/Sources/SheetsKit/SheetModel.swift
@@ -26,6 +26,12 @@ import RastrilloApple
/// on iOS a background task (a swipe away or a switch to another app does
/// not cut the send off), on the Mac no sudden termination. Returns the end.
@ObservationIgnored var keepAliveWhileSending: @MainActor () -> (@MainActor () -> Void) = SheetModel.keepAlive
+ /// How long to wait, attempt by attempt, for an ended session to be renewed
+ /// before an edit is marked as not saved (about a minute in all; Oficina ID
+ /// re-mints at most once a minute per team).
+ @ObservationIgnored var sessionRetryDelays: [Duration] = [
+ .milliseconds(500), .seconds(1), .seconds(2), .seconds(4), .seconds(8), .seconds(15), .seconds(30),
+ ]
/// 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.
diff --git a/native/apple/Sources/SheetsKit/SheetWrites.swift b/native/apple/Sources/SheetsKit/SheetWrites.swift
index 7053a55..bd95c18 100644
--- a/native/apple/Sources/SheetsKit/SheetWrites.swift
+++ b/native/apple/Sources/SheetsKit/SheetWrites.swift
@@ -135,6 +135,7 @@ struct PendingEdit: Sendable, Equatable {
/// One send per document at a time. Everything queued when a send starts
/// goes in it; edits made meanwhile wait and go together in the next.
private func sendQueued() async {
+ var sessionWaits = 0
while !Task.isCancelled {
let batch = pending.values.filter { $0.state == .queued }.sorted { $0.generation < $1.generation }
guard !batch.isEmpty else { return }
@@ -149,6 +150,10 @@ struct PendingEdit: Sendable, Equatable {
let chunk = try await wire.encode(writes, startingAt: offset)
let (bytes, status) = try await client.response(
source + "/cells/batch", method: "POST", body: chunk.data, maxBytes: 64 << 20)
+ // 401, or the 303 to sign-in (the Oficina ID transport also reports
+ // the guards' "Sign in first." 403 as 401): the session ended and is
+ // being renewed. That refuses nothing about the edit.
+ if status == 401 || status == 303 { throw NativeClientError.unauthorized }
guard (200..<300).contains(status) else {
throw NativeClientError.message(sheetsMacString("Not saved"))
}
@@ -158,9 +163,18 @@ struct PendingEdit: Sendable, Equatable {
resolve(batch[offset..<(offset + chunk.count)], failed: false)
offset += chunk.count
}
+ sessionWaits = 0
error = ""
if !isSending { notice = "Saved" }
if showTable { await loadTable() }
+ } catch NativeClientError.unauthorized where sessionWaits < sessionRetryDelays.count {
+ guard grid == source else { return abandon(batch) }
+ // Hold the queue while the session is renewed, then send again: the
+ // edits stay pending (Saving…), and edits made meanwhile join them.
+ requeue(batch[offset...])
+ let delay = sessionRetryDelays[sessionWaits]
+ sessionWaits += 1
+ try? await Task.sleep(for: delay)
} catch {
guard grid == source else { return abandon(batch) }
// The cells say so themselves, with Retry and Revert; editing goes on.
@@ -169,6 +183,14 @@ struct PendingEdit: Sendable, Equatable {
}
}
+ private func requeue(_ sent: ArraySlice<PendingEdit>) {
+ var next = pending
+ for edit in sent where next[edit.write.coordinate]?.generation == edit.generation {
+ next[edit.write.coordinate]?.state = .queued
+ }
+ pending = next
+ }
+
/// 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]) {
diff --git a/native/apple/Tests/SheetsKitTests/OptimisticEditTests.swift b/native/apple/Tests/SheetsKitTests/OptimisticEditTests.swift
index 65668ed..ceb0cac 100644
--- a/native/apple/Tests/SheetsKitTests/OptimisticEditTests.swift
+++ b/native/apple/Tests/SheetsKitTests/OptimisticEditTests.swift
@@ -270,3 +270,31 @@ private let b1 = Coordinate(r: 0, c: 1)
#expect(model.saveStatus == "Saved")
#expect(held == released && held >= 1, "every hold on the system was let go")
}
+
+// Review #72, finding 5: an ended session is renewed in the background; edits
+// wait for it and go again by themselves, and are not marked as refused.
+@MainActor @Test func anEndedSessionHoldsTheQueueAndResends() async {
+ let server = SheetServerFixture()
+ server.unauthorizeNext(2)
+ let model = fixtureModel(server)
+ model.sessionRetryDelays = [.milliseconds(20), .milliseconds(20), .milliseconds(20)]
+ type(model, a1, "first")
+ type(model, a2, "second")
+ #expect(!model.hasFailedEdits)
+ await model.settle()
+ #expect(!model.hasFailedEdits, "a renewal is not a refusal")
+ #expect(model.pending.isEmpty)
+ #expect(server.value(0, 0) == "first")
+ #expect(server.value(1, 0) == "second")
+}
+
+@MainActor @Test func aSessionThatNeverReturnsIsMarkedInTheEnd() async {
+ let server = SheetServerFixture()
+ server.unauthorizeNext(10)
+ let model = fixtureModel(server)
+ model.sessionRetryDelays = [.milliseconds(10), .milliseconds(10)]
+ type(model, a1, "x")
+ await model.settle()
+ #expect(model.editState(a1) == .failed)
+ #expect(server.batches.count == 3)
+}