graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(ios): serialize session sync so late writes cannot roll history back (#310)
justrachdcd85b779dcd
diff --git a/apps/ios/Graff/Sources/GraffAccount.swift b/apps/ios/Graff/Sources/GraffAccount.swiftindex 9c969121..3c3d1509 100644--- a/apps/ios/Graff/Sources/GraffAccount.swift+++ b/apps/ios/Graff/Sources/GraffAccount.swift@@ -339,7 +339,19 @@ enum AppSessionSync {}}- // Fire-and-forget: history sync must never block or break the chat.+ // #310: every write is stamped with a monotonic revision HERE, on the main+ // actor, in the order the caller made it. Detaching first and numbering+ // later would let two saves reach the sync engine in either order, which+ // is the bug this is guarding against.+ @MainActor private static var revisionCounter: UInt64 = 0+ @MainActor private static func nextRevision() -> UInt64 {+ revisionCounter += 1+ return revisionCounter+ }++ // Still fire-and-forget from the caller's point of view — history sync must+ // never block or break the chat — but no longer unordered (#310).+ @MainActorstatic func save(_ session: AgentSession) {guard Gateway.apiKey != nil else { return }let id = session.id.uuidString.lowercased()@@ -347,9 +359,131 @@ enum AppSessionSync {let title = session.titlelet model = session.modellet sandboxID = session.cube?.sandboxID- Task.detached {- try? await Gateway.putAppSession(id: id, title: title, model: model,- sandboxID: sandboxID, transcript: transcript)+ let revision = nextRevision()+ Task {+ await AppSessionSyncEngine.shared.save(id: id, revision: revision, title: title,+ model: model, sandboxID: sandboxID,+ transcript: transcript)+ }+ }++ @MainActor+ static func delete(_ sessionID: UUID) {+ guard Gateway.apiKey != nil else { return }+ let id = sessionID.uuidString.lowercased()+ let revision = nextRevision()+ Task { await AppSessionSyncEngine.shared.delete(id: id, revision: revision) }+ }+}++// #310: session persistence used to be a bare `Task.detached` per save, with no+// ordering, no revision and no relationship to the equally detached DELETE. An+// older PUT could land after a newer one and roll the synced transcript+// backward, and a delayed PUT could land after a DELETE and resurrect a session+// the user had removed. The gateway's /v1/app/sessions PUT takes no If-Match or+// version — there is nothing to make conditional — so the invariant is enforced+// entirely on this side:+//+// * writes for one session id run strictly one at a time, in issue order;+// * a payload that has been superseded while it waited its turn is dropped+// rather than sent, so an older transcript never reaches the gateway;+// * a deleted id is tombstoned, which drops every queued and future save for+// it, and the DELETE is chained behind any PUT already in flight so the+// row cannot come back.+//+// Server-side gap: without a conditional PUT, a second device racing this one+// is still last-writer-wins. That needs a gateway revision/If-Match, which does+// not exist yet.+// One write as it reaches the wire. `transcript == nil` is a delete.+struct AppSessionWrite: Sendable {+ let id: String+ let title: String+ let model: String+ let sandboxID: String?+ let transcript: String?+}++actor AppSessionSyncEngine {+ static let shared = AppSessionSyncEngine()++ // The gateway leg, injectable so the ordering invariants can be asserted+ // against a deterministically delayed transport (--autotest-sync).+ static let gatewayTransport: @Sendable (AppSessionWrite) async -> Void = { w in+ if let transcript = w.transcript {+ try? await Gateway.putAppSession(id: w.id, title: w.title, model: w.model,+ sandboxID: w.sandboxID, transcript: transcript)+ } else {+ try? await Gateway.deleteAppSession(w.id)+ }+ }++ private let transport: @Sendable (AppSessionWrite) async -> Void+ init(transport: @escaping @Sendable (AppSessionWrite) async -> Void = AppSessionSyncEngine.gatewayTransport) {+ self.transport = transport+ }++ // Newest revision issued per session id; anything older is obsolete.+ private var latest: [String: UInt64] = [:]+ // Tail of each session's serial chain, so the next operation can await it.+ private var chain: [String: Task<Void, Never>] = [:]+ private var chainGeneration: [String: UInt64] = [:]+ private var generationCounter: UInt64 = 0+ private var tombstones: Set<String> = []++ func save(id: String, revision: UInt64, title: String, model: String,+ sandboxID: String?, transcript: String) {+ guard !tombstones.contains(id) else { return }+ // Out-of-order arrival at the actor is fine: revisions were stamped in+ // call order, so an older one simply never becomes the latest.+ guard revision > (latest[id] ?? 0) else { return }+ latest[id] = revision+ let write = AppSessionWrite(id: id, title: title, model: model,+ sandboxID: sandboxID, transcript: transcript)+ let send = transport+ link(id) { [self] in+ // Superseded while queued — sending it would roll the gateway back.+ guard await isCurrent(id, revision) else { return }+ await send(write)}}++ func delete(id: String, revision: UInt64) {+ // Tombstone first: queued saves are already obsolete, and any save+ // issued later (a stale chat view finishing a turn) is refused above.+ tombstones.insert(id)+ latest[id] = revision+ let write = AppSessionWrite(id: id, title: "", model: "", sandboxID: nil, transcript: nil)+ let send = transport+ link(id) { await send(write) }+ }++ // Wait until every queued write has run. Only the in-process harness needs+ // this; the app never blocks on sync.+ func quiesce() async {+ while let task = chain.values.first { await task.value }+ }++ private func isCurrent(_ id: String, _ revision: UInt64) -> Bool {+ !tombstones.contains(id) && latest[id] == revision+ }++ // Append to this session's serial chain. Different sessions still overlap;+ // only same-id writes are ordered against each other.+ private func link(_ id: String, _ work: @escaping @Sendable () async -> Void) {+ let previous = chain[id]+ generationCounter += 1+ let generation = generationCounter+ chainGeneration[id] = generation+ chain[id] = Task { [self] in+ await previous?.value+ await work()+ release(id, generation)+ }+ }++ private func release(_ id: String, _ generation: UInt64) {+ guard chainGeneration[id] == generation else { return } // a newer write owns the chain+ chain[id] = nil+ chainGeneration[id] = nil+ }}diff --git a/apps/ios/Graff/Sources/GraffApp.swift b/apps/ios/Graff/Sources/GraffApp.swiftindex 28807c55..e105739b 100644--- a/apps/ios/Graff/Sources/GraffApp.swift+++ b/apps/ios/Graff/Sources/GraffApp.swift@@ -22,6 +22,10 @@ struct GraffApp: App {// Turn-model invariants (#307/#285/#309) checked in memory —// no network, no taps, so it runs anywhere the app launches.TurnStateCheckView()+ } else if CommandLine.arguments.contains("--autotest-sync") {+ // Session-sync ordering invariants (#310) against a delayed+ // in-memory transport — deterministic, no network, no taps.+ SyncOrderCheckView()} else if CommandLine.arguments.contains("--autotest-compose") {// Render the new-session compose sheet standalone for visual QA.NewSessionView { _ in }@@ -164,6 +168,99 @@ struct TurnStateCheckView: View {}}+// Launch with `--autotest-sync` to reproduce #310's delayed-response scenarios+// against an in-memory transport that stalls the FIRST write it receives — the+// exact "delay the PUT produced after turn 1" setup from the issue — and assert+// what actually reached the wire. Gates on SYNCORDER-PASS.+struct SyncOrderCheckView: View {+ @State private var report = "running…"+ var body: some View {+ Text(report)+ .font(.system(.footnote, design: .monospaced))+ .padding()+ .task { report = await Self.run() }+ }++ // Records every write in the order it reached the transport, holding the+ // first one open long enough that anything issued after it must queue.+ private actor Recorder {+ private var seen = 0+ private var log: [String] = []+ func apply(_ write: AppSessionWrite) async {+ seen += 1+ if seen == 1 { try? await Task.sleep(nanoseconds: 200_000_000) }+ log.append(write.transcript ?? "DELETE")+ }+ func applied() -> [String] { log }+ }++ static func run() async -> String {+ var lines: [String] = []+ func check(_ name: String, _ ok: Bool) { lines.append((ok ? "ok " : "FAIL ") + name) }++ func harness() -> (Recorder, AppSessionSyncEngine) {+ let recorder = Recorder()+ return (recorder, AppSessionSyncEngine(transport: { await recorder.apply($0) }))+ }+ func put(_ engine: AppSessionSyncEngine, _ rev: UInt64, _ body: String) async {+ await engine.save(id: "s1", revision: rev, title: "t", model: "m",+ sandboxID: nil, transcript: body)+ }++ // save/save: the delayed turn-1 PUT must not be the last word.+ var (recorder, engine) = harness()+ await put(engine, 1, "turn-1")+ await put(engine, 2, "turn-2")+ await engine.quiesce()+ var applied = await recorder.applied()+ check("the newer transcript wins the save/save race", applied.last == "turn-2")+ check("writes reach the gateway in issue order", applied == ["turn-1", "turn-2"])++ // An obsolete save queued behind a slow one is dropped, not sent.+ (recorder, engine) = harness()+ await put(engine, 1, "turn-1")+ await put(engine, 2, "turn-2")+ await put(engine, 3, "turn-3")+ await engine.quiesce()+ applied = await recorder.applied()+ check("a superseded queued save is never sent", applied == ["turn-1", "turn-3"])++ // An out-of-order arrival (older revision, later call) is refused.+ (recorder, engine) = harness()+ await put(engine, 5, "newer")+ await put(engine, 2, "older")+ await engine.quiesce()+ applied = await recorder.applied()+ check("an older revision never clobbers a newer one", applied == ["newer"])++ // save/delete: the tombstone survives a delayed PUT.+ (recorder, engine) = harness()+ await put(engine, 1, "turn-1")+ await engine.delete(id: "s1", revision: 2)+ await put(engine, 3, "late-save")+ await engine.quiesce()+ applied = await recorder.applied()+ check("DELETE is ordered after the in-flight PUT", applied == ["turn-1", "DELETE"])+ check("a late save never resurrects a deleted session", !applied.contains("late-save"))++ // Different sessions are independent — serialization is per id.+ (recorder, engine) = harness()+ await put(engine, 1, "a")+ await engine.save(id: "s2", revision: 2, title: "t", model: "m",+ sandboxID: nil, transcript: "b")+ await engine.quiesce()+ applied = await recorder.applied()+ check("a second session is not blocked by the first",+ applied.sorted() == ["a", "b"])++ let failures = lines.filter { $0.hasPrefix("FAIL") }.count+ let summary = failures == 0 ? "SYNCORDER-PASS" : "SYNCORDER-FAIL (\(failures))"+ print(summary)+ for l in lines { print(l) }+ return ([summary] + lines).joined(separator: "\n")+ }+}+// MARK: - Liquid Glass helpersextension View {func glassPanel(_ radius: CGFloat = 22) -> some View {diff --git a/apps/ios/Graff/Sources/SessionsListView.swift b/apps/ios/Graff/Sources/SessionsListView.swiftindex a718b325..b66d138b 100644--- a/apps/ios/Graff/Sources/SessionsListView.swift+++ b/apps/ios/Graff/Sources/SessionsListView.swift@@ -51,10 +51,10 @@ struct SessionsListView: View {.onDelete { offsets inlet doomed = offsets.map { sessions[$0] }sessions.remove(atOffsets: offsets)- for s in doomed {- let id = s.id.uuidString.lowercased()- Task.detached { try? await Gateway.deleteAppSession(id) }- }+ // #310: routed through the sync engine so the DELETE is+ // ordered against this session's in-flight saves and the id+ // is tombstoned — a late PUT can no longer resurrect it.+ for s in doomed { AppSessionSync.delete(s.id) }}}.navigationTitle("Sessions")