open-code-review icon indicating copy to clipboard operation
open-code-review copied to clipboard

Handle non-UTF-8 source files without corrupting review comments

Open baoj39532 opened this issue 3 months ago • 6 comments

Problem Statement

Summary

Open Code Review currently assumes that source files and Git diff output are UTF-8. Repositories may contain files encoded in GBK, GB18030, Big5, Shift-JIS, or other legacy encodings, sometimes without any predictable path or extension pattern.

When such content is sent to the LLM, invalid UTF-8 bytes may be replaced or corrupted, causing Chinese or other non-ASCII text to appear as mojibake or replacement characters (�) in review comments.

Current behavior

Several input paths currently convert raw bytes directly to Go strings without validating or decoding the source encoding:

  • Full-file scan reads files with os.ReadFile and converts them using string(content).
  • Diff review consumes raw git diff and git show output.
  • The file_read tool returns file content without encoding conversion.

When these strings are serialized into a JSON request, invalid UTF-8 content may be replaced before it reaches the model.

This also affects comment positioning:

  1. The model sees corrupted or converted content.
  2. The model returns existing_code as UTF-8.
  3. The line resolver attempts to match it against the original undecoded diff or file content.
  4. The match may fail, causing missing or incorrect line locations.

Steps to reproduce

  1. Add a source file containing Chinese text and save it as GBK or GB18030.

  2. Commit the file or include it in a full-file scan.

  3. Run either:

    ocr scan
    

    or:

    ocr review --from <base> --to <head>
    
  4. Observe that the source content or generated review comment contains mojibake or �.

  5. Comments whose existing_code contains non-ASCII text may also fail line-number resolution.

Expected behavior

  • OCR should safely review repositories containing files with different text encodings.
  • Content sent to the LLM should always be valid UTF-8.
  • existing_code should be matched against the same decoded UTF-8 content shown to the model.
  • Decoding must not modify files in the working tree.
  • UTF-8 repositories should retain their current behavior and performance as much as possible.
  • If an encoding cannot be detected with sufficient confidence, OCR should warn and skip the file instead of silently replacing invalid bytes.

Acceptance criteria

  • [ ] Valid UTF-8 files are unchanged.
  • [ ] A repository can contain UTF-8 and GBK/GB18030 files simultaneously.
  • [ ] Chinese content from a GBK/GB18030 file is readable in the LLM request and generated comments.
  • [ ] existing_code containing decoded Chinese text resolves to the correct line.
  • [ ] Diff and full-file scan modes behave consistently.
  • [ ] file_read returns valid UTF-8 content for supported legacy encodings.
  • [ ] Line numbers remain unchanged after decoding.
  • [ ] Low-confidence or unsupported encodings produce a clear warning and are skipped.
  • [ ] Invalid bytes are not silently replaced with �.
  • [ ] Unit tests cover mixed-encoding repositories and line-number resolution.

Additional notes

Automatic character-set detection is inherently heuristic. The implementation should therefore expose the detected encoding and confidence in debug output and prefer an explicit warning or skip over silently delivering corrupted content to the model.

Proposed Solution

Proposed approach

Introduce a shared in-memory text decoding layer.

For each file:

  1. Preserve valid UTF-8 content without modification.
  2. Detect BOM-based encodings where applicable.
  3. Detect the encoding of non-UTF-8 content on a per-file basis.
  4. Decode the content into UTF-8 before it is used by the prompt, tools, or line resolver.
  5. Use the same detected encoding for both:
    • the per-file unified diff;
    • the complete new-file content.

For unified diffs, only hunk payload lines should be decoded. Git metadata such as diff --git, file paths, and hunk headers should remain unchanged.

The decoding layer should be applied consistently to:

  • ocr review diff content;
  • NewFileContent;
  • ocr scan;
  • file_read and line-based file reads;
  • other tool results that may contain raw source lines.

The existing line resolver should then continue matching UTF-8 existing_code against UTF-8 diff and file content without requiring encoding-specific logic.

Alternatives Considered

No response

Affected Area

Built-in Tools (file_read, code_search, etc.)

Additional Context

No response

baoj39532 avatar Aug 18 '26 03:08 baoj39532

Reproduced this. Adding the exact mechanism, since it pins down where the content is lost.

The corruption is not gradual — it happens in one step, at request serialization, and it is not reversible.

A file holding GBK 你好 is the 4 bytes BD E3 BA C3. readFromDisk in internal/tool/filereader.go does string(content) on those bytes, and internal/scan/provider.go does the same for ScanItem.Content. Neither is valid UTF-8, which is fine in Go — but the request builder is not so forgiving.

Passing that string through the vendored Anthropic SDK:

p := anthropic.MessageNewParams{
    Model: "claude-x", MaxTokens: 10,
    Messages: []anthropic.MessageParam{
        anthropic.NewUserMessage(anthropic.NewTextBlock(gbk)),
    },
}
b, _ := p.MarshalJSON()

produces

{"max_tokens":10,"messages":[{"content":[{"text":"����","type":"text"}],"role":"user"}],"model":"claude-x"}

Every invalid byte becomes U+FFFD. Go's encoding/json does this by design, so any provider SDK built on it behaves the same way. By the time the request leaves the process the original bytes are gone — the model never sees the file, and existing_code can never match the source, which is the line-resolution half of this report.

Two consequences worth weighing for the fix:

  • The damage is at the boundary, so decoding has to happen before the string is built, not anywhere downstream. Sanitising later cannot recover the bytes.
  • utf8.ValidString is a cheap and exact gate for the "valid UTF-8 files are unchanged" criterion — no detection library runs at all for a UTF-8 repository.

I have not started on a patch. The acceptance criteria span four input paths and a detection-confidence policy, so I would rather not guess at the direction. Happy to take a slice of it if you say which one and how you want low-confidence files handled.

Huang-404-Q avatar Aug 19 '26 02:08 Huang-404-Q

While investigating #972, I ran into the same invalid UTF-8 path described here and traced where the source bytes are lost.

For example, GBK 你好 is stored as C4 E3 BA C3. Both internal/tool/filereader.go and internal/scan/provider.go convert raw bytes directly with string(content). The Go string still contains those bytes, but JSON serialization replaces invalid UTF-8 with U+FFFD. Once the request is serialized, the model only sees ����, and a UTF-8 existing_code response can no longer match the original source.

A focused first step could add utf8.Valid checks at every raw source-byte ingress. Valid UTF-8 would keep the current fast path without running detection. Invalid files would produce a warning and be skipped while other files continue, and file_read would return an explicit error instead of corrupted content. Diff validation would need to happen per file so one invalid file does not discard the rest of the review.

A fuller solution could then introduce one shared in-memory decoding layer before any Go string is built. It could prefer deterministic signals in this order: valid UTF-8, BOM, Git working-tree-encoding, then heuristic detection only when confidence clears an agreed threshold. Low-confidence or unsupported content would still be skipped. The decoded UTF-8 result, detected encoding, and confidence would be reused by diff payloads, NewFileContent, scan, file_read, and line resolution. Diff mode may need to decode old and new snapshots independently before producing normalized UTF-8 hunks, since a commit can also change a file's encoding.

This staged approach prevents silent corruption first, then adds legacy-encoding support without making heuristic guesses part of the UTF-8 path. Would this split fit the intended direction for #987? If so, I can start with the fail-closed validation and regression tests, leaving the shared decoder as a follow-up.

bailu-ZZ avatar Aug 19 '26 03:08 bailu-ZZ

Correction to my byte values above: GBK 你好 is C4 E3 BA C3, as @bailu-ZZ has it — the BD E3 I wrote is not 你. The U+FFFD result is the same for any invalid sequence, so the mechanism stands, but the example was wrong.

Your staged split reads better than what I had. Two points I had not considered: per-file diff validation so one bad file does not sink the whole review, and a commit changing a file's encoding, which forces the old and new snapshots to decode independently.

You have the wider context from #972 — this is yours as far as I am concerned. Happy to review or test against a mixed-encoding fixture if that helps.

Huang-404-Q avatar Aug 19 '26 06:08 Huang-404-Q

I’ve verified the current fix branch locally, and it works as expected. Thanks a lot for addressing this issue and for the quick turnaround! Hope it will be merged into the main branch in the future

baoj39532 avatar Aug 21 '26 06:08 baoj39532

@bailu-ZZ, have you started the UTF-8 validation fix you proposed here? If you haven’t, I’d be happy to take it on, following the maintainer’s suggestion: keep valid UTF-8 unchanged, report and skip files with invalid UTF-8, and continue reviewing the rest. I used OpenAI Codex (GPT-6) to research this issue and trace the affected code paths.

LuisQin01 avatar Nov 21 '26 10:11 LuisQin01

@bailu-ZZ, have you started the UTF-8 validation fix you proposed here? If you haven’t, I’d be happy to take it on, following the maintainer’s suggestion: keep valid UTF-8 unchanged, report and skip files with invalid UTF-8, and continue reviewing the rest. I used OpenAI Codex (GPT-6) to research this issue and trace the affected code paths.

Hi, I haven't started it. I saw that @chethanuk was already working on this, so I held off on implementation. You're welcome to take this on, Looking forward to your PR!

bailu-ZZ avatar Nov 22 '26 13:11 bailu-ZZ