Artifact 442b64d2e49c3cb0afdaca88a71820d48bbe9fa0af31a9cc8b52db282b04b6ba:
- File
src/store.c
— part of check-in
[7e7550292a]
at
2026-11-18 12:30:18
on branch tracer-bullet
— Add the first durable agent loop in C
pic keeps its journal in its own libfossil-hosted SQLite database: an idempotent admission per request key, then one short transaction per state change, never held across provider or tool I/O. A replay-safe write tool reruns after a crash; a replay-unsafe exec records an unknown outcome and never reruns. exec runs under a supervisor that starts the command only after the started commit and kills its group if pic dies or is interrupted. A second pic on the same database is refused.
test/pic/crash.sh crashes at every commit and effect boundary and checks the journal against an external ledger, plus deadline, output redirection, background child, crash and interrupt orphaning, and second-writer cases. Vendored SQLite and libfossil match ctx byte for byte. (user: dmestas, size: 9253) [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')));" "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);" "CREATE TABLE IF NOT EXISTS pic_effect(" " id INTEGER PRIMARY KEY," " entry_seq INTEGER NOT NULL UNIQUE," " tool TEXT NOT NULL," " args 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'))," " result TEXT);"; 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; } 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; } /* 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 || 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; } } /* 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')"}, {"assistant entry without effect", "SELECT count(*) FROM pic_entry e WHERE e.kind='assistant' AND NOT EXISTS (SELECT 1 FROM pic_effect f WHERE f.entry_seq=e.seq)"}, {"effect left started", "SELECT count(*) FROM pic_effect WHERE state='started'"}, {"terminal effect without exactly one result", "SELECT count(*) FROM pic_effect f WHERE f.state IN ('done','unknown') 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'))"}, {"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)"}, {"more than one unfinished effect in a submission", "SELECT count(*) FROM (SELECT a.submission_id FROM pic_effect f JOIN pic_entry a ON a.seq=f.entry_seq" " WHERE f.state IN ('intent','started') GROUP BY a.submission_id HAVING count(*) > 1)"}, {"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