Skip to content

fix: cosy word identity dedupe - #2396

Merged
wangyoucao577 merged 11 commits into
mainfrom
fix/cosy-word-identity-dedupe
Nov 10, 2026
Merged

wangyoucao577 merged 11 commits into
mainfrom
fix/cosy-word-identity-dedupe

Conversation

@YiminW

@YiminW YiminW commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Two production Cosy TTS sessions exposed duplicate subtitle output:

  1. In one production session (turn 25), the provider emitted the same sentence twice under different sentence.index values. Both sentence.index=5 and sentence.index=6 contained 今道不行,吾等宁为义死,不为利生. Sentence index is therefore not a reliable identity for a new subtitle segment.
  2. In another production session (request id 3), the provider sent cumulative word lists repeatedly. The final cumulative event replayed words that had already been published, followed by an inconsistent terminal result. Republishing the cumulative prefix duplicated the final subtitle content and made the end state inconsistent.

Solution

Add provider-aware, request-scoped deduplication with safe fallbacks:

  • When begin_index/end_index are present, treat the provider word indexes as the request-level identity and publish only words beyond the already emitted boundary. This works across sentence indexes and prevents cross-sentence replays.
  • When indexes are absent, deduplicate on the sentence PCM timeline using adjusted (text, begin_ms, end_ms) identities. The boundary state is sentence-scoped and retains all identities at the current boundary, including multiple zero-duration words, so repeated cumulative events remain idempotent without unbounded per-request word storage.
  • Record a sentence's PCM origin at sentence-begin, including empty word lists, so delayed word metadata is aligned to the correct audio origin.
  • Keep terminal subtitle emission and tts_audio_end exactly once when the provider sends repeated cumulative or terminal events.

Regression coverage

  • Replay fixtures extracted from both production cases.
  • Cross-sentence duplicate sentence indexes and cumulative trailing terminal events.
  • Repeated cumulative lists with indexed and index-less words, including zero-duration words.
  • Cancellation cleanup racing with a replacement connection.
  • TTFB callback/request binding and interrupted request interval accounting.

The Cosy extension version is bumped to 0.5.1.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

[P2] Preserve distinct words when timestamps are sentence-relative
ai_agents/agents/ten_packages/extension/cosy_tts_python/cosy_tts.py:677

The fallback key is request-wide but uses unadjusted timestamps. For an index-less response with sentence-relative timing, which this adapter explicitly supports, the same word at 0-200 ms in two sentences gets the same key, so the second occurrence is silently omitted even though its PCM origin is different. Timestamp revisions to an already emitted word can also produce a new key and replay it. Preserve sentence/position identity for index-less events, while still handling actual cross-sentence replays, and cover repeated words and revisions.

[P2] Update the subtitle reference for cross-sentence replays
ai_agents/agents/ten_packages/extension/cosy_tts_python/cosy_tts.py:622

The registered Cosy subtitle timing hook still counts emitted words separately for each sentence. In the new cross_sentence_quote fixture, sentence 6 ends with the same words as sentence 5: this change correctly suppresses them, but the hook records a second caption for sentence 6. The guarder compares caption counts and therefore rejects that valid output instead of providing usable independent alignment coverage for the case this PR fixes. Update the reference and add a hook regression using the recorded event ordering.

[P2] Assert audio-end intervals on interrupted requests
ai_agents/agents/ten_packages/extension/cosy_tts_python/tests/test_words_alignment.py:536

The extension-local suite checks the exact controlled-clock event interval for success and zero for no audio, but its partial-error and flush-after-audio tests assert only PCM duration, not request_event_interval_ms. Those terminal paths can therefore use the wrong start/end boundary without failing the required accounting tests. Add controlled-clock assertions for both paths, including exactly-once termination.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

[P2] Scope the timing-based word key so sentence-relative timestamps are not dropped
ai_agents/agents/ten_packages/extension/cosy_tts_python/cosy_tts.py:673-677

When a word has no begin_index/end_index, _word_key falls back to ("timing", text, begin_ms, end_ms) and checks it against _emitted_word_keys, which covers the whole request. This fallback uses the raw provider times. The extension still supports providers that restart word times at 0 for each sentence (_sentence_word_offset, exercised by the 低头思故乡 plan in tests/test_words_alignment.py:93-106). With such a provider, two sentences can contain the same character at the same relative time and duration, for example two sentences that both open with 我 at 80–200 ms. The second word gets the same key, is treated as already published, and is silently left out of tts_text_result. The client then gets a caption and word list missing that word, even though its audio is played. The old per-sentence counter in _emitted_words could not collide across sentences.

Fix direction: build the timing fallback from the aligned request-timeline start (begin_ms + offset_ms for that sentence), or add the sentence index to the key when no provider indexes exist. Add a unit case with two index-less, sentence-relative sentences that repeat a word at the same relative timing.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

[P2] Preserve index-less words when sentence timestamps restart
ai_agents/agents/ten_packages/extension/cosy_tts_python/cosy_tts.py:631

_fallback_end_ms is request-wide, but this comparison uses the raw sentence-relative time. If an index-less sentence ends at 1600 ms and the next sentence restarts at 0 ms, every word beginning before 1600 ms is discarded even though its audio is new. The existing test_words_are_published_once_on_the_pcm_clock has exactly this case: its third sentence uses index-less 0–800 ms timestamps, so it no longer receives the expected subtitle batches. Keep the fallback identity aligned to the sentence/request PCM origin (while still handling actual cross-sentence replays) and cover this existing case.

[P2] Keep the independent subtitle reference consistent with cross-sentence replays
ai_agents/agents/ten_packages/extension/cosy_tts_python/cosy_tts.py:624

The registered Cosy timing hook still counts words independently by sentence. In the new cross_sentence_quote capture, the provider repeats sentence 5 words in sentence 6: this change suppresses the repeated words, but the hook records them again. The guarder compares the emitted captions to that reference and consequently rejects this valid output. Update the independent reference to recognize provider word identity across sentences and add a regression using the recorded event order.

[P2] Associate TTFB hook observations with the originating request
ai_agents/agents/ten_packages/extension/cosy_tts_python/cosy_tts.py:450

The required Cosy TTFB observer wraps each SDK callback but records audio against the reference’s current request rather than the callback’s request. After a flush, a late audio callback from the canceled request can arrive after the next request sends text; the hook records that old audio as the new request’s first audio before forwarding it to the canceled callback, which would discard it. This produces an incorrect independent TTFB reference. Bind the observer to the callback/request or provider task identity and test a late old callback after a new request begins, as well as pool reuse.

[P2] Assert audio-end intervals for interrupted requests
ai_agents/agents/ten_packages/extension/cosy_tts_python/tests/test_words_alignment.py:536

The extension-local suite asserts a controlled-clock event interval for success and zero for no audio, but the partial-error and flush-after-audio tests assert only emitted PCM duration. An incorrect request_event_interval_ms on either terminal path can therefore pass the required accounting tests. Add controlled-clock start-to-end interval assertions for both paths and verify exactly-once termination.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

[P1] Keep the timestamp fallback scoped to its sentence timeline
ai_agents/agents/ten_packages/extension/cosy_tts_python/cosy_tts.py:41 (diff: else word.begin_ms >= self._fallback_end_ms)

When word entries have no begin_index/end_index, the new dedupe compares raw provider begin_ms against a request-wide _fallback_end_ms. That comparison runs before _sentence_word_offset maps the times onto the PCM clock. The extension still supports providers whose word times restart at 0 for each sentence (the offset branch in _sentence_word_offset). For those providers, every word after the first sentence has begin_ms below the previous sentence end and lands outside unseen, so all later subtitles are silently dropped. The existing test_words_are_published_once_on_the_pcm_clock exercises this path. Its third SentencePlan (低头思故乡, words starting at 0 after _fallback_end_ms reaches 1600, no indexes) expects starts[6:] == [1600, 1800, 2000], and with this change that sentence publishes no batches, so the test should fail. Fix direction: in the no-index path, compare after the offset is applied (PCM-timeline ms), or keep the fallback boundary per sentence as the old _emitted_words did.

[P3] Avoid republishing zero-duration words in the timestamp fallback
ai_agents/agents/ten_packages/extension/cosy_tts_python/cosy_tts.py:41

On the no-index path, _fallback_end_ms is set to the last published end_ms, and the filter keeps words with begin_ms >= _fallback_end_ms. If the last published word has zero duration (begin_time == end_time, which happens for punctuation), it passes the filter again on the next cumulative event and is published twice. The index path uses >= safely because end_index > begin_index, but a time-only filter needs a strict comparison or a (begin, end, text) identity check to stay idempotent. Add a unit case that repeats a cumulative list ending in a zero-duration word without indexes.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

[P3] Keep all zero-duration words at a timestamp idempotent
ai_agents/agents/ten_packages/extension/cosy_tts_python/cosy_tts.py:709

The fallback remembers only the last published word at the boundary. If an index-less cumulative event contains two different zero-duration entries at the same timestamp followed by another word, both zero-duration entries are published in the first batch; on the next identical event, the earlier one passes key != _fallback_last_key and is emitted again. _parse_words explicitly accepts zero-duration entries, and the one-word subtitle lag does not prevent this sequence. Preserve enough identity at the boundary to deduplicate all entries sharing it, and add a repeated cumulative-event test.

[P2] Update the independent subtitle reference for cross-sentence replays
ai_agents/agents/ten_packages/extension/cosy_tts_python/cosy_tts.py:631

The registered Cosy timing hook counts words independently per sentence, but the new cross_sentence_quote capture ends sentence 6 with the same 17 indexed words as sentence 5. This change suppresses those words while the reference records them again, so the subtitle guarder rejects the output for the provider sequence this PR fixes. Update the independent reference to recognize cross-sentence provider identity and cover the recorded ordering.

[P2] Bind the TTFB reference to the originating request
ai_agents/agents/ten_packages/extension/cosy_tts_python/cosy_tts.py:450

The mandatory Cosy TTFB hook wraps each SDK callback but records audio against the reference current request, rather than the callback request. After a flush, a late audio callback from the cancelled request can arrive after the next request sends text; the observer then records that old audio as the new request first audio, even though the cancelled production callback discards it. Associate the observation with the callback or provider task and test a late old callback after the next request starts, including pool reuse.

[P2] Assert the event interval on interrupted requests
ai_agents/agents/ten_packages/extension/cosy_tts_python/tests/test_words_alignment.py:536

The local suite checks a controlled-clock request_event_interval_ms for success and zero for no audio, but the partial-error and flush-after-audio tests assert only PCM duration. An incorrect start or end boundary on either interrupted path therefore passes the required audio-end accounting tests. Add controlled-clock interval assertions to both paths while retaining the existing exactly-once termination checks.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

No actionable TTS-specific findings.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

[P2] Test cancellation against an active replacement connection
ai_agents/agents/ten_packages/extension/cosy_tts_python/tests/test_connection_reuse.py:486

The local suite checks flush accounting and that a subsequent request can begin, but it does not hold the old task’s streaming_cancel or lease cleanup open while a replacement request acquires its connection, then release the old cleanup and verify the replacement completes. _cancel_active runs in the background and discards its lease after cancel() permits a new request, so this ordering is important to the required custom-transport coverage: a regression that closes the replacement or delivers stale callbacks could pass the existing sequential tests. Add a deterministic fake with synchronization barriers, and assert the replacement remains usable, receives only its own audio, and ends exactly once after the old cleanup finishes.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

No actionable TTS-specific findings.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

Correction to my previous comment: there is one finding.

[P2] Choose the sentence time offset from new words, not from replayed words that dedupe skips
ai_agents/agents/ten_packages/extension/cosy_tts_python/cosy_tts.py:630

_sentence_word_offset decides once per sentence. It looks only at the first word it receives, and that decision is reused for every later word in the sentence. This PR now passes it the full words list before filtering by begin_index. In the cross-sentence replay case this PR targets, sentence N+1 opens with words from sentence N, so the decision is based on a word that is about to be dropped.

Here is how it goes wrong. Take the shape in test_word_identity_is_shared_across_sentences: sentence 5 has 今 (0–200 ms) and 道 (200–400 ms). Sentence 6 begins after about 400 ms of PCM and replays 今道 first.

  • first_begin_ms = 0 is less than origin_ms - SENTENCE_TIME_TOLERANCE_MS (about 200 ms).
  • So sentence 6 is classified as sentence-relative, with offset_ms ≈ 400.
  • The replayed words are dropped correctly. But every new word in sentence 6, and its start_ms, is shifted about 400 ms later than the audio.

This happens whenever the replayed prefix starts more than 200 ms before the new sentence origin, for example two or more replayed CJK characters. The unit test misses it because it never feeds PCM, so origin_samples stays 0.

Fix direction: compute the offset from unseen[0], or from the first word at or past the index boundary. Add a unit test that feeds PCM between sentence 5 and sentence 6, then asserts the absolute start_ms of sentence 6's first new word.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

Retraction of my previous comment: the offset finding does not meet the "introduced by this PR" bar. On the base branch, the first _build_subtitle call for a sentence also passed words[0:limit], so _sentence_word_offset already decided from the first replayed word. This PR keeps that behavior and does not make it worse. A replayed prefix more than 200 ms before the sentence origin can still shift that sentence's captions, but that is a separate, pre-existing issue and not a blocker here.

No actionable TTS-specific findings.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

[P2] Restore the flush-during-finalization test
ai_agents/agents/ten_packages/extension/cosy_tts_python/tests/test_connection_reuse.py:369

The new test is inserted before the rest of test_finalizing_request_does_not_block_next_request_after_flush, so that existing test now ends immediately after the first audio frame. Its original wait for finish-task, flush, and replacement request have become the tail of the new test, where they execute after a different request has already completed. As a result, no test verifies that flushing while streaming_complete is blocked lets a replacement request start promptly. Move the original body back into its test and keep the new cancellation scenario separate.

[P2] Wait for old cleanup while the replacement is still active
ai_agents/agents/ten_packages/extension/cosy_tts_python/tests/test_connection_reuse.py:416

Releasing finish_task_release does not wait for the old streaming_cancel and lease discard to finish, and the replacement server can already have sent its audio and terminal event by this point. The test can therefore pass even if old cleanup later closes or disrupts an active replacement connection, which is the race this test is intended to cover. Add a barrier around completion of the old client-side cleanup, hold the replacement open until that barrier is reached, and then verify its own audio and exactly one terminal event.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

[P2] Move the new connection-reuse test out of the existing finalizing test body
ai_agents/agents/ten_packages/extension/cosy_tts_python/tests/test_connection_reuse.py:367

test_replacement_survives_blocked_cancel_cleanup was inserted right after await ctx.expect_audio_frame(timeout=0.5) inside test_finalizing_request_does_not_block_next_request_after_flush. The hunk context shows the rest of that older test (finish_started = await asyncio.to_thread(...), the flush-finalizing flush, and the request-after-finalizing-cancel request) now sits at the end of the new test. Two things break as a result:

  • The finalizing regression test now stops after the first audio frame. It no longer checks that a flush during finish-task returns tts_flush_end or that the next request still gets audio, so the flush/finalize race it was written for has no coverage.
  • The new test inherits that tail. After its own assert_no_data, it sends a second flush and another request, and it waits on finish_task_received, which is already set. So it checks a different sequence than its docstring says, and it uses part of its 3.0 s budget on steps unrelated to blocked-cancel isolation.

Fix: put the new test after the end of the original finalizing test, and keep the original test body in one piece.

No other actionable TTS-specific findings. The request-scoped begin_index/end_index dedupe and the time-boundary fallback in cosy_tts.py reset per request, because a new AsyncIteratorCallback is created for each active task. The recorded fixtures confirm that indexes run across sentences (sentence 1 starts at index 13).

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

[P2] Consume the first request terminal event before starting the next
ai_agents/agents/ten_packages/extension/cosy_tts_python/tests/test_connection_reuse.py:285

Removing the first tts_audio_end read leaves request-0’s terminal event in TenTestContext.received_data. The next _synthesize waits for request-1 audio and then reads the first tts_audio_end by name, so it receives the queued request-0 event and fails its request-ID assertion. The connect-delay metric is emitted before synthesis, and expect_audio_frame uses a separate queue, so neither consumes that terminal event. Restore the read (and assert its request ID) before the loop so the sequential pool-reuse test can pass and check each request independently.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

No actionable TTS-specific findings.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

Correction to my previous comment: there is one finding.

[P3] Restore the first request's tts_audio_end wait in the sequential reuse test
ai_agents/agents/ten_packages/extension/cosy_tts_python/tests/test_connection_reuse.py:285

This PR removes await ctx.expect_data("tts_audio_end", timeout=0.5) after request-0. That end event is still emitted, and TenTestContext.expect_data(name) returns the first queued data with that name. The next call, _synthesize(ctx, "request-1", ...), therefore reads request-0's tts_audio_end. Every later iteration then reads the previous request's end. One of two things follows. The payload_dict["request_id"] == request_id assertion fails. Or, if the end event for request-0 is not emitted, the test no longer checks that request-0 terminates exactly once. In both cases the sequential-lifecycle check is weakened. The change is also unrelated to word dedupe. Fix: restore the wait and assert that its request_id is request-0.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

No actionable TTS-specific findings.

Scope reviewed: cosy_tts_python (existing WebSocket/custom extension) covering cosy_tts.py, manifest.json, pyproject.toml, and the extension-local tests and fixtures. The cosy TTFB hook and subtitle timing hook are present and updated for the touched extension. tts_audio_end paths are unchanged by this diff, and the new tests now assert request_event_interval_ms on the error and flush paths.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

[P2] Preserve overlapping index-less words across cumulative events
ai_agents/agents/ten_packages/extension/cosy_tts_python/cosy_tts.py:725

The timestamp fallback treats the end of the last emitted word as a lower bound on the start of every later word. For an index-less cumulative stream with A at 0–200 ms and B at 180–400 ms, sentence-begin publishes A (the last word is held back), then sentence-end discards B because 180 < 200. Both intervals pass _parse_words, and the former per-sentence count published both; overlapping alignment intervals therefore now silently remove spoken words from captions. Track already-published word identity or position rather than requiring disjoint timing intervals, and add a cumulative-event regression with overlapping words.

[P2] Hold the old cancellation itself until the replacement is active
ai_agents/agents/ten_packages/extension/cosy_tts_python/tests/test_connection_reuse.py:428

Blocking the fake server’s finish-task response does not guarantee that old client cleanup is still pending: active.callback.cancel() sets the SDK complete_event before _cancel_active calls streaming_cancel, so the SDK wait can return without the server response and discard_lease may complete before the replacement is started. The test only waits for cleanup_done after starting the replacement; it never establishes that cleanup was pending at that point. Consequently it can pass without exercising the required concurrent cancellation/connection-ownership race. Put a barrier in the old client cancellation or discard path, assert it is reached and not released when the replacement acquires its connection, then release it and verify the replacement completes.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

[P2] Preserve index-less words whose timestamps overlap
ai_agents/agents/ten_packages/extension/cosy_tts_python/cosy_tts.py:727

The fallback treats a word as new only when its start is at or after the previous published end, but valid word timings can overlap and the parser does not require non-overlapping intervals. For an index-less cumulative event containing A at 0–200 ms and B at 150–300 ms, sentence-synthesis publishes A and holds B back; when sentence-end repeats both, B starts before the 200 ms boundary and is discarded, so the audio plays without B in tts_text_result. The previous per-sentence position counter emitted B. Track word identity or position independently of the prior word’s end time, and add a cumulative-event regression with overlapping timings.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

No actionable TTS-specific findings.

Scope reviewed: cosy_tts_python (WebSocket/custom transport, existing extension). I checked the request-scoped begin_index/end_index dedupe in _handle_output, the timestamp fallback for words without indexes, _parse_words, and the new local tests (cross-sentence replay fixtures, repeated cumulative lists, zero-duration boundary words, blocked-cancel replacement isolation, and the request_event_interval_ms assertions on the error and flush paths). The callback is created once per task, so the new boundary state cannot leak between requests. The PR does not touch any tts_audio_end path. The Cosy TTFB hook and the subtitle timing hook are both still registered and were updated for the new identity scheme. This is not a new extension, so the guarder screenshot and PCM evidence requirement does not apply. The PR is not ASR-related.

@wangyoucao577
wangyoucao577 merged commit ac38c97 into main Nov 10, 2026
37 checks passed
@wangyoucao577
wangyoucao577 deleted the fix/cosy-word-identity-dedupe branch November 10, 2026 13:54
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