Product case study · November 24, 2026

Ask Claude Code to fix text broken at byte boundaries

Repair a Python decoder that loses characters between byte chunks. Give Claude Code tests for split UTF-8, invalid bytes and unfinished streams.

Reading time
6 min
Checked
Nov 24, 2026
Blue paper fragments travel through cream trays and a charcoal frame to reunite as a complete circle beside an ochre end marker.
Transport can split a character. Your decoder must keep the pieces.
Bottom line

A chunk boundary is not a character boundary. Keep decoder state across chunks and check for unfinished characters at the end.

A streamed message says Price: €5. Your reader displays Price: 5. Nothing crashed, and all the byte chunks arrived. The decoder threw away the currency symbol because its bytes came in separate deliveries.

This is a useful repair task for Claude Code: a tiny bug with a result you can prove. The interesting part is the acceptance test. Sending the whole message in one chunk would let the broken implementation pass.

You need Bash, Python 3, and an installed, signed-in Claude Code. The Python baseline and reference patch below were tested locally; the agent prompt is an authored exercise, not a recorded Claude run. Sources were checked November 24, 2026.

Make the missing symbol reproducible

Create a practice folder and save a deliberately broken decoder:

utf8_lab=$(mktemp -d /tmp/claude-utf8-chunks.XXXXXX)
cd "$utf8_lab"
cat > decoder.py <<'PY'
def decode_chunks(chunks):
    for chunk in chunks:
        yield chunk.decode("utf-8", errors="ignore")
PY
python3 - <<'PY'
from decoder import decode_chunks

chunks = [b"Price: \xe2", b"\x82", b"\xac5"]
print(repr("".join(decode_chunks(chunks))))
print(repr(b"".join(chunks).decode("utf-8")))
PY

The local baseline printed:

'Price: 5'
'Price: €5'

The same bytes produce different text depending on where decoding happens. Python’s bytes.decode() decodes the bytes supplied to that call. With errors="ignore", decoding errors discard malformed data. Here, each fragment of the euro sign looks incomplete or invalid on its own.

Changing ignore to replace would make the damage visible as replacement characters. Changing it to strict would raise an exception on a valid message split at an inconvenient position. Neither change alone repairs the boundary problem.

Specify the stream contract

Save this as SPEC.md:

decode_chunks(chunks) yields strings from one UTF-8 byte stream.
The input is a finite iterable of bytes objects; chunks may be empty.
Joined output must equal decoding the concatenated bytes as strict UTF-8.
Preserve whitespace, punctuation and Unicode exactly.
Reject invalid bytes and incomplete characters at end of input with
UnicodeDecodeError. Consume input incrementally, without joining all
input bytes first. Keep state local to each call.
Change only decoder.py. Use the Python standard library.
Keep this specification and the tests unchanged.

This API does not promise one output string per input chunk. A chunk may finish no character at all. The consumer cares about the joined text, not the number of yielded fragments.

Save these six tests as test_decoder.py:

import unittest
from decoder import decode_chunks


class DecodeTests(unittest.TestCase):
    def test_every_single_split(self):
        text = "Price: €5 / café / 香港 / 🙂\n"
        raw = text.encode("utf-8")
        for cut in range(len(raw) + 1):
            with self.subTest(cut=cut):
                chunks = [raw[:cut], b"", raw[cut:]]
                self.assertEqual("".join(decode_chunks(chunks)), text)

    def test_one_byte_at_a_time(self):
        text = "é€🙂"
        chunks = (bytes([value]) for value in text.encode("utf-8"))
        self.assertEqual("".join(decode_chunks(chunks)), text)

    def test_empty_input_and_ascii(self):
        for chunks, expected in [([], ""), ([b"", b""], ""),
                                 ([b"a", b"\r\n", b"b"], "a\r\nb")]:
            self.assertEqual("".join(decode_chunks(chunks)), expected)

    def test_invalid_byte(self):
        with self.assertRaises(UnicodeDecodeError):
            list(decode_chunks([b"ok", b"\xff"]))

    def test_incomplete_final_character(self):
        with self.assertRaises(UnicodeDecodeError):
            list(decode_chunks([b"ok", b"\xe2", b"\x82"]))

    def test_emits_before_reading_the_next_chunk(self):
        consumed = []

        def source():
            consumed.append(1)
            yield b"ready"
            consumed.append(2)
            yield b" later"

        output = iter(decode_chunks(source()))
        self.assertEqual(next(output), "ready")
        self.assertEqual(consumed, [1])
        self.assertEqual("".join(output), " later")

Run:

python3 -m unittest -v test_decoder

The broken implementation failed four test methods locally; the empty/ASCII and incremental-consumption methods passed. The single-split test reports multiple failing subtests because several byte positions cut through characters.

The last test prevents a tempting shortcut: collecting all bytes and decoding once. That would fix the text but postpone output until the entire input arrives. For a small completed payload, joining first can be a sensible implementation. This exercise deliberately requires incremental output.

Give Claude the failure and the boundary

Start claude inside the practice folder and paste:

Read SPEC.md, decoder.py and test_decoder.py.
Run python3 -m unittest -v test_decoder and report the baseline.
Explain why a valid UTF-8 message loses characters at chunk boundaries.
Change only decoder.py to satisfy the fixed tests and specification.
Do not join all input bytes, weaken decoding errors, edit tests,
install packages, commit, delegate or change files outside this folder.
Run the same tests after the repair and report actual command output.
Explain how incomplete input is detected when the iterable ends.

Anthropic’s debugging workflow recommends supplying reproduction steps and the failing command. This prompt adds a specific output contract, so a patch that merely stops the exception does not count as success. Review tool actions under your active Claude permissions; the folder boundary in a prompt is an instruction, not process isolation.

Inspect the decoder’s memory and its final check

Compare the agent’s patch with this reference implementation:

import codecs


def decode_chunks(chunks):
    decoder = codecs.getincrementaldecoder("utf-8")(errors="strict")
    for chunk in chunks:
        text = decoder.decode(chunk, final=False)
        if text:
            yield text
    tail = decoder.decode(b"", final=True)
    if tail:
        yield tail

All six test methods passed locally with this patch. The initial demonstration now prints Price: €5 both ways.

Python’s incremental decoder API keeps decoding state between calls. The final call tells it that no more bytes are coming, so an unfinished sequence must be handled as an error. That is why the empty-byte flush belongs after the loop. It is also why the decoder is created inside the function: each stream needs its own state.

I would keep the truncated-ending test even in a very small project. It catches a repair that handles every middle-of-stream split correctly yet quietly drops the last character.

Know what passing the tests does not promise

Rerun the tests yourself after leaving Claude. If they passed before any change, check the imported file:

python3 -c 'import decoder; print(decoder.__file__)'

If an agent patch still fails on split characters, look for a new decoder created inside the loop. If only the truncated-ending case fails, check for the final flush. Restore any altered tests before assessing the patch.

A generator can yield a valid prefix before encountering a later error. This function does not roll back text already displayed or written. A consumer that requires an all-or-nothing import must stage the output until decoding completes successfully. A consumer that stops iteration early also never reaches the end-of-stream check.

Use this helper when you receive raw bytes known to be UTF-8. It is not encoding detection, a network client, or a complete event-stream parser. If an SDK already gives you strings, inspect its text-stream API before adding another decoder. And if an earlier reader has already discarded bytes with ignore, re-read the original data: a downstream patch cannot reconstruct the missing symbol.

Sources

Checked November 24, 2026:

Put this to work

Why decoding each byte chunk independently can corrupt otherwise valid UTF-8.

Try

Repair a small Python generator in a disposable folder with a scoped Claude Code prompt.

Prove it worked

Run six tests against the broken decoder and the reference implementation.

Keep in view

  • Reproduce a decoder that silently drops a split euro sign.
  • Give Claude Code fixed tests for chunk boundaries and invalid input.
  • Verify that the decoder rejects an incomplete final character.
Learn the workflow: Set up a scoped Claude Code project session