Skip to content
pi-c Documentation
Login

Documentation

/* Storage: one libfossil-hosted SQLite database, shared by the pic processes
 * of a workspace; each conversation is worked by one of them at a time
 * (docs/design/shared-store.md). */
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#include "libfossil.h"
#include "pic.h"
#include "platform.h"
#include "inbox.h"
#include "sqlar.h"
#include "userdb.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','stopped')),"
    "  error TEXT,"
    "  session_id TEXT,"
    /* stopped: ended cleanly before its answer, for stop_reason (request_cap:
     * it would have sent more than max_requests provider requests). trial:
     * the benchmark arm it ran under (pic --trial), NULL when unset. */
    "  stop_reason TEXT,"
    "  trial TEXT,"
    "  max_requests INTEGER,"
    /* The model ("provider/id") and thinking level it was admitted with,
     * which it finishes with whoever runs it; NULL: the runner's. */
    "  model TEXT,"
    "  thinking 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','hook',"
    "   'branch_summary')),"
    "  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,"
    /* branch_summary (Pi's, made when /tree leaves a branch): body is the
     * summary, native the files read and modified; it follows the entry it
     * was made at (parent_seq) and belongs to that entry's request, though
     * only the conversation it starts has it on its path. from_seq is the
     * head of the conversation it summarized (Pi's fromId). A compaction
     * made outside a turn (Pi's compact command over RPC), and the
     * instructions it carries over, also name the head they followed in
     * from_seq: they belong to the conversation's latest request, after its
     * end, as a branch summary does. */
    "  from_seq INTEGER);"
    /* A tool call's result entry, found by its effect. */
    "CREATE INDEX IF NOT EXISTS pic_entry_effect ON pic_entry(effect_id);"
    /* 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;
     * branch_summary: one made when /tree left a branch, by the request of
     * the entry it was made at, turn numbering that request's branch
     * summaries (1, 2, ...) and attempt its tries at one. */
    "  purpose TEXT NOT NULL DEFAULT 'reply' CHECK(purpose IN ('reply','compaction','branch_summary')),"
    /* compaction: why (manual, threshold, lapse) and the context's tokens
     * then; lapse: the seconds since the conversation's last reply. */
    "  reason TEXT,"
    "  idle_seconds INTEGER,"
    "  context_tokens INTEGER,"
    "  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 of the bytes,
     * hex); sqlar rule: data is deflated only when that is smaller, raw when
     * sz is its length. mime is the type sniffed from the bytes (never a
     * declared one), width and height its header's. data is NULL once
     * pruned (pic_prune); the rest stays. */
    "CREATE TABLE IF NOT EXISTS pic_image("
    "  hash TEXT PRIMARY KEY,"
    "  mime TEXT NOT NULL,"
    "  width INTEGER NOT NULL,"
    "  height INTEGER NOT NULL,"
    "  sz INTEGER NOT NULL,"
    "  data BLOB);"
    /* 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));"
    /* A command the user ran (Pi's bashExecution message): the user entry
     * entry_seq of its own already-answered request carries Pi's text for the
     * model in body; this row keeps the parts. exclude: "!!", never sent to
     * the model. full: the whole output when it was cut (read pic:bash/SEQ). */
    "CREATE TABLE IF NOT EXISTS pic_bash("
    "  entry_seq INTEGER PRIMARY KEY,"
    "  command TEXT NOT NULL,"
    "  output TEXT NOT NULL,"
    "  exit_code INTEGER,"
    "  cancelled INTEGER NOT NULL CHECK(cancelled IN (0,1)),"
    "  truncated INTEGER NOT NULL CHECK(truncated IN (0,1)),"
    "  exclude INTEGER NOT NULL CHECK(exclude IN (0,1)),"
    "  full_sz INTEGER,"
    "  full BLOB);"
    /* One row per hook command run (hooks.h), journaled as started before
     * the command runs and done after, as an unsafe effect is: a run a crash
     * interrupted is never run again, and its event's safe default applies.
     * A row with no command marks a firing where none matched. ref is what
     * it ran for: the effect (PreToolUse, PostToolUse), the reply entry
     * (Stop), the compaction entry (SessionStart after one), the turn
     * (PreCompact) or the queued message (UserPromptSubmit for a steer or
     * follow-up). owner is the pic process (or terminal) whose conversation
     * it is. A UserPromptSubmit context belongs to the request its prompt
     * became (submission_id; none while it is not admitted); context and
     * PostToolUse feedback are pending until they become hook entry entry_seq.
     * A row in state pending (no command; ref the queued message) is a steer
     * or follow-up queued before its prompt hooks ran: they run before it can
     * be delivered, after a crash too (pic_hooks_run_pending). */
    "CREATE TABLE IF NOT EXISTS pic_hook_run("
    "  id INTEGER PRIMARY KEY,"
    "  event TEXT NOT NULL,"
    "  session_id TEXT,"
    "  submission_id INTEGER,"
    "  ref INTEGER,"
    "  owner TEXT,"
    "  command TEXT,"
    "  exit_code INTEGER,"
    "  duration_ms INTEGER,"
    "  error TEXT,"
    "  outcome TEXT CHECK(outcome IN ('allow','ask','deny','block')),"
    "  reason TEXT,"
    "  context TEXT,"
    "  entry_seq INTEGER,"
    "  created_ms INTEGER NOT NULL,"
    "  state TEXT NOT NULL DEFAULT 'done' CHECK(state IN ('started','done','interrupted','pending')));";

/* The inbox (inbox.c). */
static const char inbox_sql[] =
    /* A message for a conversation from another process (inbox.c,
     * docs/design/grapevine.md): one Pi RPC command line, inserted by its
     * sender with no lease and delivered by the conversation's lease holder
     * in one transaction with what it made. msg_key is the sender's
     * idempotency key, kept for ever; command_hash (SHA3-256 of command)
     * tells a retry from a conflict. target: an abort's request, the one
     * running when it was sent. Pruned 7 days after it left pending:
     * command and response become NULL, the key stays. */
    "CREATE TABLE IF NOT EXISTS pic_inbox("
    "  id INTEGER PRIMARY KEY,"
    "  msg_key TEXT NOT NULL UNIQUE,"
    "  command_hash TEXT NOT NULL,"
    "  session_id TEXT NOT NULL,"
    "  sender TEXT NOT NULL,"
    "  command TEXT,"
    "  hops INTEGER NOT NULL DEFAULT 0,"
    "  target INTEGER,"
    "  created_ms INTEGER NOT NULL,"
    "  expires_ms INTEGER NOT NULL,"
    "  state TEXT NOT NULL CHECK(state IN ('pending','delivered','refused','expired')),"
    "  response TEXT,"
    "  submission_id INTEGER,"
    "  queued_id INTEGER,"
    "  settled_ms INTEGER);"
    "CREATE INDEX IF NOT EXISTS pic_inbox_waiting ON pic_inbox(session_id, state);";

/* The file history (filelog.c). */
static const char files_sql[] =
    /* A file as a write or edit (effect_id) found it before touching it, or
     * as a rewind's restore (restore_id) found it, and what it left: pre_*
     * the file before (exists 0: none; hash: SHA3-256 of the bytes, NULL when
     * it could not be read; kept: the bytes are in pic_blob, 0 past
     * rewindMaxBytes), post_* after (an effect's once its result commits, a
     * restore's what it puts back). outcome: a restore's, per file
     * (filelog.c). */
    "CREATE TABLE IF NOT EXISTS pic_file_change("
    "  id INTEGER PRIMARY KEY,"
    "  effect_id INTEGER UNIQUE,"
    "  restore_id INTEGER,"
    "  path TEXT NOT NULL,"
    "  pre_exists INTEGER NOT NULL CHECK(pre_exists IN (0,1)),"
    "  pre_mode INTEGER,"
    "  pre_size INTEGER,"
    "  pre_hash TEXT,"
    "  pre_kept INTEGER NOT NULL CHECK(pre_kept IN (0,1)),"
    "  post_exists INTEGER CHECK(post_exists IN (0,1)),"
    "  post_mode INTEGER,"
    "  post_hash TEXT,"
    "  outcome TEXT CHECK(outcome IN ('restored','unchanged','changed','failed')),"
    "  CHECK((effect_id IS NULL) != (restore_id IS NULL)));"
    "CREATE INDEX IF NOT EXISTS pic_file_change_restore ON pic_file_change(restore_id);"
    /* File bytes, once per distinct content (hash: SHA3-256, hex); sqlar rule. */
    "CREATE TABLE IF NOT EXISTS pic_blob(hash TEXT PRIMARY KEY, sz INTEGER NOT NULL, data BLOB NOT NULL);"
    /* A rewind's file restore of conversation session_id to before entry
     * to_seq, or the undoing of restore undoes. Journaled with its files
     * before any is touched; a dead process's started one is finished by the
     * conversation's next owner. fork_at: the conversation is forked there in
     * the transaction that ends it (0: a new, empty one), the fork in forked
     * ("" for an empty one); NULL: files only. */
    "CREATE TABLE IF NOT EXISTS pic_restore("
    "  id INTEGER PRIMARY KEY,"
    "  session_id TEXT NOT NULL,"
    "  to_seq INTEGER,"
    "  undoes INTEGER,"
    "  fork_at INTEGER,"
    "  forked TEXT,"
    "  state TEXT NOT NULL CHECK(state IN ('started','done')),"
    "  created_ms INTEGER NOT NULL);";

/* 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 void sha3_fn(sqlite3_context *ctx, int argc, sqlite3_value **argv);

static int st_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 = st_fail(s, "sql: %s", msg ? msg : sqlite3_errmsg(s->db));
        sqlite3_free(msg);
        return rc;
    }
    return 0;
}

#ifdef PIC_FAULTS
/* A write begun while one of this connection's statements is mid-row fails
 * with SQLITE_BUSY_SNAPSHOT once another process has committed since that
 * statement's first row; no wait gets past it. Dev builds stop at the first
 * write that could: at pic_begin, and at a row written with no transaction
 * begun. */
static void no_open_read(sqlite3 *db) {
    for (sqlite3_stmt *q = sqlite3_next_stmt(db, NULL); q; q = sqlite3_next_stmt(db, q)) {
        if (sqlite3_stmt_busy(q) && sqlite3_stmt_readonly(q)) {
            fprintf(stderr, "pic: internal: a write begun under an open read: %s\n", sqlite3_sql(q));
            abort();
        }
    }
}

static void on_row_written(void *db, int op, const char *schema, const char *table, sqlite3_int64 rowid) {
    (void)op;
    (void)schema;
    (void)table;
    (void)rowid;
    if (sqlite3_get_autocommit(db)) {
        no_open_read(db);
    }
}
#endif

/* Inside pic_begin_outer's transaction, a begin is a savepoint, so code
 * that keeps its own transaction (a queued message's) commits as part of
 * the outer one (an inbox delivery's), or rolls back alone. */
int pic_begin(pic_store *s) {
    if (s->nest > 0) {
        if (pic_exec(s, "SAVEPOINT pic_nested") != 0) {
            return -1;
        }
        s->nest++;
        return 0;
    }
#ifdef PIC_FAULTS
    no_open_read(s->db);
#endif
    return pic_exec(s, "BEGIN IMMEDIATE");
}
int pic_commit(pic_store *s) {
    if (s->nest > 1) {
        s->nest--;
        return pic_exec(s, "RELEASE pic_nested");
    }
    s->nest = 0;
    return pic_exec(s, "COMMIT");
}

void pic_rollback(pic_store *s) {
    if (s->nest > 1) {
        s->nest--;
        (void)sqlite3_exec(s->db, "ROLLBACK TO pic_nested; RELEASE pic_nested", NULL, NULL, NULL);
        return;
    }
    s->nest = 0;
    if (!sqlite3_get_autocommit(s->db)) {
        (void)sqlite3_exec(s->db, "ROLLBACK", NULL, NULL, NULL);
    }
}

int pic_begin_outer(pic_store *s) {
    if (pic_begin(s) != 0) {
        return -1;
    }
    s->nest = 1;
    return 0;
}

/* How long a write waits for another process's write transaction. They are
 * a few statements and one fsync each; past this the statement fails, the
 * process stops as on any storage error, and its work is recovered. */
#define JOURNAL_BUSY_MS 30000
/* How long open waits for the journal lock, and a claimer for a lease: a
 * holder that is on its way out (a killed pic's command supervisor) lets go
 * within moments. */
#define LOCK_WAIT_MS 1000

static int host(void) { return pic_platform_get() == pic_platform_host(); }

/* The journal lock, <journal>.pic-lock: every open store holds it shared;
 * creating or migrating the schema takes it exclusive, so that never
 * happens under a running pic. A pic from before journals were shared takes
 * it exclusive for its whole run, and so is kept apart from these. Waits up
 * to WAIT_MS. 0; 1 when another process holds it the other way; -1. */
static int journal_lock(pic_store *s, int shared, int wait_ms) {
    for (int waited = 0;; waited += 20) {
        s->lock_fd = pic_platform_get()->lock(s->lock_path, shared);
        if (s->lock_fd >= 0) {
            return 0;
        }
        if (s->lock_fd == -1) {
            return st_fail(s, "cannot open lock %s: %s", s->lock_path, strerror(errno));
        }
        s->lock_fd = -1;
        if (errno != EWOULDBLOCK) {
            return st_fail(s, "cannot lock %s: %s", s->lock_path, strerror(errno));
        }
        if (waited >= wait_ms) {
            return 1;
        }
        (void)usleep(20000);
    }
}

static void journal_unlock(pic_store *s) {
    if (s->lock_fd >= 0) {
        pic_platform_get()->unlock(s->lock_fd);
        s->lock_fd = -1;
    }
}

/* The locks are named by the journal's real path, so every path to one
 * journal reaches the same locks. */
static int lock_paths(pic_store *s, const char *db_path) {
    char real[4096], dir[4096];
    const char *slash = strrchr(db_path, '/'), *base = slash ? slash + 1 : db_path;
    size_t n;
    if (host() && realpath(db_path, real)) {
        db_path = real;
    } else if (host()) { /* not there yet: its directory's real path */
        if (slash && (size_t)(slash - db_path) < sizeof dir) {
            memcpy(dir, db_path, (size_t)(slash - db_path));
            dir[slash - db_path] = '\0';
        } else {
            (void)snprintf(dir, sizeof dir, ".");
        }
        if (realpath(slash == db_path ? "/" : dir, real) && strlen(real) + strlen(base) + 2 < sizeof real) {
            n = strlen(real);
            (void)snprintf(real + n, sizeof real - n, "%s%s", n && real[n - 1] == '/' ? "" : "/", base);
            db_path = real;
        }
    }
    n = strlen(db_path) + sizeof ".pic-leases";
    s->lock_path = malloc(n);
    s->lease_dir = malloc(n);
    if (!s->lock_path || !s->lease_dir) {
        return st_fail(s, "out of memory");
    }
    (void)snprintf(s->lock_path, n, "%s.pic-lock", db_path);
    (void)snprintf(s->lease_dir, n, "%s.pic-leases", db_path);
    return 0;
}

/* ---- conversation leases ----------------------------------------------- */

struct pic_lease {
    char session[64];
    int handle;
};

/* <journal>.pic-leases/ID; an id that is not plain is named by its bytes. */
static int lease_path(pic_store *s, const char *session, char *out, size_t cap) {
    char name[160];
    size_t n = strlen(session);
    if (n > 0 && n < 64 && session[0] != '.' &&
        strspn(session, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-") == n) {
        (void)snprintf(name, sizeof name, "%s", session);
    } else {
        if (n >= 64) {
            return st_fail(s, "conversation id too long");
        }
        name[0] = '%';
        for (size_t i = 0; i < n; i++) {
            (void)snprintf(name + 1 + 2 * i, 3, "%02x", (unsigned char)session[i]);
        }
        name[1 + 2 * n] = '\0';
    }
    return snprintf(out, cap, "%s/%s", s->lease_dir, name) < (int)cap ? 0 : st_fail(s, "database path too long");
}

static struct pic_lease *lease_find(pic_store *s, const char *session) {
    for (size_t i = 0; i < s->nleases; i++) {
        if (strcmp(s->leases[i].session, session) == 0) {
            return &s->leases[i];
        }
    }
    return NULL;
}

int pic_leased(pic_store *s, const char *session) { return lease_find(s, session) != NULL; }

/* The pid a lease file names, or 0. */
static long lease_pid(const char *path) {
    char buf[32] = "";
    long pid = 0;
    int fd = host() ? open(path, O_RDONLY | O_CLOEXEC) : -1;
    if (fd >= 0) {
        ssize_t n = read(fd, buf, sizeof buf - 1);
        close(fd);
        pid = n > 0 ? strtol(buf, NULL, 10) : 0;
    }
    return pid > 0 ? pid : 0;
}

long pic_lease_holder(pic_store *s, const char *session) {
    char path[4096];
    struct stat st;
    int h;
    if (lease_find(s, session)) {
        return (long)getpid();
    }
    if (lease_path(s, session, path, sizeof path) != 0 || (host() && stat(path, &st) != 0)) {
        return 0; /* never leased */
    }
    /* Shared: a look never keeps another look, and at most delays a taker. */
    h = pic_platform_get()->lock(path, 1);
    if (h >= 0) { /* let go, or left by a crash: nobody's */
        pic_platform_get()->unlock(h);
        return 0;
    }
    if (h == -1 || errno != EWOULDBLOCK) {
        return 0;
    }
    h = (int)lease_pid(path);
    return h ? h : -1;
}

void pic_lease_err(pic_store *s, const char *what, const char *session) {
    long pid = pic_lease_holder(s, session);
    char who[48] = "";
    if (pid > 0) {
        (void)snprintf(who, sizeof who, " (pid %ld)", pid);
    }
    (void)st_fail(s, "%s %s is in use by another pic process%s", what, session, who);
}

int pic_lease(pic_store *s, const char *session, int wait_ms) {
    char path[4096];
    struct pic_lease *grown;
    int h;
    if (lease_find(s, session)) {
        return 0;
    }
    if (lease_path(s, session, path, sizeof path) != 0) {
        return -1;
    }
    if (host() && mkdir(s->lease_dir, 0700) != 0 && errno != EEXIST) {
        return st_fail(s, "cannot create %s: %s", s->lease_dir, strerror(errno));
    }
    /* Even with no wait asked, a few tries a millisecond apart: another
     * process looking at who holds it (pic_lease_holder) has it for an
     * instant, and that is not an owner. */
    for (int waited = -3;; waited += waited < 0 ? 1 : 20) {
        h = pic_platform_get()->lock(path, 0);
        if (h >= 0) {
            break;
        }
        if (h == -1 || errno != EWOULDBLOCK) {
            return st_fail(s, "cannot lock %s: %s", path, strerror(errno));
        }
        if (waited >= wait_ms) {
            pic_lease_err(s, "conversation", session);
            return 1;
        }
        (void)usleep(waited < 0 ? 1000 : 20000);
    }
    if (host()) { /* who has it, for the message another process gives; the lock is the truth */
        int fd = open(path, O_WRONLY | O_TRUNC | O_CLOEXEC);
        if (fd >= 0) {
            char pid[32];
            int n = snprintf(pid, sizeof pid, "%ld\n", (long)getpid());
            if (write(fd, pid, (size_t)n) != n) {
                (void)ftruncate(fd, 0);
            }
            close(fd);
        }
    }
    grown = realloc(s->leases, (s->nleases + 1) * sizeof *grown);
    if (!grown) {
        pic_platform_get()->unlock(h);
        return st_fail(s, "out of memory");
    }
    s->leases = grown;
    (void)snprintf(grown[s->nleases].session, sizeof grown[s->nleases].session, "%s", session);
    grown[s->nleases].handle = h;
    s->nleases++;
    /* Its new owner settles what the last one left unfinished: a restore,
     * which writes files, only outside a caller's transaction (open's
     * recovery is outside one, and comes first). */
    if (pic_recover_session(s, session) != 0 ||
        (sqlite3_get_autocommit(s->db) && pic_restore_resume(s, session) != 0)) {
        pic_unlease(s, session);
        return -1;
    }
    return 0;
}

/* The file stays: it holds no state, and a child this process forked may
 * still hold the lock on it. */
void pic_unlease(pic_store *s, const char *session) {
    struct pic_lease *l = lease_find(s, session);
    if (!l) {
        return;
    }
    pic_platform_get()->unlock(l->handle);
    *l = s->leases[--s->nleases];
}

/* pic_leased(session_id): this store holds its lease. */
static void leased_fn(sqlite3_context *ctx, int argc, sqlite3_value **argv) {
    const char *id = (const char *)sqlite3_value_text(argv[0]);
    (void)argc;
    sqlite3_result_int(ctx, id && pic_leased(sqlite3_user_data(ctx), id));
}

/* Settles what dead processes left: every conversation with work under way
 * whose lease is free is taken, which recovers it, and let go. One a live
 * process holds is left alone. */
static int recover_abandoned(pic_store *s) {
    sqlite3_stmt *q = NULL;
    char (*ids)[64] = NULL;
    size_t n = 0;
    int rc = 0, step;
    if (sqlite3_prepare_v2(s->db,
                           "SELECT u.session_id FROM pic_effect f JOIN pic_entry e ON e.seq = f.entry_seq"
                           " JOIN pic_submission u ON u.id = e.submission_id WHERE f.state = 'started'"
                           " UNION SELECT u.session_id FROM pic_generation g JOIN pic_submission u ON u.id = g.submission_id"
                           " WHERE g.state = 'started'"
                           " UNION SELECT coalesce(session_id, '') FROM pic_hook_run WHERE state = 'started'"
                           " UNION SELECT session_id FROM pic_restore WHERE state = 'started'"
                           /* an inbox abort delivered, its cancel not journaled (loop.c) */
                           " UNION SELECT u.session_id FROM pic_submission u JOIN pic_inbox i ON i.target = u.id"
                           " AND i.state = 'delivered' WHERE u.status = 'admitted'",
                           -1, &q, NULL) != SQLITE_OK) {
        return st_fail(s, "sql: %s", sqlite3_errmsg(s->db));
    }
    while ((step = sqlite3_step(q)) == SQLITE_ROW) {
        const char *id = (const char *)sqlite3_column_text(q, 0);
        char (*grown)[64] = realloc(ids, (n + 1) * sizeof *ids);
        if (!grown || !id || strlen(id) >= 64) {
            free(grown ? grown : ids);
            sqlite3_finalize(q);
            return st_fail(s, grown ? "conversation id too long" : "out of memory");
        }
        ids = grown;
        (void)snprintf(ids[n++], 64, "%s", id);
    }
    if (step != SQLITE_DONE) { /* an error is never "nothing abandoned" */
        rc = st_fail(s, "sql: %s", sqlite3_errmsg(s->db));
    }
    sqlite3_finalize(q);
    for (size_t i = 0; i < n && rc == 0; i++) {
        int held = pic_leased(s, ids[i]);
        rc = pic_lease(s, ids[i], 0);
        if (rc == 0 && !held) {
            pic_unlease(s, ids[i]);
        }
        if (rc == 1) { /* a live owner */
            s->err[0] = '\0';
            rc = 0;
        }
    }
    free(ids);
    return rc;
}

/* 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 st_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 st_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'"); }

/* Version 9 kept no image sizes and could not prune: pic_image is rebuilt
 * with each image's header read again (one that no longer passes is
 * pruned) and its type the sniffed one. */
static int migrate_from_9(pic_store *s) {
    sqlite3_stmt *q = NULL, *put = NULL;
    int rc = 0;
    if (pic_exec(s, "CREATE TABLE pic_image_v10(hash TEXT PRIMARY KEY, mime TEXT NOT NULL, width INTEGER NOT NULL,"
                    " height INTEGER NOT NULL, sz INTEGER NOT NULL, data BLOB)") != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(s->db, "SELECT hash, mime, sz, data, sqlar_uncompress(data, sz) FROM pic_image", -1, &q, NULL) !=
            SQLITE_OK ||
        sqlite3_prepare_v2(s->db, "INSERT INTO pic_image_v10 VALUES(?1, ?2, ?3, ?4, ?5, ?6)", -1, &put, NULL) != SQLITE_OK) {
        sqlite3_finalize(q);
        return st_fail(s, "sql: %s", sqlite3_errmsg(s->db));
    }
    while (rc == 0 && sqlite3_step(q) == SQLITE_ROW) {
        pic_image img = {NULL, sqlite3_column_blob(q, 4), (size_t)sqlite3_column_bytes(q, 4), 0, 0};
        int ok = img.data && pic_image_inspect(&img, NULL, NULL, 0) == PIC_IMAGE_OK && pic_image_inline_mime(img.mime);
        sqlite3_bind_value(put, 1, sqlite3_column_value(q, 0));
        if (ok) {
            sqlite3_bind_text(put, 2, img.mime, -1, SQLITE_STATIC);
        } else {
            sqlite3_bind_value(put, 2, sqlite3_column_value(q, 1));
        }
        sqlite3_bind_int64(put, 3, ok ? img.width : 0);
        sqlite3_bind_int64(put, 4, ok ? img.height : 0);
        sqlite3_bind_value(put, 5, sqlite3_column_value(q, 2));
        if (ok) {
            sqlite3_bind_value(put, 6, sqlite3_column_value(q, 3));
        } else {
            sqlite3_bind_null(put, 6);
        }
        rc = sqlite3_step(put) == SQLITE_DONE ? 0 : st_fail(s, "migrating images: %s", sqlite3_errmsg(s->db));
        sqlite3_reset(put);
    }
    sqlite3_finalize(q);
    sqlite3_finalize(put);
    return rc != 0 ? -1
                   : pic_exec(s, "DROP TABLE pic_image; ALTER TABLE pic_image_v10 RENAME TO pic_image;"
                                 "UPDATE pic_meta SET value='10' WHERE key='schema_version'");
}

/* Version 10 had no hooks: pic_entry is rebuilt for the hook kind; the
 * schema above has just created pic_hook_run, empty. */
static int migrate_from_10(pic_store *s) {
    return pic_exec(
        s, "CREATE TABLE pic_entry_v11(seq INTEGER PRIMARY KEY, submission_id INTEGER NOT NULL,"
           " kind TEXT NOT NULL CHECK(kind IN ('user','assistant','tool_result','answer','instructions','compaction','hook')),"
           " 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_v11 SELECT seq, submission_id, kind, body, effect_id, native, provider, api, model,"
           " parent_seq, created_ms, first_kept_seq, tokens_before FROM pic_entry;"
           "DROP TABLE pic_entry;"
           "ALTER TABLE pic_entry_v11 RENAME TO pic_entry;"
           "UPDATE pic_meta SET value='11' WHERE key='schema_version'");
}

static int has_column(pic_store *s, const char *table, const char *column) {
    sqlite3_stmt *q = NULL;
    int has = 0;
    if (sqlite3_prepare_v2(s->db, "SELECT count(*) FROM pragma_table_info(?1) WHERE name = ?2", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, table, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, column, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            has = sqlite3_column_int(q, 0);
        }
    }
    sqlite3_finalize(q);
    return has;
}

/* Version 11 had no stopped requests, trial labels, request caps or
 * compaction reasons: pic_submission is rebuilt for the new status (a CHECK
 * constraint cannot be altered); the rest are new columns, NULL in old rows.
 * A table the schema above created has them already. */
static int migrate_from_11(pic_store *s) {
    if (!has_column(s, "pic_submission", "trial") &&
        pic_exec(s, "DROP TRIGGER IF EXISTS pic_entry_link;" /* it names pic_submission; open makes it again */
                    "CREATE TABLE pic_submission_v12(id INTEGER PRIMARY KEY, request_key TEXT NOT NULL UNIQUE,"
                    " content TEXT NOT NULL, status TEXT NOT NULL CHECK(status IN ('admitted','answered','failed','stopped')),"
                    " error TEXT, session_id TEXT, stop_reason TEXT, trial TEXT, max_requests INTEGER);"
                    "INSERT INTO pic_submission_v12(id, request_key, content, status, error, session_id)"
                    " SELECT id, request_key, content, status, error, session_id FROM pic_submission;"
                    "DROP TABLE pic_submission;"
                    "ALTER TABLE pic_submission_v12 RENAME TO pic_submission") != 0) {
        return -1;
    }
    if (!has_column(s, "pic_generation", "reason") &&
        pic_exec(s, "ALTER TABLE pic_generation ADD COLUMN reason TEXT;"
                    "ALTER TABLE pic_generation ADD COLUMN idle_seconds INTEGER;"
                    "ALTER TABLE pic_generation ADD COLUMN context_tokens INTEGER") != 0) {
        return -1;
    }
    return pic_exec(s, "UPDATE pic_meta SET value='12' WHERE key='schema_version'");
}

/* Version 12 had no branch summaries: pic_entry and pic_generation are
 * rebuilt for the new kind, column and purpose (a CHECK constraint cannot be
 * altered). The link trigger names pic_entry; open makes it again. */
static int migrate_from_12(pic_store *s) {
    return pic_exec(
        s, "DROP TRIGGER IF EXISTS pic_entry_link;"
           "CREATE TABLE pic_entry_v13(seq INTEGER PRIMARY KEY, submission_id INTEGER NOT NULL,"
           " kind TEXT NOT NULL CHECK(kind IN ('user','assistant','tool_result','answer','instructions','compaction','hook',"
           " 'branch_summary')),"
           " 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, from_seq INTEGER);"
           "INSERT INTO pic_entry_v13 SELECT seq, submission_id, kind, body, effect_id, native, provider, api, model,"
           " parent_seq, created_ms, first_kept_seq, tokens_before, NULL FROM pic_entry;"
           "DROP TABLE pic_entry;"
           "ALTER TABLE pic_entry_v13 RENAME TO pic_entry;"
           "CREATE TABLE pic_generation_v13(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','branch_summary')),"
           " reason TEXT, idle_seconds INTEGER, context_tokens INTEGER,"
           " UNIQUE(submission_id, purpose, turn, attempt));"
           "INSERT INTO pic_generation_v13 SELECT id, submission_id, turn, attempt, state, entry_seq, stop_reason, usage,"
           " request_id, error, purpose, reason, idle_seconds, context_tokens FROM pic_generation;"
           "DROP TABLE pic_generation;"
           "ALTER TABLE pic_generation_v13 RENAME TO pic_generation;"
           "UPDATE pic_meta SET value='13' WHERE key='schema_version'");
}

/* Version 13 had no index of result entries by effect (version 14 added it). */
static int migrate_from_13(pic_store *s) {
    return pic_exec(s, "CREATE INDEX IF NOT EXISTS pic_entry_effect ON pic_entry(effect_id);"
                       "UPDATE pic_meta SET value='14' WHERE key='schema_version'");
}

/* Version 14 did not keep the model a request was admitted with. Both of
 * 15's changes apply here, each only if missing, so a journal that reached
 * 14 either way (with or without the index) arrives the same. */
static int migrate_from_14(pic_store *s) {
    if (!has_column(s, "pic_submission", "model") &&
        pic_exec(s, "ALTER TABLE pic_submission ADD COLUMN model TEXT;"
                    "ALTER TABLE pic_submission ADD COLUMN thinking TEXT") != 0) {
        return -1;
    }
    return pic_exec(s, "CREATE INDEX IF NOT EXISTS pic_entry_effect ON pic_entry(effect_id);"
                       "UPDATE pic_meta SET value='15' WHERE key='schema_version'");
}

/* Version 15 kept no file history; the schema above has just created its
 * tables, empty, so a rewind reaches back only to changes made from now on. */
static int migrate_from_15(pic_store *s) { return pic_exec(s, "UPDATE pic_meta SET value='16' WHERE key='schema_version'"); }

/* Version 16 had no inbox; the schema above has just created it, empty. */
static int migrate_from_16(pic_store *s) { return pic_exec(s, "UPDATE pic_meta SET value='17' WHERE key='schema_version'"); }

/* Steps an older journal up to the current version, one version at a time. */
static int st_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 st_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 if (strcmp(version, "9") == 0) {
            rc = migrate_from_9(s);
        } else if (strcmp(version, "10") == 0) {
            rc = migrate_from_10(s);
        } else if (strcmp(version, "11") == 0) {
            rc = migrate_from_11(s);
        } else if (strcmp(version, "12") == 0) {
            rc = migrate_from_12(s);
        } else if (strcmp(version, "13") == 0) {
            rc = migrate_from_13(s);
        } else if (strcmp(version, "14") == 0) {
            rc = migrate_from_14(s);
        } else if (strcmp(version, "15") == 0) {
            rc = migrate_from_15(s);
        } else if (strcmp(version, "16") == 0) {
            rc = migrate_from_16(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 st_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 = st_fail(s, "unsupported schema version %s", v ? v : "(null)");
        }
    }
    sqlite3_finalize(q);
    return rc;
}

/* Whether the journal already has this build's schema: then opening it
 * changes nothing a running pic relies on. */
static int schema_current(pic_store *s) {
    sqlite3_stmt *q = NULL;
    int current = 0;
    /* Anything but a plain yes (no table yet, a journal being made right
     * now) is a no: the caller then waits its turn for the lock alone. */
    if (sqlite3_prepare_v2(s->db, "SELECT value = '" PIC_SCHEMA_VERSION "' FROM pic_meta WHERE key='schema_version'", -1,
                           &q, NULL) == SQLITE_OK &&
        sqlite3_step(q) == SQLITE_ROW) {
        current = sqlite3_column_int(q, 0);
    }
    sqlite3_finalize(q);
    return current;
}

int pic_open(pic_store *s, const char *db_path) {
    char *msg = NULL;
    int rc, alone = 0;
    memset(s, 0, sizeof *s);
    s->lock_fd = -1;
    if (lock_paths(s, db_path) != 0) {
        return -1;
    }
    if ((rc = journal_lock(s, 1, LOCK_WAIT_MS)) != 0) {
        return rc < 0 ? -1 : st_fail(s, "database is owned by another pic process");
    }
    if (sqlite3_open_v2(db_path, &s->db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, pic_platform_get()->vfs) !=
        SQLITE_OK) {
        return st_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) {
        rc = st_fail(s, "libfossil extension: %s", msg ? msg : "failed");
        sqlite3_free(msg);
        return rc;
    }
    if (pic_sqlar_register(s->db) != 0) {
        return st_fail(s, "cannot register sqlar functions: %s", sqlite3_errmsg(s->db));
    }
    if (sqlite3_create_function(s->db, "pic_sha3", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, sha3_fn, NULL, NULL) !=
            SQLITE_OK ||
        sqlite3_create_function(s->db, "pic_leased", 1, SQLITE_UTF8, s, leased_fn, NULL, NULL) != SQLITE_OK) {
        return st_fail(s, "cannot register pic_sha3: %s", sqlite3_errmsg(s->db));
    }
    if (pic_transform_register(s->db) != 0) {
        return st_fail(s, "cannot register pic_norm_id: %s", sqlite3_errmsg(s->db));
    }
    /* Other pic processes write this journal too: a write waits its turn. A
     * platform with its own VFS is the only process there is, and keeps the
     * journal to itself (no shared memory is asked of its VFS). */
#ifdef PIC_FAULTS
    (void)sqlite3_update_hook(s->db, on_row_written, s->db);
#endif
    if (pic_busy_wait(s->db, JOURNAL_BUSY_MS) != 0) {
        return st_fail(s, "cannot set the busy handler: %s", sqlite3_errmsg(s->db));
    }
    if ((pic_platform_get()->vfs && pic_exec(s, "PRAGMA locking_mode=EXCLUSIVE") != 0) ||
        pic_exec(s, "PRAGMA synchronous=FULL; PRAGMA fullfsync=ON; PRAGMA foreign_keys=OFF") != 0) {
        return -1;
    }
    /* A journal to create or migrate: with no other pic in it. Another pic
     * may be doing just that, and then have it open for as long as it runs:
     * so each try for the lock alone looks again, shared, at what is there. */
    for (int waited = 0; !alone && !schema_current(s); waited += 20) {
        journal_unlock(s);
        if ((rc = journal_lock(s, 0, 0)) < 0) {
            return -1;
        }
        if (rc == 0) {
            alone = 1;
            break;
        }
        if (waited >= 2 * LOCK_WAIT_MS) {
            return st_fail(s, "this journal needs migrating to schema " PIC_SCHEMA_VERSION
                           " and another pic process has it open; let it finish, then run pic again");
        }
        (void)usleep(20000);
        if ((rc = journal_lock(s, 1, LOCK_WAIT_MS)) != 0) {
            return rc < 0 ? -1 : st_fail(s, "database is owned by another pic process");
        }
    }
    /* A new journal becomes a WAL one here, alone: SQLite does not wait for
     * other connections when it changes the journal mode, it fails. One
     * with the schema is in WAL mode already (a mode kept in the file). */
    if (alone && pic_exec(s, "PRAGMA journal_mode=WAL") != 0) {
        return -1;
    }
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (pic_exec(s, schema_sql) != 0 || pic_exec(s, files_sql) != 0 || pic_exec(s, inbox_sql) != 0 || st_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 (alone) {
        journal_unlock(s);
        if ((rc = journal_lock(s, 1, 2 * LOCK_WAIT_MS)) != 0) {
            return rc < 0 ? -1 : st_fail(s, "database is owned by another pic process");
        }
    }
    if (recover_abandoned(s) != 0 || pic_check(s) != 0) {
        return -1;
    }
    /* Image retention, at most hourly, in its own transaction; a failure
     * here leaves the journal as it was and is not one of open's. */
    {
        sqlite3_stmt *q = NULL;
        long long last = 0, now = (long long)(pic_platform_get()->wall_ns() / 1000000), count, bytes;
        if (sqlite3_prepare_v2(s->db, "SELECT CAST(value AS INTEGER) FROM pic_meta WHERE key = 'last_prune_ms'", -1, &q, NULL) ==
                SQLITE_OK &&
            sqlite3_step(q) == SQLITE_ROW) {
            last = sqlite3_column_int64(q, 0);
        }
        sqlite3_finalize(q);
        if (now - last >= 3600000LL || now < last) {
            (void)pic_prune(s, 0, &count, &bytes);
            (void)pic_inbox_retain(s, now);
            s->err[0] = '\0';
        }
    }
    return 0;
}

void pic_close(pic_store *s) {
    while (s->nleases) {
        pic_unlease(s, s->leases[0].session);
    }
    free(s->leases);
    s->leases = NULL;
    if (s->db) {
        sqlite3_close(s->db);
        s->db = NULL;
    }
    journal_unlock(s);
    free(s->lock_path);
    free(s->lease_dir);
    s->lock_path = s->lease_dir = NULL;
}

/* The narrow open (docs/design/grapevine.md): for a process that is not
 * the journal's worker (a sender, an observer). The journal lock shared, so
 * no migration runs under it; never created, migrated or recovered; refused
 * unless it has this build's schema and belongs to this user. */
int pic_open_narrow(pic_store *s, const char *db_path) {
    struct stat st;
    int rc;
    memset(s, 0, sizeof *s);
    s->lock_fd = -1;
    if (host() && stat(db_path, &st) != 0) {
        return st_fail(s, "no journal at %s", db_path);
    }
    if (host() && st.st_uid != getuid()) {
        return st_fail(s, "%s belongs to another user", db_path);
    }
    if (lock_paths(s, db_path) != 0) {
        return -1;
    }
    if ((rc = journal_lock(s, 1, LOCK_WAIT_MS)) != 0) {
        return rc < 0 ? -1 : st_fail(s, "the journal is being migrated by another pic process; try again");
    }
    if (sqlite3_open_v2(db_path, &s->db, SQLITE_OPEN_READWRITE, pic_platform_get()->vfs) != SQLITE_OK) {
        return st_fail(s, "cannot open %s: %s", db_path, s->db ? sqlite3_errmsg(s->db) : "no memory");
    }
    if (pic_busy_wait(s->db, JOURNAL_BUSY_MS) != 0 ||
        pic_exec(s, "PRAGMA synchronous=FULL; PRAGMA fullfsync=ON; PRAGMA foreign_keys=OFF") != 0) {
        return -1;
    }
    if (!schema_current(s)) {
        return st_fail(s, "the journal is not at schema " PIC_SCHEMA_VERSION "; run pic in it once to bring it up to date");
    }
    return 0;
}

int pic_bell_path(pic_store *s, const char *session, char *out, size_t cap) {
    size_t n;
    if (lease_path(s, session, out, cap) != 0) {
        return -1;
    }
    n = strlen(out);
    return n + sizeof ".bell" <= cap ? (memcpy(out + n, ".bell", sizeof ".bell"), 0) : st_fail(s, "database path too long");
}

#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"},
    /* CROSS JOIN keeps the few delivered messages outermost: from the tool
     * results, the check is quadratic in a long conversation. */
    {"delivered message before a tool result of its turn",
     "SELECT count(*) FROM pic_queued q CROSS 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)"},
    /* Under an unfinished request a started call, reply or hook run is one a
     * live process is at, or one its conversation's next owner will settle. */
    {"effect left started in a finished request",
     "SELECT count(*) FROM pic_effect f JOIN pic_entry e ON e.seq=f.entry_seq JOIN pic_submission u ON u.id=e.submission_id"
     " WHERE f.state='started' AND u.status != 'admitted'"},
    {"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.from_seq IS NULL AND 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 AND p.from_seq IS NULL)"},
    /* Made outside a turn (Pi's compact command): a compaction, and the
     * instructions it carries over, after the head they name. */
    {"entry made outside a turn that is not a compaction or its instructions, or not after the head it names",
     "SELECT count(*) FROM pic_entry e WHERE e.from_seq IS NOT NULL AND e.kind != 'branch_summary' AND (e.kind NOT IN"
     " ('compaction','instructions') OR e.parent_seq IS NULL OR e.parent_seq < e.from_seq)"},
    {"branch summary not after an entry of its request, or without where it came from",
     "SELECT count(*) FROM pic_entry e WHERE e.kind = 'branch_summary' AND (e.from_seq IS NULL OR NOT EXISTS"
     " (SELECT 1 FROM pic_entry p WHERE p.seq = e.parent_seq AND p.submission_id = e.submission_id AND p.kind != 'branch_summary'))"},
    {"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')"},
    {"reply left started in a finished request",
     "SELECT count(*) FROM pic_generation g JOIN pic_submission u ON u.id=g.submission_id"
     " WHERE g.state='started' AND g.purpose='reply' AND u.status != 'admitted'"},
    /* A branch summary with nothing that fit its budget made no request. */
    {"reply or compaction entry without exactly one done generation, or branch summary with more",
     "SELECT count(*) FROM pic_entry e WHERE e.kind IN ('assistant','answer','compaction','branch_summary') AND"
     " (SELECT count(*) FROM pic_generation g WHERE g.entry_seq=e.seq AND g.state='done' AND g.submission_id=e.submission_id)"
     " NOT IN (1, iif(e.kind = 'branch_summary', 0, 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','branch_summary'))"},
    {"too many attempts for a turn",
     "SELECT count(*) FROM pic_generation WHERE attempt < 1 OR attempt > " STR(PIC_GENERATION_ATTEMPTS)},
    {"stopped submission without its reason, or another with one, or with unfinished effects",
     "SELECT count(*) FROM pic_submission s WHERE (s.status='stopped') != (s.stop_reason IS NOT NULL) OR (s.status='stopped' AND 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'))"},
    {"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'))"},
    /* Calls of one turn may finish in any order; their results follow in call
     * order, so a settled call waits for its entry while an earlier one runs. */
    {"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) NOT IN (1, iif(EXISTS (SELECT 1 FROM pic_effect g WHERE"
     " g.entry_seq=f.entry_seq AND g.ordinal<f.ordinal AND g.state IN ('intent','started')), 0, 1))"},
    {"tool result while an earlier call of its turn has none",
     "SELECT count(*) FROM pic_entry r JOIN pic_effect f ON f.id=r.effect_id JOIN pic_effect g ON g.entry_seq=f.entry_seq"
     " AND g.ordinal<f.ordinal WHERE r.kind='tool_result' AND NOT EXISTS (SELECT 1 FROM pic_entry x WHERE"
     " x.kind='tool_result' AND x.effect_id=g.id)"},
    {"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')"
     " AND NOT EXISTS (SELECT 1 FROM pic_bash b JOIN pic_entry x ON x.seq=b.entry_seq WHERE x.submission_id=s.id)"},
    {"bash message that is not the only user entry of an answered request",
     "SELECT count(*) FROM pic_bash b WHERE NOT EXISTS (SELECT 1 FROM pic_entry e JOIN pic_submission u ON u.id=e.submission_id"
     " WHERE e.seq=b.entry_seq AND e.kind='user' AND u.status='answered'"
     " AND (SELECT count(*) FROM pic_entry x WHERE x.submission_id=u.id AND x.from_seq IS NULL)=1)"},
    {"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 (data IS NOT NULL AND (length(data) > sz OR typeof(data) != 'blob'))"},
    {"image not of an inline type, or without its size",
     "SELECT count(*) FROM pic_image WHERE mime NOT IN ('image/png','image/jpeg','image/gif','image/webp')"
     " OR NOT ((width > 0 AND height > 0) OR (data IS NULL AND width = 0 AND height = 0))"},
    {"hook entry without the hook run it came from",
     "SELECT count(*) FROM pic_entry e WHERE e.kind='hook' AND NOT EXISTS (SELECT 1 FROM pic_hook_run r WHERE r.entry_seq=e.seq)"},
    {"hook run naming a missing hook entry",
     "SELECT count(*) FROM pic_hook_run r WHERE r.entry_seq IS NOT NULL AND NOT EXISTS"
     " (SELECT 1 FROM pic_entry e WHERE e.seq=r.entry_seq AND e.kind='hook')"},
    {"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"
     " AND b.from_seq IS NULL"},
    {"file change of no write, edit or restore",
     "SELECT count(*) FROM pic_file_change c WHERE (c.effect_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM pic_effect f"
     " WHERE f.id=c.effect_id AND f.tool IN ('write','edit'))) OR (c.restore_id IS NOT NULL AND NOT EXISTS"
     " (SELECT 1 FROM pic_restore r WHERE r.id=c.restore_id))"},
    {"kept pre-image without its bytes",
     "SELECT count(*) FROM pic_file_change c WHERE c.pre_kept=1 AND c.pre_exists=1 AND c.pre_hash IS NOT NULL"
     " AND NOT EXISTS (SELECT 1 FROM pic_blob b WHERE b.hash=c.pre_hash)"},
    /* The inbox (inbox.c). A pruned row keeps its key and state only. */
    {"inbox message without its expiry", "SELECT count(*) FROM pic_inbox WHERE expires_ms IS NULL"},
    {"settled inbox message without its response, or with more than one thing it made, or an abort that made one",
     "SELECT count(*) FROM pic_inbox WHERE state != 'pending' AND command IS NOT NULL AND (response IS NULL"
     " OR (submission_id IS NOT NULL AND queued_id IS NOT NULL) OR (json_extract(command, '$.type') = 'abort'"
     " AND coalesce(submission_id, queued_id) IS NOT NULL))"},
    {"pending inbox message with a response or something it made",
     "SELECT count(*) FROM pic_inbox WHERE state = 'pending' AND (command IS NULL OR response IS NOT NULL"
     " OR submission_id IS NOT NULL OR queued_id IS NOT NULL)"},
    {"inbox message's queued message missing or in another conversation",
     "SELECT count(*) FROM pic_inbox i WHERE i.queued_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM pic_queued q"
     " WHERE q.id = i.queued_id AND q.session_id = i.session_id)"},
    {"unfinished write or edit with an after-image, or finished restore without its outcomes",
     "SELECT (SELECT count(*) FROM pic_file_change c JOIN pic_effect f ON f.id=c.effect_id"
     " WHERE f.state IN ('intent','started') AND c.post_exists IS NOT NULL)"
     " + (SELECT count(*) FROM pic_file_change c JOIN pic_restore r ON r.id=c.restore_id WHERE r.state='done' AND c.outcome IS NULL)"},
};

/* One read transaction, so every invariant is checked against one state of
 * a journal other processes are writing. */
int pic_check(pic_store *s) {
    int own = sqlite3_get_autocommit(s->db), rc = 0;
    if (own && pic_exec(s, "BEGIN") != 0) {
        return -1;
    }
    for (size_t i = 0; i < sizeof invariants / sizeof invariants[0] && rc == 0; i++) {
        sqlite3_stmt *q = NULL;
        sqlite3_int64 bad = 0;
        if (sqlite3_prepare_v2(s->db, invariants[i].sql, -1, &q, NULL) != SQLITE_OK) {
            rc = st_fail(s, "check %s: %s", invariants[i].name, sqlite3_errmsg(s->db));
            break;
        }
        if (sqlite3_step(q) == SQLITE_ROW) {
            bad = sqlite3_column_int64(q, 0);
        }
        sqlite3_finalize(q);
        if (bad != 0) {
            rc = st_fail(s, "integrity violation: %s", invariants[i].name);
        }
    }
    if (own) {
        (void)sqlite3_exec(s->db, "ROLLBACK", NULL, NULL, NULL);
    }
    return rc;
}

int pic_check_deep(pic_store *s) {
    sqlite3_stmt *q = NULL;
    sqlite3_int64 bad = 0;
    if (pic_check(s) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(s->db,
                           "SELECT count(*) FROM pic_image WHERE data IS NOT NULL AND hash IS NOT pic_sha3(sqlar_uncompress(data, sz))",
                           -1, &q, NULL) != SQLITE_OK) {
        return st_fail(s, "check images: %s", sqlite3_errmsg(s->db));
    }
    if (sqlite3_step(q) == SQLITE_ROW) {
        bad = sqlite3_column_int64(q, 0);
    } else {
        bad = -1;
    }
    sqlite3_finalize(q);
    return bad == 0 ? 0 : bad < 0 ? st_fail(s, "check images: %s", sqlite3_errmsg(s->db))
                                  : st_fail(s, "integrity violation: image content does not match its hash");
}

/* pic_sha3(blob): its SHA3-256, hex, as images are named. */
static void sha3_fn(sqlite3_context *ctx, int argc, sqlite3_value **argv) {
    const unsigned char *in = sqlite3_value_blob(argv[0]);
    size_t n = (size_t)sqlite3_value_bytes(argv[0]);
    fsl_sha3_cx cx;
    (void)argc;
    if (sqlite3_value_type(argv[0]) == SQLITE_NULL) {
        sqlite3_result_null(ctx);
        return;
    }
    fsl_sha3_init2(&cx, FSL_SHA3_256);
    for (size_t at = 0; at < n; at += 1u << 30) {
        fsl_sha3_update(&cx, in + at, (unsigned)(n - at < (1u << 30) ? n - at : 1u << 30));
    }
    fsl_sha3_end(&cx);
    sqlite3_result_text(ctx, (const char *)cx.hex, -1, SQLITE_TRANSIENT);
}

#ifdef PIC_FAULTS
/* PIC_CRASH_AT=point:n exits abruptly on the nth arrival at point;
 * PIC_RUN_AT=point:COMMAND runs COMMAND with the shell at each arrival (a
 * test's change made at an exact moment). */
void pic_fault(const char *point) {
    static int arrivals;
    const char *spec = getenv("PIC_CRASH_AT"), *run = getenv("PIC_RUN_AT");
    const char *colon;
    size_t len;
    if (run && (colon = strchr(run, ':')) && strlen(point) == (size_t)(colon - run) &&
        strncmp(run, point, (size_t)(colon - run)) == 0 && system(colon + 1) != 0) {
        fprintf(stderr, "pic: PIC_RUN_AT command failed at %s\n", point);
    }
    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