Skip to content

Optimize sanitize_text_for_encoding fast path#2815

Closed
danielaskdd wants to merge 1 commit intomainfrom
jules-12837766569150318299-4b794a7a
Closed

Optimize sanitize_text_for_encoding fast path#2815
danielaskdd wants to merge 1 commit intomainfrom
jules-12837766569150318299-4b794a7a

Conversation

@danielaskdd
Copy link
Copy Markdown
Collaborator

I have successfully optimized the sanitize_text_for_encoding function within lightrag/utils.py. The previous implementation was parsing characters one by one via a python loop and doing regex replacements twice.

In this commit:

  • I've introduced a fast-path try-except block that first tries to encode the text using utf-8. If it succeeds without a UnicodeEncodeError, the code entirely skips the slow O(n) surrogate fallback logic loop.
  • The control character removal regex has been compiled outside of the function globally.
  • I've merged the 2 separate regex substitutions into one pass that correctly preserves whitespace characters like \n and \t.

Performance tests indicate that this is vastly faster on average strings, fulfilling the "one small improvement" mandate. Tests also confirm that the utility still functions correctly, and that the fallback accurately parses out surrogate characters from malformed inputs.


PR created automatically by Jules for task 12837766569150318299 started by @danielaskdd

…and global regex

Co-authored-by: danielaskdd <36760595+danielaskdd@users.noreply.github.com>
@google-labs-jules
Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@danielaskdd danielaskdd deleted the jules-12837766569150318299-4b794a7a branch March 21, 2026 15:46
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.

1 participant