Skip to content
pi-c Artifact [9f77cfcf3b]
Login

Artifact [9f77cfcf3b]

Artifact 9f77cfcf3ba24726a7cf58c2fa78f638318e6cb24484344fb2e80de7e5448f99:


/* 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 <unistd.h>

#include "libfossil.h"
#include "pic.h"
#include "platform.h"
#include "sqlar.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,"
    "  session_id TEXT);"
    /* A conversation: a path through the tree of entries, ending at its head.
     * Its opening system prompt and tools are frozen at its first request;
     * instructions_hash fingerprints the project instructions it last saw. */
    "CREATE TABLE IF NOT EXISTS pic_session("
    "  id TEXT PRIMARY KEY,"
    "  name TEXT,"
    "  created_ms INTEGER NOT NULL,"
    "  updated_ms INTEGER NOT NULL,"
    "  head_seq INTEGER,"
    "  forked_from TEXT,"
    "  system_prompt TEXT,"
    "  tools TEXT,"
    "  instructions_hash TEXT,"
    "  compact_requested TEXT);" /* pic compact: NULL, or its instructions ("" for none) */
    /* 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','instructions','compaction')),"
    "  body TEXT NOT NULL,"
    "  effect_id INTEGER,"
    "  native TEXT,"
    "  provider TEXT,"
    "  api TEXT,"
    "  model TEXT,"
    "  parent_seq INTEGER,"
    "  created_ms INTEGER,"
    /* compaction: body is the summary, native the files read and modified;
     * first_kept_seq is the first entry still sent verbatim after it. */
    "  first_kept_seq INTEGER,"
    "  tokens_before INTEGER);"
    /* 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. */
    /* The full output of a truncated bash result, by effect; sqlar rule. */
    "CREATE TABLE IF NOT EXISTS pic_output(effect_id INTEGER PRIMARY KEY, sz INTEGER NOT NULL, data BLOB NOT NULL);"
    "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,"
    /* compaction: a summary request made before the reply of that turn */
    "  purpose TEXT NOT NULL DEFAULT 'reply' CHECK(purpose IN ('reply','compaction')),"
    "  UNIQUE(submission_id, purpose, turn, attempt));"
    /* Steering and follow-up messages (Pi's steer and follow_up), journaled
     * as they arrive. submission_id is the request that holds it (always an
     * admitted one while queued); a delivered message became the user entry
     * entry_seq of that request: after a turn's tool results (steer), or its
     * first entries (the queue of the answered request before it). returned:
     * its request failed or was cancelled, so it was never run. */
    "CREATE TABLE IF NOT EXISTS pic_queued("
    "  id INTEGER PRIMARY KEY,"
    "  session_id TEXT NOT NULL,"
    "  submission_id INTEGER NOT NULL,"
    "  kind TEXT NOT NULL CHECK(kind IN ('steer','follow_up')),"
    "  text TEXT NOT NULL,"
    "  state TEXT NOT NULL CHECK(state IN ('queued','delivered','cleared','returned')),"
    "  entry_seq INTEGER UNIQUE,"
    "  created_ms INTEGER NOT NULL);"
    /* Image bytes, once per distinct content (hash: SHA3-256, hex); sqlar
     * rule: data is deflated only when that is smaller, raw when sz is its
     * length. mime is the inline type it is sent as. */
    "CREATE TABLE IF NOT EXISTS pic_image("
    "  hash TEXT PRIMARY KEY,"
    "  mime TEXT NOT NULL,"
    "  sz INTEGER NOT NULL,"
    "  data BLOB NOT NULL);"
    /* The images of a user or tool_result entry, or of a queued message, in
     * order after its text (Pi's content: the text, then each image). A
     * delivered message's images are copied to its entry. */
    "CREATE TABLE IF NOT EXISTS pic_attachment("
    "  id INTEGER PRIMARY KEY,"
    "  entry_seq INTEGER,"
    "  queued_id INTEGER,"
    "  ordinal INTEGER NOT NULL,"
    "  image TEXT NOT NULL,"
    "  CHECK((entry_seq IS NULL) != (queued_id IS NULL)),"
    "  UNIQUE(entry_seq, ordinal),"
    "  UNIQUE(queued_id, ordinal));";

/* Links every new entry into its conversation: its parent is the session's
 * head, and the head moves to it. Run inside the inserting transaction, so
 * the tree is consistent on every path, recovery and cancel included. */
static const char link_sql[] =
    "CREATE TRIGGER IF NOT EXISTS pic_entry_link AFTER INSERT ON pic_entry WHEN NEW.parent_seq IS NULL BEGIN"
    "  UPDATE pic_entry SET parent_seq = (SELECT s.head_seq FROM pic_session s JOIN pic_submission u"
    "    ON u.session_id = s.id WHERE u.id = NEW.submission_id),"
    "    created_ms = coalesce(NEW.created_ms, CAST(unixepoch('subsec') * 1000 AS INTEGER)) WHERE seq = NEW.seq;"
    "  UPDATE pic_session SET head_seq = NEW.seq, updated_ms = CAST(unixepoch('subsec') * 1000 AS INTEGER)"
    "    WHERE id = (SELECT session_id FROM pic_submission WHERE id = NEW.submission_id);"
    "END;";

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");
    }
    for (int tries = 0; (s->lock_fd = pic_platform_get()->lock(path)) < 0; tries++) {
        if (s->lock_fd == -1) {
            return fail(s, "cannot open lock %s: %s", path, strerror(errno));
        }
        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_from_3(pic_store *s) {
    sqlite3_stmt *q = NULL;
    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='4' WHERE key='schema_version'");
}

/* Version 4 had no conversations: each submission becomes its own session,
 * its entries chained in order; pic_entry is rebuilt for the new kind and
 * columns (a CHECK constraint cannot be altered). The frozen system prompt
 * is taken at the session's next request. */
static int migrate_from_4(pic_store *s) {
    return pic_exec(
        s, "CREATE TABLE pic_entry_v5(seq INTEGER PRIMARY KEY, submission_id INTEGER NOT NULL,"
           " kind TEXT NOT NULL CHECK(kind IN ('user','assistant','tool_result','answer','instructions')),"
           " body TEXT NOT NULL, effect_id INTEGER, native TEXT, provider TEXT, api TEXT, model TEXT,"
           " parent_seq INTEGER, created_ms INTEGER);"
           "INSERT INTO pic_entry_v5 SELECT seq, submission_id, kind, body, effect_id, native, provider, api, model,"
           " (SELECT max(p.seq) FROM pic_entry p WHERE p.submission_id = e.submission_id AND p.seq < e.seq), NULL"
           " FROM pic_entry e;"
           "DROP TABLE pic_entry;"
           "ALTER TABLE pic_entry_v5 RENAME TO pic_entry;"
           "ALTER TABLE pic_submission ADD COLUMN session_id TEXT;"
           "INSERT INTO pic_session(id, created_ms, updated_ms, head_seq)"
           " SELECT printf('s%07d', id), CAST(unixepoch('subsec') * 1000 AS INTEGER),"
           " CAST(unixepoch('subsec') * 1000 AS INTEGER),"
           " (SELECT max(seq) FROM pic_entry e WHERE e.submission_id = u.id) FROM pic_submission u;"
           "UPDATE pic_submission SET session_id = printf('s%07d', id);"
           "UPDATE pic_meta SET value='5' WHERE key='schema_version'");
}

/* Version 5 had no compaction: pic_entry is rebuilt for the new kind and
 * columns, and sessions gain the on-demand flag. */
static int migrate_from_5(pic_store *s) {
    sqlite3_stmt *q = NULL;
    int has = 0;
    /* A journal older than version 4 got pic_session from the current schema. */
    if (sqlite3_prepare_v2(s->db, "SELECT count(*) FROM pragma_table_info('pic_session') WHERE name = 'compact_requested'",
                           -1, &q, NULL) == SQLITE_OK &&
        sqlite3_step(q) == SQLITE_ROW) {
        has = sqlite3_column_int(q, 0);
    }
    sqlite3_finalize(q);
    if (!has && pic_exec(s, "ALTER TABLE pic_session ADD COLUMN compact_requested TEXT") != 0) {
        return -1;
    }
    return pic_exec(
        s, "CREATE TABLE pic_entry_v6(seq INTEGER PRIMARY KEY, submission_id INTEGER NOT NULL,"
           " kind TEXT NOT NULL CHECK(kind IN ('user','assistant','tool_result','answer','instructions','compaction')),"
           " body TEXT NOT NULL, effect_id INTEGER, native TEXT, provider TEXT, api TEXT, model TEXT,"
           " parent_seq INTEGER, created_ms INTEGER, first_kept_seq INTEGER, tokens_before INTEGER);"
           "INSERT INTO pic_entry_v6 SELECT seq, submission_id, kind, body, effect_id, native, provider, api, model,"
           " parent_seq, created_ms, NULL, NULL FROM pic_entry;"
           "DROP TABLE pic_entry;"
           "ALTER TABLE pic_entry_v6 RENAME TO pic_entry;"
           "CREATE TABLE pic_generation_v6(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,"
           " purpose TEXT NOT NULL DEFAULT 'reply' CHECK(purpose IN ('reply','compaction')),"
           " UNIQUE(submission_id, purpose, turn, attempt));"
           "INSERT INTO pic_generation_v6 SELECT id, submission_id, turn, attempt, state, entry_seq, stop_reason, usage,"
           " request_id, error, 'reply' FROM pic_generation;"
           "DROP TABLE pic_generation;"
           "ALTER TABLE pic_generation_v6 RENAME TO pic_generation;"
           "UPDATE pic_meta SET value='6' WHERE key='schema_version'");
}

/* Version 6 is unchanged in shape; it fills in the times older versions
 * never wrote. An entry without a time takes its request's start, which an
 * ask key records (ask-SECONDS-NANOSECONDS-PID); a session takes its first
 * entry's time when that is earlier (version 4's migration stamped sessions
 * with the time it ran). */
static int migrate_from_6(pic_store *s) {
    return pic_exec(
        s, "UPDATE pic_entry SET created_ms = (SELECT"
           " CAST(substr(u.request_key, 5, instr(substr(u.request_key, 5), '-') - 1) AS INTEGER) * 1000"
           " + CAST(substr(u.request_key, 5 + instr(substr(u.request_key, 5), '-'), 3) AS INTEGER)"
           " FROM pic_submission u WHERE u.id = pic_entry.submission_id"
           " AND u.request_key GLOB 'ask-[0-9]*-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-*')"
           " WHERE created_ms IS NULL;"
           "UPDATE pic_session SET created_ms = min(created_ms, coalesce((SELECT min(e.created_ms) FROM pic_entry e"
           " JOIN pic_submission u ON u.id = e.submission_id WHERE u.session_id = pic_session.id), created_ms));"
           "UPDATE pic_meta SET value='7' WHERE key='schema_version'");
}

/* Version 7 had no queue of steering and follow-up messages; the schema
 * above has just created it, empty. */
static int migrate_from_7(pic_store *s) { return pic_exec(s, "UPDATE pic_meta SET value='8' WHERE key='schema_version'"); }

/* Version 8 had no images; the schema above has just created their tables,
 * empty. */
static int migrate_from_8(pic_store *s) { return pic_exec(s, "UPDATE pic_meta SET value='9' WHERE key='schema_version'"); }

/* Steps an older journal up to the current version, one version at a time. */
static int migrate(pic_store *s) {
    for (;;) {
        sqlite3_stmt *q = NULL;
        char version[16] = "";
        int rc;
        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) {
            rc = migrate_from_3(s);
        } else if (strcmp(version, "4") == 0) {
            rc = migrate_from_4(s);
        } else if (strcmp(version, "5") == 0) {
            rc = migrate_from_5(s);
        } else if (strcmp(version, "6") == 0) {
            rc = migrate_from_6(s);
        } else if (strcmp(version, "7") == 0) {
            rc = migrate_from_7(s);
        } else if (strcmp(version, "8") == 0) {
            rc = migrate_from_8(s);
        } else {
            return 0; /* new, current, or a version schema_version_ok refuses */
        }
        if (rc != 0) {
            return -1;
        }
    }
}

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, pic_platform_get()->vfs) !=
        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_sqlar_register(s->db) != 0) {
        return fail(s, "cannot register sqlar functions: %s", sqlite3_errmsg(s->db));
    }
    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, link_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) {
        pic_platform_get()->unlock(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 whose first entry is not its user entry",
     "SELECT count(*) FROM pic_submission s WHERE coalesce((SELECT kind FROM pic_entry e WHERE e.submission_id=s.id ORDER BY seq LIMIT 1), '') != 'user'"},
    /* A request's later user entries are steering or follow-ups delivered into it. */
    {"user entry after the first that is not a delivered message",
     "SELECT count(*) FROM pic_entry e WHERE e.kind='user' AND e.seq != (SELECT min(x.seq) FROM pic_entry x WHERE x.submission_id=e.submission_id)"
     " AND NOT EXISTS (SELECT 1 FROM pic_queued q WHERE q.entry_seq=e.seq)"},
    {"queued message without its session or request",
     "SELECT count(*) FROM pic_queued q WHERE NOT EXISTS (SELECT 1 FROM pic_submission u WHERE u.id=q.submission_id AND u.session_id=q.session_id)"},
    {"delivered message without its user entry, or another with one",
     "SELECT count(*) FROM pic_queued q WHERE (q.state='delivered') != (q.entry_seq IS NOT NULL) OR (q.entry_seq IS NOT NULL AND NOT EXISTS"
     " (SELECT 1 FROM pic_entry e JOIN pic_submission u ON u.id=e.submission_id WHERE e.seq=q.entry_seq AND e.kind='user'"
     " AND e.body=q.text AND u.session_id=q.session_id))"},
    {"queued message held by a finished request",
     "SELECT count(*) FROM pic_queued q JOIN pic_submission u ON u.id=q.submission_id WHERE q.state='queued' AND u.status != 'admitted'"},
    {"delivered message not in the request that holds it",
     "SELECT count(*) FROM pic_queued q JOIN pic_entry e ON e.seq=q.entry_seq WHERE e.submission_id != q.submission_id"},
    {"delivered message before a tool result of its turn",
     "SELECT count(*) FROM pic_queued q JOIN pic_entry m ON m.seq=q.entry_seq JOIN pic_entry r ON r.submission_id=m.submission_id"
     " AND r.kind='tool_result' AND r.seq > m.seq JOIN pic_effect f ON f.id=r.effect_id WHERE f.entry_seq < m.seq"},
    {"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'"},
    {"submission without a session",
     "SELECT count(*) FROM pic_submission u WHERE NOT EXISTS (SELECT 1 FROM pic_session s WHERE s.id = u.session_id)"},
    {"session head missing",
     "SELECT count(*) FROM pic_session s WHERE s.head_seq IS NOT NULL AND NOT EXISTS (SELECT 1 FROM pic_entry e WHERE e.seq = s.head_seq)"},
    {"entry parent missing or not earlier",
     "SELECT count(*) FROM pic_entry e WHERE e.parent_seq IS NOT NULL AND (e.parent_seq >= e.seq OR NOT EXISTS"
     " (SELECT 1 FROM pic_entry p WHERE p.seq = e.parent_seq))"},
    {"a submission's entries are not one chain",
     "SELECT count(*) FROM pic_entry e WHERE e.seq != (SELECT min(x.seq) FROM pic_entry x WHERE x.submission_id=e.submission_id) AND e.parent_seq IS NOT"
     " (SELECT max(p.seq) FROM pic_entry p WHERE p.submission_id = e.submission_id AND p.seq < e.seq)"},
    {"more than one unfinished submission in a session",
     "SELECT count(*) FROM (SELECT session_id FROM pic_submission WHERE status = 'admitted' GROUP BY session_id HAVING count(*) > 1)"},
    {"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'"},
    {"reply or compaction entry without exactly one done generation",
     "SELECT count(*) FROM pic_entry e WHERE e.kind IN ('assistant','answer','compaction') 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','compaction'))"},
    {"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"},
    {"attachment without its image",
     "SELECT count(*) FROM pic_attachment a WHERE NOT EXISTS (SELECT 1 FROM pic_image i WHERE i.hash=a.image)"},
    {"attachment on something other than a user entry, tool result or queued message",
     "SELECT count(*) FROM pic_attachment a WHERE CASE WHEN a.entry_seq IS NOT NULL THEN NOT EXISTS"
     " (SELECT 1 FROM pic_entry e WHERE e.seq=a.entry_seq AND e.kind IN ('user','tool_result'))"
     " ELSE NOT EXISTS (SELECT 1 FROM pic_queued q WHERE q.id=a.queued_id) END"},
    {"attachment ordinals not 0..n-1",
     "SELECT count(*) FROM (SELECT 1 FROM pic_attachment GROUP BY entry_seq, queued_id"
     " HAVING min(ordinal) != 0 OR max(ordinal) != count(*) - 1)"},
    {"delivered message without its images",
     "SELECT count(*) FROM pic_queued q WHERE q.state='delivered' AND"
     " (SELECT group_concat(image) FROM (SELECT image FROM pic_attachment WHERE queued_id=q.id ORDER BY ordinal)) IS NOT"
     " (SELECT group_concat(image) FROM (SELECT image FROM pic_attachment WHERE entry_seq=q.entry_seq ORDER BY ordinal))"},
    {"image stored larger than its content",
     "SELECT count(*) FROM pic_image WHERE sz < 0 OR length(data) > sz OR typeof(data) != 'blob'"},
    {"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