Skip to content

Checkpoint: Sticky Error and Reset

The Course
•
60 min study

Once the decoder rejects a frame, it no longer knows where the next frame begins. The bad frame's remaining bytes are still coming, and any of them could look like magic. So the project makes errors sticky: after DECODE_ERROR, every later decoder_feed returns DECODE_ERROR again with zero bytes consumed and the output untouched, and decoder_finish reports an error too. Nothing is skipped and nothing is guessed. Recovery happens only when the caller says so, by calling decoder_reset, typically because it has opened a new file or reconnected.

That design puts every recovery decision where the knowledge is. The decoder knows the stream is broken. Only the caller knows when a new, independent stream starts. Reset restores the initial logical state: no partial bytes and no error. It does not allocate or free anything, it leaves the caller's previously published Reading alone, and destroy still releases the handle exactly once, whether decoding ended cleanly, failed or was reset many times.

Predict and run

Read the program before pressing Run. Predict the output, then explain what would go wrong if reset cleared failed but left used at 5.

Predict before running C
#include <stdio.h>

typedef struct { size_t used; int failed; } State;
void reset(State *state) { state->used = 0; state->failed = 0; }

int main(void) {
    State state = {5,1};
    reset(&state);
    printf("%zu %d\n", state.used,state.failed);
    return 0;
}
Check your prediction
Text
0 0

Both fields go back to their initial values in one operation. If used stayed at 5, the decoder would believe it already held a header, and the first five bytes of the new stream would be treated as payload and checksum for the old stream's header. The result could be a reading assembled from two unrelated streams, or a confusing checksum error on perfectly valid input. The project's mutation list contains exactly this bug, "reset leaves partial count", and the tests catch it.

What you already have

  • The frame rules from Days 2 and 3: magic 0x54 in octet 0, then version 1, type 1 and a big-endian length of 4 in octets 1 to 4 (checkable once five octets have arrived), the sensor in octets 5 and 6, and in octet 9 the low eight bits of the sum of octets 0 to 8.
  • A consumed count from Report Exactly What Was Consumed: a call reports exactly how many input octets it used, and stops after one frame.
  • Sticky error and clean finish from Partial Input and End-of-Stream.
  • Publish only on success from Publish Caller-Owned Values.

Plan before you type

Goals, not statements. The decoder is yours this time; only the caller and finish are given.

  1. Write the expected result of each call in the starter's main before you write feed; the brief's output is there to check your reasoning, not to replace it.
  2. Decide what a failed decoder does on the very first line of feed, and what a call that detects an error reports as consumed.
  3. Decide where feed must stop when one call holds two frames, so the caller can tell which octets belong to which reading.
  4. Decide what reset must restore so that the first frame after it cannot be mixed with bytes from before it.

Practice

Exercise

Your turn

The starter gives the Decoder state, finish, a step helper that prints one call, and the caller's sequence in main. Write the decoder:

  • FeedResult feed(Decoder *d, const unsigned char *bytes, size_t size, unsigned *sensor) buffers octets into d->frame and validates each check at the earliest octet that makes it possible. It returns FRAME_READY as soon as one frame completes (even if more input follows), NEED_MORE when the input ran out mid-frame, or DECODE_ERROR when a check failed. consumed is the number of input octets this call used, including the bad octet on an error. *sensor is written only on FRAME_READY. Once failed, every call returns DECODE_ERROR with 0 consumed.
  • void reset(Decoder *d) makes a failed or half-full decoder behave like a new one.

The starter's main must print:

Text
first frame: FRAME_READY, consumed 10, out 1
stray byte: DECODE_ERROR, consumed 1, out 1
while failed: DECODE_ERROR, consumed 0, out 1
finish while failed: DECODE_ERROR
after reset: FRAME_READY, consumed 10, out 2
finish after reset: STREAM_END
two frames, call 1: FRAME_READY, consumed 10, out 1
two frames, call 2: FRAME_READY, consumed 10, out 2
half frame: NEED_MORE, consumed 5, out 2
finish after half: DECODE_ERROR
Your workspace C
#include <stdio.h>

typedef enum { NEED_MORE, FRAME_READY, DECODE_ERROR, STREAM_END } Status;
typedef struct { Status status; size_t consumed; } FeedResult;
typedef struct { unsigned char frame[22]; size_t used; int failed; } Decoder;
static const char *names[] = {"NEED_MORE", "FRAME_READY", "DECODE_ERROR", "STREAM_END"};
static const unsigned char one[10] = {0x54, 1, 1, 0, 4, 0, 1, 0, 25, 0x74};
static const unsigned char two[10] = {0x54, 1, 1, 0, 4, 0, 2, 0, 40, 0x84};

/* Write feed here, from the contract in the brief:
   static FeedResult feed(Decoder *d, const unsigned char *bytes, size_t size, unsigned *sensor) */

static Status finish(Decoder *d) {
    if (d->failed || d->used != 0) { d->failed = 1; return DECODE_ERROR; }
    return STREAM_END;
}

/* Write reset here. */

static void step(Decoder *d, const char *label, const unsigned char *bytes, size_t size, unsigned *out) {
    FeedResult r = feed(d, bytes, size, out);
    printf("%s: %s, consumed %zu, out %u\n", label, names[r.status], r.consumed, *out);
}

int main(void) {
    Decoder d = {{0}, 0, 0};
    unsigned out = 77;
    const unsigned char stray[1] = {0x00};
    step(&d, "first frame", one, 10, &out);
    step(&d, "stray byte", stray, 1, &out);
    step(&d, "while failed", two, 10, &out);
    printf("finish while failed: %s\n", names[finish(&d)]);
    reset(&d);
    step(&d, "after reset", two, 10, &out);
    printf("finish after reset: %s\n", names[finish(&d)]);
    unsigned char both[20];
    for (size_t i = 0; i < 10; ++i) { both[i] = one[i]; both[10 + i] = two[i]; }
    step(&d, "two frames, call 1", both, 20, &out);
    step(&d, "two frames, call 2", both + 10, 10, &out);
    step(&d, "half frame", one, 5, &out);
    printf("finish after half: %s\n", names[finish(&d)]);
    return 0;
}
Hint 1: the idea

Process one octet at a time inside the call: store it, run whichever check that octet completes, and return the moment the frame is ready or broken. Counting consumed as you go makes it right on every exit, and checking failed before the loop makes the sticky rule a single line.

Hint 2: a first step

Write a feed that only buffers octets, counts consumed and returns FRAME_READY when 10 are buffered, with no checks at all, and a reset that does nothing. Run it: the first line is right, and the stray-byte line says NEED_MORE. Add the checks one at a time, running after each, and watch which line each one fixes.

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

typedef enum { NEED_MORE, FRAME_READY, DECODE_ERROR, STREAM_END } Status;
typedef struct { Status status; size_t consumed; } FeedResult;
typedef struct { unsigned char frame[22]; size_t used; int failed; } Decoder;
static const char *names[] = {"NEED_MORE", "FRAME_READY", "DECODE_ERROR", "STREAM_END"};
static const unsigned char one[10] = {0x54, 1, 1, 0, 4, 0, 1, 0, 25, 0x74};
static const unsigned char two[10] = {0x54, 1, 1, 0, 4, 0, 2, 0, 40, 0x84};

/* At most one frame per call. On FRAME_READY, *sensor is the frame's sensor
   and consumed counts that frame's octets; *sensor changes on no other path.
   On DECODE_ERROR the decoder is failed: consumed counts up to and including
   the bad octet, and while failed every call consumes 0. */
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 && (d->frame[1] != 1 || d->frame[2] != 1 || d->frame[3] != 0 || d->frame[4] != 4));
        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 Status finish(Decoder *d) {
    if (d->failed || d->used != 0) { d->failed = 1; return DECODE_ERROR; }
    return STREAM_END;
}

void reset(Decoder *d) { d->used = 0; d->failed = 0; }

static void step(Decoder *d, const char *label, const unsigned char *bytes, size_t size, unsigned *out) {
    FeedResult r = feed(d, bytes, size, out);
    printf("%s: %s, consumed %zu, out %u\n", label, names[r.status], r.consumed, *out);
}

int main(void) {
    Decoder d = {{0}, 0, 0};
    unsigned out = 77;
    const unsigned char stray[1] = {0x00};
    step(&d, "first frame", one, 10, &out);
    step(&d, "stray byte", stray, 1, &out);
    step(&d, "while failed", two, 10, &out);
    printf("finish while failed: %s\n", names[finish(&d)]);
    reset(&d);
    step(&d, "after reset", two, 10, &out);
    printf("finish after reset: %s\n", names[finish(&d)]);
    unsigned char both[20];
    for (size_t i = 0; i < 10; ++i) { both[i] = one[i]; both[10 + i] = two[i]; }
    step(&d, "two frames, call 1", both, 20, &out);
    step(&d, "two frames, call 2", both + 10, 10, &out);
    step(&d, "half frame", one, 5, &out);
    printf("finish after half: %s\n", names[finish(&d)]);
    return 0;
}
Text
first frame: FRAME_READY, consumed 10, out 1
stray byte: DECODE_ERROR, consumed 1, out 1
while failed: DECODE_ERROR, consumed 0, out 1
finish while failed: DECODE_ERROR
after reset: FRAME_READY, consumed 10, out 2
finish after reset: STREAM_END
two frames, call 1: FRAME_READY, consumed 10, out 1
two frames, call 2: FRAME_READY, consumed 10, out 2
half frame: NEED_MORE, consumed 5, out 2
finish after half: DECODE_ERROR

The "while failed" line is the sticky contract in one row: a perfectly valid frame is refused, nothing is consumed, and the output still holds sensor 1. Reset restores both fields, which is what made the same frame decode one call later. The two-frame chunk shows why consumed matters: the first call stops after ten octets, and the caller resumes at offset 10. The half frame is accepted as NEED_MORE, and only finish turns it into an error. Day 6 turns these behaviors into a regression suite and then proves the suite would notice if any of them broke.

Prove it can fail

After your output matches, make reset clear only failed. The "after reset" line becomes DECODE_ERROR, consumed 4, out 1: the stale stray byte still counts as byte 1 of a frame, so the new frame's magic lands at offset 1 and the header check fails on the fourth byte consumed. A valid stream was rejected because of the previous one. Restore it, then delete the sticky check at the top of feed. Now "while failed" reports consumed 4: the broken decoder keeps appending good bytes to the bad frame and eats part of a valid one before failing again. Neither behavior is what any caller would want.

Mistakes worth checking for

  • The caller loops forever after an error. It advanced by consumed, which is 0 in sticky error, and never checked the status. Stop on DECODE_ERROR.
  • The second frame of a chunk is lost. feed kept consuming after the first frame completed, so the caller never saw the first reading, or never saw the second.
  • The first frame after reset fails its header check. Reset left used nonzero, so old bytes were mixed with new ones.
  • Output changes on a refused feed. The sticky branch wrote a default value into *sensor before returning. Error paths must not publish.
  • Finish returns STREAM_END on a failed decoder. It only checked used, which can be 0 if the failure happened on the first byte. Check failed too.

Was this article helpful?

Your response is saved on this device.