Skip to content

fix(voice): don't duplicate queued speeches on scheduling tie - #7283

Open
yaosongding wants to merge 1 commit into
livekit:mainfrom
yaosongding:audit/main-2025-09-14
Open

yaosongding wants to merge 1 commit into
livekit:mainfrom
yaosongding:audit/main-2025-09-14

Conversation

@yaosongding

Copy link
Copy Markdown

Problem: AgentActivity._schedule_speech pushes (-priority, time.perf_counter_ns(), speech) onto self._speech_q in a while True loop that catches TypeError. When priority and timestamp tie, Python compares the unorderable SpeechHandle and raises TypeError. Because heapq.heappush appends the item to the underlying list before sifting up, catching TypeError and retrying leaves the first item in the queue and appends a duplicate, breaking the heap invariant and scheduling duplicate playout tasks.

Fix: Break ties using a strictly increasing counter (itertools.count()) instead of timestamps. Since (priority, seq) never ties, comparison never reaches SpeechHandle, eliminating the TypeError and retry loop while guaranteeing strict FIFO order for equal-priority speeches.

Verification

  • Added regression test tests/test_speech_queue.py verifying same-priority speeches are enqueued without duplicates.
  • Ran pytest tests/test_speech_queue.py tests/test_interrupt_protected_speech.py --unit -q.
  • Passed ruff check and mypy -p livekit.agents.

`_schedule_speech` pushed `(-priority, time.perf_counter_ns(), speech)` into a max-heap and swallowed `TypeError` to retry when timestamps tied. Because `heapq.heappush` appends the item before sifting, catching `TypeError` from the unorderable `SpeechHandle` leaves the failed item in the list. Each retry appends another copy and breaks the heap invariant, causing duplicate generation and playout tasks.

Break ties with a strictly increasing counter (`itertools.count()`) instead. `(priority, seq)` never ties, eliminating the `TypeError` and the retry loop while guaranteeing strict FIFO order for equal priorities.
@CLAassistant

CLAassistant commented Sep 15, 2026

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@yaosongding
yaosongding marked this pull request as ready for review September 15, 2026 04:53
@yaosongding
yaosongding requested a review from a team as a code owner September 15, 2026 04:53

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ Devin Review: No Issues Found

Devin Review analyzed this PR and found no bugs or issues to report.

Devin Review

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