Skip to content

Fastest and only macOS Dictation app with on-device STT and custom trained AI enhancement model. Windows, iOS testflight! Android, Linux waitlist open! A local Wispr Flow alternative. Follow https://x.com/fluidvoiceapp for more

Fix unbounded FluidMeeting recording memory growth (#1034)

Rohith Gandhi Gf0ef01c1e1d2
diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingPCMFormatContract.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingPCMFormatContract.swift
index f435c3e8..0e5cfcf8 100644
--- a/Sources/Fluid/Services/Meeting/Backend/MeetingPCMFormatContract.swift
+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingPCMFormatContract.swift
@@ -141,6 +141,12 @@ nonisolated enum MeetingPCMFormatResolver {
}
}
-nonisolated enum MeetingPCMFormatContractError: Error, Equatable, Sendable {
+nonisolated enum MeetingPCMFormatContractError: LocalizedError, Equatable, Sendable {
case unsupported(String)
+
+ var errorDescription: String? {
+ switch self {
+ case let .unsupported(reason): return "Unsupported PCM format: \(reason)."
+ }
+ }
}
diff --git a/Sources/Fluid/Services/Meeting/MeetingAudioChunkWriter.swift b/Sources/Fluid/Services/Meeting/MeetingAudioChunkWriter.swift
index 9fb59476..77eaaa13 100644
--- a/Sources/Fluid/Services/Meeting/MeetingAudioChunkWriter.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingAudioChunkWriter.swift
@@ -93,6 +93,9 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {
private var lastHealthEmission = Date.distantPast
private var lastLevelMeasurement = Date.distantPast
private var silenceAccumulatedSeconds: Double = 0
+ /// Cleared by a successful append so a later failure is a new episode. Repeated rejected
+ /// buffers must not produce an unbounded session-event history.
+ private var hasReportedWriterFailure = false
/// Peak amplitude (0...1) below which a buffer counts as silent for watchdog purposes.
private static let silenceAmplitudeThreshold: Float = 0.0001
@@ -496,6 +499,8 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {
try self.writeCheckpoint(for: &activeChunk)
}
self.activeChunk = activeChunk
+ let recoveredFromWriterFailure = self.hasReportedWriterFailure
+ self.hasReportedWriterFailure = false
self.track.health.status = .healthy
self.track.health.lastPresentationTime = Self.mediaTime(presentationTime)
let now = Date()
@@ -514,14 +519,12 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {
self.track.health.level = Self.normalizedLevel(fromPeak: peak ?? 0)
}
self.track.health.detail = nil
- self.emitHealthIfNeeded()
+ self.emitHealthIfNeeded(force: recoveredFromWriterFailure)
} catch {
// A sink failure poisons the current container. Retire it immediately so the next
- // callback can establish a fresh chunk instead of retrying the same invalid sink and
- // emitting an error storm for every subsequent buffer.
- var retiredChunk = false
+ // callback can establish a fresh chunk. Chunk-start failures have no sink to retire,
+ // but must use the same failure-episode reporting as append/finalization failures.
if let failedChunk = self.activeChunk {
- retiredChunk = true
self.activeChunk = nil
self.lastFinalizedEnd = failedChunk.end
failedChunk.sink.cancel()
@@ -529,15 +532,8 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {
Self.failedChunk(from: failedChunk),
"PCM chunk write failed: \(error.localizedDescription)"
))
- }
- if !retiredChunk {
- self.track.health.status = .degraded
- self.track.health.detail = error.localizedDescription
- self.eventHandler(.interrupted(
- kind: .writerFailure,
- trackID: self.track.id,
- detail: error.localizedDescription
- ))
+ } else {
+ self.reportWriterFailure(detail: error.localizedDescription, sampleBuffer: sampleBuffer)
}
}
}
@@ -685,9 +681,7 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {
self.track.chunks[index].finalizationState = .failed
self.track.chunks[index].captureAnalysisAsset?.presence = .failed
}
- self.track.health.status = .degraded
- self.track.health.detail = "PCM chunk ledger terminal failed: \(error.localizedDescription)"
- self.eventHandler(.interrupted(kind: .writerFailure, trackID: self.track.id, detail: self.track.health.detail ?? "PCM chunk ledger terminal failed."))
+ self.reportWriterFailure(detail: "PCM chunk ledger terminal failed: \(error.localizedDescription)")
try? self.persistTrackManifest()
return
}
@@ -701,13 +695,32 @@ final nonisolated class MeetingAudioChunkWriter: @unchecked Sendable {
updatedAt: Date(),
detail: detail
), for: chunk.id)
- self.track.health.status = .degraded
- self.track.health.detail = detail
+ self.reportWriterFailure(detail: detail)
try? self.persistTrackManifest()
- self.eventHandler(.interrupted(kind: .writerFailure, trackID: self.track.id, detail: detail))
}
}
+ private func reportWriterFailure(detail: String, sampleBuffer: CMSampleBuffer? = nil) {
+ guard !self.hasReportedWriterFailure else { return }
+ self.hasReportedWriterFailure = true
+ if DebugLogger.diagnosticsEnabled,
+ let sampleBuffer,
+ let description = CMSampleBufferGetFormatDescription(sampleBuffer),
+ let asbd = CMAudioFormatDescriptionGetStreamBasicDescription(description)?.pointee
+ {
+ FileLogger.shared.appendSync(line:
+ "[MeetingPCMProbe] rejected-format track=\(self.track.kind.rawValue) " +
+ "formatID=\(asbd.mFormatID) rate=\(asbd.mSampleRate) channels=\(asbd.mChannelsPerFrame) " +
+ "flags=\(asbd.mFormatFlags) bits=\(asbd.mBitsPerChannel) " +
+ "bytesPerFrame=\(asbd.mBytesPerFrame) bytesPerPacket=\(asbd.mBytesPerPacket) " +
+ "framesPerPacket=\(asbd.mFramesPerPacket)")
+ }
+ self.track.health.status = .degraded
+ self.track.health.detail = detail
+ self.eventHandler(.interrupted(kind: .writerFailure, trackID: self.track.id, detail: detail))
+ self.emitHealthIfNeeded(force: true)
+ }
+
private func completeStop() {
self.track.chunks.sort { $0.sequence < $1.sequence }
self.track.health.status = self.track.chunks.contains(where: { $0.finalizationState == .finalized })
diff --git a/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift b/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift
index 2150b0e0..3d6ef98b 100644
--- a/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift
@@ -124,9 +124,10 @@ final class MeetingSessionCoordinator: ObservableObject {
private let audioArbiter: any MeetingAudioActivityArbitrating
private let preferredMicrophoneUID: @MainActor () -> String?
- private enum DegradeReason { case silence, sourceLoss, sticky }
+ private enum DegradeReason { case silence, sourceLoss, startupWriterFailure, sticky }
private var degradeReason: DegradeReason?
+ private var silenceWatchdogActive = false
private var activityLease: MeetingAudioActivityLease?
/// Reservation held from the public start entry point through every async start step.
/// This closes the preflight/lease window where two starts could otherwise pass guards.
@@ -135,6 +136,8 @@ final class MeetingSessionCoordinator: ObservableObject {
}
private var liveTranscriptionCoordinator: MeetingLiveTranscriptionCoordinator?
+ private var startupTrackHealth: [MeetingAudioTrackID: MeetingTrackHealth] = [:]
+ private var startupWriterFailures: Set<MeetingAudioTrackID?> = []
private var captureGeneration: UUID?
private var operationGeneration: UUID?
private var stopTask: Task<MeetingSession, Error>? {
@@ -147,8 +150,7 @@ final class MeetingSessionCoordinator: ObservableObject {
willSet { if (newValue == nil) != (self.retryTask == nil) { self.objectWillChange.send() } }
}
- private var persistenceTail: Task<Void, Never>?
- private var persistenceGeneration = 0
+ private let persistence: MeetingSessionPersistenceQueue
private var restoreTask: Task<Void, Never>?
private var isDeleting = false {
willSet { if newValue != self.isDeleting { self.objectWillChange.send() } }
@@ -198,6 +200,7 @@ final class MeetingSessionCoordinator: ObservableObject {
validateRecordingModels: @escaping @MainActor () async throws -> Void = {}
) {
self.store = store
+ self.persistence = MeetingSessionPersistenceQueue(store: store)
self.capture = capture
self.processing = processing
self.audioArbiter = audioArbiter
@@ -407,6 +410,7 @@ final class MeetingSessionCoordinator: ObservableObject {
let generation = UUID()
self.captureGeneration = generation
self.degradeReason = nil
+ self.silenceWatchdogActive = false
self.operationGeneration = generation
if passiveOffer != nil {
self.activeSession = nil
@@ -419,6 +423,9 @@ final class MeetingSessionCoordinator: ObservableObject {
.retainUntil(startedAt: session.startedAt)
self.activeSession = session
self.state = .preparing(session.id)
+ self.startupTrackHealth.removeAll()
+ self.startupWriterFailures.removeAll()
+ defer { self.startupTrackHealth.removeAll() }
var captureStarted = false
var captureStartAttempted = false
@@ -454,7 +461,8 @@ final class MeetingSessionCoordinator: ObservableObject {
configuration: configuration,
sessionDirectory: sessionDirectory,
eventHandler: { [weak self] event in
- Task { @MainActor [weak self] in
+ // Preserve failure/recovery emission order across the capture-to-main hop.
+ DispatchQueue.main.async { [weak self] in
self?.handleCaptureEvent(event, generation: generation)
}
},
@@ -470,14 +478,31 @@ final class MeetingSessionCoordinator: ObservableObject {
liveTranscriptionCoordinator.setMicrophoneCaptureMethod(microphoneTrack.captureMethod)
}
session.audioTracks = startResult.tracks
+ for index in session.audioTracks.indices {
+ if let health = self.startupTrackHealth[session.audioTracks[index].id] {
+ session.audioTracks[index].health = health
+ }
+ }
+ self.startupTrackHealth.removeAll()
+ // Capture can report its first writer failure before start() returns. Preserve that
+ // one-shot event and the settled writer health instead of replacing them with the
+ // original preparing snapshot.
+ session.events = self.activeSession?.events ?? session.events
if let firstPresentationTime = startResult.firstPresentationTime {
session.timebase.firstPresentationTime = firstPresentationTime
}
- session.state = .recording
+ let hasOtherDegradedTrack = session.audioTracks.contains {
+ $0.health.status == .degraded && !self.startupWriterFailures.contains($0.id)
+ }
+ let startedDegraded = self.degradeReason != nil || hasOtherDegradedTrack || !self.startupWriterFailures.isEmpty
+ session.state = startedDegraded ? .recordingDegraded : .recording
+ if startedDegraded {
+ self.degradeReason = hasOtherDegradedTrack ? .sticky : (self.degradeReason ?? .startupWriterFailure)
+ }
session.updatedAt = Date()
self.activeSession = session
self.trackHealth = Dictionary(uniqueKeysWithValues: session.audioTracks.map { ($0.kind, $0.health) })
- self.state = .recording(session.id)
+ self.state = startedDegraded ? .recordingDegraded(session.id) : .recording(session.id)
try await self.store.save(session)
guard self.startReservation == reservation,
self.operationGeneration == generation, !Task.isCancelled
@@ -536,6 +561,9 @@ final class MeetingSessionCoordinator: ObservableObject {
}
}
}
+ if let latestSession = self.activeSession, latestSession.id == session.id {
+ session.events = latestSession.events
+ }
let hasRecoverableAudio = Self.hasRecoverableAudio(session)
let failureDomain: MeetingFailureDomain = captureStarted
? .persistence
@@ -1673,7 +1701,15 @@ final class MeetingSessionCoordinator: ObservableObject {
guard self.captureGeneration == generation, var session = self.activeSession else { return }
switch event {
case let .trackHealth(trackID, health):
- guard let index = session.audioTracks.firstIndex(where: { $0.id == trackID }) else { return }
+ if health.status == .healthy {
+ self.startupWriterFailures.remove(trackID)
+ }
+ guard let index = session.audioTracks.firstIndex(where: { $0.id == trackID }) else {
+ if session.state == .preparing {
+ self.startupTrackHealth[trackID] = health
+ }
+ return
+ }
var health = health
let kind = session.audioTracks[index].kind
let watchdogTripped = kind == .applicationAudio && health.status != .degraded
@@ -1681,6 +1717,9 @@ final class MeetingSessionCoordinator: ObservableObject {
&& (self.trackHealth[.microphone]?.silentForSeconds).map {
$0 < Self.microphoneRecentActivityThresholdSeconds
} == true
+ if kind == .applicationAudio {
+ self.silenceWatchdogActive = watchdogTripped
+ }
if watchdogTripped {
health.status = .degraded
health.detail = "No meeting audio is being captured while your microphone is active."
@@ -1690,8 +1729,19 @@ final class MeetingSessionCoordinator: ObservableObject {
if health.status == .degraded {
session.state = .recordingDegraded
self.state = .recordingDegraded(session.id)
- // Writer-reported degrades stay sticky; only watchdog degrades may self-restore.
- self.degradeReason = watchdogTripped ? (self.degradeReason ?? .silence) : .sticky
+ if watchdogTripped {
+ self.degradeReason = self.degradeReason ?? .silence
+ } else if !self.startupWriterFailures.contains(trackID) {
+ self.degradeReason = .sticky
+ }
+ } else if session.state == .recordingDegraded,
+ self.degradeReason == .startupWriterFailure,
+ self.startupWriterFailures.isEmpty,
+ !session.audioTracks.contains(where: { $0.health.status == .degraded })
+ {
+ session.state = .recording
+ self.state = .recording(session.id)
+ self.degradeReason = nil
} else if kind == .applicationAudio, session.state == .recordingDegraded,
self.degradeReason == .silence,
(health.silentForSeconds ?? 0) < Self.silenceWatchdogThresholdSeconds,
@@ -1738,6 +1788,26 @@ final class MeetingSessionCoordinator: ObservableObject {
self.degradeReason = nil
}
case let .interrupted(kind, trackID, detail):
+ if session.state == .preparing {
+ switch kind {
+ case .writerFailure:
+ self.startupWriterFailures.insert(trackID)
+ if let trackID {
+ var health = self.startupTrackHealth[trackID] ?? .waiting
+ health.status = .degraded
+ health.detail = detail
+ self.startupTrackHealth[trackID] = health
+ }
+ case .sourceLost:
+ self.degradeReason = self.degradeReason ?? .sourceLoss
+ case .sourceRecovered:
+ if self.degradeReason == .sourceLoss { self.degradeReason = nil }
+ case .voiceProcessingDeclined:
+ break
+ default:
+ self.degradeReason = .sticky
+ }
+ }
session.events.append(MeetingSessionEvent(
id: UUID(),
occurredAt: Date(),
@@ -1757,21 +1827,38 @@ final class MeetingSessionCoordinator: ObservableObject {
self.beginUnexpectedStop(sessionID: session.id)
return
} else if kind == .sourceRecovered, session.state == .recordingDegraded,
- self.degradeReason == .sourceLoss,
- !session.audioTracks.contains(where: { $0.health.status == .degraded })
+ self.degradeReason == .sourceLoss
+ {
+ if !self.startupWriterFailures.isEmpty {
+ self.degradeReason = .startupWriterFailure
+ } else if !session.audioTracks.contains(where: { $0.health.status == .degraded }) {
+ session.state = .recording
+ self.state = .recording(session.id)
+ self.degradeReason = nil
+ } else if self.silenceWatchdogActive,
+ !session.audioTracks.contains(where: { $0.kind != .applicationAudio && $0.health.status == .degraded })
+ {
+ self.degradeReason = .silence
+ }
+ } else if kind != .sourceRecovered, kind != .voiceProcessingDeclined,
+ session.state == .recording || session.state == .recordingDegraded
{
- session.state = .recording
- self.state = .recording(session.id)
- self.degradeReason = nil
- } else if kind != .sourceRecovered, session.state == .recording {
session.state = .recordingDegraded
self.state = .recordingDegraded(session.id)
- self.degradeReason = kind == .sourceLost ? (self.degradeReason ?? .sourceLoss) : .sticky
+ if kind == .sourceLost, self.degradeReason != .sticky {
+ self.degradeReason = .sourceLoss
+ } else {
+ self.degradeReason = .sticky
+ }
}
}
session.updatedAt = Date()
self.activeSession = session
- self.enqueuePersistence(session)
+ // startRecording persists the settled tracks and any startup events together. Queuing
+ // a preparing snapshot here could overwrite that newer state after start returns.
+ if session.state != .preparing {
+ self.enqueuePersistence(session)
+ }
}
private func beginUnexpectedStop(sessionID: MeetingSessionID) {
@@ -1855,24 +1942,11 @@ final class MeetingSessionCoordinator: ObservableObject {
}
private func enqueuePersistence(_ session: MeetingSession) {
- self.persistenceGeneration += 1
- let previous = self.persistenceTail
- let store = self.store
- self.persistenceTail = Task {
- _ = await previous?.value
- try? await store.save(session)
- }
+ self.persistence.enqueue(session)
}
private func flushQueuedPersistence() async {
- while let tail = self.persistenceTail {
- let generation = self.persistenceGeneration
- _ = await tail.value
- if self.persistenceGeneration == generation {
- self.persistenceTail = nil
- return
- }
- }
+ await self.persistence.flush()
}
/// Must complete before any code path that calls into `processing.process`, so both live
diff --git a/Sources/Fluid/Services/Meeting/MeetingSessionPersistenceQueue.swift b/Sources/Fluid/Services/Meeting/MeetingSessionPersistenceQueue.swift
new file mode 100644
index 00000000..f05745d0
--- /dev/null
+++ b/Sources/Fluid/Services/Meeting/MeetingSessionPersistenceQueue.swift
@@ -0,0 +1,42 @@
+import Foundation
+
+/// Serializes background saves while retaining only the latest pending snapshot per session.
+/// Separate session slots preserve recovery updates when a new recording starts before a save
+/// finishes. Intermediate snapshots are superseded, but their events remain in the latest one.
+@MainActor
+final class MeetingSessionPersistenceQueue {
+ private let store: any MeetingSessionStoring
+ private var pending: [MeetingSessionID: MeetingSession] = [:]
+ private var order: [MeetingSessionID] = []
+ private var task: Task<Void, Never>?
+
+ init(store: any MeetingSessionStoring) {
+ self.store = store
+ }
+
+ func enqueue(_ session: MeetingSession) {
+ if self.pending[session.id] == nil {
+ self.order.append(session.id)
+ }
+ self.pending[session.id] = session
+ guard self.task == nil else { return }
+ self.task = Task {
+ while !self.order.isEmpty {
+ let id = self.order.removeFirst()
+ guard let snapshot = self.pending.removeValue(forKey: id) else { continue }
+ // Match the coordinator's best-effort background-save policy. A failed save
+ // must not strand the worker or prevent newer snapshots from being written.
+ try? await self.store.save(snapshot)
+ }
+ self.task = nil
+ }
+ }
+
+ /// Includes updates enqueued during a save and any replacement worker started before this
+ /// waiter resumes. Callers can then persist terminal state without an older queued overwrite.
+ func flush() async {
+ while let task = self.task {
+ await task.value
+ }
+ }
+}
diff --git a/Tests/FluidDictationIntegrationTests/MeetingAudioChunkSinkTests.swift b/Tests/FluidDictationIntegrationTests/MeetingAudioChunkSinkTests.swift
index 0a253b07..b129be6f 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingAudioChunkSinkTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingAudioChunkSinkTests.swift
@@ -13,9 +13,85 @@ private final class MeetingPCMFailureCounter: @unchecked Sendable {
func value() -> Int { self.lock.lock(); defer { lock.unlock() }; return self.count }
}
+private final class MeetingWriterEventRecorder: @unchecked Sendable {
+ private let lock = NSLock()
+ private var events: [MeetingCaptureEvent] = []
+
+ func record(_ event: MeetingCaptureEvent) {
+ self.lock.withLock { self.events.append(event) }
+ }
+
+ func snapshot() -> [MeetingCaptureEvent] {
+ self.lock.withLock { self.events }
+ }
+}
+
/// P1a's sink fixtures intentionally use real ready CMSampleBuffers. These tests stay in the
/// integration target because the sink is an internal harness type, not a package product.
final class MeetingAudioChunkSinkTests: XCTestCase {
+ func testUnsupportedMicrophoneBuffersReportOneFailureAndRecover() async throws {
+ let root = try self.makeDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let track = MeetingAudioTrack(
+ id: UUID(),
+ kind: .microphone,
+ sourceIdentifier: "test",
+ sourceDisplayName: "Test",
+ format: nil,
+ timebase: MeetingTimebaseMetadata(startedHostTime: 0, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil),
+ health: .waiting,
+ chunks: []
+ )
+ let events = MeetingWriterEventRecorder()
+ let writer = try MeetingAudioChunkWriter(track: track, sessionDirectory: root, chunkDuration: 60) {
+ events.record($0)
+ }
+ let integerFormat = try XCTUnwrap(AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: 48_000, channels: 1, interleaved: true))
+ let integerBytes = [Int16](repeating: 100, count: 480).withUnsafeBytes { Data($0) }
+ for index in 0..<1_000 {
+ let sample = try self.makeSampleBuffer(format: integerFormat, bytes: integerBytes, frameCount: 480, pts: Double(index) * 0.01)
+ XCTAssertTrue(writer.enqueue(sample))
+ // Drain each callback to test format rejection, rather than producer backpressure.
+ _ = await writer.snapshot()
+ }
+ let rejected = await writer.snapshot()
+ XCTAssertEqual(rejected.health.status, .degraded)
+ XCTAssertTrue(rejected.chunks.isEmpty)
+ XCTAssertEqual(rejected.health.detail, "Unsupported PCM format: native Float32 LPCM required.")
+ XCTAssertEqual(events.snapshot().count, 2, "One interruption and one degraded health update for the whole failure episode")
+ if case let .trackHealth(trackID, health) = events.snapshot().last {
+ XCTAssertEqual(trackID, track.id)
+ XCTAssertEqual(health.status, .degraded)
+ } else {
+ XCTFail("The coordinator must receive degraded track health")
+ }
+
+ writer.enqueue(try self.makeRawSampleBuffer(channelCount: 1, layoutTag: nil, frameCount: 480, pts: 10))
+ let recovered = await writer.snapshot()
+ XCTAssertEqual(recovered.health.status, .healthy)
+ XCTAssertNil(recovered.health.detail)
+ if case let .trackHealth(_, health) = events.snapshot().last {
+ XCTAssertEqual(health.status, .healthy)
+ } else {
+ XCTFail("Recovery must publish healthy track status immediately")
+ }
+
+ // The first rejection retires the active sink; later ones fail before a sink exists.
+ // Both paths belong to one new failure episode, even though their error strings differ.
+ for index in 1_001..<1_101 {
+ writer.enqueue(try self.makeSampleBuffer(format: integerFormat, bytes: integerBytes, frameCount: 480, pts: Double(index) * 0.01))
+ _ = await writer.snapshot()
+ }
+ let failures = events.snapshot().filter {
+ if case .interrupted(.writerFailure, _, _) = $0 { return true }
+ return false
+ }
+ XCTAssertEqual(failures.count, 2, "Recovery re-arms reporting exactly once")
+ writer.enqueue(try self.makeRawSampleBuffer(channelCount: 1, layoutTag: nil, frameCount: 480, pts: 11.01))
+ let stopped = await writer.stop()
+ XCTAssertEqual(stopped.chunks.filter { $0.finalizationState == .finalized }.count, 1)
+ }
+
func testLayoutlessThreeChannelMicrophoneResolvesCopiesConvertsAndWrites() async throws {
let root = try self.makeDirectory()
defer { try? FileManager.default.removeItem(at: root) }
@@ -445,7 +521,12 @@ final class MeetingAudioChunkSinkTests: XCTestCase {
}
private func makeSampleBuffer(format: AVAudioFormat, interleavedSamples: [Float], frameCount: Int, pts: Double) throws -> CMSampleBuffer {
- let bytes = interleavedSamples.withUnsafeBytes { Data($0) }
+ try self.makeSampleBuffer(
+ format: format, bytes: interleavedSamples.withUnsafeBytes { Data($0) }, frameCount: frameCount, pts: pts
+ )
+ }
+
+ private func makeSampleBuffer(format: AVAudioFormat, bytes: Data, frameCount: Int, pts: Double) throws -> CMSampleBuffer {
var block: CMBlockBuffer?
var status = CMBlockBufferCreateWithMemoryBlock(
allocator: kCFAllocatorDefault,
diff --git a/Tests/FluidDictationIntegrationTests/MeetingRecoveryTests.swift b/Tests/FluidDictationIntegrationTests/MeetingRecoveryTests.swift
index 62c32cd3..90414360 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingRecoveryTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingRecoveryTests.swift
@@ -11,6 +11,483 @@ import XCTest
// Existing recovery suite shares setup across crash and corruption scenarios.
// swiftlint:disable:next type_body_length
final class MeetingRecoveryTests: XCTestCase {
+ func testVoiceProcessingFallbackDoesNotDegradeHealthyRecording() async throws {
+ for deliverDuringStart in [false, true] {
+ let dir = self.makeTempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let store = MeetingSessionStore(rootDirectory: dir)
+ let capture = StubCaptureController()
+ var microphone = self.makeMicrophoneTrack(chunks: [])
+ microphone.health.status = .healthy
+ var applicationAudio = self.makeMicrophoneTrack(chunks: [])
+ applicationAudio.kind = .applicationAudio
+ applicationAudio.health.status = .healthy
+ capture.startResult = MeetingCaptureStartResult(tracks: [microphone, applicationAudio], firstPresentationTime: nil)
+ let fallback = MeetingCaptureEvent.interrupted(kind: .voiceProcessingDeclined, trackID: nil, detail: "The output device is Bluetooth.")
+ if deliverDuringStart { capture.startupEvents = [fallback] }
+ capture.onStart = { @MainActor in await self.drainCaptureEvents() }
+ let coordinator = MeetingSessionCoordinator(
+ store: store, capture: capture, processing: StubProcessingController(), audioArbiter: StubArbiter()
+ )
+ var configuration = self.makeConfiguration()
+ configuration.mode = .onlineCall
+ configuration.application = MeetingApplicationIdentity(bundleIdentifier: "us.zoom.xos", displayName: "Zoom")
+
+ let started = try await coordinator.startRecording(configuration: configuration)
+ XCTAssertEqual(started.state, .recording)
+ let persisted = try await store.load(id: started.id)
+ XCTAssertEqual(persisted?.state, .recording)
+ if !deliverDuringStart {
+ capture.emit(fallback)
+ await self.drainCaptureEvents()
+ }
+ XCTAssertEqual(coordinator.state, .recording(started.id), "Selecting a supported fallback is not a capture failure")
+ XCTAssertEqual(coordinator.activeSession?.events.map(\.kind), [.voiceProcessingDeclined])
+ capture.emit(.trackHealth(trackID: microphone.id, health: microphone.health))
+ capture.emit(.trackHealth(trackID: applicationAudio.id, health: applicationAudio.health))
+ await self.drainCaptureEvents()
+ XCTAssertEqual(coordinator.state, .recording(started.id))
+ XCTAssertEqual(coordinator.trackHealth[.microphone]?.status, .healthy)
+ XCTAssertEqual(coordinator.trackHealth[.applicationAudio]?.status, .healthy)
+ await coordinator.shutdownForTermination()
+ }
+ }
+
+ func testWriterFailureDuringStartPreservesEventAndDegradedHealth() async throws {
+ let dir = self.makeTempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let store = MeetingSessionStore(rootDirectory: dir)
+ let capture = StubCaptureController()
+ let microphone = self.makeMicrophoneTrack(chunks: [])
+ var degradedHealth = microphone.health
+ degradedHealth.status = .degraded
+ degradedHealth.detail = "Unsupported PCM format"
+ // The snapshot can precede the writer failure while capture.start is still suspended.
+ capture.startResult = MeetingCaptureStartResult(tracks: [microphone], firstPresentationTime: nil)
+ capture.startupEvents = [
+ .trackHealth(trackID: microphone.id, health: degradedHealth),
+ .interrupted(kind: .writerFailure, trackID: microphone.id, detail: degradedHealth.detail),
+ ]
+ let coordinator = MeetingSessionCoordinator(
+ store: store, capture: capture, processing: StubProcessingController(), audioArbiter: StubArbiter()
+ )
+ capture.onStart = { @MainActor in
+ for _ in 0..<100 {
+ if coordinator.activeSession?.events.count == 1 { break }
+ await Task.yield()
+ }
+ XCTAssertEqual(coordinator.activeSession?.events.count, 1, "Deliver the failure while capture.start is suspended")
+ }
+ let started = try await coordinator.startRecording(configuration: self.makeConfiguration())
+ XCTAssertEqual(started.events.map(\.kind), [.writerFailure])
+ XCTAssertEqual(started.audioTracks.first?.health.status, .degraded)
+ XCTAssertEqual(coordinator.state, .recordingDegraded(started.id))
+ XCTAssertEqual(coordinator.trackHealth[.microphone]?.status, .degraded)
+ let persisted = try await store.load(id: started.id)
+ XCTAssertEqual(persisted?.state, .recordingDegraded)
+ XCTAssertEqual(persisted?.events.map(\.kind), [.writerFailure])
+ XCTAssertEqual(persisted?.audioTracks.first?.health.status, .degraded)
+ await coordinator.shutdownForTermination()
+ }
+
+ func testRecoveredWriterDuringStartKeepsHistoryWithoutDegradingRecording() async throws {
+ let dir = self.makeTempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let store = MeetingSessionStore(rootDirectory: dir)
+ let capture = StubCaptureController()
+ var microphone = self.makeMicrophoneTrack(chunks: [])
+ microphone.health.status = .healthy
+ capture.startResult = MeetingCaptureStartResult(tracks: [microphone], firstPresentationTime: nil)
+ capture.startupEvents = [
+ .interrupted(kind: .writerFailure, trackID: microphone.id, detail: "Temporary writer failure"),
+ .trackHealth(trackID: microphone.id, health: microphone.health),
+ ]
+ let coordinator = MeetingSessionCoordinator(
+ store: store, capture: capture, processing: StubProcessingController(), audioArbiter: StubArbiter()
+ )
+ capture.onStart = { @MainActor in
+ for _ in 0..<100 {
+ if coordinator.activeSession?.events.count == 1 { break }
+ await Task.yield()
+ }
+ XCTAssertEqual(coordinator.activeSession?.events.count, 1)
+ }
+
+ let started = try await coordinator.startRecording(configuration: self.makeConfiguration())
+ XCTAssertEqual(started.events.map(\.kind), [.writerFailure])
+ XCTAssertEqual(started.state, .recording)
+ XCTAssertEqual(coordinator.state, .recording(started.id))
+ XCTAssertEqual(coordinator.trackHealth[.microphone]?.status, .healthy)
+ let persisted = try await store.load(id: started.id)
+ XCTAssertEqual(persisted?.state, .recording)
+ XCTAssertEqual(persisted?.events.map(\.kind), [.writerFailure])
+ await coordinator.shutdownForTermination()
+ }
+
+ func testStartupWriterFailureWithoutHealthyTrackRemainsDegraded() async throws {
+ let dir = self.makeTempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let store = MeetingSessionStore(rootDirectory: dir)
+ let capture = StubCaptureController()
+ let microphone = self.makeMicrophoneTrack(chunks: [])
+ capture.startResult = MeetingCaptureStartResult(tracks: [microphone], firstPresentationTime: nil)
+ capture.startupEvents = [
+ .interrupted(kind: .writerFailure, trackID: microphone.id, detail: "No successful writes yet"),
+ ]
+ let coordinator = MeetingSessionCoordinator(
+ store: store, capture: capture, processing: StubProcessingController(), audioArbiter: StubArbiter()
+ )
+ capture.onStart = { @MainActor in
+ for _ in 0..<100 {
+ if coordinator.activeSession?.events.count == 1 { break }
+ await Task.yield()
+ }
+ XCTAssertEqual(coordinator.activeSession?.events.count, 1)
+ }
+
+ let started = try await coordinator.startRecording(configuration: self.makeConfiguration())
+ XCTAssertEqual(started.state, .recordingDegraded)
+ XCTAssertEqual(coordinator.state, .recordingDegraded(started.id))
+ let persisted = try await store.load(id: started.id)
+ XCTAssertEqual(persisted?.state, .recordingDegraded)
+ XCTAssertEqual(persisted?.events.map(\.kind), [.writerFailure])
+ await coordinator.shutdownForTermination()
+ }
+
+ func testStaleStartupHealthDoesNotClearFailureAndLaterHealthCanRecover() async throws {
+ for emitEarlierHealth in [false, true] {
+ let dir = self.makeTempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let store = MeetingSessionStore(rootDirectory: dir)
+ let capture = StubCaptureController()
+ var microphone = self.makeMicrophoneTrack(chunks: [])
+ microphone.health.status = .healthy
+ capture.startResult = MeetingCaptureStartResult(tracks: [microphone], firstPresentationTime: nil)
+ if emitEarlierHealth {
+ capture.startupEvents.append(.trackHealth(trackID: microphone.id, health: microphone.health))
+ }
+ capture.startupEvents.append(.interrupted(kind: .writerFailure, trackID: microphone.id, detail: "New writer failure"))
+ let coordinator = MeetingSessionCoordinator(
+ store: store, capture: capture, processing: StubProcessingController(), audioArbiter: StubArbiter()
+ )
+ capture.onStart = { @MainActor in
+ for _ in 0..<100 {
+ if coordinator.activeSession?.events.count == 1 { break }
+ await Task.yield()
+ }
+ XCTAssertEqual(coordinator.activeSession?.events.count, 1)
+ }
+
+ let started = try await coordinator.startRecording(configuration: self.makeConfiguration())
+ XCTAssertEqual(started.state, .recordingDegraded, "An older healthy snapshot or event cannot prove recovery")
+ XCTAssertEqual(coordinator.trackHealth[.microphone]?.status, .degraded)
+ var degraded = microphone.health
+ degraded.status = .degraded
+ degraded.detail = "Delayed failure health"
+ capture.emit(.trackHealth(trackID: microphone.id, health: degraded))
+ for _ in 0..<100 {
+ if coordinator.trackHealth[.microphone]?.detail == degraded.detail { break }
+ await Task.yield()
+ }
+ XCTAssertEqual(coordinator.state, .recordingDegraded(started.id))
+ capture.emit(.trackHealth(trackID: microphone.id, health: microphone.health))
+ for _ in 0..<100 {
+ if coordinator.state == .recording(started.id) { break }
+ await Task.yield()
+ }
+ XCTAssertEqual(coordinator.state, .recording(started.id), "A later healthy callback resolves the startup failure")
+ XCTAssertEqual(coordinator.activeSession?.events.map(\.kind), [.writerFailure])
+ await coordinator.shutdownForTermination()
+ }
+ }
+
+ func testStartupWriterRecoveryDoesNotClearAnotherInterruption() async throws {
+ for (interruptDuringStart, sourceLost) in [(false, false), (true, false), (false, true), (true, true)] {
+ let dir = self.makeTempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let store = MeetingSessionStore(rootDirectory: dir)
+ let capture = StubCaptureController()
+ let microphone = self.makeMicrophoneTrack(chunks: [])
+ capture.startResult = MeetingCaptureStartResult(tracks: [microphone], firstPresentationTime: nil)
+ capture.startupEvents = [.interrupted(kind: .writerFailure, trackID: microphone.id, detail: "Startup failure")]
+ if sourceLost { capture.startupEvents.append(.interrupted(kind: .sourceLost, trackID: nil, detail: nil)) }
+ let diskFull = MeetingCaptureEvent.interrupted(kind: .diskExhausted, trackID: nil, detail: "Disk full")
+ if interruptDuringStart { capture.startupEvents.append(diskFull) }
+ capture.onStart = { @MainActor in await self.drainCaptureEvents() }
+ let coordinator = MeetingSessionCoordinator(
+ store: store, capture: capture, processing: StubProcessingController(), audioArbiter: StubArbiter()
+ )
+ let started = try await coordinator.startRecording(configuration: self.makeConfiguration())
+ if !interruptDuringStart {
+ capture.emit(diskFull)
+ await self.drainCaptureEvents()
+ }
+ XCTAssertEqual(coordinator.activeSession?.events.count, sourceLost ? 3 : 2)
+ var healthy = microphone.health
+ healthy.status = .healthy
+ capture.emit(.trackHealth(trackID: microphone.id, health: healthy))
+ await self.drainCaptureEvents()
+ XCTAssertEqual(coordinator.trackHealth[.microphone]?.status, .healthy)
+ XCTAssertEqual(coordinator.state, .recordingDegraded(started.id))
+ if sourceLost {
+ capture.emit(.interrupted(kind: .sourceRecovered, trackID: nil, detail: nil))
+ await self.drainCaptureEvents()
+ XCTAssertEqual(coordinator.state, .recordingDegraded(started.id), "Source recovery cannot clear a disk failure")
+ }
+ await coordinator.shutdownForTermination()
+ }
+ }
+
+ func testStartupSourceLossAndWriterFailureRequireBothRecoveries() async throws {
+ for (writerDuringStart, sourceDuringStart) in [(false, false), (true, false), (false, true), (true, true)] {
+ for sourceRecoversFirst in [false, true] {
+ let dir = self.makeTempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let store = MeetingSessionStore(rootDirectory: dir)
+ let capture = StubCaptureController()
+ var microphone = self.makeMicrophoneTrack(chunks: [])
+ microphone.health.status = .healthy
+ var applicationAudio = self.makeMicrophoneTrack(chunks: [])
+ applicationAudio.kind = .applicationAudio
+ applicationAudio.health.status = .healthy
+ capture.startResult = MeetingCaptureStartResult(tracks: [microphone, applicationAudio], firstPresentationTime: nil)
+ capture.startupEvents = [
+ .interrupted(kind: .writerFailure, trackID: microphone.id, detail: "Startup writer failure"),
+ .interrupted(kind: .sourceLost, trackID: nil, detail: "Application audio source lost"),
+ ]
+ let writerRecovery = MeetingCaptureEvent.trackHealth(trackID: microphone.id, health: microphone.health)
+ let sourceRecovery = MeetingCaptureEvent.interrupted(kind: .sourceRecovered, trackID: nil, detail: nil)
+ let recoveries: [(event: MeetingCaptureEvent, duringStart: Bool)] = sourceRecoversFirst
+ ? [(sourceRecovery, sourceDuringStart), (writerRecovery, writerDuringStart)]
+ : [(writerRecovery, writerDuringStart), (sourceRecovery, sourceDuringStart)]
+ capture.startupEvents += recoveries.filter(\.duringStart).map(\.event)
+ capture.onStart = { @MainActor in await self.drainCaptureEvents() }
+ let coordinator = MeetingSessionCoordinator(
+ store: store, capture: capture, processing: StubProcessingController(), audioArbiter: StubArbiter()
+ )
+
+ var configuration = self.makeConfiguration()
+ configuration.mode = .onlineCall
+ configuration.application = MeetingApplicationIdentity(bundleIdentifier: "us.zoom.xos", displayName: "Zoom")
+ let started = try await coordinator.startRecording(configuration: configuration)
+ let expectedStart: MeetingSessionState = writerDuringStart && sourceDuringStart ? .recording : .recordingDegraded
+ XCTAssertEqual(started.state, expectedStart)
+ let persisted = try await store.load(id: started.id)
+ XCTAssertEqual(persisted?.state, expectedStart)
+ if !writerDuringStart {
+ var degraded = microphone.health
+ degraded.status = .degraded
+ capture.emit(.trackHealth(trackID: microphone.id, health: degraded))
+ await self.drainCaptureEvents()
+ XCTAssertEqual(coordinator.state, .recordingDegraded(started.id))
+ }
+ let pendingRecoveries = recoveries.filter { !$0.duringStart }
+ for (index, recovery) in pendingRecoveries.enumerated() {
+ capture.emit(recovery.event)
+ await self.drainCaptureEvents()
+ let expected: MeetingCoordinatorState = index == pendingRecoveries.count - 1
+ ? .recording(started.id) : .recordingDegraded(started.id)
+ XCTAssertEqual(coordinator.state, expected, "Both the writer and the lost source must recover")
+ }
+ XCTAssertEqual(coordinator.state, .recording(started.id))
+ XCTAssertEqual(coordinator.activeSession?.events.map(\.kind), [.writerFailure, .sourceLost, .sourceRecovered])
+ await coordinator.shutdownForTermination()
+ }
+ }
+ }
+
+ func testSourceRecoveryPreservesSilenceWatchdogRecovery() async throws {
+ for sourceLostFirst in [false, true] {
+ for sourceRecoversFirst in [false, true] {
+ let dir = self.makeTempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let capture = StubCaptureController()
+ var microphone = self.makeMicrophoneTrack(chunks: [])
+ microphone.health.status = .healthy
+ microphone.health.silentForSeconds = 0
+ var applicationAudio = self.makeMicrophoneTrack(chunks: [])
+ applicationAudio.kind = .applicationAudio
+ applicationAudio.health.status = .healthy
+ applicationAudio.health.silentForSeconds = 0
+ capture.startResult = MeetingCaptureStartResult(tracks: [microphone, applicationAudio], firstPresentationTime: nil)
+ let coordinator = MeetingSessionCoordinator(
+ store: MeetingSessionStore(rootDirectory: dir),
+ capture: capture,
+ processing: StubProcessingController(),
+ audioArbiter: StubArbiter()
+ )
+ var configuration = self.makeConfiguration()
+ configuration.mode = .onlineCall
+ configuration.application = MeetingApplicationIdentity(bundleIdentifier: "us.zoom.xos", displayName: "Zoom")
+ let started = try await coordinator.startRecording(configuration: configuration)
+ var silentHealth = applicationAudio.health
+ silentHealth.silentForSeconds = 100
+ let silence = MeetingCaptureEvent.trackHealth(trackID: applicationAudio.id, health: silentHealth)
+ let sourceLoss = MeetingCaptureEvent.interrupted(kind: .sourceLost, trackID: nil, detail: nil)
+ for event in sourceLostFirst ? [sourceLoss, silence] : [silence, sourceLoss] {
+ capture.emit(event)
+ await self.drainCaptureEvents()
+ XCTAssertEqual(coordinator.state, .recordingDegraded(started.id))
+ }
+ XCTAssertEqual(coordinator.trackHealth[.applicationAudio]?.status, .degraded)
+ let audioRecovery = MeetingCaptureEvent.trackHealth(trackID: applicationAudio.id, health: applicationAudio.health)
+ let sourceRecovery = MeetingCaptureEvent.interrupted(kind: .sourceRecovered, trackID: nil, detail: nil)
+ let recoveries = sourceRecoversFirst ? [sourceRecovery, audioRecovery] : [audioRecovery, sourceRecovery]
+ capture.emit(recoveries[0])
+ await self.drainCaptureEvents()
+ XCTAssertEqual(coordinator.state, .recordingDegraded(started.id), "Both the source and captured audio must recover")
+ capture.emit(recoveries[1])
+ await self.drainCaptureEvents()
+ XCTAssertEqual(coordinator.state, .recording(started.id))
+ await coordinator.shutdownForTermination()
+ }
+ }
+ }
+
+ private func drainCaptureEvents() async {
+ await withCheckedContinuation { continuation in
+ DispatchQueue.main.async { continuation.resume() }
+ }
+ }
+
+ func testCaptureStartFailurePersistsStartupWriterEvent() async throws {
+ let dir = self.makeTempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let store = MeetingSessionStore(rootDirectory: dir)
+ let capture = StubCaptureController()
+ let trackID = UUID()
+ capture.startError = MeetingCaptureError.captureStartFailed("Capture could not finish starting")
+ capture.startupEvents = [
+ .interrupted(kind: .writerFailure, trackID: trackID, detail: "Unsupported PCM format"),
+ ]
+ let coordinator = MeetingSessionCoordinator(
+ store: store, capture: capture, processing: StubProcessingController(), audioArbiter: StubArbiter()
+ )
+ capture.onStart = { @MainActor in
+ for _ in 0..<100 {
+ if coordinator.activeSession?.events.count == 1 { break }
+ await Task.yield()
+ }
+ XCTAssertEqual(coordinator.activeSession?.events.count, 1)
+ }
+
+ do {
+ _ = try await coordinator.startRecording(configuration: self.makeConfiguration())
+ XCTFail("Expected capture startup to fail")
+ } catch let error as MeetingCaptureError {
+ guard case .captureStartFailed = error else { return XCTFail("Unexpected capture error: \(error)") }
+ }
+ let sessions = try await store.loadAll()
+ XCTAssertEqual(sessions.count, 1)
+ let failed = try XCTUnwrap(sessions.first)
+ XCTAssertEqual(failed.state, .failed)
+ XCTAssertEqual(failed.events.map(\.kind), [.writerFailure])
+ XCTAssertEqual(failed.events.first?.trackID, trackID)
+ XCTAssertEqual(failed.events.first?.detail, "Unsupported PCM format")
+ XCTAssertEqual(failed.failures.last?.domain, .capture)
+ XCTAssertNil(coordinator.activeSession)
+ }
+
+ func testPersistenceCoalescesSlowStoreAndFlushesNewestSnapshot() async throws {
+ let dir = self.makeTempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let realStore = MeetingSessionStore(rootDirectory: dir)
+ let recorder = EventRecorder()
+ let store = GatedThrowingSaveStore(inner: realStore, recorder: recorder)
+ let queue = MeetingSessionPersistenceQueue(store: store)
+ var session = self.makeSession(state: .recording, audioTracks: [self.makeMicrophoneTrack(chunks: [])])
+ session.events.append(MeetingSessionEvent(id: UUID(), occurredAt: Date(), kind: .writerFailure, trackID: nil, detail: "First failure"))
+ await store.closeGate()
+ queue.enqueue(session)
+ for _ in 0..<100 {
+ if await recorder.events.contains("store.save.start") { break }
+ await Task.yield()
+ }
+ let started = await recorder.events.contains("store.save.start")
+ XCTAssertTrue(started, "The first snapshot must be in flight before the burst")
+ for index in 1..<1_000 {
+ session.events.append(MeetingSessionEvent(id: UUID(), occurredAt: Date(), kind: .writerFailure, trackID: nil, detail: "Failure \(index)"))
+ queue.enqueue(session)
+ }
+ let firstFlush = Task { await queue.flush() }
+ let secondFlush = Task { await queue.flush() }
+ await store.openGate()
+ await firstFlush.value
+ await secondFlush.value
+
+ let savedCounts = await store.savedEventCounts
+ XCTAssertEqual(savedCounts, [1, 1_000], "Slow storage must not save or retain every intermediate snapshot")
+ let persisted = try await store.load(id: session.id)
+ XCTAssertEqual(persisted?.events.map(\.id), session.events.map(\.id))
+ XCTAssertEqual(persisted?.events.last?.detail, session.events.last?.detail)
+
+ // A direct terminal save after flush must never be overwritten by an older queued state.
+ session.state = .interrupted
+ session.endedAt = Date()
+ try await store.save(session)
+ await queue.flush()
+ let terminal = try await store.load(id: session.id)
+ XCTAssertEqual(terminal?.state, .interrupted)
+
+ session.title = "Worker restarted"
+ queue.enqueue(session)
+ await queue.flush()
+ let restarted = try await store.load(id: session.id)
+ XCTAssertEqual(restarted?.title, "Worker restarted")
+ }
+
+ func testPersistenceKeepsLatestSnapshotForEachSession() async throws {
+ let dir = self.makeTempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let recorder = EventRecorder()
+ let store = GatedThrowingSaveStore(inner: MeetingSessionStore(rootDirectory: dir), recorder: recorder)
+ let queue = MeetingSessionPersistenceQueue(store: store)
+ var previous = self.makeSession(state: .interrupted, endedAt: Date(), audioTracks: [self.makeMicrophoneTrack(chunks: [])])
+ var current = self.makeSession(state: .recording, audioTracks: [self.makeMicrophoneTrack(chunks: [])])
+ await store.closeGate()
+ queue.enqueue(previous)
+ for _ in 0..<100 {
+ if await recorder.events.contains("store.save.start") { break }
+ await Task.yield()
+ }
+ let started = await recorder.events.contains("store.save.start")
+ XCTAssertTrue(started)
+ queue.enqueue(current)
+ previous.recoveryResolvedAt = Date()
+ queue.enqueue(previous)
+ current.title = "Newest recording snapshot"
+ queue.enqueue(current)
+ await store.openGate()
+ await queue.flush()
+ let persistedPrevious = try await store.load(id: previous.id)
+ let persistedCurrent = try await store.load(id: current.id)
+ XCTAssertNotNil(persistedPrevious?.recoveryResolvedAt)
+ XCTAssertEqual(persistedCurrent?.title, current.title)
+ let savedCounts = await store.savedEventCounts
+ XCTAssertEqual(savedCounts.count, 3, "One in-flight save and one pending save per session")
+ }
+
+ func testPersistenceContinuesAfterSaveFailure() async throws {
+ let dir = self.makeTempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let recorder = EventRecorder()
+ let store = GatedThrowingSaveStore(inner: MeetingSessionStore(rootDirectory: dir), recorder: recorder)
+ let queue = MeetingSessionPersistenceQueue(store: store)
+ var session = self.makeSession(state: .recording, audioTracks: [self.makeMicrophoneTrack(chunks: [])])
+ let nextSession = self.makeSession(state: .recording, audioTracks: [self.makeMicrophoneTrack(chunks: [])])
+ await store.throwOnNextSave()
+ queue.enqueue(session)
+ queue.enqueue(nextSession)
+ await queue.flush()
+ let savedNext = try await store.load(id: nextSession.id)
+ XCTAssertEqual(savedNext?.id, nextSession.id, "A failed save must not strand another pending session")
+ session.title = "Recovered save"
+ queue.enqueue(session)
+ await queue.flush()
+ let persisted = try await store.load(id: session.id)
+ XCTAssertEqual(persisted?.title, session.title)
+ }
+
func testFileTranscriptRenamePreservesSourceAndSelection() throws {
let suite = "FileRenameTests.\(UUID().uuidString)"
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
@@ -4061,11 +4538,15 @@ private actor EventRecorder {
private final class StubCaptureController: MeetingCaptureControlling, @unchecked Sendable {
var startResult = MeetingCaptureStartResult(tracks: [], firstPresentationTime: nil)
var startError: Error?
+ var startupEvents: [MeetingCaptureEvent] = []
var onStart: (@Sendable () async -> Void)?
var preflightError: Error?
var onPreflight: (@Sendable () async -> Void)?
private(set) var preflightCount = 0
private(set) var startCount = 0
+ private var eventHandler: (@Sendable (MeetingCaptureEvent) -> Void)?
+
+ func emit(_ event: MeetingCaptureEvent) { self.eventHandler?(event) }
func preflightPermissions() async throws {
self.preflightCount += 1
@@ -4081,6 +4562,8 @@ private final class StubCaptureController: MeetingCaptureControlling, @unchecked
liveAudioHandler: (@Sendable (MeetingAudioTrackKind, CMSampleBuffer) -> Void)?
) async throws -> MeetingCaptureStartResult {
self.startCount += 1
+ self.eventHandler = eventHandler
+ for event in self.startupEvents { eventHandler(event) }
await self.onStart?()
if let startError { throw startError }
return self.startResult
@@ -4433,6 +4916,7 @@ private actor GatedThrowingSaveStore: MeetingSessionStoring {
private var isOpen = true
private var continuation: CheckedContinuation<Void, Never>?
private var throwOnNextSaveCount = 0
+ private(set) var savedEventCounts: [Int] = []
init(inner: MeetingSessionStore, recorder: EventRecorder) {
self.inner = inner
@@ -4459,6 +4943,7 @@ private actor GatedThrowingSaveStore: MeetingSessionStoring {
await withCheckedContinuation { self.continuation = $0 }
}
try await self.inner.save(session)
+ self.savedEventCounts.append(session.events.count)
}
func load(id: MeetingSessionID) async throws -> MeetingSession? { try await self.inner.load(id: id) }