Skip to content
pi-c Artifact [0a701a89e9]
Login

Artifact [0a701a89e9]

Artifact 0a701a89e9ca6c8d175d3ef91dd81d47654f23ad8db87ce22cfe4f1a595567df:


/* The inbox: accepting a message (the sender) and delivering it (the
 * conversation's worker). See inbox.h and docs/design/grapevine.md. */
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <pthread.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>

#include "commands.h"
#include "events.h"
#include "hooks.h"
#include "inbox.h"
#include "libfossil.h"
#include "net.h"
#include "platform.h"
#include "wake.h"

static long long inbox_now_ms(void) { return (long long)(pic_platform_get()->wall_ns() / 1000000); }

static int inbox_fail(pic_store *s, int rc, const char *msg) {
    (void)snprintf(s->err, sizeof s->err, "%s", msg);
    return rc;
}

static int inbox_sql_fail(pic_store *s) {
    (void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db));
    return -1;
}

/* ---- the bell ------------------------------------------------------------- */

/* The counter in a bell file, 0 when it has none. */
static long long inbox_bell_read(const char *path) {
    char buf[32] = "";
    int fd = open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
    long long n = 0;
    if (fd >= 0) {
        ssize_t got = read(fd, buf, sizeof buf - 1);
        close(fd);
        n = got > 0 ? strtoll(buf, NULL, 10) : 0;
    }
    return n;
}

/* Creates SESSION's bell (and the lease directory) when missing; when RING,
 * adds one to its counter, rewritten in place. Advisory: a failure only
 * leaves the message to the worker's next look. */
static void inbox_bell(pic_store *s, const char *session, int ring, char *path, size_t cap) {
    char buf[32];
    int fd;
    if (pic_bell_path(s, session, path, cap) != 0) {
        path[0] = '\0';
        return;
    }
    if (pic_platform_get() != pic_platform_host()) {
        return;
    }
    (void)mkdir(s->lease_dir, 0700);
    fd = open(path, O_RDWR | O_CREAT | O_CLOEXEC | O_NOFOLLOW, 0600); /* a planted link is not followed */
    if (fd < 0) {
        return;
    }
    if (ring) {
        ssize_t got = pread(fd, buf, sizeof buf - 1, 0);
        long long n;
        int len;
        buf[got > 0 ? got : 0] = '\0';
        n = strtoll(buf, NULL, 10) + 1;
        len = snprintf(buf, sizeof buf, "%020lld\n", n); /* one width: rewritten in place */
        if (pwrite(fd, buf, (size_t)len, 0) != len) {
            if (ftruncate(fd, 0) != 0) {
                /* a counter left as it was is read again as a number next time */
            }
        }
    }
    close(fd);
}

/* ---- accepting -------------------------------------------------------------- */

/* A message's identity: its conversation, sender and command, so a key
 * reused for any other is a conflict, never a retry. */
static void inbox_hash(const char *session, const char *sender, const char *line, char out[65]) {
    fsl_sha3_cx cx;
    fsl_sha3_init2(&cx, FSL_SHA3_256);
    fsl_sha3_update(&cx, session, (unsigned)strlen(session) + 1); /* each with its NUL, so no two split alike */
    fsl_sha3_update(&cx, sender, (unsigned)strlen(sender) + 1);
    fsl_sha3_update(&cx, line, (unsigned)strlen(line));
    fsl_sha3_end(&cx);
    (void)snprintf(out, 65, "%s", (const char *)cx.hex);
}

static int inbox_random_key(char *out, size_t cap) {
    unsigned char raw[16];
    if (cap < 33 || pic_platform_get()->entropy(raw, sizeof raw) != 0) {
        return -1;
    }
    for (size_t i = 0; i < sizeof raw; i++) {
        (void)snprintf(out + 2 * i, 3, "%02x", raw[i]);
    }
    return 0;
}

/* The command's type when the inbox takes it (prompt, steer and follow_up
 * with a string message, abort), else NULL with s->err. */
static const char *inbox_type(pic_store *s, const char *line) {
    sqlite3_stmt *q = NULL;
    const char *type = NULL;
    if (sqlite3_prepare_v2(s->db,
                           "SELECT json_valid(?1) AND json_type(?1) = 'object', CASE WHEN json_valid(?1) THEN"
                           " json_extract(?1, '$.type') END, CASE WHEN json_valid(?1) THEN json_type(?1, '$.message') END",
                           -1, &q, NULL) != SQLITE_OK) {
        (void)inbox_sql_fail(s);
        return NULL;
    }
    sqlite3_bind_text(q, 1, line, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        const char *t = (const char *)sqlite3_column_text(q, 1), *m = (const char *)sqlite3_column_text(q, 2);
        if (!sqlite3_column_int(q, 0)) {
            (void)inbox_fail(s, 0, "the command is not a JSON object");
        } else if (t && (strcmp(t, "steer") == 0 || strcmp(t, "follow_up") == 0 || strcmp(t, "prompt") == 0)) {
            type = strcmp(t, "steer") == 0 ? "steer" : strcmp(t, "prompt") == 0 ? "prompt" : "follow_up";
            if (!m || strcmp(m, "text") != 0) {
                type = NULL;
                (void)inbox_fail(s, 0, "message must be a string");
            }
        } else if (t && strcmp(t, "abort") == 0) {
            type = "abort";
        } else {
            (void)snprintf(s->err, sizeof s->err, "the inbox takes prompt, steer, follow_up and abort, not %.60s", t ? t : "(no type)");
        }
    }
    sqlite3_finalize(q);
    return type;
}

static int inbox_int(pic_store *s, const char *sql, const char *text, long long *out) {
    sqlite3_stmt *q = NULL;
    int rc;
    *out = 0;
    if (sqlite3_prepare_v2(s->db, sql, -1, &q, NULL) != SQLITE_OK) {
        return inbox_sql_fail(s);
    }
    sqlite3_bind_text(q, 1, text, -1, SQLITE_STATIC);
    rc = sqlite3_step(q);
    if (rc == SQLITE_ROW) {
        *out = sqlite3_column_int64(q, 0);
    }
    sqlite3_finalize(q);
    return rc == SQLITE_ROW || rc == SQLITE_DONE ? 0 : inbox_sql_fail(s);
}

/* SQL's one text value for TEXT bound as ?1, into OUT ("" for NULL). 0 or -1. */
static int inbox_text(pic_store *s, const char *sql, const char *text, char *out, size_t cap) {
    sqlite3_stmt *q = NULL;
    int rc;
    out[0] = '\0';
    if (sqlite3_prepare_v2(s->db, sql, -1, &q, NULL) != SQLITE_OK) {
        return inbox_sql_fail(s);
    }
    sqlite3_bind_text(q, 1, text, -1, SQLITE_STATIC);
    rc = sqlite3_step(q);
    if (rc == SQLITE_ROW && sqlite3_column_text(q, 0)) {
        (void)snprintf(out, cap, "%s", (const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    return rc == SQLITE_ROW || rc == SQLITE_DONE ? 0 : inbox_sql_fail(s);
}

int pic_inbox_accept(pic_store *s, const pic_inbox_msg *m, char *key, size_t key_cap, char *state, size_t state_cap) {
    sqlite3_stmt *q = NULL;
    const char *type, *refusal = NULL;
    char hash[65], path[4096], behavior[16] = "";
    long long expires_s = m->expires_s, exists = 0, rows = 0, bytes = 0, target = 0, now = inbox_now_ms();
    int rc;
    s->err[0] = '\0';
    if (strlen(m->line) > PIC_INBOX_LINE_CAP) {
        return inbox_fail(s, 1, "the command is longer than 16 MB");
    }
    if (!(type = inbox_type(s, m->line))) {
        return s->err[0] && strncmp(s->err, "sql:", 4) == 0 ? -1 : 1;
    }
    if (expires_s < 0 || expires_s > PIC_INBOX_MAX_SECONDS) {
        return inbox_fail(s, 1, "--expires is 1 to 604800 seconds");
    }
    if (m->hops > (m->max_hops > 0 ? m->max_hops : PIC_INBOX_MAX_HOPS)) { /* two conversations answering each other */
        (void)snprintf(s->err, sizeof s->err, "refused: the message has passed through %ld conversations (grapevine.maxHops is %ld)",
                       m->hops, m->max_hops > 0 ? m->max_hops : (long)PIC_INBOX_MAX_HOPS);
        return 1;
    }
    if (strcmp(type, "prompt") == 0 && inbox_text(s, "SELECT CASE json_extract(?1, '$.streamingBehavior') WHEN 'steer' THEN 'steer'"
                                                     " WHEN 'followUp' THEN 'follow_up' ELSE '' END",
                                                     m->line, behavior, sizeof behavior) != 0) {
        return -1;
    }
    if (expires_s == 0) { /* a prompt is a follow-up unless it says it steers */
        expires_s = strcmp(type, "follow_up") == 0 || (strcmp(type, "prompt") == 0 && strcmp(behavior, "steer") != 0)
                        ? PIC_INBOX_FOLLOW_UP_SECONDS
                        : PIC_INBOX_STEER_SECONDS;
    }
    if (m->key) {
        if (!*m->key || strlen(m->key) >= key_cap || strlen(m->key) > 200) {
            return inbox_fail(s, 1, "a key is 1 to 200 bytes");
        }
        (void)snprintf(key, key_cap, "%s", m->key);
    } else if (inbox_random_key(key, key_cap) != 0) {
        return inbox_fail(s, -1, "cannot draw a key");
    }
    inbox_hash(m->session, m->sender, m->line, hash);
    if (pic_begin(s) != 0) {
        return -1;
    }
    /* A known key: the same command is a retry, another a conflict. */
    if (sqlite3_prepare_v2(s->db, "SELECT command_hash, state FROM pic_inbox WHERE msg_key = ?", -1, &q, NULL) != SQLITE_OK) {
        rc = inbox_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_text(q, 1, key, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        int same = strcmp((const char *)sqlite3_column_text(q, 0), hash) == 0;
        (void)snprintf(state, state_cap, "%s", (const char *)sqlite3_column_text(q, 1));
        sqlite3_finalize(q);
        pic_rollback(s);
        if (!same) {
            (void)snprintf(s->err, sizeof s->err, "key %.200s was used for another command", key); /* or conversation */
            return 1;
        }
        return 0;
    }
    sqlite3_finalize(q);
    if (inbox_int(s, "SELECT count(*) FROM pic_session WHERE id = ?", m->session, &exists) != 0 ||
        inbox_int(s, "SELECT count(*) FROM pic_inbox WHERE session_id = ? AND state = 'pending'", m->session, &rows) != 0 ||
        inbox_int(s, "SELECT coalesce(sum(length(CAST(command AS BLOB))), 0) FROM pic_inbox WHERE session_id = ? AND state = 'pending'",
                  m->session, &bytes) != 0 ||
        ((strcmp(type, "abort") == 0 || strcmp(type, "prompt") == 0) &&
         inbox_int(s, "SELECT coalesce(max(id), 0) FROM pic_submission WHERE session_id = ? AND status = 'admitted'", m->session,
                   &target) != 0)) {
        pic_rollback(s);
        return -1;
    }
    if (!exists || rows >= PIC_INBOX_PENDING_ROWS || bytes + (long long)strlen(m->line) > PIC_INBOX_PENDING_BYTES) {
        pic_rollback(s);
        if (!exists) {
            (void)snprintf(s->err, sizeof s->err, "no conversation %.64s", m->session);
        } else {
            (void)snprintf(s->err, sizeof s->err, "the inbox of %.64s is full (%d messages or 64 MB waiting)", m->session,
                           PIC_INBOX_PENDING_ROWS);
        }
        return 1;
    }
    /* Refused at once, as Pi refuses them: an abort sent while nothing runs can never run, and a
     * prompt that does not say how to join a running request is not queued behind it. */
    if (strcmp(type, "abort") == 0 && target == 0) {
        refusal = "nothing to abort: no request is running";
    } else if (strcmp(type, "prompt") == 0 && target != 0 && !behavior[0]) {
        refusal = PIC_INBOX_BUSY;
    }
    if (strcmp(type, "abort") != 0) {
        target = 0; /* only an abort names its request */
    }
    if (sqlite3_prepare_v2(s->db,
                           "INSERT INTO pic_inbox(msg_key, command_hash, session_id, sender, command, hops, target, created_ms,"
                           " expires_ms, state, response, settled_ms) VALUES (?1, ?2, ?3, ?4, ?5, ?11, nullif(?6, 0), ?7, ?8,"
                           " iif(?9 IS NOT NULL, 'refused', 'pending'), CASE WHEN ?9 IS NOT NULL THEN json_patch('{}',"
                           " json_object('id', CASE WHEN json_type(?5, '$.id') IS NOT NULL THEN json_extract(?5, '$.id') END,"
                           " 'type', 'response', 'command', ?10, 'success', json('false'), 'error', ?9)) END,"
                           " CASE WHEN ?9 IS NOT NULL THEN ?7 END)",
                           -1, &q, NULL) != SQLITE_OK) {
        rc = inbox_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_text(q, 1, key, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, hash, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 3, m->session, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 4, m->sender, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 5, m->line, -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 6, target);
    sqlite3_bind_int64(q, 7, now);
    sqlite3_bind_int64(q, 8, now + expires_s * 1000);
    if (refusal) {
        sqlite3_bind_text(q, 9, refusal, -1, SQLITE_STATIC);
    }
    sqlite3_bind_text(q, 10, type, -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 11, m->hops);
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    if (rc != SQLITE_DONE) {
        rc = inbox_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    pic_fault("inbox_accept");
    if (pic_commit(s) != 0) {
        pic_rollback(s);
        return -1;
    }
    pic_fault("inbox_accept");
    (void)snprintf(state, state_cap, "%s", refusal ? "refused" : "pending");
    inbox_bell(s, m->session, 1, path, sizeof path);
    return 0;
}

void pic_inbox_ring(pic_store *s, const char *session) {
    char path[4096];
    inbox_bell(s, session, 1, path, sizeof path);
}

int pic_inbox_status(pic_store *s, const char *key, char *state, size_t cap, char **response) {
    sqlite3_stmt *q = NULL;
    int rc;
    if (response) {
        *response = NULL;
    }
    if (sqlite3_prepare_v2(s->db, "SELECT state, response FROM pic_inbox WHERE msg_key = ?", -1, &q, NULL) != SQLITE_OK) {
        return inbox_sql_fail(s);
    }
    sqlite3_bind_text(q, 1, key, -1, SQLITE_STATIC);
    rc = sqlite3_step(q);
    if (rc == SQLITE_ROW) {
        (void)snprintf(state, cap, "%s", (const char *)sqlite3_column_text(q, 0));
        if (response && sqlite3_column_text(q, 1)) {
            *response = strdup((const char *)sqlite3_column_text(q, 1));
        }
    }
    sqlite3_finalize(q);
    return rc == SQLITE_ROW ? 0 : rc == SQLITE_DONE ? 1 : inbox_sql_fail(s);
}

/* ---- delivering ------------------------------------------------------------- */

/* The watch: a thread waits on the bell (the platform's watch, or a stat
 * every 200 ms where there is none, and every 30 s regardless) and writes a
 * byte to a pipe whose read end is pic_watch_fd, which every wait polls. */
static struct {
    pic_store *s;
    char session[64];
    char bell[4096];
    int pipe[2];
    pthread_t thread;
    int running;
    atomic_int stop;
} inbox_w = {.pipe = {-1, -1}};

static void *inbox_watch_main(void *arg) {
    const pic_platform *p = pic_platform_get();
    int fd = p->watch ? p->watch(inbox_w.bell) : -1, ticks = 0;
    long long last = fd < 0 ? inbox_bell_read(inbox_w.bell) : 0;
    (void)arg;
    while (!atomic_load(&inbox_w.stop)) {
        int ring = 0;
        if (fd >= 0) {
            struct pollfd w = {fd, POLLIN, 0};
            if (poll(&w, 1, 200) > 0) {
                if (p->watch_clear) {
                    p->watch_clear(fd);
                }
                ring = 1;
            }
        } else {
            struct timespec ts = {0, 200000000L};
            long long now;
            (void)nanosleep(&ts, NULL);
            now = inbox_bell_read(inbox_w.bell);
            ring = now != last; /* the counter, not the mtime: two rings in one tick are two */
            last = now;
        }
        if (++ticks >= 150) { /* 30 s: a sender that died before its ring */
            ring = 1;
        }
        if (ring) {
            ticks = 0;
            if (write(inbox_w.pipe[1], "b", 1) < 0) {
                /* a full pipe already says it */
            }
        }
    }
    if (fd >= 0) {
        if (p->watch_end) {
            p->watch_end(fd);
        } else {
            close(fd);
        }
    }
    return NULL;
}

static void inbox_watch_ready(void) {
    char buf[64];
    while (read(inbox_w.pipe[0], buf, sizeof buf) > 0) {
    }
    if (inbox_w.s) {
        pic_inbox_poll(inbox_w.s);
    }
}

void pic_inbox_stop(void) {
    if (inbox_w.running) {
        atomic_store(&inbox_w.stop, 1);
        (void)pthread_join(inbox_w.thread, NULL);
        inbox_w.running = 0;
    }
    for (int i = 0; i < 2; i++) {
        if (inbox_w.pipe[i] >= 0) {
            close(inbox_w.pipe[i]);
            inbox_w.pipe[i] = -1;
        }
    }
    if (pic_watch_ready == inbox_watch_ready) {
        pic_watch_fd = -1;
        pic_watch_ready = NULL;
    }
    inbox_w.s = NULL;
    inbox_w.session[0] = '\0';
}

static void inbox_watch(pic_store *s, const char *session) {
    if (inbox_w.s == s && strcmp(inbox_w.session, session) == 0) {
        return;
    }
    pic_inbox_stop();
    inbox_w.s = s;
    (void)snprintf(inbox_w.session, sizeof inbox_w.session, "%s", session);
    if (pic_platform_get() != pic_platform_host()) {
        return; /* no other process to hear from */
    }
    inbox_bell(s, session, 0, inbox_w.bell, sizeof inbox_w.bell);
    if (!inbox_w.bell[0] || pipe(inbox_w.pipe) != 0) {
        inbox_w.pipe[0] = inbox_w.pipe[1] = -1;
        return;
    }
    for (int i = 0; i < 2; i++) {
        (void)fcntl(inbox_w.pipe[i], F_SETFD, FD_CLOEXEC);
        (void)fcntl(inbox_w.pipe[i], F_SETFL, O_NONBLOCK);
    }
    atomic_store(&inbox_w.stop, 0);
    if (pthread_create(&inbox_w.thread, NULL, inbox_watch_main, NULL) != 0) {
        return; /* turn boundaries still deliver */
    }
    inbox_w.running = 1;
    pic_watch_fd = inbox_w.pipe[0];
    pic_watch_ready = inbox_watch_ready;
}

/* The response line commands.c gives a delivered command. */
static void inbox_take(void *ctx, const char *response) {
    char **out = ctx;
    if (!*out) {
        *out = strdup(response);
    }
}

static long long inbox_woken(pic_store *s, const char *key);

/* SQL with ?1 and ?2 bound to A and B. 0, or -1. */
static int run_stmt_id(pic_store *s, const char *sql, long long a, long long b) {
    sqlite3_stmt *q = NULL;
    int rc;
    if (sqlite3_prepare_v2(s->db, sql, -1, &q, NULL) != SQLITE_OK) {
        return inbox_sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, a);
    sqlite3_bind_int64(q, 2, b);
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    return rc == SQLITE_DONE ? 0 : inbox_sql_fail(s);
}

/* Inside the delivery's transaction: settles row ID. */
static int inbox_settle(pic_store *s, long long id, const char *state, const char *response, long long queued) {
    sqlite3_stmt *q = NULL;
    int rc;
    if (sqlite3_get_autocommit(s->db) || s->nest != 1) { /* the delivery's transaction was lost: settle nothing */
        return inbox_fail(s, -1, "the delivery's transaction ended early");
    }
#ifdef PIC_FAULTS
    if (getenv("PIC_INBOX_FAIL_SETTLE")) { /* tests: a settle that fails after the command ran */
        return inbox_fail(s, -1, "settle failed (PIC_INBOX_FAIL_SETTLE)");
    }
#endif
    if (sqlite3_prepare_v2(s->db,
                           "UPDATE pic_inbox SET state = ?2, response = ?3, queued_id = nullif(?4, 0), settled_ms = ?5"
                           " WHERE id = ?1 AND state = 'pending'",
                           -1, &q, NULL) != SQLITE_OK) {
        return inbox_sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, id);
    sqlite3_bind_text(q, 2, state, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 3, response, -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 4, queued);
    sqlite3_bind_int64(q, 5, inbox_now_ms());
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    if (rc != SQLITE_DONE) {
        return inbox_sql_fail(s);
    }
    return sqlite3_changes(s->db) == 1 ? 0 : inbox_fail(s, -1, "the message was settled by another process");
}

/* Pi's response line for COMMAND: success, or an error. */
static char *inbox_response(pic_store *s, const char *line, const char *type, const char *error) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (sqlite3_prepare_v2(s->db,
                           "SELECT json_patch('{}', json_object('id', CASE WHEN json_valid(?1) AND json_type(?1) = 'object'"
                           " THEN json_extract(?1, '$.id') END, 'type', 'response', 'command', ?2,"
                           " 'success', json(iif(?3 IS NULL, 'true', 'false')), 'error', ?3))",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, line, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, type, -1, SQLITE_STATIC);
        if (error) {
            sqlite3_bind_text(q, 3, error, -1, SQLITE_STATIC);
        }
        if (sqlite3_step(q) == SQLITE_ROW) {
            out = strdup((const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    return out;
}

/* The events a delivery makes (queue_update, a delivered message) are held
 * in memory while its write transaction is open, and written only once it
 * has committed: a slow reader of them never holds the journal's write
 * lock, and a rolled-back delivery shows nothing. */
typedef struct {
    pic_events *e;
    FILE *out, *notes;     /* the real streams */
    FILE *mem_out, *mem_notes;
    char *buf_out, *buf_notes;
    size_t len_out, len_notes;
} inbox_held;

static void inbox_hold(pic_store *s, inbox_held *h) {
    if (!s->events || h->e) {
        return;
    }
    h->mem_out = open_memstream(&h->buf_out, &h->len_out);
    h->mem_notes = s->events->notes ? open_memstream(&h->buf_notes, &h->len_notes) : NULL;
    if (!h->mem_out || (s->events->notes && !h->mem_notes)) { /* no memory: the events go out as they come */
        if (h->mem_out) {
            fclose(h->mem_out);
        }
        if (h->mem_notes) {
            fclose(h->mem_notes);
        }
        free(h->buf_out);
        free(h->buf_notes);
        memset(h, 0, sizeof *h);
        return;
    }
    h->e = s->events;
    h->out = h->e->out;
    h->notes = h->e->notes;
    h->e->out = h->mem_out;
    if (h->notes) {
        h->e->notes = h->mem_notes;
    }
}

static void inbox_release(pic_store *s, inbox_held *h, int committed) {
    (void)s;
    if (!h->e) {
        return;
    }
    h->e->out = h->out;
    h->e->notes = h->notes;
    fclose(h->mem_out);
    if (h->mem_notes) {
        fclose(h->mem_notes);
    }
    if (committed) {
        if (h->len_out) {
            (void)fwrite(h->buf_out, 1, h->len_out, h->out);
            (void)fflush(h->out);
        }
        if (h->len_notes && h->notes) {
            (void)fwrite(h->buf_notes, 1, h->len_notes, h->notes);
            (void)fflush(h->notes);
        }
    }
    free(h->buf_out);
    free(h->buf_notes);
    memset(h, 0, sizeof *h);
}

/* One pending message of SESSION, oldest first: 1 when one was settled, 0
 * when none can be now (none pending, or the first waits for a request),
 * -1 on an error (rolled back). */
static int inbox_deliver_one(pic_store *s, const char *session) {
    sqlite3_stmt *q = NULL;
    long long id = 0, expires = 0, target = 0, running = 0, answered = 0, before = 0, after = 0, woken = 0, made = 0;
    char *line = NULL, *type = NULL, *response = NULL, key[256] = "";
    const char *state = NULL;
    int rc = -1, abort_now = 0;
    int64_t running_was = s->running;
    inbox_held held = {0};
    if (pic_begin_outer(s) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(s->db,
                           "SELECT id, command, expires_ms, coalesce(target, 0), json_extract(command, '$.type'), msg_key FROM pic_inbox"
                           " WHERE session_id = ? AND state = 'pending' ORDER BY id LIMIT 1",
                           -1, &q, NULL) != SQLITE_OK) {
        (void)inbox_sql_fail(s);
        goto out;
    }
    sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        id = sqlite3_column_int64(q, 0);
        line = strdup((const char *)sqlite3_column_text(q, 1));
        expires = sqlite3_column_int64(q, 2);
        target = sqlite3_column_int64(q, 3);
        type = sqlite3_column_text(q, 4) ? strdup((const char *)sqlite3_column_text(q, 4)) : strdup("");
        (void)snprintf(key, sizeof key, "%s", (const char *)sqlite3_column_text(q, 5));
    }
    sqlite3_finalize(q);
    if (!id) {
        rc = 0;
        goto out;
    }
    if (!line || !type) {
        (void)inbox_fail(s, -1, "out of memory");
        goto out;
    }
    if (inbox_int(s, "SELECT coalesce(max(id), 0) FROM pic_submission WHERE session_id = ? AND status = 'admitted'", session,
                  &running) != 0) {
        goto out;
    }
    if (strcmp(type, "prompt") == 0 && (woken = inbox_woken(s, key)) != 0) {
        /* a wake admitted it and died before settling it: it is that request, not a follow-up */
        if (woken < 0) {
            goto out;
        }
        state = "delivered";
        response = inbox_response(s, line, type, NULL);
        made = woken;
    } else if (expires <= inbox_now_ms()) {
        state = "expired";
        response = inbox_response(s, line, type, "expired before it was delivered");
    } else if (strcmp(type, "abort") == 0) {
        if (target && running == target) {
            state = "delivered";
            response = inbox_response(s, line, type, NULL);
            abort_now = 1;
        } else {
            state = "refused";
            response = inbox_response(s, line, type, "nothing to abort: the request it was sent for is not running");
        }
    } else {
        /* A steer, follow-up or prompt joins the running request, or the
         * answered one this process just finished (its queue becomes the next). */
        sqlite3_stmt *a = NULL;
        if (!running && sqlite3_prepare_v2(s->db,
                                           "SELECT count(*) FROM pic_submission WHERE id = ?1 AND status = 'answered'"
                                           " AND session_id = ?2",
                                           -1, &a, NULL) == SQLITE_OK) {
            sqlite3_bind_int64(a, 1, (sqlite3_int64)s->running);
            sqlite3_bind_text(a, 2, session, -1, SQLITE_STATIC);
            answered = sqlite3_step(a) == SQLITE_ROW ? sqlite3_column_int64(a, 0) : 0;
            sqlite3_finalize(a);
        }
        if ((!running && !answered) || !pic_commands_active()) {
            rc = 0; /* it waits for a request */
            goto out;
        }
        if (inbox_int(s, "SELECT coalesce(max(id), 0) FROM pic_queued WHERE ?1 IS NOT NULL", session, &before) != 0) {
            goto out;
        }
        pic_commands_sink(inbox_take, &response);
        inbox_hold(s, &held);
        if (strcmp(type, "prompt") == 0) { /* Pi's queued prompt: a steer when it says so, else a follow-up */
            char kind[16], *message = NULL;
            sqlite3_stmt *p = NULL;
            if (inbox_text(s, "SELECT iif(json_extract(?1, '$.streamingBehavior') = 'steer', 'steer', 'follow_up')", line, kind,
                           sizeof kind) == 0 &&
                sqlite3_prepare_v2(s->db, "SELECT json_extract(?1, '$.message')", -1, &p, NULL) == SQLITE_OK) {
                sqlite3_bind_text(p, 1, line, -1, SQLITE_STATIC);
                if (sqlite3_step(p) == SQLITE_ROW && sqlite3_column_text(p, 0)) {
                    message = strdup((const char *)sqlite3_column_text(p, 0));
                }
            }
            sqlite3_finalize(p);
            if (message) {
                (void)pic_commands_enqueue(line, "prompt", kind, message);
            }
            free(message);
        } else {
            pic_commands_line(line);
        }
        pic_commands_sink(NULL, NULL);
        if (inbox_int(s, "SELECT coalesce(max(id), 0) FROM pic_queued WHERE ?1 IS NOT NULL", session, &after) != 0) {
            goto out;
        }
        if (!response) {
            response = inbox_response(s, line, type, "the command was not answered");
        }
        {
            long long ok = 0;
            if (inbox_int(s, "SELECT coalesce(json_extract(?1, '$.success'), 0)", response ? response : "{}", &ok) != 0) {
                goto out;
            }
            state = ok ? "delivered" : "refused";
        }
    }
    if (!response) {
        (void)inbox_fail(s, -1, "out of memory");
        goto out;
    }
    if (inbox_settle(s, id, state, response, strcmp(state, "delivered") == 0 && after > before ? after : 0) != 0 ||
        (made && run_stmt_id(s, "UPDATE pic_inbox SET submission_id = ?2 WHERE id = ?1", id, made) != 0)) {
        goto out;
    }
    pic_fault("inbox_deliver");
    if (pic_commit(s) != 0) {
        goto out;
    }
    pic_fault("inbox_deliver");
    if (abort_now && !pic_interrupted) { /* Ctrl-C's cancel, at the loop's next step */
        pic_interrupted = 2;
    }
    rc = 1;
out:
    if (rc != 1) {
        pic_rollback(s);
        s->running = running_was; /* a follow-up's admitted request is gone with the rollback */
    }
    inbox_release(s, &held, rc == 1);
    free(line);
    free(type);
    free(response);
    return rc;
}

void pic_inbox_poll(pic_store *s) {
    char sid[64] = "", saved[PIC_ERR_CAP];
    sqlite3_stmt *q = NULL;
    int rc;
    if (!s->running || !s->db || !sqlite3_get_autocommit(s->db)) {
        return;
    }
    if (sqlite3_prepare_v2(s->db, "SELECT session_id FROM pic_submission WHERE id = ?", -1, &q, NULL) != SQLITE_OK) {
        return;
    }
    sqlite3_bind_int64(q, 1, (sqlite3_int64)s->running);
    if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
        (void)snprintf(sid, sizeof sid, "%s", (const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    if (!sid[0] || !pic_leased(s, sid)) {
        return;
    }
    inbox_watch(s, sid);
    (void)snprintf(saved, sizeof saved, "%s", s->err);
    {
        /* This conversation's loops that are due fire here, as a follow-up to the running request. */
        int fired = 0;
        long long next = 0;
        if (pic_wake_due(s, NULL, sid, 0, &fired, &next) != 0) {
            fprintf(stderr, "pic: loop: %s\n", s->err);
        }
    }
    while ((rc = inbox_deliver_one(s, sid)) == 1) {
    }
    if (rc < 0) { /* the message stays pending for the next look */
        fprintf(stderr, "pic: inbox: %s\n", s->err);
    }
    (void)snprintf(s->err, sizeof s->err, "%s", saved);
}

/* Inside a transaction: pending rows past their expiry (KEY's alone, when
 * not NULL) settled as expired. Changes no request, so needs no lease; a
 * worker delivering reads the state again in its own transaction. */
static int inbox_expire(pic_store *s, const char *key, long long now_ms) {
    sqlite3_stmt *q = NULL;
    int rc;
    if (sqlite3_prepare_v2(
            s->db,
            "UPDATE pic_inbox SET state = 'expired', settled_ms = ?1, response = json_patch('{}', json_object('id',"
            " CASE WHEN json_valid(command) AND json_type(command) = 'object' THEN json_extract(command, '$.id') END,"
            " 'type', 'response', 'command', json_extract(command, '$.type'), 'success', json('false'),"
            " 'error', 'expired before it was delivered')) WHERE state = 'pending' AND expires_ms <= ?1"
            " AND (?2 IS NULL OR msg_key = ?2)",
            -1, &q, NULL) != SQLITE_OK) {
        return inbox_sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, now_ms);
    if (key) {
        sqlite3_bind_text(q, 2, key, -1, SQLITE_STATIC);
    }
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    return rc == SQLITE_DONE ? 0 : inbox_sql_fail(s);
}

int pic_inbox_expire(pic_store *s, const char *key) {
    long long due = 0;
    /* A read first: a waiter polls this, and must not take the write lock to learn nothing. */
    if (inbox_int(s, "SELECT count(*) FROM pic_inbox WHERE msg_key = ?1 AND state = 'pending'"
                  " AND expires_ms <= CAST(unixepoch('subsec') * 1000 AS INTEGER)", key,
                  &due) != 0) {
        return -1;
    }
    if (!due) {
        return 0;
    }
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (inbox_expire(s, key, inbox_now_ms()) != 0) {
        pic_rollback(s);
        return -1;
    }
    return pic_commit(s);
}

int pic_inbox_withdraw(pic_store *s, const char *key, const char *why) {
    sqlite3_stmt *q = NULL;
    int rc, changed;
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(s->db,
                           "UPDATE pic_inbox SET state = 'refused', settled_ms = ?3, response = json_patch('{}', json_object('id',"
                           " CASE WHEN json_valid(command) AND json_type(command) = 'object' THEN json_extract(command, '$.id') END,"
                           " 'type', 'response', 'command', json_extract(command, '$.type'), 'success', json('false'),"
                           " 'error', ?2)) WHERE msg_key = ?1 AND state = 'pending'",
                           -1, &q, NULL) != SQLITE_OK) {
        rc = inbox_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_text(q, 1, key, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, why, -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 3, inbox_now_ms());
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    changed = sqlite3_changes(s->db);
    if (rc != SQLITE_DONE) {
        rc = inbox_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    return pic_commit(s) == 0 ? changed == 1 : -1;
}

int pic_inbox_retain(pic_store *s, long long now_ms) {
    sqlite3_stmt *q = NULL;
    int rc;
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (inbox_expire(s, NULL, now_ms) != 0) {
        pic_rollback(s);
        return -1;
    }
    if (sqlite3_prepare_v2(s->db,
                                                "UPDATE pic_inbox SET command = NULL, response = NULL WHERE state != 'pending'"
                                                " AND command IS NOT NULL AND settled_ms <= ?1",
                                                -1, &q, NULL) != SQLITE_OK) {
        rc = inbox_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_int64(q, 1, now_ms - PIC_INBOX_KEEP_MS);
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    if (rc != SQLITE_DONE) {
        rc = inbox_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    return pic_commit(s);
}

long long pic_inbox_hops(pic_store *s, long long submission) {
    sqlite3_stmt *q = NULL;
    long long hops = -1;
    if (sqlite3_prepare_v2(s->db,
                           "SELECT coalesce(max(i.hops), 0) FROM pic_inbox i WHERE i.state = 'delivered' AND (i.submission_id = ?1"
                           " OR i.queued_id IN (SELECT q.id FROM pic_queued q WHERE q.submission_id = ?1)"
                           " OR i.queued_id = (SELECT CAST(substr(u.request_key, 8) AS INTEGER) FROM pic_submission u"
                           "  WHERE u.id = ?1 AND u.request_key LIKE 'queued-%'))",
                           -1, &q, NULL) != SQLITE_OK) {
        (void)inbox_sql_fail(s);
        return -1;
    }
    sqlite3_bind_int64(q, 1, submission);
    if (sqlite3_step(q) == SQLITE_ROW) {
        hops = sqlite3_column_int64(q, 0);
    }
    sqlite3_finalize(q);
    return hops;
}

/* Row ID settled as STATE with ERROR (NULL: success) and the request it made, in a transaction of
 * its own. 0, or -1. */
static int inbox_settle_alone(pic_store *s, long long id, const char *state, const char *error, long long submission) {
    sqlite3_stmt *q = NULL;
    int rc;
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(s->db,
                           "UPDATE pic_inbox SET state = ?2, settled_ms = ?3, submission_id = nullif(?5, 0),"
                           " response = json_patch('{}', json_object('id', CASE WHEN json_valid(command) AND json_type(command) ="
                           " 'object' THEN json_extract(command, '$.id') END, 'type', 'response', 'command',"
                           " json_extract(command, '$.type'), 'success', json(iif(?4 IS NULL, 'true', 'false')), 'error', ?4))"
                           " WHERE id = ?1 AND state = 'pending'",
                           -1, &q, NULL) != SQLITE_OK) {
        rc = inbox_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_int64(q, 1, id);
    sqlite3_bind_text(q, 2, state, -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 3, inbox_now_ms());
    if (error) {
        sqlite3_bind_text(q, 4, error, -1, SQLITE_STATIC);
    }
    sqlite3_bind_int64(q, 5, submission);
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    if (rc != SQLITE_DONE) {
        rc = inbox_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    return pic_commit(s);
}

/* The request a woken prompt became (its key inbox:KEY), or 0. */
static long long inbox_woken(pic_store *s, const char *key) {
    long long id = 0;
    char rkey[256];
    (void)snprintf(rkey, sizeof rkey, "inbox:%s", key);
    return inbox_int(s, "SELECT coalesce(max(id), 0) FROM pic_submission WHERE request_key = ?", rkey, &id) == 0 ? id : -1;
}

int pic_inbox_wake(pic_store *s, const char *session, long max_wakes) {
    sqlite3_stmt *q = NULL;
    long long id = 0, expires = 0, admitted = 0, wakes = 0, made;
    char key[256] = "", sender[300] = "", rkey[300], sid[64], err[PIC_ERR_CAP];
    char *message = NULL;
    int64_t first = 0;
    int dup = 0, rc;
    if (inbox_int(s, "SELECT count(*) FROM pic_submission WHERE session_id = ? AND status = 'admitted'", session, &admitted) != 0) {
        return -1;
    }
    if (admitted) {
        return 0;
    }
    if (sqlite3_prepare_v2(s->db,
                           "SELECT id, msg_key, sender, expires_ms, json_extract(command, '$.message') FROM pic_inbox"
                           " WHERE session_id = ? AND state = 'pending' AND json_extract(command, '$.type') = 'prompt'"
                           " AND json_type(command, '$.message') = 'text' ORDER BY id LIMIT 1",
                           -1, &q, NULL) != SQLITE_OK) {
        return inbox_sql_fail(s);
    }
    sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        id = sqlite3_column_int64(q, 0);
        (void)snprintf(key, sizeof key, "%s", (const char *)sqlite3_column_text(q, 1));
        (void)snprintf(sender, sizeof sender, "%s", (const char *)sqlite3_column_text(q, 2));
        expires = sqlite3_column_int64(q, 3);
        message = strdup((const char *)sqlite3_column_text(q, 4));
    }
    sqlite3_finalize(q);
    if (!id) {
        return 0;
    }
    if (!message) {
        return inbox_fail(s, -1, "out of memory");
    }
    rc = 0;
    if ((made = inbox_woken(s, key)) != 0) { /* admitted before a crash took the settle */
        rc = made < 0 ? -1 : inbox_settle_alone(s, id, "delivered", NULL, made) == 0 ? 2 : -1;
    } else if (expires <= inbox_now_ms()) {
        rc = inbox_settle_alone(s, id, "expired", "expired before it was delivered", 0);
    } else if (strncmp(sender, "wake:", 5) != 0 &&
               inbox_int(s,
                         "SELECT count(*) FROM pic_submission u WHERE u.session_id = ?1 AND u.request_key LIKE 'inbox:%'"
                         " AND u.request_key NOT LIKE 'inbox:wake:%' AND u.id > coalesce((SELECT max(p.id) FROM pic_submission p WHERE p.session_id = ?1"
                         " AND p.request_key NOT LIKE 'inbox:%' AND p.request_key NOT LIKE 'queued-%'), 0)",
                         session, &wakes) != 0) {
        rc = -1;
    } else if (max_wakes > 0 && strncmp(sender, "wake:", 5) != 0 && wakes >= max_wakes) { /* a fan-out: a person's prompt resets it */
        (void)snprintf(err, sizeof err, "refused: %lld requests were started by messages since a person's last prompt"
                       " (grapevine.maxWakes is %ld)", wakes, max_wakes);
        rc = inbox_settle_alone(s, id, "refused", err, 0);
    } else if ((rc = pic_hooks_prompt(s, session, message, sender, &first)) != 0) {
        if (rc == 1) { /* the receiver's policy: a hook refused the peer */
            (void)snprintf(err, sizeof err, "%s", s->err);
            rc = inbox_settle_alone(s, id, "refused", err, 0);
        }
    } else {
        /* the conversation's own model and thinking level, as its last request had them */
        const char *was_model = s->model, *was_thinking = s->thinking;
        char model[200] = "", thinking[32] = "";
        sqlite3_stmt *m = NULL;
        if (sqlite3_prepare_v2(s->db,
                               "SELECT model, thinking FROM pic_submission WHERE session_id = ? AND model IS NOT NULL"
                               " ORDER BY id DESC LIMIT 1",
                               -1, &m, NULL) == SQLITE_OK) {
            sqlite3_bind_text(m, 1, session, -1, SQLITE_STATIC);
            if (sqlite3_step(m) == SQLITE_ROW) {
                (void)snprintf(model, sizeof model, "%s", (const char *)sqlite3_column_text(m, 0));
                if (sqlite3_column_text(m, 1)) {
                    (void)snprintf(thinking, sizeof thinking, "%s", (const char *)sqlite3_column_text(m, 1));
                }
            }
        }
        sqlite3_finalize(m);
        if (!model[0] && strncmp(sender, "wake:", 5) == 0 && /* a loop in a conversation that has run nothing: its model */
            sqlite3_prepare_v2(s->db, "SELECT json_extract(options, '$.model') FROM pic_wake WHERE id = CAST(substr(?1, 6) AS INTEGER)",
                               -1, &m, NULL) == SQLITE_OK) {
            sqlite3_bind_text(m, 1, sender, -1, SQLITE_STATIC);
            if (sqlite3_step(m) == SQLITE_ROW && sqlite3_column_text(m, 0)) {
                (void)snprintf(model, sizeof model, "%s", (const char *)sqlite3_column_text(m, 0));
            }
            sqlite3_finalize(m);
        }
        if (model[0]) {
            s->model = model;
            s->thinking = thinking[0] ? thinking : NULL;
        }
        (void)snprintf(rkey, sizeof rkey, "inbox:%s", key);
        rc = pic_submit_hooked(s, rkey, message, NULL, 0, session, NULL, first, &dup, sid, sizeof sid);
        s->model = was_model;
        s->thinking = was_thinking;
        if (rc == 0 && (made = inbox_woken(s, key)) > 0) {
            pic_fault("inbox_wake");
            rc = inbox_settle_alone(s, id, "delivered", NULL, made) == 0 ? 2 : -1;
        } else if (rc == 0) {
            rc = inbox_fail(s, -1, "the woken request is not in the journal");
        }
    }
    free(message);
    if (rc == 2) {
        s->running = (int64_t)made;
        return 1;
    }
    return rc < 0 ? -1 : 0;
}