fix(sessions): re-review fixes for MMDB-2925 (PR #29 review round 2)

Round 2 of adversarial review confirmed defects 2,3,4,5,7 fixed and
raised three new ones; all three are fixed here, plus the guard-message
nit.

NEW-1 (the FAIL driver): the OneDrive send path overwrote the truthful
status from handleDidShareItems with its own success text, silently
dropping an archive failure and any state-refresh problem. The seam now
takes the caller's success summary and composes ONE truthful message:
summary (the share itself did complete) + archive error if any + refresh
problems if any. Both callers (AirDrop delegate, OneDrive) pass their
summary; the OneDrive text is never clobbered.

NEW-2: if the replacement open session could not be created after the
archive rename (disk full), the store kept reporting the already-archived
session as the open one. SpoolStore now has a truth guard
(ensureOpenSession): the open session is verified to really exist on disk
and be in state .open before any read/mutate; a stale one is replaced by
a genuinely fresh session, or the call fails loudly. Never a lie.

NEW-3: archivedSessions() read the folder tie-break dates AFTER
reconciliation, so a healed same-second session could bump its own
modification date and outrank a genuinely newer peer. The dates are now
read BEFORE reconciling.

Nit: the startNewSession guard now reports "A new session is already
being started." when the refusal is about a concurrent session start,
not a send.

Also added REDLINE_SELFTEST_PHASE=sendtruth (mirroring the existing
=onedrive escape hatch) so the SEND-TRUTH selftest can run without the
picker chain's display-dependent REGION-PERSIST phase.

Evidence: 136 swift tests pass (2 new: OneDrive summary survives
archiving; stale open session never returned as current).
REDLINE_SELFTEST_PHASE=sendtruth -> SEND-TRUTH PASS.
REDLINE_SELFTEST_PHASE=onedrive -> ONEDRIVE-SELFTEST PASS against the
real OneDrive sync root.
This commit is contained in:
Claude Fable 5
2026-10-11 13:58:45 +04:00
parent eaa5bd5884
commit 0506ce04e9
7 changed files with 148 additions and 30 deletions
+47 -17
View File
@@ -35,9 +35,28 @@ public actor SpoolStore {
}
/// The session currently accepting captures. Cheap accessor — all reconciliation already
/// happened once, inside init.
/// happened once, inside init. A truth guard: if the stored session is no longer really
/// open on disk (its directory was archived away and the replacement session could not
/// be created — e.g. disk full), a fresh session is minted, or the call fails loudly.
/// It never returns an already-archived session as the open one.
public func currentSession() throws -> CaptureSession {
openSession
try ensureOpenSession()
}
/// Mint-or-verify the open session: returns the session that is REALLY open on disk,
/// creating a fresh one when the stored one is stale (archived away mid-run). Throws
/// loudly when no new session can be created either — never substitutes a lie.
private func ensureOpenSession() throws -> CaptureSession {
let dir = paths.sessionDirectory(openSession.id)
if openSession.state == .open && FileManager.default.fileExists(atPath: dir.path) {
return openSession
}
let staleID = openSession.id.uuidString
Log.spool.error(
"The stored open session \(staleID, privacy: .public) is not really open on disk; starting a fresh one.")
let fresh = try Self.createFreshSession(paths: paths)
openSession = fresh
return fresh
}
/// Writes `pngData` to disk and fsyncs it BEFORE the manifest is touched, then updates and
@@ -47,17 +66,18 @@ public actor SpoolStore {
pngData: Data, pixelWidth: Int, pixelHeight: Int,
scale: CGFloat, capturedAt: Date
) throws -> Capture {
let open = try ensureOpenSession()
let captureID = UUID()
let sequence = openSession.nextSequence
let sequence = open.nextSequence
let fileName = "\(String(format: "%03d", sequence))-\(Self.hexSuffix(captureID)).png"
let sessionDir = paths.sessionDirectory(openSession.id)
let sessionDir = paths.sessionDirectory(open.id)
let fileURL = sessionDir.appendingPathComponent(fileName)
try AtomicFile.write(pngData, to: fileURL)
let capture = Capture(
id: captureID, sequence: sequence, fileName: fileName,
pixelWidth: pixelWidth, pixelHeight: pixelHeight,
scale: scale, capturedAt: capturedAt)
let updated = openSession.appending(capture)
let updated = open.appending(capture)
try AtomicFile.writeJSON(updated, to: sessionDir.appendingPathComponent("session.json"))
openSession = updated
return capture
@@ -71,12 +91,13 @@ public actor SpoolStore {
/// `removed/` — is pruned. That is the requested retention policy (Ben, 2026-10-11),
/// not this remove path.)
public func remove(captureID: UUID) throws -> CaptureSession {
guard let capture = openSession.captures.first(where: { $0.id == captureID }) else {
let open = try ensureOpenSession()
guard let capture = open.captures.first(where: { $0.id == captureID }) else {
throw ShotdeckError.spoolWriteFailed(
path: paths.sessionDirectory(openSession.id).path,
path: paths.sessionDirectory(open.id).path,
underlying: "capture \(captureID) is not in the open session")
}
let sessionDir = paths.sessionDirectory(openSession.id)
let sessionDir = paths.sessionDirectory(open.id)
let removedDir = sessionDir.appendingPathComponent("removed", isDirectory: true)
do {
try FileManager.default.createDirectory(at: removedDir, withIntermediateDirectories: true)
@@ -101,12 +122,13 @@ public actor SpoolStore {
/// pdfFileName, starts a fresh empty open session, and applies session retention.
/// Returns the archived one.
public func archiveCurrent(pdfFileName: String) throws -> CaptureSession {
guard !openSession.isEmpty else {
let open = try ensureOpenSession()
guard !open.isEmpty else {
throw ShotdeckError.spoolWriteFailed(
path: paths.sessionDirectory(openSession.id).path,
path: paths.sessionDirectory(open.id).path,
underlying: "cannot archive an empty session")
}
let archived = try moveOpenSessionToArchive(openSession.markArchived(pdfFileName: pdfFileName))
let archived = try moveOpenSessionToArchive(open.markArchived(pdfFileName: pdfFileName))
openSession = try Self.createFreshSession(paths: paths)
applyRetention()
return archived
@@ -120,12 +142,13 @@ public actor SpoolStore {
/// simply replaced — there is nothing to keep. Returns the archived session, or
/// nil when the open session was empty.
public func closeCurrentSession() throws -> CaptureSession? {
guard !openSession.isEmpty else {
let open = try ensureOpenSession()
guard !open.isEmpty else {
openSession = try Self.createFreshSession(paths: paths)
return nil
}
let archived = try moveOpenSessionToArchive(
openSession.markArchived(pdfFileName: openSession.pdfFileName))
open.markArchived(pdfFileName: open.pdfFileName))
openSession = try Self.createFreshSession(paths: paths)
applyRetention()
return archived
@@ -195,10 +218,11 @@ public actor SpoolStore {
/// Abandons the open session only if it is empty (mints a new id/dir/manifest); throws,
/// with no filesystem change, if the open session has captures.
public func startNewSession() throws -> CaptureSession {
guard openSession.isEmpty else {
let open = try ensureOpenSession()
guard open.isEmpty else {
throw ShotdeckError.spoolWriteFailed(
path: paths.sessionDirectory(openSession.id).path,
underlying: "cannot start a new session: \(openSession.captures.count) capture(s) present in the open session")
path: paths.sessionDirectory(open.id).path,
underlying: "cannot start a new session: \(open.captures.count) capture(s) present in the open session")
}
let fresh = try Self.createFreshSession(paths: paths)
openSession = fresh
@@ -231,9 +255,15 @@ public actor SpoolStore {
var keyed: [(session: CaptureSession, folderCreatedAt: Date, folderModifiedAt: Date)] = []
for id in ids {
let dir = paths.archiveDirectory(id)
// Read the folder dates BEFORE reconciling: reconciliation can rewrite
// session.json and bump the folder's modification date to "now", which
// would let a healed older session outrank a genuinely newer same-second
// peer in the tie-break below.
let values = try? dir.resourceValues(forKeys: [.creationDateKey, .contentModificationDateKey])
let session = try Self.reconcileSessionDirectory(
at: dir, id: id, assumedStateIfRebuilt: .archived, fileManager: .default)
let values = try? dir.resourceValues(forKeys: [.creationDateKey, .contentModificationDateKey])
// The manifest `createdAt` is the authoritative timestamp; the folder dates
// only refine ties between same-second sessions.
let folderCreatedAt = values?.creationDate ?? session.createdAt
let folderModifiedAt = values?.contentModificationDate ?? folderCreatedAt
keyed.append((session, folderCreatedAt, folderModifiedAt))