Skip to content

Extend and Download the Telemetry Library

The Course
•
50 min study

Every working library gets feature requests, and the first question to ask about each one is where it belongs. Some changes live entirely in an application and never touch the library. Others change the library's interface. The most expensive kind change the wire format, which every sender and receiver must then agree on. This lesson works through one example of each and then shows you how to run the project on your own machine.

An application feature: report the maximum

The request: after decoding, print the largest value seen. This needs no protocol knowledge at all. It is a summary of readings the library has already validated, so it belongs in main.c, in the branch that handles FRAME_READY. The rules follow from the contracts you already know:

  • Update only on FRAME_READY. On every other status reading was not written, so reading it would use an indeterminate value.
  • Define the empty case. With no frames, the maximum is 0, which matches the convention that empty input is a valid stream with Frames: 0.
  • Say what happens on ties. Keep the first sensor that reached the maximum, and write a test for it, so the rule cannot drift silently.

None of this changes telemetry.h or telemetry.c, so the library's ABI and the wire format stay exactly as they were. Programs compiled against the current library keep working without rebuilding, and every existing test keeps passing unmodified.

Predict and run

Read the program before pressing Run. Predict the output, then explain why computing the maximum in the adapter cannot change binary compatibility.

Predict before running C
#include <stdio.h>

int main(void) {
    unsigned values[3] = {25,40,10};
    unsigned best = 0;
    for (size_t i = 0; i < 3; ++i) { if (values[i] > best) { best = values[i]; } }
    printf("%u\n", best);
    return 0;
}
Check your prediction
Text
40

Starting best at 0 is safe because 0 is the smallest legal value, so it doubles as the answer for empty input. The loop only reads values; the library is not involved. Binary compatibility is about the library's exported functions and types: their names, signatures and struct layouts. An adapter change touches none of them.

A protocol feature: a heartbeat frame

The second request: let devices send a heartbeat, type 2, with an empty payload, so a silent sensor can be told apart from a dead one. It looks like a one-line change, accepting type 2 in the header check, but that line would be a bug. Follow what the decoder currently assumes about every frame:

  • Expected frame length. The decoder completes a frame at used == 10. A heartbeat would be 6 bytes: header plus checksum. With only the type check relaxed, the decoder would wait for four more bytes and read the next frame's first four bytes as this one's payload.
  • Checksum position. The checksum is at offset 9 today. For a heartbeat it is at offset 5.
  • Header rule. length == 4 becomes a per-type rule: 4 for readings, 0 for heartbeats, still under the 16-byte limit.
  • Output representation. Reading has no way to say "heartbeat". The output needs a frame kind, which changes a public type and therefore the ABI.
  • Fixtures and tests. A hand-derived heartbeat fixture, partition tests for the shorter frame, and new mutants, such as "heartbeat accepted with payload".

A protocol change is a design task with its own specification, so keep it optional until the existing contracts are completely clear to you. The safe habit is to list every assumption a change touches before you edit any line.

Practice the design

Do this on paper before you look at the answer. It is the planning half of the change, and it is the half that decides whether the code is right. Use the version 2 rules from Validate Length Before Payload on Day 3: a heartbeat is type 2, allowed only in version 2, with length 0.

  1. Write the six octets of a version 2 heartbeat frame, including its checksum (the low eight bits of the sum of the octets before it).
  2. Name the places in decoder_feed that assume a frame is 10 octets, and say what each must depend on instead.
  3. Write one partition test and one mutant that would catch a decoder which accepts the heartbeat header but still waits for 10 octets.
Compare your plan
  1. 54 02 02 00 00 58: magic, version 2, type 2, length 0, and 0x54 + 0x02 + 0x02 = 0x58.
  2. Three places: the completion test used == 10, the checksum position (offset 9), and the header rule length != 4. All three must come from the type, through one expected-length value chosen when the header is validated at used == 5, so the frame ends at 5 + length + 1. The publish step must also stop assuming every completed frame holds a sensor and value, which is the change to the public output type.
  3. Feed the heartbeat followed by a reading frame, split at every point: a correct decoder reports a heartbeat and then the reading in every partition, while the buggy one swallows four octets of the reading. A matching mutant restores used == 10 as the completion test; that partition test must kill it.

Practice

Exercise

Your turn

Write a Summary with frames, max and max_sensor, a summary_add(Summary *s, Reading r) that keeps the first sensor to reach the maximum, and a report that prints it. Run the four acceptance cases in the starter and print:

Text
empty: frames 0, max 0
one record: frames 1, max 25 (sensor 1)
reverse order: frames 2, max 40 (sensor 2)
tie keeps first: frames 2, max 40 (sensor 2)
Your workspace C
#include <stdio.h>

typedef struct { unsigned sensor; unsigned value; } Reading;

int main(void) {
    const Reading one[1] = {{1, 25}};
    const Reading reverse[2] = {{2, 40}, {1, 25}};
    const Reading tie[2] = {{2, 40}, {3, 40}};
    /* Write Summary, summary_add and report above, then run the four cases. */
    (void)one; (void)reverse; (void)tie;
    return 0;
}
Hint 1: the idea

"First to reach the maximum" means the comparison must be strict. With >=, the second sensor of a tie would replace the first.

Hint 2: a first step

Write summary_add with only the frame count and run: frames should match. Then add the maximum, and test it on the two awkward cases: a tie, where the first sensor must stay, and a first reading whose value is 0.

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

typedef struct { unsigned sensor; unsigned value; } Reading;
typedef struct { size_t frames; unsigned max; unsigned max_sensor; } Summary;

void summary_add(Summary *s, Reading r) {
    ++s->frames;
    if (r.value > s->max || s->frames == 1) { s->max = r.value; s->max_sensor = r.sensor; }
}

static void report(const char *label, const Reading *readings, size_t count) {
    Summary s = {0, 0, 0};
    for (size_t i = 0; i < count; ++i) { summary_add(&s, readings[i]); }
    printf("%s: frames %zu, max %u", label, s.frames, s.max);
    if (s.frames > 0) { printf(" (sensor %u)", s.max_sensor); }
    printf("\n");
}

int main(void) {
    const Reading one[1] = {{1, 25}};
    const Reading reverse[2] = {{2, 40}, {1, 25}};
    const Reading tie[2] = {{2, 40}, {3, 40}};
    report("empty", NULL, 0);
    report("one record", one, 1);
    report("reverse order", reverse, 2);
    report("tie keeps first", tie, 2);
    return 0;
}
Text
empty: frames 0, max 0
one record: frames 1, max 25 (sensor 1)
reverse order: frames 2, max 40 (sensor 2)
tie keeps first: frames 2, max 40 (sensor 2)

The reverse-order case is the one that catches a "keep the last value" bug, and the tie case pins the documented choice. The empty case passes NULL with count 0, which is safe because the loop never reads through it. To ship this in the application, call summary_add in the FRAME_READY branch of main.c and print the summary after Frames:. The next lesson asks you to design a different decoder from scratch.

Optional local setup

Download the streaming telemetry decoder. The archive includes maintained sources, tests, mutation manifest, sample input and README. It does not contain your browser edits; copy changes into the extracted files to retain them.

Install a C17-capable Clang or GCC compiler. In a POSIX terminal inside the extracted folder:

Shell
cc -std=c17 -Wall -Wextra -Wpedantic main.c telemetry.c -o telemetry-decoder
./telemetry-decoder < sample-input.txt
cc -std=c17 -Wall -Wextra -Wpedantic test_telemetry.c telemetry.c -o test-telemetry
./test-telemetry

Compile the application and the tests separately: each has its own main. Keep assertions enabled by not defining NDEBUG. Windows may add .exe; the commands work in an MSYS2 terminal. All required exercises run in the browser without local setup.

Going further

With a supporting native toolchain, add -g -fsanitize=address,undefined -fno-omit-frame-pointer to the test build, and try a mutation that changes memory behavior, such as making reset set used to 30, past the 22-byte frame, to see how a sanitizer reports the write that follows. (The manifest's "reset leaves partial count" mutation sets it to 1, which the tests catch without any sanitizer.) Use a debugger to stop at used == 5 and used == 10 inside decoder_feed and inspect the frame buffer at each transition. A native fuzzing harness, such as one built for libFuzzer, can feed bounded arbitrary byte sequences while asserting the progress and output-preservation contracts; keep the corpus seeds and every failing input so each finding becomes a reproducible regression test. Fuzzing is optional and not part of browser practice.

Was this article helpful?

Your response is saved on this device.