/* Deleted conversations (docs/design/session-delete.md): a pic_trash row hides one, removing it
* restores it, and a purge empties its text for good. A purge keeps every row the journal's
* invariants count (entries are numbered without gaps, a tool call keeps its result) and the costs
* of its requests; it touches only requests no other conversation's path reaches, since a fork
* shares the entries it was forked from. */
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "pic.h"
#include "platform.h"
static int tr_fail(pic_store *s) {
(void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db));
return -1;
}
static long long tr_now(void) { return (long long)(pic_platform_get()->wall_ns() / 1000000); }
/* SQL with up to two text parameters, run to its end. */
static int tr_exec(pic_store *s, const char *sql, const char *a, const char *b) {
sqlite3_stmt *q = NULL;
int rc;
if (sqlite3_prepare_v2(s->db, sql, -1, &q, NULL) != SQLITE_OK) {
return tr_fail(s);
}
if (a) {
sqlite3_bind_text(q, 1, a, -1, SQLITE_STATIC);
}
if (b) {
sqlite3_bind_text(q, 2, b, -1, SQLITE_STATIC);
}
rc = sqlite3_step(q) == SQLITE_DONE ? 0 : tr_fail(s);
sqlite3_finalize(q);
return rc;
}
/* The conversation ARG names among those deleted (DELETED) or not: an exact id, else a unique id
* prefix, else a unique name. Purged ones are never found. Its id and title into ID and TITLE. */
static int tr_resolve(pic_store *s, const char *arg, int deleted, char *id, size_t idcap, char *title, size_t tcap) {
static const char *const how[] = {"s.id = ?1", "s.id LIKE ?1 || '%'", "s.name = ?1"};
for (size_t h = 0; h < sizeof how / sizeof how[0]; h++) {
sqlite3_stmt *q = NULL;
char *sql = sqlite3_mprintf("SELECT s.id, coalesce(" PIC_TITLE_SQL("s") ", '') FROM pic_session s WHERE %s AND %s%s LIMIT 2",
how[h], deleted ? "NOT " : "", deleted ? PIC_LISTED_SQL("s") " AND NOT " PIC_PURGED_SQL("s")
: PIC_LISTED_SQL("s"));
int n = 0;
if (!sql || sqlite3_prepare_v2(s->db, sql, -1, &q, NULL) != SQLITE_OK) {
sqlite3_free(sql);
return tr_fail(s);
}
sqlite3_free(sql);
sqlite3_bind_text(q, 1, arg, -1, SQLITE_STATIC);
while (sqlite3_step(q) == SQLITE_ROW) {
if (n++ == 0) {
(void)snprintf(id, idcap, "%s", (const char *)sqlite3_column_text(q, 0));
(void)snprintf(title, tcap, "%s", (const char *)sqlite3_column_text(q, 1));
}
}
sqlite3_finalize(q);
if (n > 1) {
(void)snprintf(s->err, sizeof s->err, "more than one %sconversation is %s %s", deleted ? "deleted " : "",
h == 2 ? "named" : "an id starting", arg);
return -1;
}
if (n == 1) {
return 0;
}
}
(void)snprintf(s->err, sizeof s->err, deleted ? "no deleted conversation %s (pic sessions trash lists them)"
: "no conversation %s (pic sessions lists them)",
arg);
return -1;
}
/* 1 when ARG is exactly the id of a conversation deleted (DELETED) or listed, its id and title in
* ID and TITLE; 0 when not. */
static int tr_exact(pic_store *s, const char *arg, int deleted, char *id, size_t idcap, char *title, size_t tcap) {
sqlite3_stmt *q = NULL;
int found = 0;
if (sqlite3_prepare_v2(s->db,
deleted ? "SELECT s.id, coalesce(" PIC_TITLE_SQL("s") ", '') FROM pic_session s WHERE s.id = ?1 AND NOT "
PIC_LISTED_SQL("s") " AND NOT " PIC_PURGED_SQL("s")
: "SELECT s.id, coalesce(" PIC_TITLE_SQL("s") ", '') FROM pic_session s WHERE s.id = ?1 AND "
PIC_LISTED_SQL("s"),
-1, &q, NULL) != SQLITE_OK) {
return 0;
}
sqlite3_bind_text(q, 1, arg, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW) {
(void)snprintf(id, idcap, "%s", (const char *)sqlite3_column_text(q, 0));
(void)snprintf(title, tcap, "%s", (const char *)sqlite3_column_text(q, 1));
found = 1;
}
sqlite3_finalize(q);
return found;
}
static int tr_has_request(pic_store *s, const char *id, int *yes) {
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(s->db, "SELECT EXISTS (SELECT 1 FROM pic_submission WHERE session_id = ? AND status = 'admitted')", -1,
&q, NULL) != SQLITE_OK) {
return tr_fail(s);
}
sqlite3_bind_text(q, 1, id, -1, SQLITE_STATIC);
*yes = sqlite3_step(q) == SQLITE_ROW && sqlite3_column_int(q, 0);
sqlite3_finalize(q);
return 0;
}
int pic_trash_delete(pic_store *s, const char *session, char *id, size_t idcap, char *title, size_t tcap) {
char when[32];
int unfinished = 0;
long holder;
if (pic_begin(s) != 0) {
return -1;
}
if (tr_exact(s, session, 1, id, idcap, title, tcap) == 1) { /* deleted already: a repeat */
pic_rollback(s);
return 0;
}
if (tr_resolve(s, session, 0, id, idcap, title, tcap) != 0 || tr_has_request(s, id, &unfinished) != 0) {
pic_rollback(s);
return -1;
}
/* In this transaction: a request admitted after it finds the conversation deleted and is
* refused (choose_session), so nothing starts in it between the look and the row. */
holder = pic_lease_holder(s, id);
if (unfinished || (holder != 0 && holder != (long)getpid())) {
pic_rollback(s);
(void)snprintf(s->err, sizeof s->err, "\"%s\" is running. Stop it, then delete it.", *title ? title : id);
return 1;
}
(void)snprintf(when, sizeof when, "%lld", tr_now());
if (tr_exec(s, "INSERT INTO pic_trash(session_id, deleted_ms) VALUES(?1, CAST(?2 AS INTEGER))", id, when) != 0 ||
pic_commit(s) != 0) {
pic_rollback(s);
return -1;
}
return 0;
}
int pic_trash_restore(pic_store *s, const char *session, char *id, size_t idcap, char *title, size_t tcap) {
if (pic_begin(s) != 0) {
return -1;
}
if (session && tr_exact(s, session, 0, id, idcap, title, tcap) == 1) { /* listed already: a repeat */
pic_rollback(s);
return 0;
}
if (session) {
if (tr_resolve(s, session, 1, id, idcap, title, tcap) != 0) {
pic_rollback(s);
return -1;
}
} else {
sqlite3_stmt *q = NULL;
int found = 0;
if (sqlite3_prepare_v2(s->db,
"SELECT s.id, coalesce(" PIC_TITLE_SQL("s") ", '') FROM pic_trash t JOIN pic_session s ON s.id = t.session_id"
" WHERE t.purged_ms IS NULL ORDER BY t.deleted_ms DESC, t.rowid DESC LIMIT 1",
-1, &q, NULL) != SQLITE_OK) {
pic_rollback(s);
return tr_fail(s);
}
if (sqlite3_step(q) == SQLITE_ROW) {
(void)snprintf(id, idcap, "%s", (const char *)sqlite3_column_text(q, 0));
(void)snprintf(title, tcap, "%s", (const char *)sqlite3_column_text(q, 1));
found = 1;
}
sqlite3_finalize(q);
if (!found) {
pic_rollback(s);
(void)snprintf(s->err, sizeof s->err, "no deleted conversation to restore");
return -1;
}
}
if (tr_exec(s, "DELETE FROM pic_trash WHERE session_id = ?1 AND purged_ms IS NULL", id, NULL) != 0 || pic_commit(s) != 0) {
pic_rollback(s);
return -1;
}
return 0;
}
int pic_archive_known(pic_store *s) {
sqlite3_stmt *q = NULL;
int yes = 0;
if (sqlite3_prepare_v2(s->db, "SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'pic_archive'", -1, &q, NULL) ==
SQLITE_OK) {
yes = sqlite3_step(q) == SQLITE_ROW;
}
sqlite3_finalize(q);
return yes;
}
int pic_archive_set(pic_store *s, const char *session, int on, char *id, size_t idcap, char *title, size_t tcap, long long *ms) {
sqlite3_stmt *q = NULL;
char when[32];
*ms = 0;
if (pic_begin(s) != 0) {
return -1;
}
/* made here too: a journal pic remote opened narrowly may not have it yet */
if (pic_exec(s, PIC_ARCHIVE_TABLE_SQL) != 0 || (tr_exact(s, session, 0, id, idcap, title, tcap) != 1 &&
tr_resolve(s, session, 0, id, idcap, title, tcap) != 0)) {
pic_rollback(s);
return -1;
}
(void)snprintf(when, sizeof when, "%lld", tr_now());
if ((on ? tr_exec(s, "INSERT OR IGNORE INTO pic_archive(session_id, archived_ms) VALUES(?1, CAST(?2 AS INTEGER))", id, when)
: tr_exec(s, "DELETE FROM pic_archive WHERE session_id = ?1", id, NULL)) != 0) {
pic_rollback(s);
return -1;
}
if (sqlite3_prepare_v2(s->db, "SELECT archived_ms FROM pic_archive WHERE session_id = ?1", -1, &q, NULL) != SQLITE_OK) {
pic_rollback(s);
return tr_fail(s);
}
sqlite3_bind_text(q, 1, id, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW) {
*ms = sqlite3_column_int64(q, 0);
}
sqlite3_finalize(q);
if (pic_commit(s) != 0) {
pic_rollback(s);
return -1;
}
return 0;
}
int pic_archive_wake(pic_store *s, const char *session) {
return pic_archive_known(s) ? tr_exec(s, "DELETE FROM pic_archive WHERE session_id = ?1", session, NULL) : 0;
}
static int tr_purge(pic_store *s, long long before_ms, const char *only, long long *count);
int pic_trash_purge(pic_store *s, long long before_ms, long long *count) { return tr_purge(s, before_ms, NULL, count); }
int pic_trash_purge_one(pic_store *s, const char *session, long long *count) { return tr_purge(s, LLONG_MAX, session, count); }
int pic_trash_list(pic_store *s, int json, FILE *out) {
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(s->db,
"SELECT s.id, coalesce(" PIC_TITLE_SQL("s") ", '-'), t.deleted_ms,"
" strftime('%Y-%m-%d %H:%M', t.deleted_ms / 1000, 'unixepoch', 'localtime'),"
" t.deleted_ms + ?1 * 86400000, json_object('id', s.id, 'name', s.name, 'title', " PIC_TITLE_SQL("s") ","
" 'deletedMs', t.deleted_ms, 'purgeMs', t.deleted_ms + ?1 * 86400000)"
" FROM pic_trash t JOIN pic_session s ON s.id = t.session_id WHERE t.purged_ms IS NULL"
" ORDER BY t.deleted_ms DESC, t.rowid DESC",
-1, &q, NULL) != SQLITE_OK) {
return tr_fail(s);
}
sqlite3_bind_int64(q, 1, PIC_TRASH_DAYS);
while (sqlite3_step(q) == SQLITE_ROW) {
if (json) {
fprintf(out, "%s\n", (const char *)sqlite3_column_text(q, 5));
} else {
long long left = (sqlite3_column_int64(q, 4) - tr_now() + 86399999) / 86400000;
fprintf(out, "%s deleted %s %s (gone for good in %lld day%s)\n", (const char *)sqlite3_column_text(q, 0),
(const char *)sqlite3_column_text(q, 3), (const char *)sqlite3_column_text(q, 1), left < 0 ? 0 : left,
left == 1 ? "" : "s");
}
}
sqlite3_finalize(q);
return 0;
}
/* The requests a purge empties: of a purged conversation, with no entry on the path of one that is
* not purged (a fork, or the one it was forked from, still listed or still restorable). */
static const char purging_sql[] =
"INSERT INTO temp.pic_purging(id)"
" WITH RECURSIVE p(seq) AS (SELECT s.head_seq FROM pic_session s WHERE s.head_seq IS NOT NULL AND NOT " PIC_PURGED_SQL("s")
" UNION SELECT e.parent_seq FROM pic_entry e JOIN p ON e.seq = p.seq WHERE e.parent_seq IS NOT NULL)"
" SELECT u.id FROM pic_submission u JOIN pic_trash t ON t.session_id = u.session_id WHERE t.purged_ms IS NOT NULL"
" AND NOT EXISTS (SELECT 1 FROM pic_entry e WHERE e.submission_id = u.id AND e.seq IN (SELECT seq FROM p))";
#define PURGED_SESSIONS "(SELECT session_id FROM pic_trash WHERE purged_ms IS NOT NULL)"
#define PURGING_ENTRIES "(SELECT seq FROM pic_entry WHERE submission_id IN (SELECT id FROM temp.pic_purging))"
/* The purged calls' keys: their effects, and minus the rows of the calls those made (loop.c). */
#define PURGING_EFFECTS \
"(SELECT id FROM pic_effect WHERE entry_seq IN " PURGING_ENTRIES " UNION ALL SELECT -n.id FROM pic_nested_effect n" \
" JOIN pic_effect f ON f.id = n.parent_id WHERE f.entry_seq IN " PURGING_ENTRIES ")"
/* File changes to forget: the purged requests' writes and edits, and the finished restores of a
* purged conversation that made no fork still listed. */
#define PURGING_CHANGES \
"(SELECT id FROM pic_file_change WHERE effect_id IN " PURGING_EFFECTS " OR restore_id IN (SELECT r.id FROM pic_restore r" \
" WHERE r.state = 'done' AND r.session_id IN " PURGED_SESSIONS " AND (coalesce(r.forked, '') = '' OR r.forked IN " \
PURGED_SESSIONS ")))"
/* Each leaves the rows and their shape, so pic_check holds: an assistant entry keeps one stub per
* tool call, a delivered message's text stays equal to its entry's, and a finished request keeps
* its status and error. */
static const char *const scrub_sql[] = {
"DELETE FROM pic_attachment WHERE entry_seq IN " PURGING_ENTRIES
" OR queued_id IN (SELECT id FROM pic_queued WHERE submission_id IN (SELECT id FROM temp.pic_purging))",
"UPDATE pic_queued SET text = '' WHERE submission_id IN (SELECT id FROM temp.pic_purging)",
"UPDATE pic_entry SET body = CASE WHEN kind = 'assistant' AND json_valid(body) THEN (SELECT json_group_array(json_object("
" 'type', 'toolCall', 'id', json_extract(c.value, '$.id'), 'name', json_extract(c.value, '$.name'), 'arguments',"
" json_object())) FROM json_each(pic_entry.body) c WHERE json_extract(c.value, '$.type') = 'toolCall')"
" WHEN kind IN ('assistant', 'answer') THEN '[]' ELSE '' END,"
" native = CASE WHEN native IS NULL THEN NULL ELSE '' END WHERE seq IN " PURGING_ENTRIES,
"DELETE FROM pic_output WHERE effect_id IN " PURGING_EFFECTS,
"DELETE FROM pic_file_dir WHERE change_id IN " PURGING_CHANGES,
"UPDATE pic_file_change SET path = '', pre_kept = 0, pre_hash = NULL, post_hash = NULL WHERE id IN " PURGING_CHANGES,
"UPDATE pic_effect SET input = '{}', result = NULL, plan = NULL WHERE entry_seq IN " PURGING_ENTRIES,
"UPDATE pic_nested_effect SET input = '{}', result = NULL, plan = NULL WHERE parent_id IN (SELECT id FROM pic_effect"
" WHERE entry_seq IN " PURGING_ENTRIES ")",
"UPDATE pic_bash SET command = '', output = '', full = NULL, full_sz = NULL WHERE entry_seq IN " PURGING_ENTRIES,
"UPDATE pic_hook_run SET context = NULL, reason = NULL, error = NULL WHERE submission_id IN (SELECT id FROM temp.pic_purging)"
" OR entry_seq IN " PURGING_ENTRIES " OR (submission_id IS NULL AND session_id IN " PURGED_SESSIONS ")",
"UPDATE pic_verdict SET output = NULL, error = NULL WHERE submission_id IN (SELECT id FROM temp.pic_purging)",
"UPDATE pic_generation SET error = NULL WHERE submission_id IN (SELECT id FROM temp.pic_purging)",
"UPDATE pic_submission SET content = '' WHERE id IN (SELECT id FROM temp.pic_purging)",
"UPDATE pic_inbox SET command = NULL, response = NULL WHERE state != 'pending' AND session_id IN " PURGED_SESSIONS,
"UPDATE pic_session SET name = NULL, system_prompt = NULL, tools = NULL, compact_requested = NULL WHERE id IN " PURGED_SESSIONS,
};
/* The deleted conversations to purge: those deleted at or before BEFORE_MS, or ONLY alone. */
static int tr_purge(pic_store *s, long long before_ms, const char *only, long long *count) {
sqlite3_stmt *q = NULL;
char (*ids)[64] = NULL, when[32];
size_t n = 0, cap = 0, held = 0;
int rc = 0, secure = -1;
*count = 0;
if (sqlite3_prepare_v2(s->db,
"SELECT t.session_id FROM pic_trash t WHERE t.purged_ms IS NULL AND t.deleted_ms <= ?1 AND NOT EXISTS"
" (SELECT 1 FROM pic_submission u WHERE u.session_id = t.session_id AND u.status = 'admitted')"
" AND (?2 IS NULL OR t.session_id = ?2)",
-1, &q, NULL) != SQLITE_OK) {
return tr_fail(s);
}
sqlite3_bind_int64(q, 1, before_ms);
if (only) {
sqlite3_bind_text(q, 2, only, -1, SQLITE_STATIC);
}
while (sqlite3_step(q) == SQLITE_ROW) {
if (n == cap) {
char (*grown)[64] = realloc(ids, (cap = cap ? cap * 2 : 8) * sizeof *ids);
if (!grown) {
break;
}
ids = grown;
}
(void)snprintf(ids[n++], sizeof ids[0], "%s", (const char *)sqlite3_column_text(q, 0));
}
sqlite3_finalize(q);
/* Under each one's lease, so no pic works it meanwhile; one held is left for a later purge. */
for (size_t i = 0; i < n; i++) {
int got = pic_leased(s, ids[i]) ? 2 : pic_lease(s, ids[i], 0);
if (got < 0) {
rc = -1;
n = i;
break;
}
if (got == 1) {
s->err[0] = '\0';
ids[i][0] = '\0';
} else if (got == 0) {
held++;
} else {
ids[i][0] = '\0'; /* this process works it: not now */
}
}
if (rc == 0 && held > 0) {
/* Freed pages are overwritten, so the text does not linger in the file. */
if (sqlite3_prepare_v2(s->db, "PRAGMA secure_delete", -1, &q, NULL) == SQLITE_OK && sqlite3_step(q) == SQLITE_ROW) {
secure = sqlite3_column_int(q, 0);
}
sqlite3_finalize(q);
(void)pic_exec(s, "PRAGMA secure_delete = ON");
(void)snprintf(when, sizeof when, "%lld", tr_now());
rc = pic_begin(s);
for (size_t i = 0; rc == 0 && i < n; i++) {
int unfinished = 0;
if (!ids[i][0]) {
continue;
}
rc = tr_has_request(s, ids[i], &unfinished);
if (rc == 0 && !unfinished) {
rc = tr_exec(s, "UPDATE pic_trash SET purged_ms = max(deleted_ms, CAST(?2 AS INTEGER)) WHERE session_id = ?1"
" AND purged_ms IS NULL", ids[i], when);
*count += rc == 0 && sqlite3_changes(s->db) > 0;
}
}
if (rc == 0) {
rc = pic_exec(s, "CREATE TEMP TABLE IF NOT EXISTS pic_purging(id INTEGER PRIMARY KEY); DELETE FROM temp.pic_purging");
}
rc = rc == 0 ? tr_exec(s, purging_sql, NULL, NULL) : rc;
for (size_t i = 0; rc == 0 && i < sizeof scrub_sql / sizeof scrub_sql[0]; i++) {
rc = tr_exec(s, scrub_sql[i], NULL, NULL);
}
if (rc == 0) {
rc = pic_exec(s, "DELETE FROM temp.pic_purging");
}
if (rc != 0 || pic_commit(s) != 0) {
char saved[PIC_ERR_CAP];
(void)snprintf(saved, sizeof saved, "%s", s->err);
pic_rollback(s);
(void)snprintf(s->err, sizeof s->err, "purge: %s", saved);
*count = 0;
rc = -1;
}
if (secure >= 0) {
char sql[48];
(void)snprintf(sql, sizeof sql, "PRAGMA secure_delete = %d", secure);
(void)pic_exec(s, sql);
}
for (size_t i = 0; rc == 0 && i < n; i++) {
char path[4096];
if (ids[i][0] && pic_live_path(s, ids[i], path, sizeof path) == 0) {
(void)unlink(path);
}
}
}
for (size_t i = 0; i < n; i++) {
if (ids[i][0]) {
pic_unlease(s, ids[i]);
}
}
free(ids);
return rc;
}