8000 perf: optimize response pipeline latency by pi-dal · Pull Request #8 · pi-dal/VoicePi · GitHub
[go: up one dir, main page]

Skip to content

perf: optimize response pipeline latency - #8

Merged
pi-dal merged 2 commits into
mainfrom
perf/response-pipeline
Apr 15, 2026
Merged

pi-dal merged 2 commits into
mainfrom
perf/response-pipeline

Conversation

@pi-dal
@pi-dal pi-dal commented Apr 15, 2026
Copy link
Copy Markdown
Owner

Summary

  • optimize the recording response pipeline with configurable text injection timing, recording latency tracing, and benchmark/reporting support
  • reduce realtime UI churn with transcript presentation state, overlay metering gates, and targeted speech stop policy changes
  • fix post-injection learning and realtime audio ingestion concurrency races, with regression coverage for session ownership and frame backpressure

Test Plan

  • swift test --filter PostInjectionLearningTests
  • swift test --filter RealtimeAudioFramePumpTests
  • swift test --filter RealtimeASRSessionCoordinatorTests
  • swift test --filter AppControllerInteractionTests
  • ./Scripts/test.sh

@gemini-code-assist gemini-code-assist Bot left a comment
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +306 to +311
private let recordingLatencyReporter: any RecordingLatencyReporting = RecordingLatencyCompositeReporter(
reporters: [
UnifiedLogRecordingLatencyReporter(),
RecordingLatencyHistoryReporter()
]
)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The recordingLatencyReporter is initialized with a concrete RecordingLatencyCompositeReporter containing hardcoded dependencies. This makes testing and configuration difficult. Consider injecting the reporters through the initializer or a factory to improve testability and modularity.

Comment on lines +31 to +35
lock.lock()
if hasOverflowed {
lock.unlock()
return
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The lock is held while checking hasOverflowed. While this is correct for thread safety, consider if the overflow state needs to be checked inside the lock or if an atomic boolean would suffice to reduce lock contention during high-frequency frame submission.

Comment on lines +236 to +243
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)
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The append method performs a full load-modify-save cycle on every append. For high-frequency recording, this could lead to significant I/O overhead. Consider buffering these samples in memory and writing them periodically or using a more efficient append-only storage mechanism.

Copilot AI left a comment
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +47 to +51
let components = duration.components
let secondsMilliseconds = components.seconds * 1_000
let attosecondsMilliseconds = components.attoseconds / 1_000_000_000_000_000
return Int(secondsMilliseconds + attosecondsMilliseconds)
}
Copilot AI Apr 15, 2026
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
Comment on lines +64 to +68
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"
Copilot AI Apr 15, 2026
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
Comment on lines +2990 to +2994
outcome: outcome,
finishedAt: RecordingLatencyTrace.currentTimestamp()
)
recordingLatencyReporter.report(report)
self.activeRecordingLatencyTrace = nil
Copilot AI Apr 15, 2026
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Copilot uses AI. Check for mistakes.
}

func report(_ report: RecordingLatencyTrace.Report) {
logger.log("\(report.summary, privacy: .public)")
Copilot AI Apr 15, 2026
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
logger.log("\(report.summary, privacy: .public)")
logger.log("\(report.summary, privacy: .private)")

Copilot uses AI. Check for mistakes.
Comment on lines +79 to +83
}

let frame = pendingFrames.removeFirst()
pendingBytes -= frame.count
return frame
Copilot AI Apr 15, 2026
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
Comment thread 8BD0 Scripts/benchmark.sh
BINARY_PATH="$TMP_DIR/voicepi-benchmark"

swiftc \
-parse-as-library \
Copilot AI Apr 15, 2026
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
-parse-as-library \
-parse-as-library \
-O \
-whole-module-optimization \

Copilot uses AI. Check for mistakes.
Comment on lines +17 to +21
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"
Copilot AI Apr 15, 2026
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
Comment on lines +222 to +226
try? fileManager.removeItem(at: historyFileURL)
let document = RecordingLatencyHistoryDocument()
try save(document)
return document
}
Copilot AI Apr 15, 2026
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
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.
@pi-dal
pi-dal merged commit a146e44 into main Apr 15, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

0