From 6d07b5db96510deb0fb3eb437940aec742967a08 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Mon, 16 Nov 2026 19:07:02 -0500 Subject: [PATCH 1/2] Preserve file transcription failures until ingestion settles --- Sources/AuralKit/SpeechSession+File.swift | 16 +- Sources/AuralKit/SpeechSession+Pipeline.swift | 11 ++ Sources/AuralKit/SpeechSession.swift | 2 +- .../FileIngestionSettlementTests.swift | 177 ++++++++++++++++++ 4 files changed, 202 insertions(+), 4 deletions(-) create mode 100644 Tests/AuralKitTests/FileIngestionSettlementTests.swift diff --git a/Sources/AuralKit/SpeechSession+File.swift b/Sources/AuralKit/SpeechSession+File.swift index b4ffb1a..a8e62e5 100644 --- a/Sources/AuralKit/SpeechSession+File.swift +++ b/Sources/AuralKit/SpeechSession+File.swift @@ -248,7 +248,7 @@ extension SpeechSession { } } -private extension SpeechSession { +extension SpeechSession { nonisolated func feedAudioFile( _ payload: (file: AVAudioFile, totalFrames: AVAudioFramePosition), progressHandler: (@Sendable (Double) -> Void)?, @@ -286,7 +286,7 @@ private extension SpeechSession { } if buffer.frameLength == 0 { - break + throw SpeechSessionError.audioFileReadFailed(CocoaError(.fileReadCorruptFile)) } guard let bufferCopy = buffer.copy() as? AVAudioPCMBuffer else { @@ -312,6 +312,9 @@ private extension SpeechSession { return !Task.isCancelled && processedFrames >= totalFrames } +} + +private extension SpeechSession { func shouldUseNativeFileAnalyzer(progressHandler: (@Sendable (Double) -> Void)?) -> Bool { #if swift(>=6.4) if #available(iOS 27.0, macOS 27.0, *) { @@ -360,8 +363,15 @@ extension SpeechSession { guard let self else { return } do { try await ingest(self) + try Task.checkCancellation() + guard generation == sessionGeneration, continuation != nil else { return } + fileIngestionCompleted = true + if fileResultsCompleted { + await endTranscription(error: nil, generation: generation, cancelRecognizer: false) + } } catch is CancellationError { - // Cleanup cancelled the ingestion task. + // Only an existing terminal owner may suppress child cancellation. + await finishWithStartupError(CancellationError(), generation: generation) } catch { await finishWithStartupError(error, generation: generation) } diff --git a/Sources/AuralKit/SpeechSession+Pipeline.swift b/Sources/AuralKit/SpeechSession+Pipeline.swift index 7ed51f9..f77fe75 100644 --- a/Sources/AuralKit/SpeechSession+Pipeline.swift +++ b/Sources/AuralKit/SpeechSession+Pipeline.swift @@ -78,6 +78,8 @@ extension SpeechSession { /// session moved on to another stream) cannot tear down state it no longer owns. func beginStreamGeneration() -> Int { sessionGeneration &+= 1 + fileIngestionCompleted = false + fileResultsCompleted = false return sessionGeneration } @@ -214,6 +216,11 @@ extension SpeechSession { } func finishFromRecognizerTask(error: Error?, generation: Int) async { + guard generation == sessionGeneration else { return } + if error == nil, streamingMode == .filePlayback || streamingMode == .mediaPlayback { + fileResultsCompleted = true + guard fileIngestionCompleted else { return } + } await endTranscription(error: error, generation: generation, cancelRecognizer: error != nil) } @@ -236,6 +243,9 @@ extension SpeechSession { return } if streamingMode == .filePlayback || streamingMode == .mediaPlayback { + await pipelineTask?.value + guard generation == sessionGeneration else { return } + await fileIngestionTask?.value await recognizerTask.value return } @@ -504,6 +514,7 @@ extension SpeechSession { guard generation == sessionGeneration, terminationTask == nil else { return } streamContinuation.yield(result) } + try Task.checkCancellation() if Self.shouldLog(.notice) { Self.logger.notice("\(label, privacy: .public) completed without error") } diff --git a/Sources/AuralKit/SpeechSession.swift b/Sources/AuralKit/SpeechSession.swift index a02d504..51eec39 100644 --- a/Sources/AuralKit/SpeechSession.swift +++ b/Sources/AuralKit/SpeechSession.swift @@ -97,7 +97,6 @@ public final class SpeechSession { /// Reflects the speech detector's most recent state; defaults to `true` when monitoring is inactive. public internal(set) var isSpeechDetected: Bool = true - // Stream state management var continuation: TranscriptionContinuation? var recognizerTask: Task? var pipelineTask: Task? @@ -105,6 +104,7 @@ public final class SpeechSession { var terminationTask: Task? var cancellationRequested = false var fileIngestionTask: Task? + var fileIngestionCompleted = false, fileResultsCompleted = false var streamingMode: StreamingMode = .inactive /// Incremented for every accepted start so stale termination handlers can be ignored. var sessionGeneration: Int = 0 diff --git a/Tests/AuralKitTests/FileIngestionSettlementTests.swift b/Tests/AuralKitTests/FileIngestionSettlementTests.swift new file mode 100644 index 0000000..892a45f --- /dev/null +++ b/Tests/AuralKitTests/FileIngestionSettlementTests.swift @@ -0,0 +1,177 @@ +import AVFoundation +import Foundation +import Speech +import Testing +@testable import AuralKit + +@Suite("File ingestion settlement") +@MainActor +struct FileIngestionSettlementTests { + @Test("Independent ingestion cancellation settles the public stream", arguments: [false, true]) + func independentCancellation(throwsCancellation: Bool) async throws { + try await withSession { runtime, fixture in + runtime.session.startFileIngestion(generation: runtime.generation) { _ in + if throwsCancellation { throw CancellationError() } + withUnsafeCurrentTask { $0?.cancel() } + } + let input = fixture.track(try #require(runtime.session.fileIngestionTask)) + await #expect(throws: CancellationError.self) { + try await awaitResult(timeout: 3) { + for try await _ in runtime.results { Issue.record("Unexpected result") } + } + } + await input.value + #expect(runtime.session.status == .idle) + #expect(runtime.session.continuation == nil) + } + } + + @Test("Result EOF preserves a later input or finalization error", arguments: [false, true]) + func resultEOFDoesNotAdmitPrematureSuccess(finalization: Bool) async throws { + try await withSession { runtime, fixture in + let release = fixture.gate() + let results = AsyncThrowingStream.makeStream() + let forwarded = AsyncThrowingStream.makeStream() + defer { forwarded.continuation.finish() } + let reader = fixture.track(runtime.session.createRecognizerTask( + label: "File result fixture", results: results.stream, + streamContinuation: forwarded.continuation, generation: runtime.generation + )) + runtime.session.recognizerTask = reader + if finalization { + runtime.session.analyzer = SpeechAnalyzer(modules: []) + runtime.session.analyzerInputTask = Task { + try await release.wait() + throw SpeechSessionError.invalidAudioDataType + } + } + runtime.session.startFileIngestion(generation: runtime.generation) { session in + if finalization { + try await session.finishFileInput(generation: runtime.generation) + } else { + try await release.wait() + throw SpeechSessionError.audioFileReadFailed(nil) + } + } + let input = fixture.track(try #require(runtime.session.fileIngestionTask)) + results.continuation.finish() + await reader.value + #expect(runtime.session.continuation != nil) + release.open() + await input.value + do { + try await awaitResult(timeout: 3) { + for try await _ in runtime.results { Issue.record("Unexpected result") } + } + Issue.record("Expected the producer failure") + } catch SpeechSessionError.invalidAudioDataType { + #expect(finalization) + } catch SpeechSessionError.audioFileReadFailed { + #expect(!finalization) + } + #expect(runtime.session.status == .idle) + } + } + + @Test("A result iterator that cancels itself before EOF fails the public stream") + func selfCancelledResultEOF() async throws { + try await withSession { runtime, fixture in + let forwarded = AsyncThrowingStream.makeStream() + defer { forwarded.continuation.finish() } + runtime.session.startFileIngestion(generation: runtime.generation) { _ in } + let reader = fixture.track(runtime.session.createRecognizerTask( + label: "Self-cancelled results", results: SelfCancelledResults(), + streamContinuation: forwarded.continuation, generation: runtime.generation + )) + runtime.session.recognizerTask = reader + await #expect(throws: CancellationError.self) { + try await awaitResult(timeout: 3) { + for try await _ in runtime.results { Issue.record("Unexpected result") } + } + } + await reader.value + #expect(runtime.session.status == .idle) + } + } + + @Test("A physical short read fails before closing analyzer input") + func physicalShortRead() async throws { + let url = FileManager.default.temporaryDirectory + .appendingPathComponent("Aural-short-read-\(UUID().uuidString).caf") + defer { try? FileManager.default.removeItem(at: url) } + let format = try #require(AVAudioFormat( + commonFormat: .pcmFormatInt16, sampleRate: 16_000, channels: 1, interleaved: true + )) + let buffer = try #require(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 160)) + buffer.frameLength = 160 + buffer.int16ChannelData?.pointee.initialize(repeating: 0, count: 160) + try autoreleasepool { + let writer = try AVAudioFile( + forWriting: url, settings: format.settings, commonFormat: .pcmFormatInt16, interleaved: true + ) + try writer.write(from: buffer) + } + try await withSession { runtime, _ in + let file = try AVAudioFile(forReading: url, commonFormat: .pcmFormatInt16, interleaved: true) + let declaredFrames = file.length + 1 + let input = AsyncStream.makeStream() + defer { input.continuation.finish() } + runtime.session.inputBuilder = input.continuation + runtime.session.analyzerFormat = format + do { + _ = try await runtime.session.feedAudioFile( + (file: file, totalFrames: declaredFrames), progressHandler: { _ in }, + generation: runtime.generation + ) + Issue.record("Expected audioFileReadFailed for premature physical EOF") + } catch SpeechSessionError.audioFileReadFailed { } + if case .terminated = input.continuation.yield(AnalyzerInput(buffer: buffer)) { + Issue.record("Physical input closed before its read failure was admitted") + } + } + } + + @MainActor + private struct Runtime { + let session: SpeechSession + let results: AsyncThrowingStream + let generation: Int + + init() { + let session = SpeechSession() + let output = AsyncThrowingStream.makeStream() + self.session = session + results = output.stream + generation = session.beginStreamGeneration() + session.continuation = .speech(output.continuation) + session.streamingMode = .filePlayback + session.setStatus(.transcribing) + } + } + + private func withSession(_ body: (Runtime, CaptureFixture) async throws -> Void) async throws { + try await withCaptureFixture { fixture in + let runtime = Runtime() + do { + try await body(runtime, fixture) + } catch { + fixture.releaseAll() + await runtime.session.cancelTranscribing() + throw error + } + fixture.releaseAll() + await runtime.session.cancelTranscribing() + } + } +} + +private struct SelfCancelledResults: AsyncSequence, Sendable { + typealias Element = Int + struct AsyncIterator: AsyncIteratorProtocol { + mutating func next() async -> Int? { + withUnsafeCurrentTask { $0?.cancel() } + return nil + } + } + func makeAsyncIterator() -> AsyncIterator { AsyncIterator() } +} From 0b40a4d8981afbbbdbb3d1b2e6e8eb49f433139c Mon Sep 17 00:00:00 2001 From: rudrankriyam Date: Thu, 26 Nov 2026 13:56:08 +0530 Subject: [PATCH 2/2] Prepare 3.0.1 release --- Aural/Info.plist | 2 +- Aural/SettingsView.swift | 2 +- README.md | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Aural/Info.plist b/Aural/Info.plist index d7cb7ca..df1bc96 100644 --- a/Aural/Info.plist +++ b/Aural/Info.plist @@ -17,7 +17,7 @@ CFBundlePackageType APPL CFBundleShortVersionString - 3.0.0 + 3.0.1 CFBundleVersion 1 LSMinimumSystemVersion diff --git a/Aural/SettingsView.swift b/Aural/SettingsView.swift index 56d0ea5..2fb32f5 100644 --- a/Aural/SettingsView.swift +++ b/Aural/SettingsView.swift @@ -63,7 +63,7 @@ struct SettingsView: View { Text("AuralKit Demo") .font(.caption) .foregroundStyle(.secondary) - Text("Version 3.0.0") + Text("Version 3.0.1") .font(.caption2) .foregroundStyle(.secondary) } diff --git a/README.md b/README.md index 43e9ab5..f6ffdef 100644 --- a/README.md +++ b/README.md @@ -100,11 +100,11 @@ Add AuralKit to your project through Xcode: 2. Enter: `https://github.com/rryam/AuralKit` 3. Click Add Package -Select 3.0.0 in Xcode or add the following dependency to your `Package.swift`: +Select 3.0.1 in Xcode or add the following dependency to your `Package.swift`: ```swift dependencies: [ - .package(url: "https://github.com/rryam/AuralKit", from: "3.0.0") + .package(url: "https://github.com/rryam/AuralKit", from: "3.0.1") ] ```