Module 1 of 3Free to explore

Where records end in a byte stream

2 hoursTheory and practiceHard

Two ends of a single classroom stream

A developer is given three short events from a laboratory journal. In a line-oriented file each event had its own line. A local socket sometimes presents the end of one marker and the beginning of another in the same read. This is ordinary byte-stream behaviour. Each read returns some available bytes, and the application designer defines how those bytes describe events. An application record boundary exists only after the agreed format has been decoded. Both ends in this exercise are created in one process. No remote address, customer data or Internet connection is required.

Read the specification of a tiny format

The first byte in each record holds its payload length in bytes. This one-byte header is excluded from the length. The lab vocabulary has three ASCII values. SEEN and DONE each occupy four bytes and ACK-17 occupies six. Directly after the last byte of a payload comes the length of the following record. Spaces printed in a hexadecimal dump separate bytes for human readers. Those spaces do not appear in the encoded stream. Record these rules before making your first attempt at a decoder.

fixture length = 17 bytes
chunk 1      04 53
chunk 2      45 45 4e 06 41
chunk 3      43 4b 2d 31
chunk 4      37 04 44 4f 4e 45
vocabulary   SEEN | ACK-17 | DONE
header length = 1 byte; declared size excludes the header

Walk through the fragments from left to right on paper. When you have only a length, enter it in a waiting field. On each new fragment, append its bytes and decide whether the accumulated payload is complete. When the first record is complete, retain the remaining bytes. They may include a header or several complete records. Assign event numbers when an application record finishes. Using the read-call number would cause a change in read size to alter the meaning of the journal even when the underlying byte sequence stayed identical.

Run one experiment using two local transports

Start with BytesIO. The fixture stays in memory and you can choose any read size. Next run frame_reader.py. Where local sockets are available, it passes the same seventeen bytes between the AF_UNIX ends of a socket pair. Platforms without that family use the in-memory variant. System read boundaries are outside the success criterion in both experiments. Retain the expected marker list and total byte count. A reordered list of the same length should fail the test.

Why does the writer close its sending direction after submitting the fixture? The reader runs to end of stream. Once all data has been delivered, the absence of future data must become visible to the receiver. For a connected stream socket, recv returning empty bytes signals end of stream. If the writer merely stays idle, a subsequent read can wait. The experiment uses a fixed short input and an orderly end of writing. No remote infrastructure is needed to exercise this property. A speed benchmark would introduce noise from the learner’s laptop without improving the result.

Exercise. Split one fixture at every boundary

First write a test that supplies the entire stream as one block. Loop over the cut position and supply the same fixture in two pieces. Include offset zero and the position immediately after the final byte. Both produce an empty chunk in the input list. Within this list an empty chunk contributes no data. The end of input is signalled by iterator exhaustion, a distinct part of the decode_markers interface. The recv wrapper turns transport end of stream into iterator exhaustion before passing chunks to the decoder.

from frame_reader import FIXTURE, decode_markers, local_demo

expected = ["SEEN", "ACK-17", "DONE"]
for cut in range(len(FIXTURE) + 1):
    parts = [FIXTURE[:cut], FIXTURE[cut:]]
    assert decode_markers(parts) == expected, cut

individual = [FIXTURE[pos:pos + 1] for pos in range(len(FIXTURE))]
assert decode_markers(individual) == expected
assert local_demo() == expected

If the test fails, record the first cut at which a marker is lost. Write down bytes on both sides of the boundary and the suffix length still buffered. This observation distinguishes premature publication of an unfinished record from accidentally clearing the entire suffix after a successful record. Add a test delivering one byte at a time. Success with a two-piece split alone cannot establish that the suffix survives several consecutive short reads.

Compare the result to an offset ledger. Before the first header the reader has consumed zero bytes. After SEEN the next record starts at five. After ACK-17 the next start is twelve. DONE starts at twelve and moves the cursor to seventeen. These positions form a useful test oracle if you extend the decoder to include offsets. A common slip is to retain the last byte index and report sixteen as the final cursor. Label the next frame position and the last consumed byte as separate quantities.

Python · Socket Programming HOWTO

Test your conclusion

What can the decoder emit after its first read?

Two read results
read 1   04 53 45
read 2   45 4e 04 44 4f 4e 45
Frame contract
first byte = payload length
53 45 45 4e = SEEN
44 4f 4e 45 = DONE

Independent exercise

Два локальных конца потока и лист с границами записей.
На какой границе уже можно подтвердить получение целого события?

The receiver recorded three chunks in a new fixture. The reviewer expects two application records and wants their actual offsets.

Evidence

batch = S-BND-22; zero-based offsets; one-byte length excludes header
chunk-1 = 04 44 4f
chunk-2 = 4e 45 04 53
chunk-3 = 45 45 4e
vocabulary = DONE, SEEN, ACK-17
reader records transport chunks independently from the decoder

Assignment

Reassemble the records and report both zero-based frame starts. Show the suffix after chunk two, then move the cut and repeat.

Compare your reasoning

DONE starts at 0 and consumes five bytes. SEEN starts at 5. After chunk two the incomplete suffix is 04 53, the header and one letter. A different cut keeps the same record values and starts.

Personal practice environment

Check an excerpt, find matching lines and compute the SHA-256 of the original text. Temporary data expires after 30 minutes or when you close the environment.