/* 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 <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.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) */
/* What started a conversation (pic_store_origin), and an agent's parent, JOURNAL/ID: a table
* of its own, so no schema version (docs/dev/durability.md); no row reads as a person's. */
"CREATE TABLE IF NOT EXISTS pic_session_origin("
" session_id TEXT PRIMARY KEY,"
" origin TEXT NOT NULL,"
" parent TEXT);"
/* user: the text; tool_result: the tool's output; assistant and answer:
* Pi's neutral content array in body, the provider's content verbatim in
* native, and the reply's origin (provider, api, model). */
"CREATE TABLE IF NOT EXISTS pic_entry("
" seq INTEGER PRIMARY KEY,"
" submission_id INTEGER NOT NULL,"
" kind TEXT NOT NULL CHECK(kind IN ('user','assistant','tool_result','answer','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,"
/* The credential the request went with (cred.h's name: a stored key's
* row, or env:VAR:HASH; never key text); NULL when none was sent. */
" credential TEXT,"
" 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')));";
/* Verdicts (loop.c). */
static const char verdict_sql[] =
/* A request's verdict (docs/design/verdict.md): the workspace's verify
* command, run once as the request is about to end answered, after its
* Stop hooks let the reply stand (entry_seq). Journaled as started
* before the command runs and done with its outcome, pass by exit 0 and
* fail otherwise; a crash between the two leaves it unknown, and it is
* never run again. output: the first bytes of its stdout, then stderr. */
"CREATE TABLE IF NOT EXISTS pic_verdict("
" submission_id INTEGER PRIMARY KEY,"
" entry_seq INTEGER NOT NULL,"
" command TEXT NOT NULL,"
" state TEXT NOT NULL CHECK(state IN ('started','done','unknown')),"
" outcome TEXT CHECK(outcome IN ('pass','fail')),"
" exit_code INTEGER,"
" duration_ms INTEGER,"
" error TEXT,"
" output TEXT,"
" created_ms INTEGER NOT NULL);";
/* The deferred tools a tool_search result declared (toolsearch.c), in the result's transaction: a
* request declares the session's frozen tools and these, for the effects on its branch. Additive:
* an older pic reads none and declares only the frozen tools. */
static const char reveal_sql[] =
"CREATE TABLE IF NOT EXISTS pic_tool_reveal(effect_id INTEGER NOT NULL, ordinal INTEGER NOT NULL, name TEXT NOT NULL,"
" PRIMARY KEY(effect_id, ordinal)) WITHOUT ROWID;";
/* Deleted conversations (trash.c). */
static const char trash_sql[] =
/* A conversation deleted at deleted_ms: listed nowhere until its row is removed (restored).
* purged_ms: when its text was emptied for good (pic_trash_purge); the row stays, so it
* resolves no more. */
"CREATE TABLE IF NOT EXISTS pic_trash("
" session_id TEXT PRIMARY KEY,"
" deleted_ms INTEGER NOT NULL,"
" purged_ms INTEGER);";
/* Loops, monitors and goals (wake.c, docs/design/wakes.md). */
static const char wake_sql[] =
/* A wake: "send conversation session_id this prompt when that happens". kind: a loop fires
* every every_ms, from due_ms; a monitor on new lines of its command's spool past
* read_offset; a goal when a request ends with it unmet, checked by command when there is one.
* Each fire raises fires and inserts the inbox row wake:ID:N (sender wake:ID) in the same
* transaction. state: active fires; paused and needs (a person has to look) do not; ended is
* for good. why: the words for any state but active. creator: user, cli, remote:DEVICE or
* model. expires_ms: it ends then, 7 days after it was made. options: a JSON object of flags. */
"CREATE TABLE IF NOT EXISTS pic_wake("
" id INTEGER PRIMARY KEY,"
" session_id TEXT NOT NULL,"
" kind TEXT NOT NULL CHECK(kind IN ('loop','monitor','goal')),"
" prompt TEXT NOT NULL,"
" every_ms INTEGER,"
" command TEXT,"
" options TEXT,"
" state TEXT NOT NULL CHECK(state IN ('active','paused','needs','ended')),"
" why TEXT,"
" creator TEXT NOT NULL,"
" fires INTEGER NOT NULL DEFAULT 0,"
" due_ms INTEGER,"
" fired_ms INTEGER,"
" created_ms INTEGER NOT NULL,"
" expires_ms INTEGER NOT NULL,"
" updated_ms INTEGER NOT NULL,"
" spool TEXT,"
" read_offset INTEGER NOT NULL DEFAULT 0,"
" pid INTEGER,"
" pid_started_ms INTEGER,"
" exit_code INTEGER,"
" rounds INTEGER NOT NULL DEFAULT 0,"
" max_rounds INTEGER,"
" stalls INTEGER NOT NULL DEFAULT 0,"
" max_stalls INTEGER);"
"CREATE INDEX IF NOT EXISTS pic_wake_live ON pic_wake(state, due_ms);"
"CREATE INDEX IF NOT EXISTS pic_inbox_sender ON pic_inbox(sender, state);";
/* 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);"
/* pic prune asks which bytes a change or restore names. */
"CREATE INDEX IF NOT EXISTS pic_file_change_pre ON pic_file_change(pre_hash);"
"CREATE INDEX IF NOT EXISTS pic_file_change_post ON pic_file_change(post_hash);"
/* Folders tied to a change: those a write created (they were missing when
* its call started), and, on a restore's file, those to remove with it. */
"CREATE TABLE IF NOT EXISTS pic_file_dir(change_id INTEGER NOT NULL, path TEXT NOT NULL, PRIMARY KEY(change_id, path));"
/* 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;";
/* What the readers of a conversation look up by (pic remote's list, its notifications, a follow):
* a request's entries, a conversation's requests. Additive, so no schema version
* (docs/dev/durability.md); made after the migrations, which add the columns they name. */
static const char index_sql[] =
"CREATE INDEX IF NOT EXISTS pic_entry_submission ON pic_entry(submission_id, seq);"
"CREATE INDEX IF NOT EXISTS pic_submission_session ON pic_submission(session_id, id);"
/* a reply's generation, by its entry: without it a join to it copies the whole table */
"CREATE INDEX IF NOT EXISTS pic_generation_entry ON pic_generation(entry_seq);";
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
/* How long a migration waits for the holders that let go when asked: pic
* remote looks each second, and lets go once nothing it does is under way. */
#define MIGRATE_YIELD_MS 15000
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;
}
/* ---- who has the journal open ------------------------------------------ */
/* <journal>SUFFIX, beside the journal lock. */
static int side_path(pic_store *s, const char *suffix, char *out, size_t cap) {
size_t n = strlen(s->lock_path) - (sizeof ".pic-lock" - 1);
return snprintf(out, cap, "%.*s%s", (int)n, s->lock_path, suffix) < (int)cap ? 0 : -1;
}
static char store_role[48] = "pic";
static int store_yields;
static char store_origin[16] = "headless", store_parent[4200];
void pic_store_origin(const char *origin, const char *parent) {
(void)snprintf(store_origin, sizeof store_origin, "%s", origin && *origin ? origin : "headless");
(void)snprintf(store_parent, sizeof store_parent, "%s", parent ? parent : "");
}
const char *pic_store_origin_get(void) { return store_origin; }
const char *pic_store_parent_get(void) { return store_parent; }
int pic_session_stamp(pic_store *s, const char *id, const char *origin) {
sqlite3_stmt *q = NULL;
int rc;
if (sqlite3_prepare_v2(s->db, "INSERT OR IGNORE INTO pic_session_origin(session_id, origin, parent) VALUES(?1, ?2, nullif(?3, ''))",
-1, &q, NULL) != SQLITE_OK) {
return st_fail(s, "sql: %s", sqlite3_errmsg(s->db));
}
sqlite3_bind_text(q, 1, id, -1, SQLITE_STATIC);
sqlite3_bind_text(q, 2, origin ? origin : store_origin, -1, SQLITE_STATIC);
sqlite3_bind_text(q, 3, origin ? "" : store_parent, -1, SQLITE_STATIC);
rc = sqlite3_step(q) == SQLITE_DONE ? 0 : st_fail(s, "sql: %s", sqlite3_errmsg(s->db));
sqlite3_finalize(q);
return rc;
}
void pic_session_env(pic_store *s, const char *id) {
char db[4096], real[PATH_MAX], parent[PATH_MAX + 80];
size_t n;
if (!s->lock_path || !id || (n = strlen(s->lock_path) - (sizeof ".pic-lock" - 1)) >= sizeof db) {
return;
}
memcpy(db, s->lock_path, n);
db[n] = '\0';
(void)snprintf(parent, sizeof parent, "%s/%s", realpath(db, real) ? real : db, id);
(void)setenv("PIC_ORIGIN", "agent", 1);
(void)setenv("PIC_PARENT", parent, 1);
}
void pic_store_role(const char *role, int yields) {
(void)snprintf(store_role, sizeof store_role, "%s", role && *role ? role : "pic");
store_yields = yields != 0;
}
/* <journal>.pic-holders/PID.N, held locked while the store is open, says what this process is,
* for the message a pic that cannot migrate the journal gives. The lock is the truth: a file
* nobody holds is a dead process's. Best effort: a store opens without it. */
static int holders_scan(pic_store *s, pic_holder *out, int cap);
static void holder_register(pic_store *s) {
static unsigned seq;
char dir[4096], path[4200], line[160];
int h, fd, n;
if (!host() || s->holder_path || side_path(s, ".pic-holders", dir, sizeof dir) != 0 ||
(mkdir(dir, 0700) != 0 && errno != EEXIST) ||
snprintf(path, sizeof path, "%s/%ld.%u", dir, (long)getpid(), ++seq) >= (int)sizeof path ||
(h = pic_platform_get()->lock(path, 0)) < 0) {
return;
}
(void)holders_scan(s, NULL, 0); /* the files killed processes left */
n = snprintf(line, sizeof line, "%ld %ld %lld %d %s %s\n", (long)getpid(), (long)getppid(),
(long long)(pic_platform_get()->wall_ns() / 1000000), store_yields, PIC_SCHEMA_VERSION, store_role);
if ((fd = open(path, O_WRONLY | O_TRUNC | O_CLOEXEC)) >= 0) {
if (write(fd, line, (size_t)n) != n) {
/* a file that says nothing still counts: the lock does */
}
close(fd);
}
if (!(s->holder_path = strdup(path))) {
(void)unlink(path);
pic_platform_get()->unlock(h);
return;
}
s->holder_h = h;
}
static void holder_unregister(pic_store *s) {
if (s->holder_path) {
(void)unlink(s->holder_path);
pic_platform_get()->unlock(s->holder_h);
free(s->holder_path);
s->holder_path = NULL;
}
}
/* The live holders of S's journal but this process's, up to CAP in OUT; how many. A file nobody
* holds that is older than a moment (a crashed process's) is removed. */
static int holders_scan(pic_store *s, pic_holder *out, int cap) {
char dir[4096], path[4400], buf[160];
struct dirent *e;
struct stat sb;
DIR *d;
int n = 0;
if (!host() || side_path(s, ".pic-holders", dir, sizeof dir) != 0 || !(d = opendir(dir))) {
return 0;
}
while ((e = readdir(d))) {
pic_holder h;
int lk, fd;
ssize_t got = 0;
if (e->d_name[0] == '.' || snprintf(path, sizeof path, "%s/%s", dir, e->d_name) >= (int)sizeof path ||
strtol(e->d_name, NULL, 10) == (long)getpid()) {
continue;
}
if ((lk = pic_platform_get()->lock(path, 1)) >= 0) {
pic_platform_get()->unlock(lk);
if (stat(path, &sb) == 0 && sb.st_mtime + 2 < time(NULL)) {
(void)unlink(path);
}
continue;
}
if (lk == -1 || errno != EWOULDBLOCK) {
continue;
}
memset(&h, 0, sizeof h);
h.pid = strtol(e->d_name, NULL, 10);
if ((fd = open(path, O_RDONLY | O_CLOEXEC)) >= 0) {
got = read(fd, buf, sizeof buf - 1);
close(fd);
}
buf[got > 0 ? got : 0] = '\0';
if (sscanf(buf, "%ld %ld %lld %d %ld %47[^\n]", &h.pid, &h.ppid, &h.since_ms, &h.yields, &h.schema, h.role) != 6) {
(void)snprintf(h.role, sizeof h.role, "pic");
}
if (n < cap) {
out[n] = h;
}
n++;
}
closedir(d);
return n;
}
int pic_holders(const char *db_path, pic_holder *out, int cap) {
pic_store t;
int n = 0;
memset(&t, 0, sizeof t);
if (lock_paths(&t, db_path) == 0) {
n = holders_scan(&t, out, cap);
}
free(t.lock_path);
free(t.lease_dir);
return n;
}
int pic_journal_unheld(const char *db_path) {
pic_store t;
int free_now = 0;
memset(&t, 0, sizeof t);
t.lock_fd = -1;
if (lock_paths(&t, db_path) == 0 && journal_lock(&t, 0, 0) == 0) {
free_now = 1;
journal_unlock(&t);
}
free(t.lock_path);
free(t.lease_dir);
return free_now;
}
int pic_journal_users(const char *db_path, long *pids, char (*names)[32], int cap) {
pic_store t;
int n = -1;
memset(&t, 0, sizeof t);
if (pic_platform_get()->file_users && lock_paths(&t, db_path) == 0) {
n = pic_platform_get()->file_users(t.lock_path, pids, names, cap);
}
free(t.lock_path);
free(t.lease_dir);
return n;
}
/* <journal>.pic-migrate, held locked by a pic waiting to migrate the journal, names the schema it
* would migrate to: the holders that yield see it (pic_migration_wanted) and close the journal. A
* handle, or -1 when another pic is asking already. */
static int migrate_ask(pic_store *s) {
char path[4200], line[64];
int h, fd, n;
if (!host() || side_path(s, ".pic-migrate", path, sizeof path) != 0 || (h = pic_platform_get()->lock(path, 0)) < 0) {
return -1;
}
n = snprintf(line, sizeof line, "%s %ld\n", PIC_SCHEMA_VERSION, (long)getpid());
if ((fd = open(path, O_WRONLY | O_TRUNC | O_CLOEXEC)) >= 0) {
if (write(fd, line, (size_t)n) != n) {
/* an empty one asks nothing; the wait then ends as it would have */
}
close(fd);
}
return h;
}
static void migrate_unask(pic_store *s, int *h) {
char path[4200];
if (*h >= 0) {
if (side_path(s, ".pic-migrate", path, sizeof path) == 0) {
(void)unlink(path);
}
pic_platform_get()->unlock(*h);
*h = -1;
}
}
int pic_migration_wanted(pic_store *s) {
char path[4200], buf[64];
struct stat sb;
ssize_t got = 0;
int h, fd;
if (!host() || !s->lock_path || side_path(s, ".pic-migrate", path, sizeof path) != 0 || stat(path, &sb) != 0) {
return 0;
}
if ((h = pic_platform_get()->lock(path, 1)) >= 0) { /* nobody is waiting: left by a crash */
pic_platform_get()->unlock(h);
return 0;
}
if (h == -1 || errno != EWOULDBLOCK || (fd = open(path, O_RDONLY | O_CLOEXEC)) < 0) {
return 0;
}
got = read(fd, buf, sizeof buf - 1);
close(fd);
buf[got > 0 ? got : 0] = '\0';
{
long own = atol(PIC_SCHEMA_VERSION);
#ifdef PIC_FAULTS
if (getenv("PIC_TEST_HOLDER_SCHEMA")) { /* the tests' seam: this holder stands in for an older pic */
own = atol(getenv("PIC_TEST_HOLDER_SCHEMA"));
}
#endif
return strtol(buf, NULL, 10) > own;
}
}
/* When a holder opened the journal, as a person reads it: today's by the time alone. */
static void since_text(long long ms, char *out, size_t cap) {
time_t t = (time_t)(ms / 1000), now = time(NULL);
struct tm tm, today;
if (ms <= 0 || !localtime_r(&t, &tm) || !localtime_r(&now, &today)) {
(void)snprintf(out, cap, "an unknown time");
return;
}
(void)strftime(out, cap, tm.tm_year == today.tm_year && tm.tm_yday == today.tm_yday ? "%H:%M" : "%b %d %H:%M", &tm);
}
/* s->err when the journal needs migrating and other processes keep it: each one named, with the
* command that ends it. -1. */
static int migrate_blocked(pic_store *s) {
pic_holder h[4];
int n = holders_scan(s, h, 4);
size_t at;
at = (size_t)snprintf(s->err, sizeof s->err, "this journal needs updating for this pic and %s it open; pic doctor %s and updates it",
n > 1 ? "other pic processes have" : "another pic process has", n > 1 ? "stops them" : "stops it");
if (n == 0) {
(void)snprintf(s->err + at, sizeof s->err - at,
". It is a pic from before this one that does not say which: if pic remote runs, pic remote restart"
" restarts it (lsof %s lists them all)",
s->lock_path);
return -1;
}
for (int i = 0; i < n && i < 4 && at < sizeof s->err; i++) {
char since[32], by[40] = "", fix[48];
since_text(h[i].since_ms, since, sizeof since);
if (h[i].ppid > 1) {
(void)snprintf(by, sizeof by, " (started by pid %ld)", h[i].ppid);
}
if (strcmp(h[i].role, "pic remote") == 0) {
(void)snprintf(fix, sizeof fix, "pic remote restart");
} else {
(void)snprintf(fix, sizeof fix, "kill %ld", h[i].pid);
}
at += (size_t)snprintf(s->err + at, sizeof s->err - at, "\n pid %ld, %s%s, open since %s: %s", h[i].pid, h[i].role,
strcmp(h[i].role, "pic remote") == 0 ? "" : by, since, fix);
}
if (n > 4 && at < sizeof s->err) {
(void)snprintf(s->err + at, sizeof s->err - at, "\n and %d more", n - 4);
}
return -1;
}
/* ---- 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) {
if (ftruncate(fd, 0) != 0) {
/* a lease file that cannot be emptied names no live pid: the lock decides */
}
}
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);
char sid[64];
if (!l) {
return;
}
(void)snprintf(sid, sizeof sid, "%s", session); /* SESSION may be the entry let go below */
pic_platform_get()->unlock(l->handle);
*l = s->leases[--s->nleases];
pic_inbox_released(s, sid);
}
/* The first line of TEXT that is not blank, its runs of white space made one space and its control
* characters removed, cut to MAX characters with an ellipsis; malloc'd ("" when none). */
char *pic_one_line(const char *text, size_t max) {
size_t n = text ? strlen(text) : 0;
char *out = malloc(n + 4);
if (!out) {
return NULL;
}
for (size_t at = 0; at <= n;) {
size_t end = at, len = 0, chars = 0;
int space = 0, cut = 0;
while (end < n && text[end] != '\n') {
end++;
}
for (size_t i = at; i < end;) {
unsigned char c = (unsigned char)text[i];
size_t w = c < 0x80 ? 1 : c >= 0xF0 ? 4 : c >= 0xE0 ? 3 : c >= 0xC0 ? 2 : 1;
if (i + w > end) {
w = end - i;
}
if (c == ' ' || c == '\t' || c == '\r' || c == '\v' || c == '\f') {
space = len > 0;
i++;
continue;
}
if (c < 0x20 || c == 0x7f || (c == 0xC2 && w == 2 && (unsigned char)text[i + 1] < 0xA0) ||
(c & 0xC0) == 0x80) { /* C0, DEL, C1, a stray byte */
i += w;
continue;
}
if (chars + (size_t)space + 1 > max) {
cut = 1;
break;
}
if (space) {
out[len++] = ' ';
chars++;
space = 0;
}
memcpy(out + len, text + i, w);
len += w;
chars++;
i += w;
}
if (len) {
if (cut) {
memcpy(out + len, "\xe2\x80\xa6", 3);
len += 3;
}
out[len] = '\0';
return out;
}
at = end + 1;
}
out[0] = '\0';
return out;
}
/* pic_line(TEXT, MAX): pic_one_line in SQL; NULL for NULL. */
static void line_fn(sqlite3_context *ctx, int argc, sqlite3_value **argv) {
const char *text = (const char *)sqlite3_value_text(argv[0]);
sqlite3_int64 max = sqlite3_value_int64(argv[1]);
char *line;
(void)argc;
if (!text) {
sqlite3_result_null(ctx);
return;
}
if (!(line = pic_one_line(text, max > 0 ? (size_t)max : 1))) {
sqlite3_result_error_nomem(ctx);
return;
}
sqlite3_result_text(ctx, line, -1, free);
}
/* 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'"
" UNION SELECT u.session_id FROM pic_verdict v JOIN pic_submission u ON u.id = v.submission_id"
" WHERE v.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;
}
/* Version 3's reply content in the neutral form, as the Messages API adapter
* derived it when version 4 was cut. A frozen copy: the migration must read
* old journals the same way whatever the adapter does later. */
static char *v3_neutral(sqlite3 *db, const char *native) {
sqlite3_stmt *q = NULL;
char *out = NULL;
if (sqlite3_prepare_v2(
db,
"SELECT coalesce(json_group_array(json(x)), '[]') FROM (SELECT CASE json_extract(value,'$.type')"
" WHEN 'text' THEN json_object('type','text','text',json_extract(value,'$.text'))"
" WHEN 'thinking' THEN json_object('type','thinking','thinking',coalesce(json_extract(value,'$.thinking'),''),"
" 'signature',json_extract(value,'$.signature'))"
" WHEN 'redacted_thinking' THEN json_object('type','thinking','thinking','','signature',"
" json_extract(value,'$.data'),'redacted',json('true'))"
" WHEN 'tool_use' THEN json_object('type','toolCall','id',coalesce(json_extract(value,'$.id'),''),"
" 'name',coalesce(json_extract(value,'$.name'),''),'arguments',"
" CASE json_type(value,'$.input') WHEN 'object' THEN json(json_extract(value,'$.input'))"
" ELSE json_object('pic_invalid_input', json_extract(value,'$.input')) END)"
" END AS x FROM json_each(?1) ORDER BY key) WHERE x IS NOT NULL",
-1, &q, NULL) != SQLITE_OK) {
return NULL;
}
sqlite3_bind_text(q, 1, native, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
const char *t = (const char *)sqlite3_column_text(q, 0);
out = malloc(strlen(t) + 1);
if (out) {
memcpy(out, t, strlen(t) + 1);
}
}
sqlite3_finalize(q);
return out;
}
/* 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 derived it then. */
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 = v3_neutral(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'"); }
/* Version 17 did not say which credential each request went with. */
static int migrate_from_17(pic_store *s) {
if (!has_column(s, "pic_generation", "credential") &&
pic_exec(s, "ALTER TABLE pic_generation ADD COLUMN credential TEXT") != 0) {
return -1;
}
return pic_exec(s, "UPDATE pic_meta SET value='18' WHERE key='schema_version'");
}
/* Version 18 kept no verdicts; the schema above has just created their table, empty. */
static int migrate_from_18(pic_store *s) { return pic_exec(s, "UPDATE pic_meta SET value='19' WHERE key='schema_version'"); }
/* Version 19 kept no deleted conversations; the schema above has just created their table, empty. */
static int migrate_from_19(pic_store *s) { return pic_exec(s, "UPDATE pic_meta SET value='20' WHERE key='schema_version'"); }
/* Version 20 kept no loops, monitors or goals; the schema above has just created their table, empty. */
static int migrate_from_20(pic_store *s) { return pic_exec(s, "UPDATE pic_meta SET value='21' 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 if (strcmp(version, "17") == 0) {
rc = migrate_from_17(s);
} else if (strcmp(version, "18") == 0) {
rc = migrate_from_18(s);
} else if (strcmp(version, "19") == 0) {
rc = migrate_from_19(s);
} else if (strcmp(version, "20") == 0) {
rc = migrate_from_20(s);
} else {
return 0; /* new, current, or a version schema_version_ok refuses */
}
if (rc != 0) {
return -1;
}
}
}
/* s->err for a journal of schema V that this pic cannot use, in words a person acts on. -1. */
static int schema_refused(pic_store *s, long v) {
if (v > atol(PIC_SCHEMA_VERSION)) {
return st_fail(s, PIC_JOURNAL_NEWER);
}
if (v > 0) {
return st_fail(s, "this journal is from an older pic: pic doctor in its workspace updates it");
}
return st_fail(s, "this is not a pic journal, or it is damaged");
}
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 = schema_refused(s, v ? atol(v) : 0);
}
}
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;
}
/* The journal, its write-ahead log and its shared memory hold the whole conversation: the user's
* alone. A new journal is made 0600 (SQLite gives -wal and -shm the mode of the file they belong
* to), and one an earlier pic made 0644 is tightened whenever it is opened. */
static void journal_private(const char *db_path, int create) {
static const char *const suffix[3] = {"", "-wal", "-shm"};
char path[4200];
struct stat sb;
if (!host()) {
return;
}
for (int i = 0; i < 3; i++) {
if (snprintf(path, sizeof path, "%s%s", db_path, suffix[i]) >= (int)sizeof path) {
continue;
}
if (stat(path, &sb) == 0) {
if ((sb.st_mode & 077) && sb.st_uid == getuid()) {
(void)chmod(path, 0600);
}
} else if (create && i == 0) {
int fd = open(path, O_RDWR | O_CREAT | O_CLOEXEC, 0600);
if (fd >= 0) {
close(fd);
}
}
}
}
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");
}
journal_private(db_path, 1);
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 ||
sqlite3_create_function(s->db, "pic_line", 2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, line_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.
* The holders that keep a journal open for long are asked to let go
* (migrate_ask), and waited for while one of them is there; the others
* are named, with what ends each. */
for (int waited = 0, ask = -1, yielders = 0; !alone && !schema_current(s); waited += 20) {
journal_unlock(s);
if ((rc = journal_lock(s, 0, 0)) < 0) {
migrate_unask(s, &ask);
return -1;
}
if (rc == 0) {
migrate_unask(s, &ask); /* none can come back: they wait for the lock shared */
alone = 1;
break;
}
if (ask < 0 && waited == 0) {
ask = migrate_ask(s);
}
if (waited % 500 == 0) {
pic_holder h[16];
int n = holders_scan(s, h, 16);
yielders = 0;
for (int i = 0; i < n && i < 16; i++) {
yielders += h[i].yields;
}
}
if (waited >= 2 * LOCK_WAIT_MS && !(yielders && waited < MIGRATE_YIELD_MS)) {
migrate_unask(s, &ask);
return migrate_blocked(s);
}
(void)usleep(20000);
if ((rc = journal_lock(s, 1, LOCK_WAIT_MS)) != 0) {
migrate_unask(s, &ask);
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 || pic_exec(s, verdict_sql) != 0 || pic_exec(s, reveal_sql) != 0 || pic_exec(s, trash_sql) != 0 || pic_exec(s, wake_sql) != 0 || st_migrate(s) != 0 || pic_exec(s, link_sql) != 0 || pic_exec(s, index_sql) != 0 ||
pic_exec(s, "INSERT OR IGNORE INTO pic_meta(key,value) VALUES('schema_version','" PIC_SCHEMA_VERSION "')") != 0 ||
/* the journal's identity, for a peer's sender and keys (docs/design/grapevine.md): random,
* so a copied file is told apart only by where it is, and never changed */
pic_exec(s, "INSERT OR IGNORE INTO pic_meta(key,value) VALUES('journal_id', lower(hex(randomblob(8))))") != 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_trash_purge(s, now - PIC_TRASH_DAYS * 86400000LL, &count);
(void)pic_prune(s, 0, &count, &bytes);
(void)pic_prune_files(s, 0, &count, &bytes);
(void)pic_inbox_retain(s, now);
s->err[0] = '\0';
}
}
journal_private(db_path, 0);
holder_register(s);
return 0;
}
void pic_close(pic_store *s) {
holder_unregister(s);
pic_live_end(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;
}
/* The bell is rung in the lease directory: it too must be this user's. */
if (host() && stat(s->lease_dir, &st) == 0 && st.st_uid != getuid()) {
return st_fail(s, "%s belongs to another user", s->lease_dir);
}
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");
}
journal_private(db_path, 0);
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)) {
sqlite3_stmt *q = NULL;
long v = 0;
if (sqlite3_prepare_v2(s->db, "SELECT CAST(value AS INTEGER) FROM pic_meta WHERE key='schema_version'", -1, &q, NULL) ==
SQLITE_OK &&
sqlite3_step(q) == SQLITE_ROW) {
v = sqlite3_column_int(q, 0);
}
sqlite3_finalize(q);
return schema_refused(s, v);
}
/* A list of conversations shows their titles (PIC_TITLE_SQL). */
if (sqlite3_create_function(s->db, "pic_line", 2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, line_fn, NULL, NULL) != SQLITE_OK) {
return st_fail(s, "cannot register pic_line: %s", sqlite3_errmsg(s->db));
}
holder_register(s);
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");
}
/* SESSION's watch file, <journal>.pic-leases/ID.watch: an interface that follows the conversation
* (the terminal's idle attach, an ssh client) holds it shared for as long as it follows. */
static int watch_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 ".watch" <= cap ? (memcpy(out + n, ".watch", sizeof ".watch"), 0) : st_fail(s, "database path too long");
}
int pic_watch_hold(pic_store *s, const char *session) {
char path[4096];
if (!host() || watch_path(s, session, path, sizeof path) != 0 ||
(mkdir(s->lease_dir, 0700) != 0 && errno != EEXIST)) {
return -1;
}
return pic_platform_get()->lock(path, 1) >= 0 ? 0 : -1; /* let go when this process ends */
}
int pic_watched(pic_store *s, const char *session) {
char path[4096];
struct stat st;
int h;
if (!host() || watch_path(s, session, path, sizeof path) != 0 || stat(path, &st) != 0) {
return 0;
}
h = pic_platform_get()->lock(path, 0);
if (h >= 0) {
pic_platform_get()->unlock(h);
return 0;
}
return h == -2 && errno == EWOULDBLOCK;
}
int pic_live_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 ".live" <= cap ? (memcpy(out + n, ".live", sizeof ".live"), 0) : st_fail(s, "database path too long");
}
void pic_live_begin(pic_store *s, const char *session, long long seq) {
char path[4096];
pic_live_end(s);
if (!s->lease_dir || !session || pic_live_path(s, session, path, sizeof path) != 0) {
s->err[0] = '\0';
return;
}
(void)unlink(path); /* one a dead process left */
s->live_path = strdup(path);
s->live_seq = seq;
s->live_fd = -1;
}
/* All of it, or -1. */
static int live_write(int fd, const char *p, size_t n) {
while (n) {
ssize_t w = write(fd, p, n);
if (w < 0 && errno == EINTR) {
continue;
}
if (w <= 0) {
return -1;
}
p += w;
n -= (size_t)w;
}
return 0;
}
void pic_live_text(pic_store *s, const char *text, size_t len) {
if (!s->live_path || s->live_fd == -2 || len == 0) {
return;
}
if (s->live_fd == -1) {
char head[64];
int fd = open(s->live_path, O_WRONLY | O_CREAT | O_EXCL | O_APPEND | O_CLOEXEC, 0600);
int n = snprintf(head, sizeof head, "pic-live 1 %lld\n", s->live_seq);
if (fd < 0 || live_write(fd, head, (size_t)n) != 0) {
if (fd >= 0) {
close(fd);
(void)unlink(s->live_path);
}
s->live_fd = -2;
return;
}
s->live_fd = fd;
}
if (live_write(s->live_fd, text, len) != 0) { /* a follower sees it stop; the reply goes on */
close(s->live_fd);
s->live_fd = -2;
}
}
void pic_live_end(pic_store *s) {
if (!s->live_path) {
return;
}
if (s->live_fd >= 0) {
close(s->live_fd);
}
(void)unlink(s->live_path);
free(s->live_path);
s->live_path = NULL;
s->live_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"},
/* 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')"},
{"verdict of a missing request, or on an entry not its reply",
"SELECT count(*) FROM pic_verdict v WHERE NOT EXISTS (SELECT 1 FROM pic_entry e WHERE e.seq=v.entry_seq"
" AND e.submission_id=v.submission_id AND e.kind IN ('assistant','answer'))"},
{"verdict whose outcome disagrees with its state",
"SELECT count(*) FROM pic_verdict WHERE (state='done') != (outcome IS NOT NULL)"},
{"verdict started under a finished request",
"SELECT count(*) FROM pic_verdict v JOIN pic_submission u ON u.id=v.submission_id WHERE v.state='started'"
" AND u.status != 'admitted'"},
{"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)"},
/* Loops, monitors and goals (wake.c). A fire is its count and its inbox row together. */
{"wake of a missing conversation",
"SELECT count(*) FROM pic_wake w WHERE NOT EXISTS (SELECT 1 FROM pic_session s WHERE s.id = w.session_id)"},
{"wake whose fires disagree with its inbox messages",
"SELECT count(*) FROM pic_wake w WHERE w.fires != (SELECT count(*) FROM pic_inbox i WHERE i.sender = 'wake:' || w.id)"
" OR EXISTS (SELECT 1 FROM pic_inbox i WHERE i.sender = 'wake:' || w.id AND (CAST(substr(i.msg_key, length('wake:' || w.id) + 2)"
" AS INTEGER) NOT BETWEEN 1 AND w.fires OR i.msg_key NOT LIKE 'wake:' || w.id || ':%'))"},
{"active loop with no time to fire, active monitor with no command or spool, or a wake not active without a reason",
"SELECT count(*) FROM pic_wake WHERE (state = 'active' AND kind = 'loop' AND (due_ms IS NULL OR every_ms IS NULL))"
" OR (state = 'active' AND kind = 'monitor' AND (command IS NULL OR spool IS NULL))"
" OR (state != 'active' AND why IS NULL)"},
{"deleted conversation that does not exist, or purged before it was deleted",
"SELECT count(*) FROM pic_trash t WHERE NOT EXISTS (SELECT 1 FROM pic_session s WHERE s.id = t.session_id)"
" OR t.purged_ms < t.deleted_ms"},
{"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