fix(providers): sanitize UTF-16 surrogates at provider request boundary

Symptom
-------
LLM requests intermittently fail with:
  'utf-8' codec can't encode characters in position N-N+1: surrogates not allowed
when messages contain emoji-heavy content (e.g. HTML with mixed emoji + JSON round-trips).
This blocks the affected session until the session file is quarantined.

Root cause
----------
Surrogate sanitization was only applied at the CLI entry point
(nanobot/cli/commands.py: _sanitize_surrogates). Requests entering
the LLM provider layer through other channels (Feishu, cron, webui,
tool results, memory injection) had no defensive cleaning, so any
message that happened to carry unpaired UTF-16 surrogates (from an
upstream JSON round-trip with ensure_ascii=True on ill-formed input,
memory rehydration, or third-party content) would blow up at
json.dumps -> HTTP encode time inside the provider client.

Fix
---
1. Extract sanitize_surrogates() and sanitize_surrogates_deep() into
   nanobot/utils/helpers.py as the single source of truth. Both use
   utf-16-le round-tripping with errors='surrogatepass' / 'replace',
   so paired surrogates reconstruct back into their real code point
   and lone surrogates collapse to U+FFFD.
2. Make nanobot/cli/commands.py:_sanitize_surrogates a thin wrapper
   that re-exports the shared helper (backward compatible).
3. Add defense-in-depth at the LLM provider boundary in
   nanobot/providers/base.py:_sanitize_empty_content by running
   sanitize_surrogates_deep over each message and its content blocks
   right before requests are serialized to JSON.

Non-goals
---------
- truncate_text() is intentionally left untouched. Python str slicing
  cannot split a single code point into surrogate halves, so it is
  not the source of lone surrogates.
- session/manager storage layer is untouched. Archived sessions
  reproduced the failure only through the request path, not through
  storage.

Verification
------------
- New regression suite tests/providers/test_sanitize_surrogates.py
  covers: paired surrogate reconstruction, lone surrogate replacement,
  identity return on clean input (zero allocation), deep recursion on
  dict/list/tuple, provider _sanitize_empty_content integration, and
  full utf-8 encodability of the sanitized request body.
- 14/14 new tests pass; full existing test module also green.
- Replayed 58 archived real session messages plus adversarial
  lone-surrogate injection through the provider path with no encode
  errors after the fix.

Impact
------
- No behaviour change for clean inputs (sanitize_surrogates_deep is
  an identity return when no surrogate is present).
- Fails-safe: unpaired surrogates degrade to U+FFFD instead of
  aborting the entire request.
This commit is contained in:
Kris Lu authored and Xubin Ren committed 2026-07-21 19:17:58 +08:00
1 parent b81c05581f
commit 89d8c055a8
4 files changed
+257 -14

No files matched your search

+62
View File
@@ -21,6 +21,68 @@ _TOOLS_TOKEN_CACHE_MAX_ENTRIES = 64
_TOOLS_TOKEN_CACHE: dict[int, tuple[tuple[int, ...], dict[bool, int]]] = {}
def sanitize_surrogates(text: str) -> str:
"""Reconstruct surrogate pairs and replace unpaired surrogates.
Lone UTF-16 surrogate code points (``U+D800``..``U+DFFF``) cannot be
encoded as UTF-8 and cause ``UnicodeEncodeError`` when the message is
serialized for an HTTP request body. This helper round-trips through
UTF-16 to reconstruct genuine surrogate pairs (produced e.g. by Windows
console input for emoji) and substitutes lone surrogates with
``U+FFFD``.
Non-string inputs are returned unchanged so this helper is safe to call
on arbitrary message payload leaves.
"""
if not isinstance(text, str):
return text
# Fast path: no surrogate code points → return the original object so
# callers can rely on identity to detect an actual mutation.
for ch in text:
cp = ord(ch)
if 0xD800 <= cp <= 0xDFFF:
break
else:
return text
return text.encode("utf-16-le", errors="surrogatepass").decode(
"utf-16-le", errors="replace"
)
def sanitize_surrogates_deep(value: Any) -> Any:
"""Recursively apply :func:`sanitize_surrogates` to every string leaf.
Lists and dicts are rebuilt only when a nested string actually changes,
so the common case (no surrogates present) returns the original object
without allocations.
"""
if isinstance(value, str):
cleaned = sanitize_surrogates(value)
return cleaned
if isinstance(value, list):
result_list: list[Any] = []
mutated = False
for item in value:
new_item = sanitize_surrogates_deep(item)
if new_item is not item:
mutated = True
result_list.append(new_item)
return result_list if mutated else value
if isinstance(value, dict):
result_dict: dict[Any, Any] = {}
mutated = False
for key, item in value.items():
new_item = sanitize_surrogates_deep(item)
if new_item is not item:
mutated = True
result_dict[key] = new_item
return result_dict if mutated else value
if isinstance(value, tuple):
result_tuple = tuple(sanitize_surrogates_deep(item) for item in value)
return result_tuple if any(a is not b for a, b in zip(result_tuple, value)) else value
return value
@lru_cache(maxsize=1)
def _get_token_encoding() -> Any:
return tiktoken.get_encoding("cl100k_base")