Skip to content

fix(mcp): write_cache_text warns on text with a lone surrogate instead of raising - #1344

Merged
xaleryb merged 1 commit into
intel:mainfrom
antonwolfy:fix/cache-text-surrogate
Nov 27, 2026
Merged

xaleryb merged 1 commit into
intel:mainfrom
antonwolfy:fix/cache-text-surrogate

Conversation

@antonwolfy

Copy link
Copy Markdown
Contributor

Summary

write_cache_text (dokimi/dokimi/mcp/utils.py) promises that a failed write is a warning and returns False, but it caught only OSError. On main, write_cache_text(tmp/"k.txt", "bad \ud800 text") raises UnicodeEncodeError: 'utf-8' codec can't encode character '\ud800' in position 4: surrogates not allowed, and a URL, Context7 or topics fetch whose text holds a lone surrogate (a \ud800 from a JSON escape) fails with that traceback instead of returning what it fetched. No tmp file is left.

The issue offers two fixes. This PR takes the first: catch UnicodeEncodeError next to OSError, log the same warning and return False. Writing through utf8_bytes would store ? for the surrogate, so the cache would replay text that differs from what was fetched, with no warning. An entry that cannot be stored faithfully is not stored, and the caller keeps what it fetched.

The same cache-write contract has three callers (mcp/context7.py:194, mcp/url_client.py:175, questions/ragas_seed.py:123); all use the False return as "not stored" and go on, so none needs a change.

Closes #1251

Changes

  • write_cache_text catches (OSError, UnicodeEncodeError), logs Could not write cache entry <path>: <error> and returns False; the docstring says text that does not encode is not stored.
  • tests/test_doc_caches.py: a lone-surrogate write returns False, keeps the old entry, leaves no tmp file and names the path in the warning; a URLClient fetch of a page with a lone surrogate returns the text and stores nothing; a control that text with é and an emoji is stored and returns True. test_failed_cache_write_keeps_the_old_entry_and_leaves_no_tmp (the OSError path) is unchanged.
  • Changelog fragment (Fixed).

Risk

None for text that encodes: it is stored as before, and an OSError is still a warning and False. Text with a lone surrogate was a crash and is now a warning and a cache miss on the next fetch. No doc under dokimi/docs/ says the encode error is raised, so none changed.

Testing

On Linux, at 4f1d6f05 (on main 16738246):

  • make ci-local: 38 passed, 0 failed, 15 skipped (the other Python legs, micromamba/conda-forge, semgrep, fuzz, docs deploy, the Intel matrix jobs and the CLI-surface package step, which need CI or tools this run lacks). 30115 tests passed, 23 skipped; changed-line coverage 100%.
  • Repro: on main's code the new test_doc_caches.py tests fail (2 failed, 29 passed, first on UnicodeEncodeError: 'utf-8' codec can't encode character '\ud800' in position 4); with the change test_doc_caches.py and test_writers_keep_group.py pass (41 passed).
  • Mutants: dropping UnicodeEncodeError from the except clause fails test_text_with_a_lone_surrogate_is_a_warning_and_keeps_the_old_entry and test_page_with_a_lone_surrogate_is_returned_and_stores_nothing; writing the text with the surrogate replaced by ? (returning True) fails the same two (assert True is False, and an entry left in the cache directory).
  • Not run: Python 3.11, 3.12 and 3.14.

Open questions

None.

Revert

A plain revert restores the UnicodeEncodeError on text with a lone surrogate. Nothing is stored.

Checklist

  • Tests added/updated and pytest passes
  • ruff, mypy, and schema checks pass
  • Docs updated (or N/A) — see the docs-drift checklist in CONTRIBUTING.md
  • Self-reviewed per "Before opening a PR" in AGENTS.md
  • Each new raise/exit and test names the doc, contract or issue it traces to
  • No ad-hoc run artifacts committed
  • New files carry the SPDX license header (or are exempt in .github/.licenserc.yaml)

…#1251)

write_cache_text caught only OSError, so text that does not encode as UTF-8 (a lone surrogate) raised UnicodeEncodeError out of the URL, Context7 and topics fetches, although its docstring says a failed write is a warning and returns False.

It now catches UnicodeEncodeError next to OSError, logs the same warning naming the path and returns False. The text is not stored rather than written with `?` for the surrogate, so the cache never replays text that differs from what was fetched. An existing entry stays as it was and no tmp file is left, because the encode fails before the rename.

Signed-off-by: Anton Volkov <antonwolfy@gmail.com>
@antonwolfy
antonwolfy requested a review from a team as a code owner November 27, 2026 17:49
@antonwolfy antonwolfy self-assigned this Nov 27, 2026
@exai-bot

exai-bot commented Nov 27, 2026 •

Copy link
Copy Markdown

✅ OpenCodeReview: Review complete: 0 finding(s) across 3 selected item(s).

CI at 4f1d6f0: 21 passing, 4 skipped.

Review details
  • Commit reviewed: 4f1d6f0 against merge base 1673824
  • Coverage: 3 files in 1 groups
  • Engine: OpenCodeReview v1.13.5-exai.4.8f73eada, us.openai.gpt-6.1-sol
  • Usage: 69k tokens (41k from cache), 12s
  • Tool calls: 8 (6 file_read, 1 ci_status, 1 local_check_results)
  • small change set: 3 files

@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.18%. Comparing base (1673824) to head (4f1d6f0).
❗ Your organization needs to install the Codecov GitHub app to enable full functionality.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1344      +/-   ##
==========================================
- Coverage   96.19%   96.18%   -0.01%     
==========================================
  Files         499      499              
  Lines       66465    66465              
  Branches    11542    11542              
==========================================
- Hits        63933    63928       -5     
- Misses       1563     1565       +2     
- Partials      969      972       +3     
Files with missing lines Coverage Δ
dokimi/dokimi/mcp/utils.py 96.42% <100.00%> (ø)

... and 5 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@xaleryb xaleryb left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved on 4f1d6f0. A lone surrogate in the text or the entry path is now a warning and False with the old entry kept, a non-BMP character round-trips, and it follows the convention of the earlier surrogate writers. Tests and gates are green. Windows smoke had not started (the hosted Windows queue was stuck); every other check passed.

@xaleryb
xaleryb merged commit 5bcadc0 into intel:main Nov 27, 2026
25 checks passed
@antonwolfy
antonwolfy deleted the fix/cache-text-surrogate branch November 27, 2026 23:58
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.

write_cache_text raises UnicodeEncodeError on text with a lone surrogate instead of logging a warning and returning False

4 participants