Artifact fd15db92a418ee5d54d90769605f236af3c5887425ebcaf2f7a273adeec6a211:
- File
src/store.c
— part of check-in
[3ff8346a3f]
at
2026-11-19 00:38:38
on branch stage-4
— Journal every reply in two forms and convert across models
Assistant entries keep the provider content verbatim with its origin (provider, api, model) and Pi neutral form; tool calls come from the neutral form, the same for every provider. A turn goes back verbatim to the model that wrote it and is otherwise rebuilt from the neutral form, without thinking and with tool-call ids normalised identically in calls and results. --model resolves through the registry, keys come from the model, and schema 3 journals migrate in place on open. (user: dmestas, size: 15779) [annotate] [blame] [check-ins using] [more...]
/* Storage: one libfossil-hosted SQLite database owned by exactly one pic process. */ #include <errno.h> #include <fcntl.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/file.h> #include <unistd.h> #include "libfossil.h" #include "pic.h" /* Application tables and Fossil repositories share this file; libfossil * requires foreign_keys OFF, so pic_check() enforces references by hand. */ static const char schema_sql[] = "CREATE TABLE IF NOT EXISTS pic_meta(key TEXT PRIMARY KEY, value TEXT NOT NULL);" "CREATE TABLE IF NOT EXISTS pic_submission(" " id INTEGER PRIMARY KEY," " request_key TEXT NOT NULL UNIQUE," " content TEXT NOT NULL," " status TEXT NOT NULL CHECK(status IN ('admitted','answered','failed'))," " error TEXT);" /* user: the text; tool_result: the tool's output; assistant and answer: * Pi's neutral content array in body, the provider's content verbatim in * native, and the reply's origin (provider, api, model). */ "CREATE TABLE IF NOT EXISTS pic_entry(" " seq INTEGER PRIMARY KEY," " submission_id INTEGER NOT NULL," " kind TEXT NOT NULL CHECK(kind IN ('user','assistant','tool_result','answer'))," " body TEXT NOT NULL," " effect_id INTEGER," " native TEXT," " provider TEXT," " api TEXT," " model TEXT);" /* One row per tool call; an assistant entry may carry several. */ "CREATE TABLE IF NOT EXISTS pic_effect(" " id INTEGER PRIMARY KEY," " entry_seq INTEGER NOT NULL," " ordinal INTEGER NOT NULL," " call_id TEXT NOT NULL," " tool TEXT NOT NULL," " input TEXT NOT NULL," " replay_safe INTEGER NOT NULL CHECK(replay_safe IN (0,1))," " state TEXT NOT NULL CHECK(state IN ('intent','started','done','unknown','skipped'))," " result TEXT," " is_error INTEGER NOT NULL DEFAULT 0 CHECK(is_error IN (0,1))," /* Bytes a replay-safe tool will write, journaled with "started" so a * replay after a crash writes the same bytes. */ " plan BLOB," " UNIQUE(entry_seq, ordinal));" /* One row per provider request. A request costs money but changes nothing * outside pic, so an interrupted one is failed and asked again. */ "CREATE TABLE IF NOT EXISTS pic_generation(" " id INTEGER PRIMARY KEY," " submission_id INTEGER NOT NULL," " turn INTEGER NOT NULL," " attempt INTEGER NOT NULL," " state TEXT NOT NULL CHECK(state IN ('started','done','failed'))," " entry_seq INTEGER," " stop_reason TEXT," " usage TEXT," " request_id TEXT," " error TEXT," " UNIQUE(submission_id, turn, attempt));"; static int fail(pic_store *s, const char *fmt, ...) { va_list ap; va_start(ap, fmt); (void)vsnprintf(s->err, sizeof s->err, fmt, ap); va_end(ap); return -1; } int pic_exec(pic_store *s, const char *sql) { char *msg = NULL; if (sqlite3_exec(s->db, sql, NULL, NULL, &msg) != SQLITE_OK) { int rc = fail(s, "sql: %s", msg ? msg : sqlite3_errmsg(s->db)); sqlite3_free(msg); return rc; } return 0; } int pic_begin(pic_store *s) { return pic_exec(s, "BEGIN IMMEDIATE"); } int pic_commit(pic_store *s) { return pic_exec(s, "COMMIT"); } void pic_rollback(pic_store *s) { if (!sqlite3_get_autocommit(s->db)) { (void)sqlite3_exec(s->db, "ROLLBACK", NULL, NULL, NULL); } } /* A second pic process is refused, not queued. The lock is released by the * kernel when its holders exit or crash. A running command's supervisor holds it * too, so a restarted pic waits (briefly) until that cleanup is over. The path * lock alone can be bypassed with a symlink or hardlink; SQLite's exclusive * locking mode, set at open, fences on the file itself. */ static int take_lock(pic_store *s, const char *db_path) { char path[4096]; int n = snprintf(path, sizeof path, "%s.pic-lock", db_path); if (n < 0 || (size_t)n >= sizeof path) { return fail(s, "database path too long"); } s->lock_fd = open(path, O_RDWR | O_CREAT | O_CLOEXEC, 0600); if (s->lock_fd < 0) { return fail(s, "cannot open lock %s: %s", path, strerror(errno)); } for (int tries = 0; flock(s->lock_fd, LOCK_EX | LOCK_NB) != 0; tries++) { if (errno != EWOULDBLOCK || tries >= 20) { return fail(s, "database is owned by another pic process"); } (void)usleep(50000); } return 0; } /* Brings an older journal up to the current schema inside the open * transaction, so a crash leaves it either untouched or fully migrated. * Version 3 kept only the Anthropic content of each reply: it becomes the * native form, its neutral form is derived, and its origin is anthropic with * the model unknown, so any model is sent it converted, never verbatim. */ static int migrate(pic_store *s) { sqlite3_stmt *q = NULL; char version[16] = ""; if (sqlite3_prepare_v2(s->db, "SELECT value FROM pic_meta WHERE key='schema_version'", -1, &q, NULL) != SQLITE_OK) { return fail(s, "sql: %s", sqlite3_errmsg(s->db)); } if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) { (void)snprintf(version, sizeof version, "%s", (const char *)sqlite3_column_text(q, 0)); } sqlite3_finalize(q); if (strcmp(version, "3") != 0) { return 0; /* new, current, or a version schema_version_ok refuses */ } if (pic_exec(s, "ALTER TABLE pic_entry ADD COLUMN native TEXT;" "ALTER TABLE pic_entry ADD COLUMN provider TEXT;" "ALTER TABLE pic_entry ADD COLUMN api TEXT;" "ALTER TABLE pic_entry ADD COLUMN model TEXT;" "UPDATE pic_entry SET native=body, provider='anthropic', api='anthropic-messages', model='unknown'" " WHERE kind IN ('assistant','answer');") != 0) { return -1; } /* The neutral form, derived as the Anthropic adapter derives it now. */ if (sqlite3_prepare_v2(s->db, "SELECT seq, native FROM pic_entry WHERE kind IN ('assistant','answer')", -1, &q, NULL) != SQLITE_OK) { return fail(s, "sql: %s", sqlite3_errmsg(s->db)); } while (sqlite3_step(q) == SQLITE_ROW) { sqlite3_int64 seq = sqlite3_column_int64(q, 0); char *neutral = pic_neutral_from_anthropic(s->db, (const char *)sqlite3_column_text(q, 1)); sqlite3_stmt *u = NULL; int ok = neutral && sqlite3_prepare_v2(s->db, "UPDATE pic_entry SET body=? WHERE seq=?", -1, &u, NULL) == SQLITE_OK; if (ok) { sqlite3_bind_text(u, 1, neutral, -1, SQLITE_STATIC); sqlite3_bind_int64(u, 2, seq); ok = sqlite3_step(u) == SQLITE_DONE; } sqlite3_finalize(u); free(neutral); if (!ok) { sqlite3_finalize(q); return fail(s, "migrating entry %lld: %s", (long long)seq, sqlite3_errmsg(s->db)); } } sqlite3_finalize(q); return pic_exec(s, "UPDATE pic_generation SET stop_reason=CASE stop_reason WHEN 'end_turn' THEN 'stop'" " WHEN 'stop_sequence' THEN 'stop' WHEN 'max_tokens' THEN 'length' WHEN 'tool_use' THEN 'toolUse'" " WHEN 'pause_turn' THEN 'pause' ELSE stop_reason END;" "UPDATE pic_meta SET value='" PIC_SCHEMA_VERSION "' WHERE key='schema_version'"); } static int schema_version_ok(pic_store *s) { sqlite3_stmt *q = NULL; int rc = 0; if (sqlite3_prepare_v2(s->db, "SELECT value FROM pic_meta WHERE key='schema_version'", -1, &q, NULL) != SQLITE_OK) { return fail(s, "sql: %s", sqlite3_errmsg(s->db)); } if (sqlite3_step(q) == SQLITE_ROW) { const char *v = (const char *)sqlite3_column_text(q, 0); if (!v || strcmp(v, PIC_SCHEMA_VERSION) != 0) { rc = fail(s, "unsupported schema version %s", v ? v : "(null)"); } } sqlite3_finalize(q); return rc; } int pic_open(pic_store *s, const char *db_path) { char *msg = NULL; memset(s, 0, sizeof *s); s->lock_fd = -1; if (take_lock(s, db_path) != 0) { return -1; } if (sqlite3_open_v2(db_path, &s->db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL) != SQLITE_OK) { return fail(s, "cannot open %s: %s", db_path, s->db ? sqlite3_errmsg(s->db) : "no memory"); } /* Per connection, not process-global, so other SQLite users are unaffected. */ if (fsl_sqlext_init(s->db, &msg, NULL) != SQLITE_OK) { int rc = fail(s, "libfossil extension: %s", msg ? msg : "failed"); sqlite3_free(msg); return rc; } if (pic_transform_register(s->db) != 0) { return fail(s, "cannot register pic_norm_id: %s", sqlite3_errmsg(s->db)); } /* Exclusive locking means the only possible busy holder is another owner; * waiting would only turn "refused" into "queued". */ sqlite3_busy_timeout(s->db, 0); if (pic_exec(s, "PRAGMA locking_mode=EXCLUSIVE; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;" "PRAGMA fullfsync=ON; PRAGMA foreign_keys=OFF") != 0 || pic_begin(s) != 0) { if (sqlite3_errcode(s->db) == SQLITE_BUSY) { return fail(s, "database is owned by another pic process"); } return -1; } if (pic_exec(s, schema_sql) != 0 || migrate(s) != 0 || pic_exec(s, "INSERT OR IGNORE INTO pic_meta(key,value) VALUES('schema_version','" PIC_SCHEMA_VERSION "')") != 0 || schema_version_ok(s) != 0 || pic_commit(s) != 0) { pic_rollback(s); return -1; } if (pic_recover(s) != 0) { return -1; } return pic_check(s); } void pic_close(pic_store *s) { if (s->db) { sqlite3_close(s->db); s->db = NULL; } if (s->lock_fd >= 0) { close(s->lock_fd); s->lock_fd = -1; } } #define STR_(x) #x #define STR(x) STR_(x) /* Each query returns a count of violating rows; any nonzero count is corruption. */ static const struct { const char *name; const char *sql; } invariants[] = { {"entry sequence has gaps", "SELECT (SELECT count(*) FROM pic_entry) != coalesce((SELECT max(seq) FROM pic_entry), 0)"}, {"entry without submission", "SELECT count(*) FROM pic_entry e WHERE NOT EXISTS (SELECT 1 FROM pic_submission s WHERE s.id=e.submission_id)"}, {"submission without exactly one first user entry", "SELECT count(*) FROM pic_submission s WHERE (SELECT count(*) FROM pic_entry e WHERE e.submission_id=s.id AND e.kind='user') != 1" " OR (SELECT kind FROM pic_entry e WHERE e.submission_id=s.id ORDER BY seq LIMIT 1) != 'user'"}, {"effect not owned by an assistant entry", "SELECT count(*) FROM pic_effect f WHERE NOT EXISTS (SELECT 1 FROM pic_entry e WHERE e.seq=f.entry_seq AND e.kind='assistant')"}, {"effect ordinals not 0..n-1 per assistant entry", "SELECT count(*) FROM (SELECT entry_seq FROM pic_effect GROUP BY entry_seq HAVING min(ordinal) != 0 OR max(ordinal) != count(*) - 1)"}, {"effect left started", "SELECT count(*) FROM pic_effect WHERE state='started'"}, {"assistant or answer entry without its origin or both forms", "SELECT count(*) FROM pic_entry WHERE kind IN ('assistant','answer') AND (native IS NULL OR provider IS NULL" " OR api IS NULL OR model IS NULL OR NOT json_valid(body) OR json_type(body) != 'array')"}, {"tool calls and effects disagree", "SELECT count(*) FROM pic_entry e WHERE e.kind='assistant' AND e.seq IN (SELECT entry_seq FROM pic_effect)" " AND (SELECT count(*) FROM pic_effect f WHERE f.entry_seq=e.seq) !=" " (SELECT count(*) FROM json_each(e.body) WHERE json_extract(value,'$.type')='toolCall')"}, {"generation left started", "SELECT count(*) FROM pic_generation WHERE state='started'"}, {"assistant or answer entry without exactly one done generation", "SELECT count(*) FROM pic_entry e WHERE e.kind IN ('assistant','answer') AND" " (SELECT count(*) FROM pic_generation g WHERE g.entry_seq=e.seq AND g.state='done' AND g.submission_id=e.submission_id) != 1"}, {"done generation without its entry", "SELECT count(*) FROM pic_generation g WHERE g.state='done' AND NOT EXISTS" " (SELECT 1 FROM pic_entry e WHERE e.seq=g.entry_seq AND e.kind IN ('assistant','answer'))"}, {"too many attempts for a turn", "SELECT count(*) FROM pic_generation WHERE attempt < 1 OR attempt > " STR(PIC_GENERATION_ATTEMPTS)}, {"failed submission without its error, or with unfinished effects", "SELECT count(*) FROM pic_submission s WHERE s.status='failed' AND (s.error IS NULL OR EXISTS" " (SELECT 1 FROM pic_effect f JOIN pic_entry a ON a.seq=f.entry_seq WHERE a.submission_id=s.id AND f.state='intent'))"}, {"terminal effect without exactly one result", "SELECT count(*) FROM pic_effect f WHERE f.state IN ('done','unknown','skipped') AND (SELECT count(*) FROM pic_entry e WHERE e.kind='tool_result' AND e.effect_id=f.id) != 1"}, {"result for a non-terminal effect", "SELECT count(*) FROM pic_entry e WHERE e.kind='tool_result' AND NOT EXISTS (SELECT 1 FROM pic_effect f WHERE f.id=e.effect_id AND f.state IN ('done','unknown','skipped'))"}, {"answer count disagrees with status", "SELECT count(*) FROM pic_submission s WHERE (SELECT count(*) FROM pic_entry e WHERE e.submission_id=s.id AND e.kind='answer') != (s.status='answered')"}, {"tool result in the wrong submission or before its call", "SELECT count(*) FROM pic_entry r JOIN pic_effect f ON f.id=r.effect_id JOIN pic_entry a ON a.seq=f.entry_seq" " WHERE r.kind='tool_result' AND (r.submission_id != a.submission_id OR r.seq < a.seq)"}, {"a later assistant turn while earlier tool calls are unfinished", "SELECT count(*) FROM pic_effect f JOIN pic_entry a ON a.seq=f.entry_seq JOIN pic_entry b" " ON b.submission_id=a.submission_id AND b.seq > a.seq AND b.kind IN ('assistant','answer')" " WHERE f.state IN ('intent','started')"}, {"tool results out of call order", "SELECT count(*) FROM pic_entry r1 JOIN pic_effect f1 ON f1.id=r1.effect_id JOIN pic_entry r2 ON r2.kind='tool_result'" " JOIN pic_effect f2 ON f2.id=r2.effect_id WHERE r1.kind='tool_result' AND f1.entry_seq=f2.entry_seq" " AND f1.ordinal < f2.ordinal AND r1.seq > r2.seq"}, {"entry after answer", "SELECT count(*) FROM pic_entry a JOIN pic_entry b ON a.submission_id=b.submission_id WHERE a.kind='answer' AND b.seq > a.seq"}, }; int pic_check(pic_store *s) { for (size_t i = 0; i < sizeof invariants / sizeof invariants[0]; i++) { sqlite3_stmt *q = NULL; sqlite3_int64 bad = 0; if (sqlite3_prepare_v2(s->db, invariants[i].sql, -1, &q, NULL) != SQLITE_OK) { return fail(s, "check %s: %s", invariants[i].name, sqlite3_errmsg(s->db)); } if (sqlite3_step(q) == SQLITE_ROW) { bad = sqlite3_column_int64(q, 0); } sqlite3_finalize(q); if (bad != 0) { return fail(s, "integrity violation: %s", invariants[i].name); } } return 0; } #ifdef PIC_FAULTS /* PIC_CRASH_AT=point:n exits abruptly on the nth arrival at point. */ void pic_fault(const char *point) { static int arrivals; const char *spec = getenv("PIC_CRASH_AT"); const char *colon; size_t len; if (!spec || !(colon = strchr(spec, ':'))) { return; } len = (size_t)(colon - spec); if (strlen(point) != len || strncmp(spec, point, len) != 0) { return; } if (++arrivals == atoi(colon + 1)) { fprintf(stderr, "pic: injected crash at %s:%d\n", point, arrivals); _exit(77); } } #endif