Repository navigation
perf: optimize response pipeline latency - #8
Conversation
There was a problem hiding this comment.
Code Review
This pull request implements a performance response pipeline to reduce perceived latency by moving realtime streaming and post-injection learning to actors. It introduces a RealtimeAudioFramePump for off-thread audio handling, a RealtimeOverlayUpdateGate to throttle UI updates, and a comprehensive latency tracing system with persistence. A new benchmark reporting tool is also included to track performance metrics. Feedback suggests improving the testability of the latency reporter through dependency injection, reducing lock contention in the audio pump by using atomic types, and optimizing I/O for latency history storage.
| private let recordingLatencyReporter: any RecordingLatencyReporting = RecordingLatencyCompositeReporter( | ||
| reporters: [ | ||
| UnifiedLogRecordingLatencyReporter(), | ||
| RecordingLatencyHistoryReporter() | ||
| ] | ||
| ) |
There was a problem hiding this comment.
| lock.lock() | ||
| if hasOverflowed { | ||
| lock.unlock() | ||
| return | ||
| } |
| func append(_ sample: RecordingLatencySample) throws { | ||
| var document = try load() | ||
| document.samples.insert(sample, at: 0) | ||
| if document.samples.count > maximumSampleCount { | ||
| document.samples = Array(document.samples.prefix(maximumSampleCount)) | ||
| } | ||
| try save(document) | ||
| } |
There was a problem hiding this comment.
There was a problem hiding this comment.
Pull request overview
This PR reduces perceived recording-to-delivery latency and UI churn by introducing configurable timing/policy abstractions, moving realtime audio ingestion off the main actor, adding end-to-end latency diagnostics with persisted history, and providing a benchmark reporting workflow to make regressions measurable.
Changes:
- Add policy/value types for injection timing, speech stop fallback timing, post-injection polling cadence, and overlay update throttling.
- Introduce recording latency tracing + persisted history summaries, and wire reporting into the recording pipeline.
- Add benchmark report generation (Swift entrypoint + shell script) and regression tests for the new performance helpers and concurrency behaviors.
Reviewed changes
Copilot reviewed 33 out of 33 changed files in this pull request and generated 8 comments.
Show a summary per file
| File | Description |
|---|---|
| docs/plans/2026-04-15-performance-response-pipeline-spec.md | Implementation plan/spec for the response pipeline performance work |
| Scripts/benchmark.sh | Compiles and runs a standalone benchmark binary |
| Scripts/benchmark_main.swift | Benchmark entrypoint rendering report + microbenchmarks |
| Tests/benchmark_script_test.sh | Verifies benchmark script compiles expected inputs and prints header |
| Sources/VoicePi/PerformanceBenchmarkReport.swift | Budget/scenario metrics + deterministic text rendering |
| Tests/VoicePiTests/PerformanceBenchmarkReportTests.swift | Locks report metrics + rendered output format |
| Sources/VoicePi/TextInjectionTiming.swift | Timing policy + execution plan for injection blocking latency |
| Tests/VoicePiTests/TextInjectionExecutionPlanTests.swift | Asserts execution plan stays within latency budgets |
| Sources/VoicePi/TextInjector.swift | Uses execution plan; replaces Thread.sleep with async sleep |
| Sources/VoicePi/SpeechRecorderStopPolicy.swift | Policy for stop fallback delay based on transcript presence |
| Tests/VoicePiTests/SpeechRecorderStopPolicyTests.swift | Verifies stop fallback delay selection logic |
| Sources/VoicePi/SpeechRecorder.swift | Uses stop policy instead of fixed 450ms sleep |
| Sources/VoicePi/RecordingLatencyTrace.swift | Trace milestones + unified logging reporter |
| Tests/VoicePiTests/RecordingLatencyTraceTests.swift | Verifies milestone semantics + summary format |
| Sources/VoicePi/RecordingLatencyHistory.swift | Persisted latency history store + recent median summary |
| Tests/VoicePiTests/RecordingLatencyHistoryTests.swift | Verifies history capping + recent summary derivations |
| Sources/VoicePi/RealtimeOverlayUpdateGate.swift | Throttles meter-only overlay updates, publishes transcript changes immediately |
| Tests/VoicePiTests/RealtimeOverlayUpdateGateTests.swift | Verifies overlay throttling behavior |
| Sources/VoicePi/RealtimeAudioFramePump.swift | Buffer + drain pump with overflow handler for backpressure |
| Tests/VoicePiTests/RealtimeAudioFramePumpTests.swift | Verifies ordering + overflow reporting |
| Sources/VoicePi/RealtimeASRSessionCoordinator.swift | Converted to actor + adds status snapshots + backpressure degradation path |
| Tests/VoicePiTests/RealtimeASRSessionCoordinatorTests.swift | Uses statusSnapshot() and improves async waiting |
| Sources/VoicePi/PostInjectionLearningLoopPolicy.swift | Post-injection polling cadence policy |
| Tests/VoicePiTests/PostInjectionLearningLoopPolicyTests.swift | Verifies default polling intervals |
| Sources/VoicePi/PostInjectionLearning.swift | Coordinator becomes actor; adds run ownership registry + targeted cancellation |
| Tests/VoicePiTests/PostInjectionLearningTests.swift | Updates tests for actor access + new ownership regression coverage |
| Sources/VoicePi/FloatingPanelTranscriptPresentationState.swift | Presentation state to suppress repeated-layout work |
| Tests/VoicePiTests/FloatingPanelControllerTests.swift | Tests layout suppression + placeholder stability across phases |
| Sources/VoicePi/FloatingPanelSupport.swift | Introduces sizing state; routes transcript display through presentation state |
| Tests/VoicePiTests/FloatingPanelSizingStateTests.swift | Verifies recording width lock + refining expansion |
| Sources/VoicePi/FloatingPanelController.swift | Uses sizing/presentation state to reduce layout churn; adds level-only update |
| Sources/VoicePi/AppModel.swift | Adds overlay level-only update API |
| Sources/VoicePi/AppCoordinator.swift | Wires latency trace + overlay gate + audio frame pump + actor snapshots |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| let components = duration.components | ||
| let secondsMilliseconds = components.seconds * 1_000 | ||
| let attosecondsMilliseconds = components.attoseconds / 1_000_000_000_000_000 | ||
| return Int(secondsMilliseconds + attosecondsMilliseconds) | ||
| } |
There was a problem hiding this comment.
There are two separate implementations converting Duration to milliseconds (here and in PerformanceBenchmarkReport). Duplicating this conversion risks future drift/bugs. Consider extracting a shared helper (e.g., Duration.millisecondsInt or a small utility) and reusing it in both places.
| grep -q -- 'Sources/VoicePi/TextInjectionTiming.swift' "$TMP_DIR/.swiftc-args" | ||
| grep -q -- 'Sources/VoicePi/SpeechRecorderStopPolicy.swift' "$TMP_DIR/.swiftc-args" | ||
| grep -q -- 'Sources/VoicePi/RealtimeOverlayUpdateGate.swift' "$TMP_DIR/.swiftc-args" | ||
| grep -q -- 'Sources/VoicePi/PostInjectionLearningLoopPolicy.swift' "$TMP_DIR/.swiftc-args" | ||
| grep -q -- 'Sources/VoicePi/RecordingLatencyTrace.swift' "$TMP_DIR/.swiftc-args" |
There was a problem hiding this comment.
Scripts/benchmark.sh includes Sources/VoicePi/RecordingLatencyHistory.swift in the swiftc inputs, but this test doesn’t assert it. Add a grep -q check for that path alongside the other swiftc-arg assertions here so accidental removals from the benchmark build are caught.
| outcome: outcome, | ||
| finishedAt: RecordingLatencyTrace.currentTimestamp() | ||
| ) | ||
| recordingLatencyReporter.report(report) | ||
| self.activeRecordingLatencyTrace = nil |
There was a problem hiding this comment.
finishActiveRecordingLatency runs on the MainActor and calls recordingLatencyReporter.report(report), but the history reporter does synchronous JSON file I/O. This can add UI latency at the end of a recording. Consider offloading the history append off-main (e.g., via a detached Task/background queue or an async reporting API).
| } | ||
|
|
||
| func report(_ report: RecordingLatencyTrace.Report) { | ||
| logger.log("\(report.summary, privacy: .public)") |
There was a problem hiding this comment.
The unified log reporter marks the entire latency summary as privacy: .public, including the failure reason string. Since the reason may include user-visible error text (and potentially user content depending on error sources), consider using .private (or logging only sanitized / structured fields as public) to avoid leaking data into system logs.
| logger.log("\(report.summary, privacy: .public)") | |
| logger.log("\(report.summary, privacy: .private)") |
| } | ||
|
|
||
| let frame = pendingFrames.removeFirst() | ||
| pendingBytes -= frame.count | ||
| return frame |
There was a problem hiding this comment.
pendingFrames.removeFirst() is O(n) and will repeatedly shift the backing array while draining, which can become expensive when many small audio frames queue up. Consider switching to an O(1) queue (e.g., head index + periodic compaction, or a ring buffer) to keep the pump overhead predictable.
| BINARY_PATH="$TMP_DIR/voicepi-benchmark" | ||
|
|
||
| swiftc \ | ||
| -parse-as-library \ |
There was a problem hiding this comment.
The benchmark script compiles without optimizations. For microbenchmarks, Debug builds can produce misleading numbers and increase noise across runs. Consider adding -O (and optionally -whole-module-optimization) to the swiftc invocation so the reported ns/op is closer to release performance.
| -parse-as-library \ | |
| -parse-as-library \ | |
| -O \ | |
| -whole-module-optimization \ |
| touch "$TMP_DIR/Sources/VoicePi/TextInjectionTiming.swift" | ||
| touch "$TMP_DIR/Sources/VoicePi/SpeechRecorderStopPolicy.swift" | ||
| touch "$TMP_DIR/Sources/VoicePi/RealtimeOverlayUpdateGate.swift" | ||
| touch "$TMP_DIR/Sources/VoicePi/PostInjectionLearningLoopPolicy.swift" | ||
| touch "$TMP_DIR/Sources/VoicePi/RecordingLatencyTrace.swift" |
There was a problem hiding this comment.
The fixture doesn’t create Sources/VoicePi/RecordingLatencyHistory.swift, but Scripts/benchmark.sh compiles it. Add a touch "$TMP_DIR/Sources/VoicePi/RecordingLatencyHistory.swift" near the other touch calls so the test fixture mirrors the real benchmark inputs.
| try? fileManager.removeItem(at: historyFileURL) | ||
| let document = RecordingLatencyHistoryDocument() | ||
| try save(document) | ||
| return document | ||
| } |
There was a problem hiding this comment.
On decode/read errors, load() removes the existing history file and recreates a fresh document. This can silently wipe user history due to transient I/O issues or partial writes. Consider preserving the original file (e.g., rename to a .corrupt backup) and only resetting when you’re sure recovery isn’t possible.
This commit brings three performance and reliability improvements to the recording latency reporting system: - Non-blocking appends: RecordingLatencyHistoryReporter now uses a dedicated DispatchQueue to asynchronously append samples, ensuring the caller is never blocked. This prevents latency measurements from being skewed by slow disk writes. - Benchmark compiler optimizations: Added -O and -whole-module-optimization flags to the benchmark build script, enabling aggressive compiler optimizations for accurate performance profiling. - Code reuse via Duration.wholeMilliseconds: Extracted the repeated duration-to-milliseconds conversion into a shared extension method, eliminating duplication across TextInjectionExecutionPlan and PerformanceBenchmarkReport. Additional improvements: - UnifiedLogRecordingLatencyReporter now uses .private privacy to avoid leaking potentially sensitive audio/transcript content to system logs. - Corrupt history files are now backed up with a timestamp instead of being silently deleted, preserving diagnostic data for post-mortem analysis.
Summary
Test Plan