Skip to content

Checkpoint: Chunk-Independent Decoding

The Course
•
45 min study

A streaming decoder makes one central promise: the readings it produces depend only on the bytes, never on how those bytes were split into chunks. Ten bytes in one call, ten calls of one byte, or a split of 3, 1 and 6 must all give the same reading, the same consumed counts and the same clean finish. Bugs that break this promise are notoriously hard to find in production, because they only appear when the network happens to split a frame at one particular offset, perhaps once a week.

The fix is to stop relying on luck and test every split. A ten-byte frame has nine internal positions where a chunk can end: after byte 1, after byte 2, and so on up to after byte 9. Each position is either a split or not, independently, so there are 2 to the power 9, which is 512, ways to cut the frame into nonempty contiguous chunks. That is small enough to test all of them on every run.

Predict and run

Read the program before pressing Run. Predict the output, then explain why ten bytes have nine split positions rather than ten.

Predict before running C
#include <stdio.h>

int main(void) {
    unsigned boundaries = 9;
    printf("Partitions: %u\n", 1u << boundaries);
    return 0;
}
Check your prediction
Text
Partitions: 512

A split before byte 1 or after byte 10 would create an empty chunk, which says nothing about the frame, so only the nine interior positions count. Each partition is a 9-bit number: if bit k - 1 is set, a chunk ends after byte k. Mask 0 means one ten-byte chunk; mask 511 means ten one-byte chunks. Testing only one-byte chunks would miss bugs that appear when a single call delivers the end of the header and the start of the payload together, which is exactly where the five-byte check runs.

What you will use

  • A feed function with the project's contract. At most one frame per call, with a status and a consumed count.
  • A bit mask as a test generator. Looping a mask from 0 to 511 visits every partition once, in a reproducible order.
  • Sentinel outputs. Each NEED_MORE call must leave a sentinel reading untouched; only the last chunk may change it.
  • A second, coarser loop. Two concatenated frames fed in chunk sizes 1 to 20, so some chunks end between frames and others cross the boundary.

Plan before you type

  1. For each mask, start a fresh decoder and walk end from 1 to 10.
  2. When end is 10 or bit end - 1 is set, feed the bytes from start to end as one chunk.
  3. Check that consumed equals the chunk length, that every chunk but the last returns NEED_MORE with the sentinel intact, and that the last returns FRAME_READY with sensor 1.
  4. Count a mask as passed only if every check held and finish reports a clean end.
  5. Repeat with two frames and fixed chunk sizes, advancing by consumed inside each chunk.
Prove it can fail

Once both counts read full marks, break the decoder on purpose. First make feed return FRAME_READY with r.consumed - 1: both counts should drop to 0, because every test checks the consumed count. Restore it, then limit each call to nine bytes by changing the loop condition to r.consumed < size && r.consumed < 9. Now the output should be partitions: 511 of 512 passed and chunk sizes: 9 of 20 passed. Only mask 0, the single ten-byte chunk, and chunk sizes of 10 or more expose the bug, which is why one tidy split per test is not enough.

Mistakes worth checking for

  • 512 of 512 pass, but some splits were never tested. Using 1u << end instead of 1u << (end - 1) asks about the wrong bit for every byte. Bit 0 is never looked at, so the masks come in identical pairs, and bit 9 does not exist below 512, so no mask ever splits after byte 9: the case where the checksum arrives alone in its own call is never generated. Only 256 different partitions are tested, each twice. The test still passes; it just covers less than it claims. Print the chunk lengths for a few masks to confirm the generator does what you think.
  • The count is right, but the sentinel check never runs. The sentinel was set once outside the loop, then overwritten by the first success. Reset it before each chunk.
  • Two-frame chunk sizes fail only for sizes 11 to 19. The caller fed a chunk once and moved on, dropping the bytes after the first frame. Loop inside each chunk until it is fully consumed.
  • Finish fails after a correct reading. The decoder did not reset used to 0 after publishing, so it believes a partial frame remains.
  • A test passes that should not. The test checked only the number of readings. Check status, consumed, output and finish together.

Practice

Exercise

Your turn

The starter contains a decoder with the project's contract. Write int partition_ok(unsigned mask) and int chunks_ok(size_t chunk) as planned, then count how many of the 512 masks and the 20 chunk sizes pass. Print:

Text
partitions: 512 of 512 passed
chunk sizes: 20 of 20 passed
Your workspace C
#include <stdio.h>
#include <string.h>

typedef enum { NEED_MORE, FRAME_READY, DECODE_ERROR } Status;
typedef struct { Status status; size_t consumed; } FeedResult;
typedef struct { unsigned char frame[22]; size_t used; int failed; } Decoder;
static const unsigned char fixture[10] = {0x54, 1, 1, 0, 4, 0, 1, 0, 25, 0x74};

static FeedResult feed(Decoder *d, const unsigned char *bytes, size_t size, unsigned *sensor) {
    FeedResult r = {NEED_MORE, 0};
    if (d->failed) { r.status = DECODE_ERROR; return r; }
    while (r.consumed < size) {
        d->frame[d->used++] = bytes[r.consumed++];
        int bad = (d->used == 1 && d->frame[0] != 0x54) ||
                  (d->used == 5 && memcmp(d->frame, fixture, 5) != 0);
        if (d->used == 10) {
            unsigned char sum = 0;
            for (size_t i = 0; i < 9; ++i) { sum = (unsigned char)(sum + d->frame[i]); }
            bad = sum != d->frame[9];
        }
        if (bad) { d->failed = 1; r.status = DECODE_ERROR; return r; }
        if (d->used == 10) {
            *sensor = ((unsigned)d->frame[5] << 8) | d->frame[6];
            d->used = 0; r.status = FRAME_READY; return r;
        }
    }
    return r;
}
static int finished_clean(const Decoder *d) { return !d->failed && d->used == 0; }

int main(void) {
    /* Write partition_ok and chunks_ok above, then count passes here. */
    return 0;
}
Hint 1: the idea

A partition test is a small loop that remembers where the current chunk started. Whenever it reaches a split point, it feeds fixture + start with length end - start, checks the result, and moves start to end.

Hint 2: a first step

Start with mask 0, which should mean one chunk: the whole fixture. Write the loop so it feeds only at a split point, and treat the end of the fixture as always being one. Then decide which bit of mask means "split after byte end". Before each feed, put a known value in sensor, so you can check that a NEED_MORE left it alone.

Show one solution
Run the solution C
#include <stdio.h>
#include <string.h>

typedef enum { NEED_MORE, FRAME_READY, DECODE_ERROR } Status;
typedef struct { Status status; size_t consumed; } FeedResult;
typedef struct { unsigned char frame[22]; size_t used; int failed; } Decoder;
static const unsigned char fixture[10] = {0x54, 1, 1, 0, 4, 0, 1, 0, 25, 0x74};

static FeedResult feed(Decoder *d, const unsigned char *bytes, size_t size, unsigned *sensor) {
    FeedResult r = {NEED_MORE, 0};
    if (d->failed) { r.status = DECODE_ERROR; return r; }
    while (r.consumed < size) {
        d->frame[d->used++] = bytes[r.consumed++];
        int bad = (d->used == 1 && d->frame[0] != 0x54) ||
                  (d->used == 5 && memcmp(d->frame, fixture, 5) != 0);
        if (d->used == 10) {
            unsigned char sum = 0;
            for (size_t i = 0; i < 9; ++i) { sum = (unsigned char)(sum + d->frame[i]); }
            bad = sum != d->frame[9];
        }
        if (bad) { d->failed = 1; r.status = DECODE_ERROR; return r; }
        if (d->used == 10) {
            *sensor = ((unsigned)d->frame[5] << 8) | d->frame[6];
            d->used = 0; r.status = FRAME_READY; return r;
        }
    }
    return r;
}
static int finished_clean(const Decoder *d) { return !d->failed && d->used == 0; }

int partition_ok(unsigned mask) {
    Decoder d = {{0}, 0, 0};
    size_t start = 0;
    for (size_t end = 1; end <= 10; ++end) {
        if (end != 10 && (mask & (1u << (end - 1))) == 0) { continue; }
        unsigned sensor = 77;
        FeedResult r = feed(&d, fixture + start, end - start, &sensor);
        if (r.consumed != end - start) { return 0; }
        if (end == 10 && (r.status != FRAME_READY || sensor != 1)) { return 0; }
        if (end != 10 && (r.status != NEED_MORE || sensor != 77)) { return 0; }
        start = end;
    }
    return finished_clean(&d);
}

int chunks_ok(size_t chunk) {
    unsigned char stream[20];
    memcpy(stream, fixture, 10); memcpy(stream + 10, fixture, 10);
    Decoder d = {{0}, 0, 0};
    size_t offset = 0, frames = 0;
    while (offset < 20) {
        size_t end = offset + chunk < 20 ? offset + chunk : 20;
        while (offset < end) {
            unsigned sensor = 77;
            FeedResult r = feed(&d, stream + offset, end - offset, &sensor);
            if (r.status == DECODE_ERROR || r.consumed == 0 || r.consumed > end - offset) { return 0; }
            offset += r.consumed;
            if (r.status == FRAME_READY) { if (sensor != 1) { return 0; } ++frames; }
            else if (offset != end || sensor != 77) { return 0; }
        }
    }
    return frames == 2 && finished_clean(&d);
}

int main(void) {
    unsigned passed = 0;
    for (unsigned mask = 0; mask < 512; ++mask) { passed += (unsigned)partition_ok(mask); }
    printf("partitions: %u of 512 passed\n", passed);
    unsigned sizes = 0;
    for (size_t chunk = 1; chunk <= 20; ++chunk) { sizes += (unsigned)chunks_ok(chunk); }
    printf("chunk sizes: %u of 20 passed\n", sizes);
    return 0;
}
Text
partitions: 512 of 512 passed
chunk sizes: 20 of 20 passed

Every one of the 512 partitions exercises the same ten bytes, so any difference in outcome can only come from the split, which is the property under test. The chunk-size loop adds what partitions of one frame cannot: chunks that end mid-frame, exactly between frames, or contain the end of one frame and the start of the next. Below, the project's own suite runs the same two loops against the real decoder, together with every other check you will meet on Days 5 and 6.

Run the partition tests

Streaming decoder contracts C
#include "telemetry.h" #include <assert.h> #include <stdlib.h> #include <string.h> #include <stdio.h> typedef struct { size_t calls; size_t live; int fail; } Probe; static void *allocate(void *context, size_t bytes) { Probe *probe = context; ++probe->calls; if (probe->fail) { return NULL; } void *storage = malloc(bytes); if (storage != NULL) { ++probe->live; } return storage; } static void release(void *context, void *storage) { Probe *probe = context; assert(probe->live == 1 && storage != NULL); --probe->live; free(storage); } static const unsigned char fixture[10] = {0x54,1,1,0,4,0,1,0,25,0x74}; static void decode_chunks(Decoder *decoder, const unsigned char *data, size_t size, size_t chunk) { decoder_reset(decoder); size_t offset = 0, frames = 0; while (offset < size) { size_t end = offset + chunk; if (end > size) { end = size; } while (offset < end) { Reading out = {77,88}; FeedResult result = decoder_feed(decoder, data + offset, end - offset, &out); assert(result.consumed > 0 && result.consumed <= end - offset); assert(result.status != DECODE_ERROR); offset += result.consumed; if (result.status == FRAME_READY) { assert(out.sensor == 1 && out.value == 25); ++frames; } else { assert(result.status == NEED_MORE && offset == end); assert(out.sensor == 77 && out.value == 88); } } } assert(frames == size / 10 && decoder_finish(decoder) == STREAM_END); } int main(void) { Probe probe = {0,0,1}; TelemetryAllocator allocator = {allocate, release, &probe}; assert(decoder_create(allocator) == NULL && probe.live == 0); probe.fail = 0; Decoder *decoder = decoder_create(allocator); assert(decoder != NULL && probe.live == 1 && probe.calls == 2); size_t allocations = probe.calls; unsigned char encoded[10]; memset(encoded, 0xaa, sizeof encoded); size_t written = 77; assert(!telemetry_encode((Reading){0,25}, encoded, sizeof encoded, &written)); assert(written == 77); for (size_t i = 0; i < sizeof encoded; ++i) { assert(encoded[i] == 0xaa); } assert(!telemetry_encode((Reading){1,25}, encoded, 9, &written) && written == 77); assert(!telemetry_encode((Reading){4096,25}, encoded, 10, &written)); assert(!telemetry_encode((Reading){1,10001}, encoded, 10, &written)); assert(telemetry_encode((Reading){1,25}, encoded, sizeof encoded, &written)); assert(written == 10 && memcmp(encoded, fixture, 10) == 0); Reading sentinel = {77,88}; FeedResult empty = decoder_feed(decoder, NULL, 0, &sentinel); assert(empty.status == NEED_MORE && empty.consumed == 0); assert(sentinel.sensor == 77 && sentinel.value == 88); assert(decoder_finish(decoder) == STREAM_END); unsigned char stream[20]; memcpy(stream, fixture, 10); memcpy(stream + 10, fixture, 10); for (size_t chunk = 1; chunk <= 20; ++chunk) { decode_chunks(decoder, stream, 20, chunk); } /* Every possible partition of a single 10-byte frame (2^9 cases). */ for (unsigned mask = 0; mask < 512; ++mask) { decoder_reset(decoder); size_t start = 0; for (size_t end = 1; end <= 10; ++end) { if (end == 10 || (mask & (1u << (end - 1))) != 0) { Reading out = {77,88}; FeedResult result = decoder_feed(decoder, fixture + start, end - start, &out); assert(result.consumed == end - start); if (end == 10) { assert(result.status == FRAME_READY && out.sensor == 1 && out.value == 25); } else { assert(result.status == NEED_MORE && out.sensor == 77 && out.value == 88); } start = end; } } assert(decoder_finish(decoder) == STREAM_END); } for (size_t length = 1; length < 10; ++length) { decoder_reset(decoder); Reading out = {77,88}; FeedResult result = decoder_feed(decoder, fixture, length, &out); assert(result.status == NEED_MORE && result.consumed == length); assert(decoder_finish(decoder) == DECODE_ERROR); result = decoder_feed(decoder, fixture, 10, &out); assert(result.status == DECODE_ERROR && result.consumed == 0); assert(out.sensor == 77 && out.value == 88); } for (size_t byte = 0; byte < 10; ++byte) { unsigned char corrupt[10]; memcpy(corrupt, fixture, 10); corrupt[byte] ^= 1; decoder_reset(decoder); Reading out = {77,88}; FeedResult result = decoder_feed(decoder, corrupt, 10, &out); assert(result.status == DECODE_ERROR && result.consumed > 0 && result.consumed <= 10); assert(out.sensor == 77 && out.value == 88); assert(decoder_finish(decoder) == DECODE_ERROR); result = decoder_feed(decoder, fixture, 10, &out); assert(result.status == DECODE_ERROR && result.consumed == 0); } /* Repair checksums after metadata changes to test semantic rejection independently. */ const size_t metadata[] = {0,1,2,4}; for (size_t i = 0; i < sizeof metadata / sizeof metadata[0]; ++i) { unsigned char changed[10]; memcpy(changed, fixture, 10); changed[metadata[i]] ^= 1; changed[9] = 0; for (size_t j = 0; j < 9; ++j) { changed[9] = (unsigned char)(changed[9] + changed[j]); } decoder_reset(decoder); Reading out = {77,88}; assert(decoder_feed(decoder, changed, 10, &out).status == DECODE_ERROR); assert(out.sensor == 77 && out.value == 88); } /* Domain-invalid payload with a correct checksum, rather than checksum-only failure. */ unsigned char invalid[10]; memcpy(invalid, fixture, 10); invalid[6] = 0; invalid[9]--; decoder_reset(decoder); Reading out = {77,88}; assert(decoder_feed(decoder, invalid, 10, &out).status == DECODE_ERROR); assert(out.sensor == 77 && out.value == 88); for (unsigned sensor = 1; sensor <= 4095; sensor += 683) { for (unsigned value = 0; value <= 10000; value += 2500) { decoder_reset(decoder); Reading input = {(uint_least16_t)sensor,(uint_least16_t)value}; assert(telemetry_encode(input, encoded, sizeof encoded, &written)); FeedResult result = decoder_feed(decoder, encoded, written, &out); assert(result.status == FRAME_READY && result.consumed == written); assert(out.sensor == input.sensor && out.value == input.value); } } decoder_reset(decoder); assert(telemetry_encode((Reading){4095,10000}, encoded,10,&written)); assert(decoder_feed(decoder,encoded,10,&out).status == FRAME_READY); assert(out.sensor == 4095 && out.value == 10000); assert(probe.calls == allocations && probe.live == 1); /* feed/reset/finish do not allocate. */ decoder_destroy(decoder); decoder_destroy(NULL); assert(probe.live == 0); puts("Telemetry checks passed"); return 0; } #include "telemetry.h" #include <stdlib.h> #include <string.h> struct Decoder { unsigned char frame[5 + TELEMETRY_PAYLOAD_LIMIT + 1]; size_t used; int failed; TelemetryAllocator allocator; }; static void *default_allocate(void *context, size_t bytes) { (void)context; return malloc(bytes); } static void default_deallocate(void *context, void *storage) { (void)context; free(storage); } TelemetryAllocator telemetry_default_allocator(void) { TelemetryAllocator allocator = {default_allocate, default_deallocate, NULL}; return allocator; } Decoder *decoder_create(TelemetryAllocator allocator) { if (allocator.allocate == NULL || allocator.deallocate == NULL) { return NULL; } Decoder *decoder = allocator.allocate(allocator.context, sizeof *decoder); if (decoder == NULL) { return NULL; } decoder->allocator = allocator; decoder_reset(decoder); return decoder; } void decoder_destroy(Decoder *decoder) { if (decoder != NULL) { decoder->allocator.deallocate(decoder->allocator.context, decoder); } } void decoder_reset(Decoder *decoder) { decoder->used = 0; decoder->failed = 0; } static unsigned long read_u16(const unsigned char *bytes) { return ((unsigned long)bytes[0] << 8) | (unsigned long)bytes[1]; } static void write_u16(unsigned char *bytes, unsigned long value) { bytes[0] = (unsigned char)(value >> 8); bytes[1] = (unsigned char)(value & 255UL); } static unsigned char checksum(const unsigned char *bytes, size_t size) { unsigned char sum = 0; for (size_t i = 0; i < size; ++i) { sum = (unsigned char)(sum + bytes[i]); } return sum; } int telemetry_encode(Reading record, unsigned char *out, size_t capacity, size_t *written) { if (out == NULL || written == NULL || capacity < TELEMETRY_FRAME_SIZE || record.sensor < 1 || record.sensor > 4095 || record.value > 10000) { return 0; } unsigned char frame[TELEMETRY_FRAME_SIZE] = {0x54, 1, 1, 0, 4, 0, 0, 0, 0, 0}; write_u16(frame + 5, record.sensor); write_u16(frame + 7, record.value); frame[9] = checksum(frame, 9); memcpy(out, frame, sizeof frame); *written = sizeof frame; return 1; } static FeedResult fail(Decoder *decoder, size_t consumed) { decoder->failed = 1; FeedResult result = {DECODE_ERROR, consumed}; return result; } FeedResult decoder_feed(Decoder *decoder, const unsigned char *bytes, size_t size, Reading *out) { if (decoder->failed) { FeedResult result = {DECODE_ERROR, 0}; return result; } if (out == NULL || (bytes == NULL && size != 0)) { return fail(decoder, 0); } size_t consumed = 0; while (consumed < size) { /* used is bounded by header validation before payload accumulation. */ decoder->frame[decoder->used++] = bytes[consumed++]; if (decoder->used == 1 && decoder->frame[0] != 0x54) { return fail(decoder, consumed); } if (decoder->used == 5) { unsigned long length = read_u16(decoder->frame + 3); if (decoder->frame[1] != 1 || decoder->frame[2] != 1 || length > TELEMETRY_PAYLOAD_LIMIT || length != 4) { return fail(decoder, consumed); } } if (decoder->used == TELEMETRY_FRAME_SIZE) { if (checksum(decoder->frame, 9) != decoder->frame[9]) { return fail(decoder, consumed); } Reading candidate = {(uint_least16_t)read_u16(decoder->frame + 5), (uint_least16_t)read_u16(decoder->frame + 7)}; if (candidate.sensor < 1 || candidate.sensor > 4095 || candidate.value > 10000) { return fail(decoder, consumed); } *out = candidate; decoder->used = 0; FeedResult result = {FRAME_READY, consumed}; return result; } } FeedResult result = {NEED_MORE, consumed}; return result; } DecodeStatus decoder_finish(Decoder *decoder) { if (decoder->failed || decoder->used != 0) { decoder->failed = 1; return DECODE_ERROR; } return STREAM_END; } #ifndef TELEMETRY_H #define TELEMETRY_H #include <limits.h> #include <stddef.h> #include <stdint.h> /* Wire octets require an 8-bit unsigned char. No native struct layout is serialized. */ _Static_assert(CHAR_BIT == 8, "Telemetry format requires 8-bit bytes"); #define TELEMETRY_PAYLOAD_LIMIT 16 #define TELEMETRY_FRAME_SIZE 10 typedef struct { uint_least16_t sensor; uint_least16_t value; } Reading; typedef enum { NEED_MORE, FRAME_READY, DECODE_ERROR, STREAM_END } DecodeStatus; typedef struct { DecodeStatus status; size_t consumed; } FeedResult; typedef void *(*AllocateFn)(void *context, size_t bytes); typedef void (*DeallocateFn)(void *context, void *storage); typedef struct { AllocateFn allocate; DeallocateFn deallocate; void *context; } TelemetryAllocator; typedef struct Decoder Decoder; TelemetryAllocator telemetry_default_allocator(void); /* allocator callbacks/context must remain valid until destroy. NULL on failure. One bounded allocation at creation; feed/reset/finish never allocate. */ Decoder *decoder_create(TelemetryAllocator allocator); void decoder_destroy(Decoder *decoder); /* NULL is allowed; other handles exactly once. */ void decoder_reset(Decoder *decoder); /* Requires non-NULL decoder/out; bytes may be NULL only for size zero. Processes at most one frame; caller advances by consumed, then feeds remaining bytes. NEED_MORE consumes all supplied bytes, FRAME_READY consumes through one checksum. Error is sticky until reset. Output changes only on FRAME_READY. Input is borrowed only during this call. Output is a caller-owned value. Decoder, input and output storage must not overlap. */ FeedResult decoder_feed(Decoder *decoder, const unsigned char *bytes, size_t size, Reading *out); /* Check end-of-input: STREAM_END on a clean boundary; partial frame becomes sticky error. A clean finish is a check, not a close: later feed is permitted. */ DecodeStatus decoder_finish(Decoder *decoder); /* Record: sensor 1..4095, value 0..10000. Encoder validates before writing. Requires non-NULL out/written and nonoverlapping record/out/written storage. Failure leaves output bytes and written unchanged. Capacity must be >=10. */ int telemetry_encode(Reading record, unsigned char *out, size_t capacity, size_t *written); #endif
Check your prediction
Text
Telemetry checks passed

Find the mask loop in test_telemetry.c. Each set bit chooses a split. Trace mask 17, binary 000010001, by hand: it splits after byte 1 and after byte 5, so the calls receive 1, 4 and 5 bytes, and the middle call is the one that completes the header. Then compare the loop with decode_chunks, which feeds two frames in fixed chunk sizes. The allocator probe at the top of main is explained on Day 5.

Was this article helpful?

Your response is saved on this device.