Skip to content

Cut back incomplete UTF-16 surrogate pairs in JSONCompleter - #442

Open
Pybsama wants to merge 2 commits into
huggingface:mainfrom
Pybsama:complete-partial-surrogate-pairs
Open

Pybsama wants to merge 2 commits into
huggingface:mainfrom
Pybsama:complete-partial-surrogate-pairs

Conversation

@Pybsama

@Pybsama Pybsama commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Fix JSONCompleter.completeString so that when a streamed JSON string ends right after a UTF-16 high surrogate escape (\uD800–\uDBFF) or mid-way through its trailing low surrogate (\uD83D\, \uD83D\u, \uD83D\uDE, \uD83D\uDE0), completion cuts back to the start of the high surrogate escape instead of closing the string with an unpaired high surrogate.
  • Previously, closing right after a high surrogate produced invalid JSON ("Hi \uD83D") that JSONSerialization / JSONDecoder reject, causing GeneratedContent(json:) to lose structured object decoding and fall back to .string(rawJSON) until the full low surrogate arrived.
  • Add regression tests in JSONCompleterTests.handlesPartialSurrogatePairs covering every character-by-character prefix of surrogate-pair escapes, lowercase hex, object keys/values, and GeneratedContent(json:).

Verification

  • swift format lint --strict --recursive . — passed
  • swift test --disable-index-store --filter "JSONCompleterTests|GeneratedContentJSONTests" — 41/41 tests in 2 suites passed (failed with 21 issues in handlesPartialSurrogatePairs before the fix)
  • swift test --skip-build --disable-index-store --skip OllamaLanguageModelTests — 1,104/1,104 tests in 113 suites passed

@mattt

mattt commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

Hi @Pybsama. Thanks for this! One problem before we merge: when the low-surrogate escape after a high surrogate hits a non-hex character before the end of the input, completeString still cuts the string back. For {"a":"\uD83D\uDE","b":1}, the result parses as {"a":""} and silently drops "b":1, instead of falling back to the raw string. Could you cut back only when the scan reaches the end of the input, and add a regression test for that case?

@Pybsama

Pybsama commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @mattt for catching that! Updated completeString in e3d3f5d so both short \uXXXX and trailing low-surrogate cut-backs only trigger when the scan reaches json.endIndex, and added regression tests for {"a":"\uD83D\uDE","b":1} and {"a":"\u12","b":1} verifying completer.complete leaves them untouched and GeneratedContent(json:) falls back to .string(...).

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