Skip to content

AVSpeech: reuse one synthesizer in speak_to_memory to fix a teardown crash under rapid synthesis - #80

Merged
ethindp merged 3 commits into
ethindp:masterfrom
aaronr7734:fix/avspeech-reuse-memory-synthesizer
Jul 21, 2026
Merged

ethindp merged 3 commits into
ethindp:masterfrom
aaronr7734:fix/avspeech-reuse-memory-synthesizer

Conversation

@aaronr7734

Copy link
Copy Markdown
Contributor

Summary

AVSpeechBackend::speak_to_memory allocates a new AVSpeechSynthesizer for
every call and lets the calling thread drop the last reference when the call
returns. Destroying a synthesizer while Apple's TextToSpeech framework still
has callback blocks for it queued on the main dispatch queue is racy: the
teardown runs on the framework's AXSpeech thread, and a late callback block
then dereferences freed state and crashes the process (EXC_BAD_ACCESS,
KERN_INVALID_ADDRESS).

This is hard to hit with occasional synthesis, but a caller that synthesizes
many short utterances in quick succession — dozens of speak_to_memory calls
per minute, sustained — loses the race within minutes.

This PR makes the backend keep one long-lived synthesizer for memory
synthesis, mirroring what the class already does for the live speak path
(the synthesizer member). No API or behavior change otherwise.

Crash evidence

Observed on macOS 26 in an x86_64 process running under Rosetta 2. The crash
report shows:

  • Crashed thread (main): EXC_BAD_ACCESS / KERN_INVALID_ADDRESS at 0x10
    inside a dispatch_call_block_and_release block whose program counter is in
    TextToSpeech.framework.
  • At the same moment, the AXSpeech thread is mid-teardown of TextToSpeech
    objects: a chain of _objc_rootDealloc / object_cxxDestructFromClass
    frames through TextToSpeech, including a Combine CurrentValueSubject
    deinit.
  • The only in-process TTS user is the Prism AVSpeech backend's
    speak_to_memory path; every call created and destroyed one synthesizer.

I can attach the full .ips crash report if useful.

Fix

  • Add a memory_synthesizer member, created lazily on the main thread on the
    first speak_to_memory call and reused for the life of the backend, so no
    synthesizer teardown ever runs while the framework may still hold callbacks.
  • If a previous utterance somehow left it speaking (e.g. the caller's wait
    timed out), stop it with AVSpeechBoundaryImmediate before writing the next
    utterance.
  • Release it in the destructor alongside the existing synthesizer member.

One file changed, source/backends/avspeech.cpp; formatted with the repo's
.clang-format. Most of the diff's line count is the writeUtterance: call
body re-indenting under the renamed receiver.

Why this is safe

  • speak_to_memory already serializes per backend instance in practice (the
    caller waits on the accumulator semaphore before issuing the next call), so
    the reused synthesizer never sees overlapping write requests, and the
    stop-before-reuse guard covers the timeout path.
  • The reused object holds no per-utterance state: voice, rate, pitch, and
    volume are set on each AVSpeechUtterance, not on the synthesizer.
  • Memory cost is one retained synthesizer per backend instance, in exchange
    for dropping a full registration + teardown cycle per utterance.

Testing

  • Built for x86_64 macOS with the project CMake (gdextension/tests/demos off);
    compiles with no new warnings.
  • Deployed in the application where the crash was found, which drives this
    exact path with rapid short-utterance synthesis. Before the change, the
    crash was reproducible under sustained use with the signature above; with
    the patch applied, the same workload runs without crashes or audio
    regressions.

Allocating a new AVSpeechSynthesizer per call and destroying it from the
calling thread races TextToSpeech's teardown (on its AXSpeech thread)
against callback blocks still queued on the main dispatch queue; under
sustained rapid synthesis a late block dereferences freed state and
crashes (EXC_BAD_ACCESS, KERN_INVALID_ADDRESS).

Keep one long-lived synthesizer for memory synthesis, mirroring the live
speak path: create it lazily on the main thread, stop it before reuse if
a prior utterance is still active, and release it in the destructor.
@ethindp

ethindp commented Jul 19, 2026

Copy link
Copy Markdown
Owner

@aaronr7734 Can you explain why in your diff you rewrote the entire writeUtterance block instead of just replacing the first line? (Also, the comment is unnecessary at the top of the class, as it is obvious from the member name what this synthesizer does.)

Additionally, can you provide the code that triggers this reliably? Please ensure that it is in the form of a test so that we can start creating a regression suite.

@aaronr7734

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Both cleanups are pushed.

On the diff churn: that was a clang-format artifact, not a rewrite. Renaming the receiver from mem_synth to the longer memory_synthesizer pushed the message send past the column limit, so clang-format moved the receiver onto its own line and re-indented the whole callback body. I've restored the original shape by keeping a short local alias to the member inside the sync_on_main block.

On a reliable trigger: I'm not sure that a deterministic reproduction is possible here, because the race is inside Apple's TextToSpeech framework. As far as I can tell, the crash depends on whether a queued callback block on the main queue runs before or after the framework's AXSpeech thread finishes tearing down the synthesizer. What I can offer is the full crash report, attached.

One thing I did notice when reviewing the crash report again is the crashed frame's program counter is unattributed, because the process ran x86_64 under Rosetta 2 and the PC lands in translated code that belongs to no binary image. The TextToSpeech connection is inferred from the rest of the report the crashing thread was executing a queued main-queue block, while the AXSpeech thread was simultaneously mid-dealloc of TextToSpeech objects (including a Combine CurrentValueSubject deinit), and this backend's speak_to_memory path was the only in-process TTS user.

Anyway, the crash dump can be found here.

@ethindp

ethindp commented Jul 19, 2026

Copy link
Copy Markdown
Owner

@aaronr7734 That is interesting. Can you test under ordinary execution (non-Rosetta)? I'm curious if this reoccurs there.

I would like to get some kind of reliable reproduction if at all possible, but race conditions are always annoying to (reliably) trigger.

@ethindp
ethindp merged commit 161a556 into ethindp:master Jul 21, 2026
59 checks 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