Repository navigation
fix(helpers): decode XML entities in ssml_to_deepgram - #812
Open
RaphaelFakhri wants to merge 3 commits into
Open
RaphaelFakhri wants to merge 3 commits into
RaphaelFakhri wants to merge 3 commits into
Conversation
RaphaelFakhri
requested review from
GregHolmes,
deepgram-kiley and
dg-coreylweathers
as code owners
October 22, 2026 12:46
GregHolmes
force-pushed
the
fix/ssml-xml-entities
branch
from
November 30, 2026 13:41
468a8de to
77131eb
Compare
The entity decoder added in the previous commit called `chr()` on any numeric
character reference `chr()` would accept. Three ranges that a conforming XML
parser rejects got decoded anyway, and one of them is not merely wrong output:
ssml_to_deepgram("<speak>a�b</speak>") -> 'a\ud800b'
`chr(0xD800)` is a lone UTF-16 surrogate. The resulting `str` raises
`UnicodeEncodeError` the moment anything encodes it as UTF-8, so a request
carrying it fails deep inside the HTTP client with an error that names neither
the SSML nor the reference that produced it. Before this change the same input
passed through as the literal text `a�b`, which encodes cleanly and
which the API can simply read or reject.
Decode a numeric reference only when it falls in the XML 1.0 `Char`
production, and leave it as written otherwise. That restores the prior
behavior for surrogates (`�`, `�`), NUL and the C0 controls
(`�`, ``) and the BMP non-characters (``). References past the
last code point were already left literal by the existing `try`/`except`; this
does not change them. Every code point XML does allow still decodes, including
the boundaries at 0x9, 0xD7FF, 0xE000, 0xFFFD and 0x10FFFF.
Also record a pre-existing limitation the entity decoding makes easier to
reach: a pause marker arriving as literal text never passes through
`replace_break`, so its duration is not range checked. `<break time="9999ms"/>`
raises, while the same marker written as text does not. The count limits still
apply, because `_control_counts` runs after decoding. A marker typed directly
behaves identically on main, so this is behavior worth pinning rather than a
regression this change introduces.
Entity decoding runs on the `<phoneme>` word and `ph` value while the control
is built, so `<` can put a literal `<` into text that the "remove any
remaining XML tags" pass still has to run over. That pass then deletes from
the `<` to the next `>` anywhere later in the document, and a later `>` comes
from every subsequent SSML tag, so it is the normal case rather than an edge
one. Two failure modes, both verified against production:
<speak><phoneme alphabet="ipa" ph="lɛs"><</phoneme> is
<emphasis>less</emphasis></speak>
-> '\{"word": "less'
-> HTTP 400 MALFORMED_CONTROL_CLOSURE
<phoneme alphabet="ipa" ph="x">a<b>c</phoneme>
-> '\{"word": "ac", "pronounce": "x"\}'
-> HTTP 200, dg-pronunciations-applied: 1, no dg-warnings
The second is the worse one: the response is indistinguishable from a correct
request, so the caller pays for audio that speaks the wrong word with nothing
in the headers to show it. `<` and `>` are two of the five entities this
feature exists to decode, so a caller has every reason to write them here.
Hold each built control aside behind a NUL-delimited placeholder, run the tag
strip and the entity decode over the remaining text, then put the controls
back last. Caller text cannot name a slot: NUL is not a legal XML character,
so it is removed on entry, and `_is_xml_char` already refuses to decode `�`
into one. Holding the controls aside is also what keeps their contents from
being decoded twice, which is what `_unescape_xml_outside_controls` did before;
that helper and `_CONTROL_PATTERN` are now unused and removed. Entities a
caller hand-wrote inside an inline control in SSML text are now decoded like
any other text, where they were skipped before.
Both rows now return the structurally correct control and HTTP 200 with
dg-pronunciations-applied: 1 and no warnings.
Also correct a false statement in the previous commit's docstring. A
conforming XML parser does not pass an out-of-`Char` reference through; XML 1.0
section 4.1 (WFC: Legal Character) makes it a fatal error and the parser
rejects the document. This converter is deliberately more lenient.
GregHolmes
force-pushed
the
fix/ssml-xml-entities
branch
from
December 2, 2026 16:48
e52f399 to
ad38b81
Compare
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
ssml_to_deepgram()andTextBuilder.from_ssml()strip SSML tags but never decoded XML entities. SSML is XML, so&must be written&, and apostrophes and quotes are commonly written',"or'. Those entities reached the TTS request unchanged. Fixes #811.This is not cosmetic: the voice speaks the markup
Verified against production, synthesizing with
aura-2-thalia-enand transcribing the result back withnova-3:/v1/speakCall AT&T, it's open.Call ATMT. It opposes open.Call AT&T, it's open.Call AT and T. It's open.café and caféCafan pound two hundred thirty three and cafe'is heard as "opposes".éis read aloud as "pound two hundred thirty three". The escaped audio was 159404 bytes against 113324 for the decoded text, because the voice is speaking the entity. Byte counts and exact transcripts are one run and vary between syntheses; the direction does not. The response headers below reproduced exactly across runs.The pronunciation path is worse, because the request succeeds with a warning most callers never read:
\{"word": "AT&T", "pronounce": "tə"\}\{"word": "AT&T", "pronounce": "tə"\}dg-pronunciations-applied11dg-warningsPRON-001Call Tian Pound six zero one today.Call to today.The control is not dropped, it is applied with a corrupt IPA value.
Fix
Decode the five predefined XML entities and numeric character references, in the
<phoneme>word andphvalue before building the pronunciation control, and in the remaining text after tag stripping. Inline controls are skipped so nothing is decoded twice, and escaped markup such as<break/>stays literal text rather than being parsed. HTML-only names such as©and a bare&are left alone.A numeric reference is decoded only when it falls inside the XML 1.0
Charproduction. This matters beyond correctness:chr(0xD800)is a lone UTF-16 surrogate, and the resultingstrraisesUnicodeEncodeErroras soon as anything encodes it as UTF-8, so�would fail deep inside the HTTP client with an error naming neither the SSML nor the reference. Surrogates, NUL, the C0 controls and the two non-characters at the end of the BMP (U+FFFE, U+FFFF) are left as written. U+FDD0 to U+FDEF are also non-characters but XML'sCharproduction allows them, so they still decode. A conforming parser would reject the whole document on such a reference; this converter is deliberately more lenient and passes it through as text, which is what it did before. Every code point XML allows still decodes, boundaries included.A
<decoded into a phoneme was eaten by the tag stripperDecoding runs on the
<phoneme>word andphvalue while the control is built, so<could put a literal<into text the "remove any remaining XML tags" pass still had to run over. That pass deleted from the<to the next>anywhere later in the document, and a later>comes from every subsequent SSML tag:<phoneme alphabet="ipa" ph="lɛs"><</phoneme> is <emphasis>less</emphasis>\{"word": "<", ...\} is less\{"word": "less→ HTTP 400MALFORMED_CONTROL_CLOSURE\{"word": "<", "pronounce": "lɛs"\} is less→ 200<phoneme alphabet="ipa" ph="x">a<b>c</phoneme>\{"word": "a<b>c", ...\}\{"word": "ac", ...\}→ 200, no warning\{"word": "a<b>c", "pronounce": "x"\}→ 200The second row is the worse one: headers are indistinguishable from a correct request, so the caller pays for audio speaking the wrong word with nothing to show it. Controls are now held aside behind NUL-delimited placeholders while tags are stripped and entities decoded, then restored. Caller text cannot forge a placeholder: NUL is removed on entry and
�is not decoded into one.Behavior change
No realistic SSML changes from accepted to rejected. Plain entities, numeric references, phonemes, escaped markup and breaks all still convert. Two contrived inputs do now raise, correctly, because after decoding the text really does contain what the error describes: nine pause markers written as
\{pause:500ms\}raise the eight-pause limit, and an entity-escaped pronunciation marker beside a<break>raises the mixed-controls error.Known limitation, recorded in a test
A pause marker arriving as literal text never passes through
replace_break, so its duration is not range checked:<break time="9999ms"/>raises, the same marker written as text does not. Count limits still apply, since_control_countsruns after decoding. This behaves identically on main for a marker typed directly, so entity decoding only makes an existing gap easier to reach.test_entity_injected_pause_is_not_range_checkedpins it.Verification
pytest tests/custom: 1139 passed, 1 skipped, 1 xfailed. 119 passed inpython:3.10-slimandpython:3.13-slimcontainers, covering CI's matrix ends.mypy src/: 955 files clean.mypy tests/typecheckclean.ruff checkclean on both changed files.Char-range tests fail without the range check; five of the seven invalid references were decoded before it.Both files are permanently frozen in
.fernignore, so no Fern regeneration interaction applies.The entity decoding, its four tests and the issue report are @RaphaelFakhri's work. The
Char-range restriction, the tag-stripper fix, their tests and the recorded pause limitation were added on top by a maintainer.