Artifact bed4c04539951cef711b11b016e2f0a6840af46b47afd6cc8e309443c324cd58:
- File
test/pic/decode_stream.c
— part of check-in
[1d1b0294ce]
at
2026-11-18 17:12:31
on branch stage-2
— Add the SSE framer and Messages API stream decoder
The framer is provider-neutral and pure over bytes. The decoder enforces event order and rebuilds each content block from its start object, so thinking signatures and unknown block types replay verbatim. Eleven recorded streams are decoded whole, bytewise and chunked against frozen summaries, and a libFuzzer target checks chunking independence and that decoded content is a JSON array. (user: dmestas, size: 2755) [annotate] [blame] [check-ins using] [more...]
/* Decodes recorded SSE streams and prints a canonical summary. Each stream is * decoded whole, byte by byte and in 7-byte chunks; the three must agree. * Usage: decode_stream FILE... */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "anthropic.h" #include "sse.h" static char *summarize(sqlite3 *db, const char *bytes, size_t n, size_t chunk) { pic_anthropic d; pic_sse p; char *out; size_t cap = 1u << 16; int rc = 0; if (pic_anthropic_init(&d, db) != 0 || pic_sse_init(&p, 1u << 20, 1u << 20, pic_anthropic_event, &d) != 0) { fprintf(stderr, "init failed\n"); exit(2); } for (size_t i = 0; i < n && rc == 0; i += chunk) { rc = pic_sse_feed(&p, bytes + i, n - i < chunk ? n - i : chunk); } if (rc == 0) { rc = pic_anthropic_finish(&d); } else if (d.err[0] == '\0') { (void)snprintf(d.err, sizeof d.err, "SSE framing limit exceeded"); } out = malloc(cap); if (!out) { exit(2); } (void)snprintf(out, cap, "result: %s%s\nid: %s\nmodel: %s\nstop: %s\nusage: %s\nerror: %s\ncontent: %s\n", rc == 0 ? "ok" : "fail: ", rc == 0 ? "" : d.err, d.msg.id ? d.msg.id : "-", d.msg.model ? d.msg.model : "-", d.msg.stop_reason ? d.msg.stop_reason : "-", d.msg.usage ? d.msg.usage : "-", d.msg.error ? d.msg.error : "-", d.msg.content ? d.msg.content : "-"); pic_sse_free(&p); pic_anthropic_free(&d); return out; } int main(int argc, char **argv) { sqlite3 *db; if (sqlite3_open(":memory:", &db) != SQLITE_OK) { return 2; } for (int i = 1; i < argc; i++) { FILE *f = fopen(argv[i], "rb"); char *bytes, *whole, *bytewise, *chunked; long n; if (!f || fseek(f, 0, SEEK_END) != 0 || (n = ftell(f)) < 0 || fseek(f, 0, SEEK_SET) != 0) { fprintf(stderr, "cannot read %s\n", argv[i]); return 2; } bytes = malloc((size_t)n + 1); if (!bytes || fread(bytes, 1, (size_t)n, f) != (size_t)n) { return 2; } fclose(f); whole = summarize(db, bytes, (size_t)n, (size_t)n + 1); bytewise = summarize(db, bytes, (size_t)n, 1); chunked = summarize(db, bytes, (size_t)n, 7); if (strcmp(whole, bytewise) != 0 || strcmp(whole, chunked) != 0) { fprintf(stderr, "%s: result depends on chunking\n--- whole\n%s--- bytewise\n%s--- chunked\n%s", argv[i], whole, bytewise, chunked); return 1; } fputs(whole, stdout); free(bytes); free(whole); free(bytewise); free(chunked); } sqlite3_close(db); return 0; }