A binary message can arrive in pieces that bear no resemblance to its logical boundaries. A four-byte length field might arrive as two bytes followed by two more. The next read might finish one payload and include the start of another. If generated Python code assumes that one input chunk contains one complete message, a successful demonstration can hide a broken protocol implementation.
This guide uses DeepSeek as a code-review assistant around an original, offline Python lab. We build a small length-prefixed decoder, specify what happens at every boundary, and run tests against those rules. The article includes the complete implementation, a worked byte sequence, downloadable tests, and review prompts you can adapt. The prompts are templates: no DeepSeek model or API execution was performed for this article.
The practical goal is a decoder that makes incomplete input, invalid input, and finished input visibly different. Its length and chunk limits are explicit, its output contains immutable byte strings, and a malformed stream cannot silently restart halfway through a payload. This is an educational framing component rather than a complete networking service. Transport timeouts, authentication, application validation, and downstream workload limits remain separate responsibilities.
Tested locally: All 50 unittest methods passed under CPython 3.12.14 and 3.13.5, both normally and with -O. The corpus includes every partition of the worked stream, seeded valid streams, and independent bounded raw-byte tests. These results describe the supplied finite test corpus, not a proof of correctness or a production performance benchmark.
Download the original Python binary-framing lab, with the implementation, demonstration, authored and independent tests, and reader README. No third-party packages or credentials are needed.
Start with a wire contract that fits on one page
Our frame consists of a four-byte unsigned length followed immediately by that many payload bytes. The length uses big-endian, or network, byte order. It describes the payload alone; it does not include the header. Payloads may be empty, and an empty payload is a complete message with a zero length. There are no separators, checksums, compression flags, version fields, or implicit text encodings.
Python’s struct.Struct("!I") expresses this header layout. The exclamation mark selects network byte order, standard sizes, and no alignment padding. The unsigned integer format occupies four bytes in that standard layout. This matters because a native layout can depend on the machine. A wire format needs the same interpretation on both ends, even when the computers have different native conventions.
A four-byte unsigned field can represent lengths much larger than this lab is willing to accept. Representability is not permission to allocate. The implementation has a hard educational ceiling of 1,048,576 payload bytes and a separate ceiling of 65,536 bytes per input call. A decoder can use smaller configured limits. Raising the wire-format maximum and raising the application’s resource budget are different design decisions.
The public input type is exactly bytes. We deliberately reject strings, mutable byte arrays, memory views, and subclasses rather than silently normalizing them. Python libraries often accept a broader bytes-like contract, and that can be appropriate. This lab chooses one small interface so that ownership, mutability, and test expectations remain easy to inspect. Supporting more input types would require an explicit conversion and ownership policy.
Define the receiver lifecycle alongside the frame layout. A new decoder is open. A successful finish() call confirms that no partial frame remains and closes it. A malformed length or premature finish marks it failed. Neither a closed nor a failed instance accepts more data. There is no reset operation: another logical stream gets another decoder, which avoids accidentally joining bytes from separate connections or files.
Before asking a model to write code, distinguish this problem from adjacent formats. Newline-delimited records have delimiter and text-decoding questions covered in our JSON Lines validation guide. Here, newline and zero bytes can appear freely inside a payload. Searching for a familiar character to find the next message would contradict the binary contract.
Follow one stream through three awkward chunks
Consider two messages: the ASCII bytes for cat and the two-byte sequence 00 ff. Their encoded stream has thirteen bytes. The first header says three, followed by three payload bytes. The second header says two, followed by two payload bytes. The receiver must reconstruct these same two messages whether it sees the entire stream at once or receives each byte separately.
Our demonstration divides the stream after byte two and after byte five. The first call contains half a header and returns no message. The second completes that header but includes only the first payload byte, so it also returns no message. The third supplies the remaining first payload and the entire second frame. That call returns two messages in their original order.

from framing import FrameDecoder, encode_frame
payloads = (b"cat", b"\x00\xff")
wire = b"".join(encode_frame(p) for p in payloads)
decoder = FrameDecoder(max_payload=8, max_chunk=16)
for chunk in (wire[:2], wire[2:5], wire[5:]):
print("input:", chunk.hex(" "))
print("output:", decoder.feed(chunk))
decoder.finish()
print("state:", decoder.state)
The printed input lines are hexadecimal diagnostics; the decoder receives actual bytes. Its outputs are (), (), and (b'cat', b'\x00\xff'). The last output is a tuple containing two byte strings, not one concatenated payload. Once the demonstration calls finish(), the state becomes closed. Keeping these distinctions visible makes a model’s proposed implementation much easier to evaluate.
Transport chunking is not an application-level message boundary. Python’s Socket Programming HOWTO discusses both incomplete length prefixes and reads that include the start of the following message. The same incremental design also helps when replaying a binary file in fixed-size pieces. Our tests use in-memory bytes rather than sockets, so the reported evidence covers the parser independently of any operating-system networking behavior.
Do not decode each incoming chunk as UTF-8 before framing it. A chunk can split a multi-byte text character, and this protocol also permits payloads that are not text at all. First recover the complete payload bytes. If the application defines a payload as UTF-8, decode that completed payload using an explicit error policy. Text normalization is another application decision, discussed separately in our Unicode handling guide.
Implement one clear parsing loop
Save the implementation below as framing.py and the earlier demonstration as demo.py in the same directory. The implementation uses a byte array for pending input and a local cursor for completed frames. It checks that a full header is present before unpacking it. Once the header is available, it rejects an advertised payload length above the configured limit immediately. A permitted length with missing payload bytes is incomplete input, so the parser leaves those bytes pending until a later call.
When a complete frame is available, the parser copies its payload into an immutable byte string and moves the cursor to the next header. It repeats this process because one input chunk may contain many complete frames. After the loop, it removes the consumed prefix once. The unconsumed suffix contains either a partial header or one incomplete frame; it cannot contain a complete unprocessed frame after a successful call.
"""A bounded offline decoder for four-byte big-endian length-prefixed frames."""
from struct import Struct
HEADER = Struct("!I")
MAX_PAYLOAD = 1_048_576
MAX_CHUNK = 65_536
class FrameError(ValueError):
"""Malformed or truncated wire data; this decoder cannot be reused."""
def _limit(name, value, minimum, maximum):
if type(value) is not int:
raise TypeError(f"{name} must be an exact int")
if not minimum <= value <= maximum:
raise ValueError(f"{name} must be in {minimum}..{maximum}")
def encode_frame(payload):
"""Encode one exact bytes payload under the lab's fixed upper limit."""
if type(payload) is not bytes:
raise TypeError("payload must be exact bytes")
if len(payload) > MAX_PAYLOAD:
raise ValueError("payload exceeds the lab limit")
return HEADER.pack(len(payload)) + payload
class FrameDecoder:
"""Single-owner decoder. feed() is atomic only for its returned batch."""
def __init__(self, *, max_payload=MAX_PAYLOAD, max_chunk=MAX_CHUNK):
_limit("max_payload", max_payload, 0, MAX_PAYLOAD)
_limit("max_chunk", max_chunk, 1, MAX_CHUNK)
self._max_payload = max_payload
self._max_chunk = max_chunk
self._buffer = bytearray()
self._state = "open"
@property
def pending_bytes(self):
return len(self._buffer)
@property
def state(self):
return self._state
def _require_open(self):
if self._state != "open":
raise RuntimeError(f"decoder is {self._state}")
def _fail(self, message):
self._buffer.clear()
self._state = "failed"
raise FrameError(message)
def feed(self, chunk):
self._require_open()
if type(chunk) is not bytes:
raise TypeError("chunk must be exact bytes")
if len(chunk) > self._max_chunk:
raise ValueError("chunk exceeds the configured input limit")
self._buffer.extend(chunk)
offset = 0
frames = []
while len(self._buffer) - offset >= HEADER.size:
size = HEADER.unpack_from(self._buffer, offset)[0]
if size > self._max_payload:
self._fail("declared payload exceeds the configured limit")
end = offset + HEADER.size + size
if end > len(self._buffer):
break
frames.append(bytes(self._buffer[offset + HEADER.size:end]))
offset = end
if offset:
del self._buffer[:offset]
return tuple(frames)
def finish(self):
self._require_open()
if self._buffer:
self._fail("stream ended inside a header or payload")
self._state = "closed"
The order of validation is intentional. The decoder first checks that it is open, then checks the input’s type and chunk size, and only then extends its buffer. Passing an unsupported object or an oversized input chunk is a caller-contract error. Those checks leave an open decoder’s pending bytes unchanged. A caller can correct the input delivery, split an oversized byte sequence into acceptable chunks, and continue from the same state.
An advertised length over the payload limit is different. Those four bytes are already part of the stream being interpreted. The decoder clears its pending buffer, enters the failed state, and raises FrameError. It does not wait for the claimed payload to arrive, skip an arbitrary number of bytes, or search for a plausible next header. All three alternatives would need additional protocol rules that this format does not provide.
The encoder accepts one complete payload and prefixes its byte count. It uses the lab’s fixed upper payload limit, while a receiver may impose a smaller configured limit. Therefore, successfully encoding a message does not guarantee that every configured receiver accepts it. This is an ordinary compatibility question: a sender’s permitted message size and a receiver’s resource policy must agree before integration.
The properties expose only the current state and the number of pending wire bytes. They are useful in tests and diagnostics without exposing the mutable internal buffer through the public interface. Python’s underscore convention is not a security boundary against code running in the same process. The intended owner should call the public methods, avoid changing private attributes, and use a separate instance for each logical byte stream.
Bound the input call as well as the declared message
A maximum payload size alone does not protect a naive buffer.extend(chunk) operation. A caller could supply a huge chunk containing many valid small messages, or a huge chunk beginning with an invalid header. The allocation would happen before the parser checked individual message lengths. This implementation rejects chunks over its configured input limit before extending the pending buffer, so one call cannot introduce an arbitrary amount of wire data.
After a successful call, fewer than four pending bytes can form an incomplete header. Otherwise, the header describes a permitted payload whose full frame has not arrived. If the payload limit is M, the pending buffer therefore contains at most M + 3 bytes. When the next permitted chunk of at most C bytes is appended, the logical buffer length is at most M + 3 + C before completed frames are removed.
That calculation describes logical wire bytes, not exact process memory consumption. Python objects, byte-array allocation capacity, the temporary payload slice, the immutable result bytes, and the list and tuple containers all take additional memory. The caller also still owns its input chunk. A defensible article or code review should state the bound it actually established rather than converting a buffer-length inequality into an unsupported resident-memory promise.
Zero-length messages deserve their own resource test. They carry no payload bytes, but each four-byte header still produces a result element. With the default 65,536-byte chunk limit and an initially empty buffer, one call can return 16,384 empty messages. The downloadable suite exercises that case. Applications with expensive per-message work may need a separate result-count or processing budget even though the wire-byte limits are respected.
Our interface returns all complete messages from a successful call. A pull-based iterator or callback interface could offer different downstream backpressure, but it would also change error timing, ownership, and partial-delivery behavior. Avoid replacing the return type merely because a model suggests a generator as an optimization. First write down when work happens, when errors become visible, and who is allowed to retain each payload.
These bounds do not implement a timeout. A peer could advertise a permitted payload and then stop sending bytes indefinitely while the decoder remains open with a small partial frame. A networking layer needs its own deadline, cancellation, connection-count policy, and cleanup. Our API reliability guide explains the broader distinction between bounded work, timeouts, retries, and backpressure; this parser implements only the framing portion.
Choose failure semantics before adding recovery
A particularly important case is a chunk containing one valid frame followed by an over-limit header. The parsing loop may have assembled the first payload internally before it discovers the bad header. In this lab, the entire feed() call raises and returns no batch. The accumulated local result is discarded, the buffer is cleared, and the decoder is failed. The caller must not assume that a raised call also delivered some messages.
This is atomicity of the returned batch, not a transaction over the whole stream. If an earlier successful call already returned a payload, a later failure cannot take that payload back or undo actions the application performed with it. Consequently, malformed streams may expose different successful prefixes under different input partitions. The valid-stream partition-invariance property does not imply identical partial output for every malformed stream.

If your application requires all-or-nothing processing of a complete logical exchange, add an explicit application transaction above the framing layer. That may involve validating every message before committing changes, placing the exchange inside an authenticated envelope, or using a transactional storage mechanism. None of those properties follows from returning a tuple. Do not label this small decoder transactional without naming the limited boundary of its guarantee.
Truncation is only knowable when the source declares that no more bytes will arrive. An incomplete payload during feed() is normal; the same pending payload during finish() is an error. An empty feed does not declare end-of-input in this API. The caller must invoke finish at the correct source boundary. For a real socket adapter, the adapter would translate its own end-of-stream signal into that call.
Completing an empty stream is valid, as is completing immediately after any full frame. Finishing halfway through a header or payload raises FrameError and fails the decoder. Calling finish again after a successful close raises RuntimeError, just like feeding a closed decoder. Repeated completion is deliberately not idempotent here, so integration tests can catch accidental reuse instead of silently accepting it.
Automatic resynchronization is unsafe without a specification. Any four payload bytes can resemble a permitted length, including the bytes inside an image or compressed document. Searching for the next plausible header could transform a corrupted payload into fabricated messages. Some real protocols define magic values, checksums, sequence numbers, or explicit recovery procedures. This minimal format has none, so a wire error ends the instance’s useful life.
Test partitions, boundaries, and the exact failure contract
The first tests should use manually known wire bytes rather than only encoding and then decoding with the same implementation. If both sides accidentally use little-endian lengths, an encode/decode round trip can still pass. The lab checks that cat has the exact header 00 00 00 03, and that the header for length 256 is 00 00 01 00. These are independent anchors for byte order and header size.
Next, take the thirteen-byte worked example and enumerate every possible placement of chunk boundaries between its bytes. There are twelve possible boundary locations, so there are 4,096 partitions into nonempty chunks. Every partition must produce the same two payloads in the same order and finish cleanly. This is exhaustive for that one chosen stream, not for every possible payload, stream length, or protocol input.
The suite also uses a fixed random seed to generate 1,200 valid streams with varied payload contents, message counts, zero-length messages, and chunk widths. Each stream is decoded under a smaller configured payload limit, and its pending-byte count is checked after every successful feed. The fixed seed makes failures reproducible. Random coverage supplements the known fixtures and explicit edge cases rather than replacing them.
Header tests stop after one, two, and three bytes and verify that nothing is emitted. Payload tests stop one byte before completion and check that the message appears only when the final byte arrives. Other cases put many frames in one chunk or complete one frame while retaining a partial next header. These scenarios target different branches in the parsing loop; a single happy-path round trip would not distinguish them.
Length boundaries need equality tests as well as rejection tests. A payload exactly at the configured limit must succeed, while the next larger advertised length must fail as soon as its fourth header byte arrives. The hard maximum is tested with a one-mebibyte payload delivered in permitted chunks. The all-ones unsigned header is rejected without constructing its claimed payload. The test therefore exercises the policy without allocating gigabytes.
Caller-contract failures and wire failures receive separate assertions. A wrong input type and an over-limit chunk must preserve an open decoder’s pending bytes, allowing a corrected call to complete the original message. An invalid advertised length must clear pending input and make subsequent feed and finish calls fail. These tests prevent a cleanup refactor from quietly changing whether a stream remains reusable.
The suite also checks every prefix of a chosen three-frame stream. Finish succeeds only at the empty prefix and the three complete-frame boundaries; all other prefixes are truncated. This turns an abstract instruction such as “handle EOF” into a precise set of acceptable positions. It also catches implementations that accidentally accept an incomplete final header simply because no complete message is currently available.
An independent suite uses a whole-prefix reference parser based on int.from_bytes, avoiding the implementation’s Struct and incremental cursor. It checks 57 small valid streams across all 56,617 of their chunk partitions, with empty feeds inserted, plus 449,391 partition-and-limit cases drawn from 5,461 raw byte strings. That raw corpus uses lengths zero through six and the byte alphabet 00, 01, 02, ff. These stated bounds matter: the test is exhaustive within its corpus, not over arbitrary binary input.
We also deliberately changed ten aspects of the implementation in isolated test copies, including byte order, inclusive limits, empty-message handling, one-frame-only processing, truncation acceptance, and terminal-state behavior. The authored suite rejected all ten faulty variants. That is evidence that those checks can detect the selected mistakes; it is not a mutation-coverage percentage for every possible defect.
Run the tests normally and with Python’s optimization flag. Runtime input validation must not depend on assert, because optimized execution can remove assertions. The implementation uses explicit exceptions. The downloadable package includes the commands, interpreter versions, and recorded outcomes. If you extend the lab, rerun those commands against your changed files rather than carrying forward this article’s test claim.
For a larger project, property-based testing can explore more combinations and shrink failures into readable examples. Useful properties include preserving payload order, reconstructing valid streams under changed chunk boundaries, and retaining no complete frame after a successful feed. Our property-based testing guide develops that workflow. This article’s downloadable lab intentionally uses only the Python standard library.
Give DeepSeek an inspectable contract and ask for counterexamples
The most useful first prompt describes the contract before asking for implementation. Include the byte order, length meaning, permitted empty payload, input type, limits, lifecycle, and failure behavior. Keep the request narrowly scoped to a framing component. A vague instruction to build a secure binary protocol invites unrelated encryption choices, networking scaffolding, or unjustified security claims that make the actual parser harder to review.
Review this Python framing contract before proposing code.
Header: four-byte unsigned big-endian payload-byte length.
Payload: arbitrary bytes, including an empty payload.
Input: exact bytes chunks, each within a configured limit.
Reject an excessive declared length once its header is complete.
A malformed stream poisons the decoder; do not resynchronize.
A failed feed call returns no batch. Earlier calls stay delivered.
finish() rejects a partial header or payload and otherwise closes.
Identify ambiguities and give minimal counterexamples.
Separate protocol choices from Python-library guarantees.
Do not claim you executed anything. Do not add sockets or packages.
After implementing the agreed behavior, provide the code and ask for a review organized around concrete violations. A useful finding names the violated rule, supplies the smallest input sequence that demonstrates it, explains the expected and actual result, and proposes a test. “Improve error handling” is too broad to act on. “Finishing after three header bytes succeeds when the contract requires an error” can become a regression test immediately.
Ask the model to examine the transition from one frame to the next, not just isolated frames. A cursor that advances by payload size instead of header plus payload size may pass a simplistic example while failing on the next message. A loop that processes only one frame per call might appear correct when every test uses one encoded message. Counterexamples should deliberately combine valid prefixes, short trailing headers, empty frames, and configured limits.
Keep factual claims and execution claims separate throughout the review. A model can propose that a test should pass or explain why a branch looks correct, but that is not evidence of a run in your environment. Paste actual failure output when asking for help, including the Python version and the test command. Preserve a useful failing case before changing the implementation, then rerun the whole suite after the smallest relevant fix.
A second review pass can focus entirely on misleading assurances. Ask whether the documentation overstates memory bounds, assumes that all payloads are UTF-8, confuses a successful batch with a stream-wide transaction, or implies that framing authenticates a sender. These are contract and documentation defects even when the code behaves as written. Our evidence-based code review guide offers a broader structure for turning such findings into verifiable changes.
Use synthetic payloads when sharing examples with a model. Hexadecimal representation does not anonymize the underlying bytes; a short encoded record may still contain private identifiers, secrets, or customer content. Reproduce the parser behavior with a minimal artificial sequence and keep production packet captures out of the prompt unless you have a specific, authorized reason to share them. The worked example here contains only invented demonstration data.
Integrate the parser without silently expanding its promises
A file adapter can read chunks within the configured limit, pass each to the decoder, process returned payloads, and call finish at the file’s actual end. A socket adapter would need additional decisions about read size, timeouts, cancellation, and connection shutdown. A coalesced receive is normal, and a short receive is normal; neither event should be treated as a malformed frame by itself.
Choose the completion boundary carefully when reading a container that holds several independent streams. Each logical stream should have its own decoder, or the container must define precisely how stream boundaries are represented. Reusing one instance across files without finishing it can make a truncated final payload consume bytes from the next file. Successful framing would then conceal an integration error rather than prove that the original data was complete.
Validate the payload after framing. A binary message may still have an invalid schema, prohibited command, excessive decompressed size, or untrusted serialized object. This lab never executes a payload and does not deserialize one into Python objects. In particular, a correct length prefix does not make unsafe deserialization safe. Treat framing as the boundary that extracts bytes for a separate, explicitly designed application validator.
If integrity or authenticity matters, choose an established protocol or an appropriate authenticated design rather than inventing a checksum and assuming the problem is solved. The header in this lab has no protection against modification. It can tell the parser how many bytes to expect according to the received stream, but it cannot establish who sent those bytes, whether they were altered, or whether the application should trust them.
Keep concurrency ownership simple. One decoder instance belongs to one sequential input stream and one owner at a time. This implementation provides no lock or thread-safety guarantee. Interleaving chunks from two connections would create a different byte stream even if every individual method call were locked. Before introducing shared state, identify whether the correct design is a separate instance for every source.
Measure before optimizing. This implementation copies payloads into immutable bytes and favors a straightforward contract over zero-copy tricks. Memory views, reusable buffers, and callback delivery can be valuable in specialized workloads, but each changes lifetime and mutation risks. The article reports no throughput measurements. A production performance claim would require a defined workload, machine, interpreter, measurement method, and comparison that preserves the same behavior.
Questions to settle before accepting generated framing code
Can an empty message be confused with the end of the source? In this contract, an empty payload is encoded by four zero header bytes and appears as b'' inside the returned tuple. An empty input chunk produces no message while the decoder is open. End-of-input is the explicit finish call. Keeping all three cases separate prevents a common adapter-level mistake.
Should an oversized input chunk permanently fail the decoder? This lab treats it as a caller delivery error because the chunk was rejected before any bytes were appended. A smaller sequence of chunks can still be supplied. An oversized length inside an accepted chunk is a wire violation and permanently fails the instance. Another project can choose differently, but it must document and test the difference.
Does every valid prefix get returned before a bad frame? Only batches returned by earlier successful calls are guaranteed to have reached the caller. If a later header in the same feed call is invalid, that call returns nothing. Applications that need delivery before later failure must choose a different API and test its partial-progress semantics explicitly, including what downstream side effects have already happened.
What should happen if DeepSeek proposes a clever recovery path? Ask for the protocol rule that makes the recovery unambiguous and a counterexample search against that rule. A plausible four-byte sequence inside arbitrary payload data is not enough. When the format supplies no safe synchronization marker or integrity mechanism, rejecting the corrupted stream is clearer than silently inventing a repair.
The reliable workflow is to specify the bytes, specify the boundaries, implement the smallest parser that satisfies the contract, and test its awkward cases independently. DeepSeek can help identify omissions and propose counterexamples. The executable evidence still comes from your tests, your integration, and your review of the actual guarantees. Start with the supplied lab, change one policy deliberately, and keep every claim tied to what you have verified.
Sources & References
Primary documentation was checked on October 7, 2026. Versioned Python references describe the documented behavior used in the lab; local execution versions are listed above and in the download. The DeepSeek reference documents its chat request interface, not an execution or performance result for this article.
- Python 3.13 struct: byte order, standard sizes, format characters, and unpack_from
- Python Socket Programming HOWTO: message boundaries and length-prefixed protocols
- Python 3.13 built-in types: bytes and bytearray
- Python 3.13 unittest: automated tests and exception assertions
- Python 3.13 command-line documentation: optimized execution
- DeepSeek API: create chat completion
