LLM Streaming Parity Tests: Replay One Response Through Two Adapters

Build offline LLM streaming parity tests in Python. Replay one response through two adapters and catch dropped text, missing completion, and midstream errors.

LLM streaming parity tests shown as two aligned strips with different delta cuts and the same reconstructed sentence, stop reason and terminal outcome.LLM streaming parity tests shown as two aligned strips with different delta cuts and the same reconstructed sentence, stop reason and terminal outcome.
Illustrative stream:shipping-01. Both adapters reconstruct Ships Friday. in block 0 and report end_turn and complete. The replay pattern comes from Anthropic’s Messages API migration account.

The replacement adapter streams Ships Friday. in three pieces where the legacy adapter uses two. A client that assembles text by content block can render the same answer either way. But if the replacement drops Friday. or closes before message_stop, the client can get a partial answer that looks finished. LLM streaming parity tests let you distinguish those cases by feeding both adapters the same model output and checking what the client can reconstruct from each.

This tutorial is for backend engineers replacing the streaming adapter in an LLM gateway. You need Python 3.12, a terminal, and enough familiarity with JSON and server-sent events (SSE) to recognize an event name and its data. The module runs offline using the standard library. You’ll get a passing replay case, controls that expose three distinct adapter regressions, and a concrete example of adding a fixture for a bug in block handling. All inputs and expected observations are illustrative.

In its November 25, 2026 account of migrating the Messages API from Python to Rust, Anthropic describes running inference once and replaying the output to Rust. Both implementations processed the same model response, so variation between model calls could no longer explain a difference downstream. The example below applies that idea at a single gateway boundary with synthetic fixtures you can read end to end. Anthropic’s migration account

Opening of Anthropic’s engineering article about the Messages API migration to Rust.
Anthropic Engineering’s account of migrating the Messages API from Python to Rust. · Original source

Define what the client must get back

  1. Inject the fixture where the adapter receives model output. In this module the input is a tuple of synthetic events containing block starts, text pieces, block endings, and a message ending or an error. Both adapters receive the same tuple. The payloads are generated in memory, so an assertion can show the actual synthetic text when it fails.
  2. Collect each adapter’s output after serialization. Each adapter emits named events with a JSON data line. Serialize before comparing so that a broken event name or invalid JSON surfaces at the boundary where a client would see it. The example consumes complete frames yielded by each adapter. In your gateway, use the existing SSE reader if your test seam exposes transport bytes.
  3. Write down the expected client result before looking at either output. For stream:shipping-01, block 0 contains Ships Friday., the stop reason is end_turn, and the terminal outcome is complete. Check each adapter independently against that expectation. Then compare the observations with one another so the test names the compatibility requirement explicitly.

A block index is part of the answer. A renderer may keep separate buffers for different blocks or attach different UI elements to them. The verifier stores text under its original index, appending each delta in arrival order for that block. Sorting the resulting index and text pairs makes the representation easy to compare and keeps the block boundaries visible in a diff. Joining every delta into a single string could let the replacement move content across block boundaries while still passing a text equality check.

The Messages API documents named SSE events with matching types in their JSON data. A text block opens with content_block_start, receives zero or more content_block_delta events, and closes with content_block_stop. Its index identifies its place in the final content array. One or more message_delta events update message-level fields before the final message_stop. The fold below reads stop_reason from those updates and retains the last non-null reason. Claude Platform message streaming

The worked case permits different text delta boundaries inside a block. The legacy adapter writes Ships and Friday.. The replacement writes Shi, ps and Friday.. A space at the end of a delta is still content, so the fold joins the strings directly. A comparison that strips every piece would turn the legacy output into ShipsFriday. and the replacement output into the same broken string. The independent expectation catches that shared mistake. If your client uses delta boundaries for a feature such as highlighting, capture that behavior in a separate assertion. Here the client accumulates text by block and reads the terminal outcome.

Keep the HTTP status and application outcome distinct in the test data. The overload fixture gives both adapters an already-open HTTP 200 response and places overloaded_error inside the stream. That reflects the documented possibility of an error after an HTTP 200 response. The verifier records the error type and any text that came before it. The complete label is reserved for a valid message_stop in this fixture subset. Claude API errors

The sample ignores ping and unrecognized named events after decoding their envelopes, provided they arrive before a terminal event. Anthropic’s versioning policy allows new streaming event types. The fold still checks the known block boundaries, stop reason and ending. It rejects unsupported content block and delta types explicitly because accepting a block whose data the verifier never reads would give a misleading result. Tool use and thinking streams need their own fixtures and comparison rules. Claude API versioning

Treat the expected observation as a contract with the downstream reader. For example, choosing to keep the trailing space in an interrupted answer lets this test distinguish a client that has received Ships from one whose adapter cleared its buffer during error handling. The stop reason is a separate field because a complete stream can deliver a reason the client must handle. The byte representation and the number of text events can vary in this fixture, but a changed character, a changed block index, or a changed ending needs a specific explanation before the replacement can serve this path.

Run the offline replay module

  1. Save the full block below as test_stream_parity.py in a directory where you can run Python 3.12. Use the directory containing that file as your terminal’s working directory so the test runner can import test_stream_parity by name.
  2. Run the first command shown after the module to select all its tests. The second command selects only the shipping method. The verbose option prints each test name and result. If your Python 3.12 executable is called python, use that name in place of python3.12. Python 3.12 unittest command-line reference
  3. Read the test names before treating OK as evidence. You should see the shipping case, the three regression controls, the invalid JSON control, and the two-block case. The controls include deliberate changes to captured frames and assert that the verifier identifies the expected difference.

frame encodes objects with json.dumps. decode_frame uses json.loads and wraps a JSONDecodeError with the frame number and event name. The decoder accepts the exact two-line envelope this module emits. A socket read can end halfway through an event, so the function takes frames that have already been separated. Feed it the generated fixtures as written, or put the gateway’s existing framing reader ahead of the verifier when connecting it to a real response. Python JSON encoder and decoder reference

import json
import unittest


class FrameError(ValueError):
    pass


class StreamShapeError(ValueError):
    pass


def start(index):
    return dict(type='content_block_start', index=index,
                content_block=dict(type='text', text=''))


def text(index, value):
    return dict(type='content_block_delta', index=index,
                delta=dict(type='text_delta', text=value))


def stop(index):
    return dict(type='content_block_stop', index=index)


BEGIN = dict(type='message_start', message=dict(content=[], stop_reason=None))
REASON = dict(type='message_delta', delta=dict(stop_reason='end_turn'))
END = dict(type='message_stop')
OVERLOAD = dict(type='error', error=dict(type='overloaded_error',
                                         message='Overloaded'))
SHIPPING = (BEGIN, start(0), text(0, 'Ships '), text(0, 'Friday.'),
            stop(0), REASON, END)
OVERLOADED = (BEGIN, start(0), text(0, 'Ships '), OVERLOAD)
TWO_BLOCKS = (*SHIPPING[:-2], start(1), text(1, 'Track it.'),
              stop(1), REASON, END)


def frame(event):
    return f"event: {event['type']}\ndata: {json.dumps(event)}\n\n"


def legacy(events):
    for event in events:
        yield frame(event)


def replacement(events):
    seen_text = set()
    for event in events:
        if (event['type'] == 'content_block_delta'
                and event['delta']['type'] == 'text_delta'):
            index = event['index']
            value = event['delta']['text']
            if index not in seen_text and len(value) > 3:
                seen_text.add(index)
                yield frame(text(index, value[:3]))
                yield frame(text(index, value[3:]))
                continue
            seen_text.add(index)
        yield frame(event)


def decode_frame(raw, number):
    lines = raw.split('\n')
    if (len(lines) != 4 or lines[2:] != ['', '']
            or not lines[0].startswith('event: ')
            or not lines[1].startswith('data: ')):
        raise FrameError(f'frame {number} has an invalid fixture envelope')
    name = lines[0][7:]
    try:
        event = json.loads(lines[1][6:])
    except json.JSONDecodeError as exc:
        raise FrameError(f'frame {number} ({name}) has invalid JSON') from exc
    if not name or not isinstance(event, dict) or event.get('type') != name:
        raise FrameError(f'frame {number} has mismatched event types')
    return name, event


def observe(status, frames):
    blocks = {}
    open_blocks = set()
    started = False
    reason = None
    terminal = 'incomplete'
    error_type = None
    for number, raw in enumerate(frames, 1):
        name, event = decode_frame(raw, number)
        if terminal != 'incomplete':
            raise StreamShapeError(f'frame {number} follows the terminal event')
        if name == 'ping':
            continue
        if name == 'error':
            terminal = 'error'
            error_type = event['error']['type']
            continue
        if name == 'message_start':
            if started:
                raise StreamShapeError('duplicate message_start')
            started = True
            continue
        if name not in {'content_block_start', 'content_block_delta',
                        'content_block_stop', 'message_delta', 'message_stop'}:
            continue
        if not started:
            raise StreamShapeError(f'{name} precedes message_start')
        if name in {'content_block_start', 'content_block_delta',
                    'content_block_stop'}:
            index = event['index']
            if type(index) is not int or index < 0:
                raise StreamShapeError('invalid content block index')
            if reason is not None:
                raise StreamShapeError('content event follows stop reason')
            if name == 'content_block_start':
                block = event['content_block']
                if index in blocks or block['type'] != 'text':
                    raise StreamShapeError(f'invalid text block start at {index}')
                blocks[index] = [block['text']]
                open_blocks.add(index)
            elif index not in open_blocks:
                raise StreamShapeError(f'{name} for unopened block {index}')
            elif name == 'content_block_delta':
                delta = event['delta']
                if delta['type'] != 'text_delta':
                    raise StreamShapeError(f'unsupported delta at {index}')
                blocks[index].append(delta['text'])
            else:
                open_blocks.remove(index)
        elif name == 'message_delta':
            if open_blocks:
                raise StreamShapeError('message_delta before block closure')
            update = event['delta'].get('stop_reason')
            if update is not None:
                reason = update
        elif name == 'message_stop':
            if open_blocks or reason is None:
                raise StreamShapeError('message_stop before block closure or reason')
            terminal = 'complete'
    return dict(status=status,
                text=tuple((index, ''.join(blocks[index]))
                           for index in sorted(blocks)),
                reason=reason, terminal=terminal, error=error_type)


class ParityTests(unittest.TestCase):
    def assert_contract(self, case, expected, actual):
        for field, value in expected.items():
            self.assertEqual(value, actual[field], f'{case} field={field}')

    def test_shipping(self):
        expected = dict(status=200, text=((0, 'Ships Friday.'),),
                        reason='end_turn', terminal='complete', error=None)
        old_frames = list(legacy(SHIPPING))
        new_frames = list(replacement(SHIPPING))
        self.assertNotEqual(old_frames, new_frames)
        old = observe(200, old_frames)
        new = observe(200, new_frames)
        self.assert_contract('stream:shipping-01 legacy', expected, old)
        self.assert_contract('stream:shipping-01 replacement', expected, new)
        self.assert_contract('stream:shipping-01 parity', old, new)

    def test_dropped_delta(self):
        expected = observe(200, legacy(SHIPPING))
        damaged = [raw for raw in replacement(SHIPPING)
                   if raw != frame(text(0, 'Friday.'))]
        actual = observe(200, damaged)
        self.assertEqual(((0, 'Ships '),), actual['text'])
        self.assertEqual('complete', actual['terminal'])
        with self.assertRaisesRegex(AssertionError, 'field=text'):
            self.assert_contract('stream:drop-01', expected, actual)

    def test_missing_message_stop(self):
        expected = observe(200, legacy(SHIPPING))
        damaged = [raw for raw in replacement(SHIPPING) if raw != frame(END)]
        actual = observe(200, damaged)
        self.assertEqual(expected['text'], actual['text'])
        self.assertEqual('end_turn', actual['reason'])
        self.assertEqual('incomplete', actual['terminal'])
        with self.assertRaisesRegex(AssertionError, 'field=terminal'):
            self.assert_contract('stream:no-stop-01', expected, actual)

    def test_midstream_overload(self):
        expected = dict(status=200, text=((0, 'Ships '),), reason=None,
                        terminal='error', error='overloaded_error')
        old = observe(200, legacy(OVERLOADED))
        frames = list(replacement(OVERLOADED))
        new = observe(200, frames)
        self.assert_contract('stream:overload-01 legacy', expected, old)
        self.assert_contract('stream:overload-01 replacement', expected, new)
        swallowed = observe(200, frames[:-1])
        self.assertEqual('incomplete', swallowed['terminal'])
        with self.assertRaisesRegex(AssertionError, 'field=terminal'):
            self.assert_contract('stream:overload-01 swallowed', expected, swallowed)

    def test_invalid_json(self):
        damaged = [frame(BEGIN), 'event: ping\ndata: {\n\n']
        with self.assertRaisesRegex(FrameError, 'frame 2.*invalid JSON'):
            observe(200, damaged)

    def test_two_blocks(self):
        expected = dict(status=200,
                        text=((0, 'Ships Friday.'), (1, 'Track it.')),
                        reason='end_turn', terminal='complete', error=None)
        for adapt in (legacy, replacement):
            self.assert_contract(f'stream:two-blocks-01 {adapt.__name__}',
                                 expected, observe(200, adapt(TWO_BLOCKS)))
# Expected: six tests report ok and the suite ends with OK.
python3.12 -m unittest -v test_stream_parity
# Expected: one test reports ok despite the different text delta boundaries.
python3.12 -m unittest -v test_stream_parity.ParityTests.test_shipping

The two adapters differ in one place. legacy serializes the input events as supplied. replacement splits the first text delta for each block after its third character when the delta is long enough. It creates two new events and leaves the source event untouched. With a real adapter, check that neither run mutates the shared fixture. If the integration requires mutable input, construct two fresh copies from the same saved fixture before calling either adapter. An adapter that changes the input for the next run makes the outcome dependent on test order.

The field-by-field assertion names the first differing field. The expected dictionary puts text before terminal, which makes a dropped phrase report as a content mismatch even though the stream still ends normally. The incomplete and overloaded controls deliberately preserve text so the terminal mismatch remains visible. If a real adapter differs in several fields, compare the two observations locally after identifying the first failed assertion. One regression can affect both the text and the ending.

The following is illustrative expected output. Your runtime supplies the elapsed time.

test_dropped_delta (test_stream_parity.ParityTests.test_dropped_delta) ... ok
test_invalid_json (test_stream_parity.ParityTests.test_invalid_json) ... ok
test_midstream_overload (test_stream_parity.ParityTests.test_midstream_overload) ... ok
test_missing_message_stop (test_stream_parity.ParityTests.test_missing_message_stop) ... ok
test_shipping (test_stream_parity.ParityTests.test_shipping) ... ok
test_two_blocks (test_stream_parity.ParityTests.test_two_blocks) ... ok

----------------------------------------------------------------------
Ran 6 tests in 0.001s

OK

Here test_shipping reporting ok means the two different frame lists produced the same expected observation. test_dropped_delta reporting ok means the damaged replacement failed the comparison on text as expected. test_midstream_overload requires both healthy adapters to preserve the error and requires the verifier to distinguish a stream whose error frame was swallowed. The separate one-method run is useful after changing the normal completion path because it gives you the shortest check that the worked example still passes.

If the runner reports that it cannot import the module, check the filename and your working directory before troubleshooting SSE. If it runs a different number of tests, compare the verbose method names with the listing. A copy truncated before the end can leave out the last test while the remaining methods still pass. Keep the original six-test result as the baseline for the fixture you add later.

Use the first divergence to locate the bug

Each row gives an illustrative expected observation for a concrete input. Run the corresponding method from the directory where you saved the module.

Input Action Expected result
stream:shipping-01. Block 0 receives Ships followed by a space, then Friday with a period. Run python3.12 -m unittest -v test_stream_parity.ParityTests.test_shipping to compare the legacy and replacement frame lists and fold both into client observations. The two lists differ. Both reconstruct Ships Friday., report end_turn, and return complete. The runner marks the method ok.
stream:drop-01. The replacement output loses the final Friday. delta while keeping both closing events. Run python3.12 -m unittest -v test_stream_parity.ParityTests.test_dropped_delta to exercise the text comparison against the legacy output. Block 0 contains Ships and its trailing space. The terminal outcome remains complete. The control catches a text field mismatch.
stream:no-stop-01. Only the final message_stop is removed. Run python3.12 -m unittest -v test_stream_parity.ParityTests.test_missing_message_stop to compare the remaining stream with the legacy response. Text and end_turn survive. The outcome is incomplete. The control catches a terminal field mismatch.
stream:overload-01. An overloaded_error arrives after Ships and a trailing space under HTTP 200. Run python3.12 -m unittest -v test_stream_parity.ParityTests.test_midstream_overload to check error preservation and then remove that same frame. Both adapters preserve partial text and the error type. Removing the error frame changes the terminal outcome from error to incomplete.
Invalid JSON control. Frame 2 has the name ping and a single opening brace as data. Run python3.12 -m unittest -v test_stream_parity.ParityTests.test_invalid_json to pass the malformed frame into the fixture decoder. The observer raises FrameError naming frame 2 and invalid JSON. The test catches the exception and reports ok.
stream:two-blocks-01. Index 0 carries Ships Friday. and index 1 carries Track it. Run python3.12 -m unittest -v test_stream_parity.ParityTests.test_two_blocks to fold the two blocks from each adapter. Both adapters yield the same two separate indexed strings and report end_turn and complete.

Horizontal bars showing 13 reconstructed characters in complete shipping text and 6 after dropping the final delta.Horizontal bars showing 13 reconstructed characters in complete shipping text and 6 after dropping the final delta.
Illustrative counts from stream:shipping-01 and stream:drop-01. Dropping Friday. removes seven characters while the stream still reports complete.

The text case leaves a useful clue. Both streams have a normal ending, but only one delivers all 13 characters, including the period. The dropped-delta variant delivers 6 characters including the trailing space. Start at the adapter’s emission immediately before content_block_stop. Look at whether its accumulator had pending text and whether that buffer was flushed before it emitted the boundary. Sending another end marker would leave the visible string short.

For a missing ending, check the final emitted event. The example still has end_turn because the preceding message_delta is intact. That observation narrows the search to the path between the reason update and finalization. Check whether the replacement forwards the terminal event before closing its output iterator. If the integration captures transport bytes, also check whether its SSE reader yielded the last complete frame. Compare what the adapter emitted with what the test reader delivered before editing either side.

For overload, inspect the in-stream error frame before looking for a status change. The synthetic fixture holds status=200 constant, so the important values are terminal='error' and the error type overloaded_error. With that frame removed, the stream ends with the same partial text and no terminal event. Treat that as incomplete in the verifier. The distinction matters to a client that surfaces provider failures separately from connections that end early. Preserve the partial text in the observation so the test can catch code that clears it during error handling.

A parsing failure stops the observation from being built. FrameError points to an envelope or JSON problem. Inspect the indicated synthetic frame for the matching event name and JSON type, then fix the serialization or framing boundary. StreamShapeError means the JSON decoded but the event sequence broke a rule checked by the fixture fold, such as sending a delta for an unopened block. A field assertion compares an observation with a known expected result or another observation. An unexpected parsing exception in the shipping method is a test error. A failed field comparison there is an assertion failure. The malformed fixture catches its own exception, so it passes in the unchanged suite.

When investigating a text mismatch in a larger fixture, compare the affected index first. If a block ends with the right punctuation but lacks some middle characters, inspect the deltas between its own start and stop before investigating message finalization. If the text associated with the next block starts with the missing characters, follow index assignment through the replacement’s serializer. Keep that diagnostic output local and use synthetic strings in any fixture you commit. A report that names a case, block index and first differing field is usually enough to direct someone to the failing test without copying a customer response into the report.

A valid message_stop yields complete, an in-stream error yields error with its type preserved, and EOF without either yields incomplete.A valid message_stop yields complete, an in-stream error yields error with its type preserved, and EOF without either yields incomplete.
Illustrative terminal outcomes from the tutorial’s replay verifier. The Messages API documentation defines message_stop and the in-stream error event. The verifier labels EOF without either event incomplete.

Keep the fixture when you fix the adapter

  1. Reproduce a behavior change with synthetic input. Use stream:two-blocks-01 as the worked regression. It extends SHIPPING with a second block before the reason update. The second block is deliberately recognizable as Track it. so a move into block 0 will show up even if the frontend displays every text block in one column. The expected value includes both indices and exact strings.
  2. Check that the fixture would catch the bug. For a local exercise, insert index = 0 immediately before yield frame(text(index, value[:3])) in replacement. Run python3.12 -m unittest -v test_stream_parity.ParityTests.test_two_blocks. The illustrative result is an ERROR with StreamShapeError for an unopened block 0. The first block has already closed when the replacement misroutes the second block’s text. Remove that temporary line and rerun the same method. Expect ok. In a real fix, keep the case and change the code where the wrong index is chosen.
  3. Add a fixture for a second failure shape. Paste the method below inside ParityTests, aligned with its other methods. It covers a block that opens and closes without any text deltas. Run python3.12 -m unittest -v test_stream_parity.ParityTests.test_empty_second_block. Expect one passing test. If your adapter suppresses an empty block despite promising to preserve content indices, the result would lose the pair for index 1 and the assertion would point to the text field.
  4. Rerun the entire module. Use python3.12 -m unittest -v test_stream_parity again. Expect seven passing tests with the added method and the temporary index edit removed. Then substitute your adapter entry points and run the cases through the response boundary your clients consume. Retain the written expectations so a behavior both adapters get wrong remains visible.
    def test_empty_second_block(self):
        events = (*SHIPPING[:-2], start(1), stop(1), REASON, END)
        expected = dict(status=200,
                        text=((0, 'Ships Friday.'), (1, '')),
                        reason='end_turn', terminal='complete', error=None)
        for adapt in (legacy, replacement):
            self.assert_contract(f'stream:empty-block-01 {adapt.__name__}',
                                 expected, observe(200, adapt(events)))

The empty block case makes the choice in the fold visible. The list for an index is created when the block starts, so a block with no deltas still contributes its initial text. If a real adapter intentionally hides empty blocks as part of a documented downstream contract, decide what that entails for the remaining indices and write the expected downstream observation accordingly. Editing the assertion just to make the replacement pass would obscure a change the client might rely on.

The test seam can be narrow. If your adapters take a provider SDK iterator, fake that interface and drive the real output serializer. If they take raw upstream chunks, feed the same fixture bytes into each adapter through its normal parser. In either setup, collect the actual downstream events before folding them. Stubbing the serializer would make invalid wire data invisible. When testing an SDK consumer, capture the surfaced exception at the boundary the client uses. The synthetic overload in this module exercises the raw SSE path.

When replacing the two sample functions with real adapters, remove the assertion that the frame lists must differ unless your integration deliberately promises a particular rechunking behavior. That assertion proves the teaching example exercises two chunk layouts. Real adapters may emit identical frames and still preserve the contract. Keep the decoded expectations, and feed the observer the actual status captured from each adapter if the status is part of the path you are changing. The literal status in the standalone module is part of its synthetic input.

Choose new fixtures by asking what a client would observe if one known stage were wrong. If an adapter translates stop reasons, add a case for a reason already documented and used by your client, with the expected downstream value written explicitly. If it exposes tool arguments, preserve block type and compare reconstructed arguments on fixtures appropriate to tool use. Keep latency and delivery cadence in transport tests that measure those properties. In-memory replay checks content and endings without modeling when events reach a live client.

If a mismatch remains, keep the legacy adapter selected for new requests. Where the replacement is already serving a limited route, restore the legacy selection for subsequent requests and verify that selection at the gateway boundary. For an already-open stream, use the gateway’s existing failure behavior. Appending a second adapter’s fresh response to a partial reply would produce a different stream from the one the client began reading. Keep the failing fixture, rerun the focused method after the fix, then rerun the suite with both real entry points. Use the passing result as evidence for the response shapes exercised by those fixtures. Before expanding traffic, exercise any other response shape that would change how your clients render content or handle errors.

For a companion test at the agent layer, compare the order chosen by a tool call and the final reply. LangSmith Backtesting for a Wrong Order Lookup

If you first learn about a mismatch outside a unit test, recover the trace and use the smallest relevant response shape to build a fixture. You Can’t Replay What You Can’t See · Sentry Conversation Export

Once the fixture catches the bug reliably, decide whether a failing replay should block a pull request. If the replacement also changes providers, test the routing handoff separately. Agent Evaluation CI Gates · Rehearse the Provider Cutoff

Sources

  1. Anthropic Engineering migration account
  2. Claude Platform message streaming reference
  3. Claude Platform API errors
  4. Claude Platform API versioning
  5. Python 3.12 unittest reference
  6. Python json reference
YOU'RE THROUGH THIS ONE.

Keep connecting the dots.

Back to the library

Many assistants.
One place to remember.

Bring your AI sessions, context, and usage together with Automater.

Meet Automater