/* Compaction planning: Pi's algorithm (packages/coding-agent/src/core/
* compaction), over the conversation path in the journal. The loop runs the
* plan: the summary requests, journaled like replies, then the entry. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "compact.h"
#include "userdb.h"
const char pic_summary_system_prompt[] =
"You are a context summarization assistant. Your task is to read a conversation between a user and an AI "
"assistant, then produce a structured summary following the exact format specified.\n\n"
"Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the "
"structured summary.";
static const char summarization_prompt[] =
"The messages above are a conversation to summarize. Create a structured context checkpoint summary that "
"another LLM will use to continue the work.\n\n"
"Use this EXACT format:\n\n"
"## Goal\n"
"[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]\n\n"
"## Constraints & Preferences\n"
"- [Any constraints, preferences, or requirements mentioned by user]\n"
"- [Or \"(none)\" if none were mentioned]\n\n"
"## Progress\n"
"### Done\n"
"- [x] [Completed tasks/changes]\n\n"
"### In Progress\n"
"- [ ] [Current work]\n\n"
"### Blocked\n"
"- [Issues preventing progress, if any]\n\n"
"## Key Decisions\n"
"- **[Decision]**: [Brief rationale]\n\n"
"## Next Steps\n"
"1. [Ordered list of what should happen next]\n\n"
"## Critical Context\n"
"- [Any data, examples, or references needed to continue]\n"
"- [Or \"(none)\" if not applicable]\n\n"
"Keep each section concise. Preserve exact file paths, function names, and error messages.";
static const char update_summarization_prompt[] =
"The messages above are NEW conversation messages to incorporate into the existing summary provided in "
"<previous-summary> tags.\n\n"
"Update the existing structured summary with new information. RULES:\n"
"- PRESERVE all existing information from the previous summary\n"
"- ADD new progress, decisions, and context from the new messages\n"
"- UPDATE the Progress section: move items from \"In Progress\" to \"Done\" when completed\n"
"- UPDATE \"Next Steps\" based on what was accomplished\n"
"- PRESERVE exact file paths, function names, and error messages\n"
"- If something is no longer relevant, you may remove it\n\n"
"Use this EXACT format:\n\n"
"## Goal\n"
"[Preserve existing goals, add new ones if the task expanded]\n\n"
"## Constraints & Preferences\n"
"- [Preserve existing, add new ones discovered]\n\n"
"## Progress\n"
"### Done\n"
"- [x] [Include previously done items AND newly completed items]\n\n"
"### In Progress\n"
"- [ ] [Current work - update based on progress]\n\n"
"### Blocked\n"
"- [Current blockers - remove if resolved]\n\n"
"## Key Decisions\n"
"- **[Decision]**: [Brief rationale] (preserve all previous, add new)\n\n"
"## Next Steps\n"
"1. [Update based on current state]\n\n"
"## Critical Context\n"
"- [Preserve important context, add new if needed]\n\n"
"Keep each section concise. Preserve exact file paths, function names, and error messages.";
static const char turn_prefix_prompt[] =
"The messages above are earlier context from an ongoing conversation. Later messages are stored separately "
"and do not need to be reconstructed.\n\n"
"Create a concise checkpoint of the user's request and the progress shown above. This checkpoint will be "
"placed before the later messages so the conversation can continue with the necessary context.\n\n"
"## Original Request\n"
"[What did the user ask for?]\n\n"
"## Progress So Far\n"
"- [Key decisions and work completed in these messages]\n\n"
"## Context Needed to Continue\n"
"- [Information from these messages needed to understand the later work]\n\n"
"Only summarize information explicitly present above. Do not infer or recreate later messages.";
/* One entry of the context, in order (the summary itself is not a row). */
typedef struct {
sqlite3_int64 seq, tokens, usage; /* usage: the reply's reported context, 0 if none or stale */
int cut, turn_start; /* Pi: a valid cut point; starts a turn */
char *text; /* Pi's serialization, NULL when it serializes to nothing */
} row;
static void free_rows(row *rows, size_t n) {
for (size_t i = 0; i < n; i++) {
free(rows[i].text);
}
free(rows);
}
static char *dup_text(const unsigned char *s) {
size_t n;
char *out;
if (!s) {
return NULL;
}
n = strlen((const char *)s);
out = malloc(n + 1);
if (out) {
memcpy(out, s, n + 1);
}
return out;
}
/* chars/4 rounded up, as Pi estimates, an image counting 4800 chars; a
* reply's usage normalised across the APIs (Anthropic leaves cache tokens
* out of input_tokens). */
#define TOKENS_SQL \
"(CASE WHEN e.kind IN ('user','tool_result') THEN length(e.body)" \
" + 4800 * (SELECT count(*) FROM pic_attachment r WHERE r.entry_seq = e.seq)" \
" WHEN e.kind IN ('instructions','hook','compaction','branch_summary') THEN length(e.body)" \
" ELSE (SELECT coalesce(sum(CASE json_extract(value,'$.type') WHEN 'text' THEN length(json_extract(value,'$.text'))" \
" WHEN 'thinking' THEN length(coalesce(json_extract(value,'$.thinking'),''))" \
" WHEN 'toolCall' THEN length(json_extract(value,'$.name')) + length(json(json_extract(value,'$.arguments')))" \
" ELSE 0 END), 0) FROM json_each(e.body)) END + 3) / 4"
#define USAGE_SQL \
"CASE WHEN v.fresh AND e.kind IN ('assistant','answer') THEN (SELECT coalesce(json_extract(g.usage,'$.total_tokens')," \
" coalesce(json_extract(g.usage,'$.input_tokens'), json_extract(g.usage,'$.prompt_tokens'), 0)" \
" + coalesce(json_extract(g.usage,'$.output_tokens'), json_extract(g.usage,'$.completion_tokens'), 0)" \
" + coalesce(json_extract(g.usage,'$.cache_read_input_tokens'), 0)" \
" + coalesce(json_extract(g.usage,'$.cache_creation_input_tokens'), 0))" \
" FROM pic_generation g WHERE g.entry_seq = e.seq AND g.state = 'done' AND g.purpose = 'reply') END"
/* Pi's serializeConversation, one entry: thinking left out, tool results cut
* at 2000 characters, tool calls as name(key=JSON, ...). */
#define SERIALIZE_SQL \
"CASE e.kind" \
" WHEN 'user' THEN CASE WHEN e.body != '' THEN '[User]: ' || e.body END" \
" WHEN 'instructions' THEN '[User]: <project_instructions_update>' || char(10) || e.body || char(10) ||" \
" '</project_instructions_update>'" \
" WHEN 'hook' THEN '[User]: ' || e.body" \
" WHEN 'compaction' THEN '[User]: ' || " PIC_SUMMARY_SQL("e.body") \
" WHEN 'branch_summary' THEN '[User]: ' || " PIC_BRANCH_SUMMARY_SQL("e.body") \
" WHEN 'tool_result' THEN CASE WHEN e.body != '' THEN '[Tool result]: ' || CASE WHEN length(e.body) <= 2000" \
" THEN e.body ELSE substr(e.body, 1, 2000) || char(10) || char(10) || '[... ' || (length(e.body) - 2000) ||" \
" ' more characters truncated]' END END" \
" ELSE nullif(coalesce((SELECT '[Assistant]: ' || group_concat(json_extract(value,'$.text'), char(10))" \
" FROM json_each(e.body) WHERE json_extract(value,'$.type') = 'text' HAVING count(*) > 0), '')" \
" || CASE WHEN EXISTS (SELECT 1 FROM json_each(e.body) WHERE json_extract(value,'$.type') = 'text')" \
" AND EXISTS (SELECT 1 FROM json_each(e.body) WHERE json_extract(value,'$.type') = 'toolCall')" \
" THEN char(10) || char(10) ELSE '' END" \
" || coalesce((SELECT '[Assistant tool calls]: ' || group_concat(json_extract(c.value,'$.name') || '(' ||" \
" coalesce((SELECT group_concat(a.key || '=' || CASE a.type WHEN 'text' THEN json_quote(a.value)" \
" WHEN 'true' THEN 'true' WHEN 'false' THEN 'false' WHEN 'null' THEN 'null' ELSE a.value END, ', ')" \
" FROM json_each(c.value, '$.arguments') a), '') || ')', '; ')" \
" FROM json_each(e.body) c WHERE json_extract(c.value,'$.type') = 'toolCall' HAVING count(*) > 0), ''), '')" \
" END"
static int load_rows(sqlite3 *db, int64_t submission, row **out, size_t *count) {
sqlite3_stmt *q = NULL;
row *rows = NULL;
size_t n = 0, cap = 0;
int step;
*out = NULL;
*count = 0;
if (sqlite3_prepare_v2(db,
PIC_CONTEXT_CTE "SELECT e.seq, e.kind, " TOKENS_SQL ", " USAGE_SQL ", " SERIALIZE_SQL
" FROM pic_entry e JOIN v ON v.seq = e.seq CROSS JOIN kk"
" WHERE e.kind != 'compaction' ORDER BY e.seq",
-1, &q, NULL) != SQLITE_OK) {
return -1;
}
sqlite3_bind_int64(q, 1, submission);
while ((step = sqlite3_step(q)) == SQLITE_ROW) {
const char *kind = (const char *)sqlite3_column_text(q, 1);
if (n == cap) {
row *grown = realloc(rows, (cap = cap ? cap * 2 : 64) * sizeof *rows);
if (!grown) {
break;
}
rows = grown;
}
rows[n].seq = sqlite3_column_int64(q, 0);
rows[n].tokens = sqlite3_column_int64(q, 2);
rows[n].usage = sqlite3_column_int64(q, 3);
rows[n].cut = strcmp(kind, "tool_result") != 0;
rows[n].turn_start = strcmp(kind, "user") == 0 || strcmp(kind, "instructions") == 0 ||
strcmp(kind, "branch_summary") == 0;
rows[n].text = dup_text(sqlite3_column_text(q, 4));
n++;
}
sqlite3_finalize(q);
if (step != SQLITE_DONE) {
free_rows(rows, n);
return -1;
}
*out = rows;
*count = n;
return 0;
}
/* The latest compaction's summary and file lists, or NULLs. */
static int previous(sqlite3 *db, int64_t submission, char **summary, char **details) {
sqlite3_stmt *q = NULL;
*summary = *details = NULL;
if (sqlite3_prepare_v2(db, PIC_CONTEXT_CTE "SELECT e.body, e.native FROM pic_entry e JOIN kk ON e.seq = kk.cseq", -1,
&q, NULL) != SQLITE_OK) {
return -1;
}
sqlite3_bind_int64(q, 1, submission);
if (sqlite3_step(q) == SQLITE_ROW) {
*summary = dup_text(sqlite3_column_text(q, 0));
*details = dup_text(sqlite3_column_text(q, 1));
}
sqlite3_finalize(q);
return 0;
}
/* Pi's estimate: the last fresh reply's usage plus chars/4 for what followed;
* without one, chars/4 for everything, the summary included. */
static sqlite3_int64 estimate(const row *rows, size_t n, const char *summary) {
sqlite3_int64 tokens = 0;
size_t i = n;
while (i > 0 && rows[i - 1].usage <= 0) {
i--;
}
if (i > 0) {
tokens = rows[i - 1].usage;
} else if (summary) {
tokens = ((sqlite3_int64)strlen(summary) + 3) / 4;
}
for (; i < n; i++) {
tokens += rows[i].tokens;
}
return tokens;
}
/* Real tokens per chars/4 token: the last fresh reply's reported input
* against chars/4 of the request it answered (the summary and every entry
* before it), within PIC_CALIBRATION_MIN to _MAX; 1 without such a reply.
* The system prompt and tools are in the reported input and not in the
* estimate, which errs toward keeping less. */
static int calibration(sqlite3 *db, int64_t submission, const row *rows, size_t n, const char *summary, double *ratio) {
sqlite3_stmt *q = NULL;
sqlite3_int64 seq = 0, input = 0, est = summary ? ((sqlite3_int64)strlen(summary) + 3) / 4 : 0;
double r;
*ratio = 1.0;
if (sqlite3_prepare_v2(db,
PIC_CONTEXT_CTE "SELECT e.seq, coalesce(json_extract(g.usage,'$.input_tokens'),"
" json_extract(g.usage,'$.prompt_tokens'), 0)"
" + coalesce(json_extract(g.usage,'$.cache_read_input_tokens'), 0)"
" + coalesce(json_extract(g.usage,'$.cache_creation_input_tokens'), 0) AS input"
" FROM pic_entry e JOIN v ON v.seq = e.seq JOIN pic_generation g ON g.entry_seq = e.seq"
" AND g.state = 'done' AND g.purpose = 'reply'"
" WHERE v.fresh AND e.kind IN ('assistant','answer') AND input > 0 ORDER BY e.seq DESC LIMIT 1",
-1, &q, NULL) != SQLITE_OK) {
return -1;
}
sqlite3_bind_int64(q, 1, submission);
if (sqlite3_step(q) == SQLITE_ROW) {
seq = sqlite3_column_int64(q, 0);
input = sqlite3_column_int64(q, 1);
}
sqlite3_finalize(q);
for (size_t i = 0; i < n && rows[i].seq < seq; i++) {
est += rows[i].tokens;
}
if (input <= 0 || est <= 0) {
return 0;
}
r = (double)input / (double)est;
*ratio = r < PIC_CALIBRATION_MIN ? PIC_CALIBRATION_MIN : r > PIC_CALIBRATION_MAX ? PIC_CALIBRATION_MAX : r;
return 0;
}
/* Pi's estimate of the next request and the calibration (NULL: not wanted). */
static int measure(sqlite3 *db, int64_t submission, long *tokens, double *ratio) {
row *rows;
size_t n;
char *summary, *details;
int rc;
if (load_rows(db, submission, &rows, &n) != 0) {
return -1;
}
if (previous(db, submission, &summary, &details) != 0) {
free_rows(rows, n);
return -1;
}
*tokens = (long)estimate(rows, n, summary);
rc = ratio ? calibration(db, submission, rows, n, summary, ratio) : 0;
free_rows(rows, n);
free(summary);
free(details);
return rc;
}
int pic_context_tokens(sqlite3 *db, int64_t submission, long *tokens) {
return measure(db, submission, tokens, NULL);
}
/* A builder's text in malloc'd memory (sqlite3_str uses SQLite's allocator). */
static char *finish(sqlite3_str *t) {
int failed = sqlite3_str_errcode(t) != SQLITE_OK;
char *s = sqlite3_str_finish(t), *out = failed ? NULL : dup_text((const unsigned char *)(s ? s : ""));
sqlite3_free(s);
return out;
}
static void serialize(sqlite3_str *out, const row *rows, size_t from, size_t to) {
int any = 0;
for (size_t i = from; i < to; i++) {
if (rows[i].text) {
sqlite3_str_appendall(out, any ? "\n\n" : "");
sqlite3_str_appendall(out, rows[i].text);
any = 1;
}
}
}
/* Pi's computeFileLists and formatFileOperations over ops(path, w), w for a
* write or edit: the lists as JSON, then each section present. */
#define FILES_SQL \
" r(path) AS (SELECT DISTINCT path FROM ops WHERE path NOT IN (SELECT path FROM ops WHERE w) ORDER BY path)," \
" m(path) AS (SELECT DISTINCT path FROM ops WHERE w ORDER BY path)" \
" SELECT json_object('readFiles', json((SELECT json_group_array(path) FROM r))," \
" 'modifiedFiles', json((SELECT json_group_array(path) FROM m)))," \
" (SELECT '<read-files>' || char(10) || group_concat(path, char(10)) || char(10) || '</read-files>'" \
" FROM r HAVING count(*) > 0)," \
" (SELECT '<modified-files>' || char(10) || group_concat(path, char(10)) || char(10) || '</modified-files>'" \
" FROM m HAVING count(*) > 0)"
/* Steps a FILES_SQL query (and finalizes it): the JSON lists in *json, the
* text appended to the summary in *suffix (both malloc'd). */
static int read_files(sqlite3 *db, sqlite3_stmt *q, char **json, char **suffix) {
*json = *suffix = NULL;
if (sqlite3_step(q) == SQLITE_ROW) {
/* Pi: "\n\n" + the sections present, joined by a blank line. */
sqlite3_str *t = sqlite3_str_new(db);
for (int i = 1; i <= 2; i++) {
if (sqlite3_column_text(q, i)) {
sqlite3_str_appendf(t, "\n\n%s", (const char *)sqlite3_column_text(q, i));
}
}
*json = dup_text(sqlite3_column_text(q, 0));
*suffix = finish(t);
}
sqlite3_finalize(q);
return *json && *suffix ? 0 : -1;
}
/* Read and modified files, as Pi tracks them: the previous compaction's
* lists plus read, write and edit calls in the entries summarized now. */
static int file_lists(sqlite3 *db, int64_t submission, sqlite3_int64 first_kept, const char *details, char **json,
char **suffix) {
sqlite3_stmt *q = NULL;
*json = *suffix = NULL;
if (sqlite3_prepare_v2(
db,
PIC_CONTEXT_CTE
", ops(path, w) AS ("
" SELECT json_extract(c.value,'$.arguments.path'), json_extract(c.value,'$.name') != 'read'"
" FROM pic_entry e JOIN v ON v.seq = e.seq, json_each(e.body) c"
" WHERE e.kind IN ('assistant','answer') AND e.seq < ?2 AND json_extract(c.value,'$.type') = 'toolCall'"
" AND json_extract(c.value,'$.name') IN ('read','write','edit')"
" AND json_type(c.value,'$.arguments.path') = 'text'"
" UNION ALL SELECT value, 0 FROM json_each(coalesce(json_extract(?3, '$.readFiles'), '[]'))"
" UNION ALL SELECT value, 1 FROM json_each(coalesce(json_extract(?3, '$.modifiedFiles'), '[]'))),"
/* Lists from before 2026-11-19 were stored as JSON text inside the
* object; json_extract gives the array text either way. */
FILES_SQL,
-1, &q, NULL) != SQLITE_OK) {
return -1;
}
sqlite3_bind_int64(q, 1, submission);
sqlite3_bind_int64(q, 2, first_kept);
if (details) {
sqlite3_bind_text(q, 3, details, -1, SQLITE_STATIC);
}
return read_files(db, q, json, suffix);
}
void pic_compaction_free(pic_compaction *c) {
free(c->history_prompt);
free(c->prefix_prompt);
free(c->previous_summary);
free(c->files);
free(c->details);
memset(c, 0, sizeof *c);
}
int pic_compaction_plan(sqlite3 *db, int64_t submission, const char *instructions, long keep_recent_tokens,
pic_compaction *c) {
row *rows;
size_t n, cut = 0, history_end, turn_start = 0;
char *summary, *details;
int split = 0, have_cut = 0;
sqlite3_int64 acc = 0;
memset(c, 0, sizeof *c);
if (load_rows(db, submission, &rows, &n) != 0) {
return -1;
}
if (previous(db, submission, &summary, &details) != 0) {
free_rows(rows, n);
return -1;
}
c->tokens_before = estimate(rows, n, summary);
/* Walk back from the newest entry until keepRecentTokens are kept, then
* cut at the nearest valid point at or after it (never a tool result). */
for (size_t i = 0; i < n; i++) {
if (rows[i].cut) {
cut = i;
have_cut = 1;
break;
}
}
if (have_cut) {
for (size_t i = n; i-- > 0;) {
if (rows[i].tokens == 0) {
continue;
}
acc += rows[i].tokens;
if (acc >= keep_recent_tokens) {
size_t j = i;
while (j < n && !rows[j].cut) {
j++;
}
if (j == n) {
for (j = n; j-- > 0 && !rows[j].cut;) {
}
}
cut = j;
break;
}
}
if (!rows[cut].turn_start) {
for (size_t i = cut + 1; i-- > 0;) {
if (rows[i].turn_start) {
turn_start = i;
split = 1;
break;
}
}
}
}
history_end = split ? turn_start : cut;
if (!have_cut || (history_end == 0 && (!split || turn_start == cut))) {
free_rows(rows, n);
free(summary);
free(details);
return 1; /* nothing to summarize */
}
c->first_kept_seq = rows[cut].seq;
c->split = split;
if (history_end > 0) {
sqlite3_str *p = sqlite3_str_new(db);
sqlite3_str_appendall(p, "<conversation>\n");
serialize(p, rows, 0, history_end);
sqlite3_str_appendall(p, "\n</conversation>\n\n");
if (summary) {
sqlite3_str_appendf(p, "<previous-summary>\n%s\n</previous-summary>\n\n", summary);
}
sqlite3_str_appendall(p, summary ? update_summarization_prompt : summarization_prompt);
if (instructions && *instructions) {
sqlite3_str_appendf(p, "\n\nAdditional focus: %s", instructions);
}
c->history_prompt = finish(p);
}
if (split) {
sqlite3_str *p = sqlite3_str_new(db);
sqlite3_str_appendall(p, "# Conversation\n");
serialize(p, rows, turn_start, cut);
sqlite3_str_appendall(p, "\n\n# Instructions\n");
sqlite3_str_appendall(p, turn_prefix_prompt);
if (instructions && *instructions) {
sqlite3_str_appendf(p, "\n\nAdditional focus: %s", instructions);
}
c->prefix_prompt = finish(p);
}
free_rows(rows, n);
c->previous_summary = summary;
if ((history_end > 0 && !c->history_prompt) || (split && !c->prefix_prompt) ||
file_lists(db, submission, c->first_kept_seq, details, &c->details, &c->files) != 0) {
free(details);
pic_compaction_free(c);
return -1;
}
free(details);
return 0;
}
/* A non-negative whole number at PATH of the JSON setting text, else DEF
* (Pi refuses another value; pic keeps the default). The model's override
* (modelOverrides["provider/model"]) wins when it has one. */
static long setting_tokens(sqlite3 *db, const char *json, const char *model, const char *field, long def) {
sqlite3_stmt *q = NULL;
long out = def;
if (!json || sqlite3_prepare_v2(db,
"SELECT coalesce((SELECT json_extract(o.value, '$.' || ?3) FROM json_each(?1, '$.modelOverrides') o"
" WHERE o.key = ?2 AND o.type = 'object' AND json_type(o.value, '$.' || ?3) = 'integer'"
" AND json_extract(o.value, '$.' || ?3) >= 0),"
" CASE WHEN json_type(?1, '$.' || ?3) = 'integer' AND json_extract(?1, '$.' || ?3) >= 0"
" THEN json_extract(?1, '$.' || ?3) END)"
" WHERE json_valid(?1) AND json_type(?1) = 'object'",
-1, &q, NULL) != SQLITE_OK) {
return def;
}
sqlite3_bind_text(q, 1, json, -1, SQLITE_STATIC);
sqlite3_bind_text(q, 2, model ? model : "", -1, SQLITE_STATIC);
sqlite3_bind_text(q, 3, field, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) == SQLITE_INTEGER) {
out = (long)sqlite3_column_int64(q, 0);
}
sqlite3_finalize(q);
return out;
}
/* Whether the JSON setting text has false at PATH (Pi's `?? true`). */
static int setting_false(sqlite3 *db, const char *json, const char *path) {
sqlite3_stmt *q = NULL;
int out = 0;
if (json && sqlite3_prepare_v2(db, "SELECT json_valid(?1) AND json_type(?1, ?2) = 'false'", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, json, -1, SQLITE_STATIC);
sqlite3_bind_text(q, 2, path, -1, SQLITE_STATIC);
out = sqlite3_step(q) == SQLITE_ROW && sqlite3_column_int(q, 0);
}
sqlite3_finalize(q);
return out;
}
static int setting_true(sqlite3 *db, const char *json, const char *path) {
sqlite3_stmt *q = NULL;
int out = 0;
if (json && sqlite3_prepare_v2(db, "SELECT json_valid(?1) AND json_type(?1, ?2) = 'true'", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, json, -1, SQLITE_STATIC);
sqlite3_bind_text(q, 2, path, -1, SQLITE_STATIC);
out = sqlite3_step(q) == SQLITE_ROW && sqlite3_column_int(q, 0);
}
sqlite3_finalize(q);
return out;
}
void pic_compaction_settings_get(const char *model, pic_compaction_settings *out) {
sqlite3 *db = pic_userdb(NULL, 0);
char *json = db ? pic_setting("compaction") : NULL;
out->enabled = !setting_false(db, json, "$.enabled");
out->reserve_tokens = setting_tokens(db, json, model, "reserveTokens", PIC_RESERVE_TOKENS);
out->keep_recent_tokens = setting_tokens(db, json, model, "keepRecentTokens", PIC_KEEP_RECENT_TOKENS);
free(json);
}
void pic_branch_settings_get(pic_branch_settings *out) {
sqlite3 *db = pic_userdb(NULL, 0);
char *json = db ? pic_setting("branchSummary") : NULL;
out->reserve_tokens = setting_tokens(db, json, NULL, "reserveTokens", PIC_BRANCH_RESERVE_TOKENS);
out->skip_prompt = setting_true(db, json, "$.skipPrompt");
free(json);
}
/* ---- branch summaries ----------------------------------------------------- */
static const char branch_summary_prompt[] =
"Create a structured summary of this conversation branch for context when returning later.\n\n"
"Use this EXACT format:\n\n"
"## Goal\n"
"[What was the user trying to accomplish in this branch?]\n\n"
"## Constraints & Preferences\n"
"- [Any constraints, preferences, or requirements mentioned]\n"
"- [Or \"(none)\" if none were mentioned]\n\n"
"## Progress\n"
"### Done\n"
"- [x] [Completed tasks/changes]\n\n"
"### In Progress\n"
"- [ ] [Work that was started but not finished]\n\n"
"### Blocked\n"
"- [Issues preventing progress, if any]\n\n"
"## Key Decisions\n"
"- **[Decision]**: [Brief rationale]\n\n"
"## Next Steps\n"
"1. [What should happen next to continue this work]\n\n"
"Keep each section concise. Preserve exact file paths, function names, and error messages.";
const char pic_branch_summary_preamble[] =
"The user explored a different conversation branch before returning here.\nSummary of that exploration:\n\n";
/* Pi's collectEntriesForBranchSummary: the entries on FROM's path below its
* deepest common ancestor with TARGET's (?1 FROM, ?2 TARGET); entry numbers
* grow down a path, so that ancestor is the largest number on both. */
#define BRANCH_CTE \
"WITH RECURSIVE o(seq) AS (SELECT ?1 UNION ALL SELECT x.parent_seq FROM pic_entry x JOIN o ON x.seq = o.seq" \
" WHERE x.parent_seq IS NOT NULL)," \
" t(seq) AS (SELECT ?2 UNION ALL SELECT x.parent_seq FROM pic_entry x JOIN t ON x.seq = t.seq" \
" WHERE x.parent_seq IS NOT NULL)," \
" a(seq) AS (SELECT coalesce(max(o.seq), 0) FROM o JOIN t ON t.seq = o.seq)," \
" b(seq) AS (SELECT o.seq FROM o, a WHERE o.seq > a.seq)"
void pic_branch_free(pic_branch *b) {
free(b->prompt);
free(b->files);
free(b->details);
memset(b, 0, sizeof *b);
}
int pic_branch_plan(sqlite3 *db, sqlite3_int64 from, sqlite3_int64 target, long budget, const char *instructions,
pic_branch *b) {
sqlite3_stmt *q = NULL;
row *rows = NULL;
size_t n = 0, cap = 0, first = 0, ops_from;
int step, *is_summary = NULL;
sqlite3_int64 total = 0;
memset(b, 0, sizeof *b);
/* Pi's prepareBranchEntries: tool results are left out (their calls say
* enough); summaries are messages as convertToLlm makes them. */
if (sqlite3_prepare_v2(db,
BRANCH_CTE " SELECT e.seq, e.kind, " TOKENS_SQL ", " SERIALIZE_SQL
" FROM pic_entry e JOIN b ON b.seq = e.seq WHERE e.kind != 'tool_result' ORDER BY e.seq",
-1, &q, NULL) != SQLITE_OK) {
return -1;
}
sqlite3_bind_int64(q, 1, from);
sqlite3_bind_int64(q, 2, target);
while ((step = sqlite3_step(q)) == SQLITE_ROW) {
const char *kind = (const char *)sqlite3_column_text(q, 1);
if (n == cap) {
row *grown = realloc(rows, (cap = cap ? cap * 2 : 64) * sizeof *rows);
int *flags = realloc(is_summary, cap * sizeof *is_summary);
if (grown) {
rows = grown;
}
if (flags) {
is_summary = flags;
}
if (!grown || !flags) {
break;
}
}
rows[n].seq = sqlite3_column_int64(q, 0);
rows[n].tokens = sqlite3_column_int64(q, 2);
rows[n].text = dup_text(sqlite3_column_text(q, 3));
is_summary[n] = strcmp(kind, "compaction") == 0 || strcmp(kind, "branch_summary") == 0;
n++;
}
sqlite3_finalize(q);
if (step != SQLITE_DONE) {
free_rows(rows, n);
free(is_summary);
return -1;
}
if (n == 0) {
free(rows);
free(is_summary);
return 1; /* nothing on the branch left */
}
/* Newest to oldest until the budget is spent; a summary that does not fit
* still goes in while under 90% of it. File operations are taken from
* the message that stopped the walk too, as Pi extracts them first. */
first = n;
ops_from = n;
for (size_t i = n; i-- > 0;) {
ops_from = i;
if (budget > 0 && total + rows[i].tokens > budget) {
if (is_summary[i] && (double)total < (double)budget * 0.9) {
first = i;
total += rows[i].tokens;
}
break;
}
first = i;
total += rows[i].tokens;
}
free(is_summary);
if (first < n) {
sqlite3_str *p = sqlite3_str_new(db);
sqlite3_str_appendall(p, "<conversation>\n");
serialize(p, rows, first, n);
sqlite3_str_appendall(p, "\n</conversation>\n\n");
sqlite3_str_appendall(p, branch_summary_prompt);
if (instructions && *instructions) {
sqlite3_str_appendf(p, "\n\nAdditional focus: %s", instructions);
}
b->prompt = finish(p);
if (!b->prompt) {
free_rows(rows, n);
return -1;
}
}
/* Files: read, write and edit calls from where the walk stopped, and the
* lists of every earlier branch summary on the branch. */
if (sqlite3_prepare_v2(
db,
BRANCH_CTE ", ops(path, w) AS ("
" SELECT json_extract(c.value,'$.arguments.path'), json_extract(c.value,'$.name') != 'read'"
" FROM pic_entry e JOIN b ON b.seq = e.seq, json_each(e.body) c"
" WHERE e.kind IN ('assistant','answer') AND e.seq >= ?3 AND json_extract(c.value,'$.type') = 'toolCall'"
" AND json_extract(c.value,'$.name') IN ('read','write','edit')"
" AND json_type(c.value,'$.arguments.path') = 'text'"
" UNION ALL SELECT r.value, 0 FROM pic_entry e JOIN b ON b.seq = e.seq,"
" json_each(coalesce(json_extract(e.native, '$.readFiles'), '[]')) r WHERE e.kind = 'branch_summary'"
" UNION ALL SELECT r.value, 1 FROM pic_entry e JOIN b ON b.seq = e.seq,"
" json_each(coalesce(json_extract(e.native, '$.modifiedFiles'), '[]')) r WHERE e.kind = 'branch_summary'),"
FILES_SQL,
-1, &q, NULL) != SQLITE_OK) {
free_rows(rows, n);
pic_branch_free(b);
return -1;
}
sqlite3_bind_int64(q, 1, from);
sqlite3_bind_int64(q, 2, target);
sqlite3_bind_int64(q, 3, rows[ops_from].seq);
free_rows(rows, n);
if (read_files(db, q, &b->details, &b->files) != 0) {
pic_branch_free(b);
return -1;
}
return 0;
}
/* ---- the summary-free plan ------------------------------------------------- */
int pic_compaction_trim(sqlite3 *db, int64_t submission, long keep_recent_tokens, double ratio, sqlite3_int64 *first_kept,
sqlite3_int64 *tokens_before, char **body, char **details) {
row *rows;
size_t n, cut = 0;
char *summary, *prev_details, *files = NULL;
sqlite3_int64 acc = 0, dropped = 0;
/* KEEP in chars/4 tokens: the real tokens over the calibration. */
double keep = (double)keep_recent_tokens / (ratio > 0.0 ? ratio : 1.0);
int found = 0;
*body = *details = NULL;
if (load_rows(db, submission, &rows, &n) != 0) {
return -1;
}
if (previous(db, submission, &summary, &prev_details) != 0) {
free_rows(rows, n);
return -1;
}
*tokens_before = estimate(rows, n, summary);
/* The newest entries until KEEP tokens are kept, then back to the
* start of that turn (a user message), so the kept part opens with what
* was asked; when that would keep more than twice KEEP (one long task),
* back only to the nearest reply or user message. Never from a tool
* result, so every tool call stays with its result and at least KEEP is
* kept. */
for (size_t i = n; i-- > 0;) {
acc += rows[i].tokens;
if ((double)acc >= keep) {
sqlite3_int64 more = acc - rows[i].tokens;
for (size_t j = i + 1; j-- > 0;) {
more += rows[j].tokens;
if (rows[j].cut && !found) {
cut = j;
found = 1;
}
if (rows[j].turn_start) {
if ((double)more <= 2.0 * keep) {
cut = j;
}
break;
}
if ((double)more > 2.0 * keep) {
break;
}
}
break;
}
}
free(summary);
if (!found || cut == 0) {
free_rows(rows, n);
free(prev_details);
return 1; /* everything fits: nothing to drop */
}
for (size_t i = 0; i < cut; i++) {
dropped += rows[i].tokens;
}
*first_kept = rows[cut].seq;
free_rows(rows, n);
if (file_lists(db, submission, *first_kept, prev_details, details, &files) != 0) {
free(prev_details);
free(*details);
*details = NULL;
return -1;
}
free(prev_details);
{
char *text = sqlite3_mprintf("Earlier messages (about %lld tokens) were dropped to keep the context small; no summary"
" was made. The newest messages follow.%s",
(long long)((double)dropped * (ratio > 0.0 ? ratio : 1.0)), files);
*body = text ? dup_text((const unsigned char *)text) : NULL;
sqlite3_free(text);
}
free(files);
if (!*body) {
free(*details);
*details = NULL;
return -1;
}
return 0;
}
/* ---- the context-policy component (policy.h) ------------------------------ */
static struct {
int set, on;
long seconds, floor;
} lapse_conf = {0, 1, -1, PIC_LAPSE_FLOOR};
void pic_lapse_configure(int on, long seconds, long floor) {
lapse_conf.set = 1;
lapse_conf.on = on;
lapse_conf.seconds = seconds;
lapse_conf.floor = floor;
}
/* The holdout share: PIC_LAPSE_HOLDOUT, else the lapseHoldout setting, else
* the default. main.c refuses a value outside 0 to 1 before any run. */
static double lapse_holdout(void) {
const char *e = getenv("PIC_LAPSE_HOLDOUT");
char *owned = NULL, *end = NULL;
double h = PIC_LAPSE_HOLDOUT;
const char *v = e && *e ? e : (pic_userdb(NULL, 0) ? (owned = pic_setting("lapseHoldout")) : NULL);
if (v && *v) {
double d = strtod(v, &end);
if (end && !*end && d >= 0.0 && d <= 1.0) {
h = d;
}
}
free(owned);
return h;
}
const char *pic_lapse_mode(void) {
char *v = pic_userdb(NULL, 0) ? pic_setting("lapseMode") : NULL;
const char *mode = v && strcmp(v, "summary") == 0 ? "summary" : "trim";
free(v);
return mode;
}
/* Threshold first (Pi's: the context past the window less the reserve, as
* a summary); else a lapse: before a submission's first request, idle past
* the cache's lifetime with lapse compaction on, kept with its arm (small at
* or under the floor, holdout drawn at random, else compact in lapseMode)
* and the calibration a trim measures with. */
static int policy_answer(sqlite3 *db, int64_t submission, int64_t turn, const char *facts, pic_hook_answer *a) {
sqlite3_stmt *q = NULL;
char model[160] = "";
long window = 0, cache = 0, tokens = 0, lifetime;
sqlite3_int64 idle = -1;
int first = 1;
double ratio = 1.0;
pic_compaction_settings cs;
const char *arm = "compact", *mode;
(void)turn;
if (sqlite3_prepare_v2(db,
"SELECT coalesce(json_extract(?1,'$.model'), ''), coalesce(json_extract(?1,'$.contextWindow'), 0),"
" coalesce(json_extract(?1,'$.cacheSeconds'), 0), coalesce(json_extract(?1,'$.idleSeconds'), -1),"
" coalesce(json_extract(?1,'$.firstRequest'), 1)",
-1, &q, NULL) != SQLITE_OK) {
return -1;
}
sqlite3_bind_text(q, 1, facts ? facts : "{}", -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW) {
(void)snprintf(model, sizeof model, "%s", (const char *)sqlite3_column_text(q, 0));
window = (long)sqlite3_column_int64(q, 1);
cache = (long)sqlite3_column_int64(q, 2);
idle = sqlite3_column_int64(q, 3);
first = sqlite3_column_int(q, 4) != 0;
}
sqlite3_finalize(q);
q = NULL;
if (measure(db, submission, &tokens, &ratio) != 0) {
return -1;
}
pic_compaction_settings_get(model, &cs);
if (cs.enabled && window > 0 && tokens > window - cs.reserve_tokens) {
a->reason = dup_text((const unsigned char *)"threshold");
{
char *t = sqlite3_mprintf("{\"compact\":\"summary\",\"tokens\":%ld}", tokens);
a->context = t ? dup_text((const unsigned char *)t) : NULL;
sqlite3_free(t);
}
return a->reason && a->context ? 0 : -1;
}
/* A lapse is the user coming back after the cache expired: only before
* a submission's first request. A long tool call inside one is not. */
lifetime = lapse_conf.seconds >= 0 ? lapse_conf.seconds : cache;
if (!first || !lapse_conf.on || lifetime <= 0 || idle <= lifetime) {
return 0;
}
mode = pic_lapse_mode();
if (tokens <= lapse_conf.floor) {
arm = "small";
} else {
double h = lapse_holdout();
if (h > 0.0 && sqlite3_prepare_v2(db, "SELECT (random() & 4294967295) / 4294967296.0", -1, &q, NULL) == SQLITE_OK &&
sqlite3_step(q) == SQLITE_ROW && sqlite3_column_double(q, 0) < h) {
arm = "holdout";
}
sqlite3_finalize(q);
}
{
char *t = sqlite3_mprintf("{%s%s%s\"arm\":\"%s\",\"mode\":\"%s\",\"idle\":%lld,\"tokens\":%ld,\"calibration\":%.3f}",
strcmp(arm, "compact") == 0 ? "\"compact\":\"" : "", strcmp(arm, "compact") == 0 ? mode : "",
strcmp(arm, "compact") == 0 ? "\"," : "", arm, mode, (long long)idle, tokens, ratio);
a->context = t ? dup_text((const unsigned char *)t) : NULL;
sqlite3_free(t);
}
a->reason = dup_text((const unsigned char *)"lapse");
return a->reason && a->context ? 0 : -1;
}
/* What a plan keeps for join: a summary's plan or a branch's. */
typedef struct {
int branch;
pic_compaction c;
pic_branch b;
} plan_state;
static void policy_plan_free(pic_compact_plan *p) {
plan_state *st = p->state;
if (st) {
if (st->branch) {
pic_branch_free(&st->b);
} else {
pic_compaction_free(&st->c);
}
free(st);
} else {
free(p->details);
}
free(p->body);
memset(p, 0, sizeof *p);
}
/* A trim measures with the calibration its answer recorded (1 when the
* answer has none), so recovery plans the same cut. */
static int policy_plan(sqlite3 *db, int64_t submission, const char *model, const char *mode, const char *answer,
const char *instructions, pic_compact_plan *p) {
pic_compaction_settings cs;
plan_state *st;
int rc;
memset(p, 0, sizeof *p);
pic_compaction_settings_get(model, &cs);
if (mode && strcmp(mode, "trim") == 0) {
sqlite3_stmt *q = NULL;
double ratio = 1.0;
if (answer && sqlite3_prepare_v2(db, "SELECT json_extract(?1, '$.calibration') WHERE json_valid(?1)", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, answer, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) != SQLITE_NULL) {
ratio = sqlite3_column_double(q, 0);
}
}
sqlite3_finalize(q);
return pic_compaction_trim(db, submission, cs.keep_recent_tokens, ratio, &p->first_kept_seq, &p->tokens_before,
&p->body, &p->details);
}
if (!(st = calloc(1, sizeof *st))) {
return -1;
}
if ((rc = pic_compaction_plan(db, submission, instructions, cs.keep_recent_tokens, &st->c)) != 0) {
free(st);
return rc;
}
p->state = st;
p->first_kept_seq = st->c.first_kept_seq;
p->tokens_before = st->c.tokens_before;
p->system = pic_summary_system_prompt;
p->prompt[0] = st->c.history_prompt ? st->c.history_prompt : st->c.prefix_prompt;
p->prompt[1] = st->c.history_prompt && st->c.split ? st->c.prefix_prompt : NULL;
p->details = st->c.details;
return 0;
}
static int policy_branch_plan(sqlite3 *db, sqlite3_int64 from, sqlite3_int64 at, long window, const char *instructions,
pic_compact_plan *p) {
pic_branch_settings bs;
plan_state *st;
int rc;
memset(p, 0, sizeof *p);
pic_branch_settings_get(&bs);
if (!(st = calloc(1, sizeof *st))) {
return -1;
}
st->branch = 1;
if ((rc = pic_branch_plan(db, from, at, (window > 0 ? window : PIC_BRANCH_WINDOW) - bs.reserve_tokens, instructions,
&st->b)) != 0) {
free(st);
return rc;
}
p->state = st;
p->system = pic_summary_system_prompt;
p->prompt[0] = st->b.prompt;
p->details = st->b.details;
if (!st->b.prompt && !(p->body = dup_text((const unsigned char *)"No content to summarize"))) {
policy_plan_free(p);
return -1;
}
return 0;
}
/* Pi's summary: the history's, joined to a split turn's prefix as Pi joins
* them (the previous summary, or "No prior history.", when only the split
* turn was summarized), then the file lists; a branch's: the preamble, the
* reply, the file lists. */
static char *policy_join(const pic_compact_plan *p, char *const reply[2]) {
const plan_state *st = p->state;
const pic_compaction *c;
const char *history, *prefix;
sqlite3_str *t;
if (!st || !p->prompt[0]) {
return dup_text((const unsigned char *)(p->body ? p->body : ""));
}
t = sqlite3_str_new(NULL);
if (st->branch) {
sqlite3_str_appendf(t, "%s%s%s", pic_branch_summary_preamble, reply[0] ? reply[0] : "", st->b.files ? st->b.files : "");
return finish(t);
}
c = &st->c;
history = c->history_prompt ? reply[0] : NULL;
prefix = c->split ? (c->history_prompt ? reply[1] : reply[0]) : NULL;
if (c->split) {
sqlite3_str_appendf(t, "%s\n\n---\n\n**Turn Context (split turn):**\n\n%s",
history ? history : c->previous_summary ? c->previous_summary : "No prior history.",
prefix ? prefix : "");
} else {
sqlite3_str_appendall(t, history ? history : "");
}
sqlite3_str_appendall(t, c->files ? c->files : "");
return finish(t);
}
static int policy_overflow(const char *model) {
pic_compaction_settings cs;
pic_compaction_settings_get(model, &cs);
return cs.enabled;
}
const pic_context_policy pic_compact_policy = {"pic:compact", policy_answer, policy_plan, policy_branch_plan,
policy_join, policy_plan_free, policy_overflow};
/* ---- lapse: the measurement ------------------------------------------------ */
/* A fixed-seed generator for the bootstrap, so a report reads the same twice. */
static unsigned long long lapse_rng(unsigned long long *x) {
*x ^= *x << 13;
*x ^= *x >> 7;
*x ^= *x << 17;
return *x;
}
static int cmp_double(const void *a, const void *b) {
double x = *(const double *)a, y = *(const double *)b;
return x < y ? -1 : x > y;
}
static double mean_of(const double *v, int n) {
double t = 0.0;
for (int k = 0; k < n; k++) {
t += v[k];
}
return n ? t / n : 0.0;
}
#define LAPSE_MIN_ARM 5 /* lapses each arm needs before a comparison is shown */
#define LAPSE_RESAMPLES 4000
static const char *const lapse_modes[] = {"trim", "summary"};
#define LAPSE_MODES 2
/* One mode's comparison: compacted (arm 0) against held out (arm 1). */
typedef struct {
double *cost[2];
int n[2], cap[2];
double mean[2], ratio, saved, lo_r, hi_r, lo_s, hi_s;
int enough;
} lapse_cmp;
static int lapse_compare(lapse_cmp *m) {
m->mean[0] = mean_of(m->cost[0], m->n[0]);
m->mean[1] = mean_of(m->cost[1], m->n[1]);
m->enough = m->n[0] >= LAPSE_MIN_ARM && m->n[1] >= LAPSE_MIN_ARM && m->mean[1] > 0.0;
if (m->enough) {
double *rs = malloc(sizeof(double) * LAPSE_RESAMPLES), *ss = malloc(sizeof(double) * LAPSE_RESAMPLES);
unsigned long long x = 0x9e3779b97f4a7c15ULL;
if (!rs || !ss) {
free(rs);
free(ss);
return -1;
}
for (int b = 0; b < LAPSE_RESAMPLES; b++) {
double mm[2];
for (int a = 0; a < 2; a++) {
double t = 0.0;
for (int k = 0; k < m->n[a]; k++) {
t += m->cost[a][lapse_rng(&x) % (unsigned long long)m->n[a]];
}
mm[a] = t / m->n[a];
}
rs[b] = mm[1] > 0.0 ? mm[0] / mm[1] : 1.0;
ss[b] = (mm[1] - mm[0]) * m->n[0];
}
qsort(rs, LAPSE_RESAMPLES, sizeof(double), cmp_double);
qsort(ss, LAPSE_RESAMPLES, sizeof(double), cmp_double);
m->lo_r = rs[LAPSE_RESAMPLES / 40];
m->hi_r = rs[LAPSE_RESAMPLES - 1 - LAPSE_RESAMPLES / 40];
m->lo_s = ss[LAPSE_RESAMPLES / 40];
m->hi_s = ss[LAPSE_RESAMPLES - 1 - LAPSE_RESAMPLES / 40];
m->ratio = m->mean[0] / m->mean[1];
m->saved = (m->mean[1] - m->mean[0]) * m->n[0];
free(rs);
free(ss);
}
return 0;
}
/* Each cold cache is the context policy's journaled lapse answer (or a
* pic_lapse row, from before the answers were journaled, all summaries),
* with its arm and the mode it compacts or would have compacted in. Its
* window runs from its request's turn to the next cold cache in the same
* session (or the session's end), so where a window ends does not depend
* on its arm. Its cost is every done request in it, summaries included. A
* mode's compacted lapses are compared with its held-out ones. */
int pic_lapse_report(sqlite3 *db, int json, FILE *out) {
sqlite3_stmt *q = NULL;
lapse_cmp m[LAPSE_MODES];
int small = 0, rc = -1, legacy = 0, compacted = 0, held = 0, printed = 0;
char *sql;
memset(m, 0, sizeof m);
if (sqlite3_prepare_v2(db, "SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = 'pic_lapse'", -1, &q, NULL) ==
SQLITE_OK &&
sqlite3_step(q) == SQLITE_ROW) {
legacy = sqlite3_column_int(q, 0) > 0;
}
sqlite3_finalize(q);
q = NULL;
sql = sqlite3_mprintf(
"WITH r(session_id, u, t, arm, mode) AS (SELECT session_id, submission_id, ref, json_extract(context, '$.arm'),"
" coalesce(json_extract(context, '$.mode'), 'summary') FROM pic_hook_run WHERE event = 'PreRequest'"
" AND reason = 'lapse' AND command IS NOT NULL AND state = 'done' AND json_valid(context)"
" AND json_extract(context, '$.arm') IN ('compact','holdout','small')%s),"
" l AS (SELECT session_id, u, t, arm, mode, lead(u) OVER w AS nu, lead(t) OVER w AS nt"
" FROM r WINDOW w AS (PARTITION BY session_id ORDER BY u, t))"
" SELECT l.arm, l.mode, (SELECT coalesce(sum(json_extract(g.usage, '$.pic_cost.total')), 0)"
" FROM pic_generation g JOIN pic_submission s ON s.id = g.submission_id"
" WHERE s.session_id = l.session_id AND g.state = 'done' AND json_valid(g.usage)"
" AND (g.submission_id > l.u OR (g.submission_id = l.u AND g.turn >= l.t))"
" AND (l.nu IS NULL OR g.submission_id < l.nu OR (g.submission_id = l.nu AND g.turn < l.nt)))"
" FROM l",
legacy ? " UNION ALL SELECT session_id, submission_id, turn, arm, 'summary' FROM pic_lapse" : "");
if (!sql || sqlite3_prepare_v2(db, sql, -1, &q, NULL) != SQLITE_OK) {
sqlite3_free(sql);
return -1;
}
sqlite3_free(sql);
while (sqlite3_step(q) == SQLITE_ROW) {
const char *arm = (const char *)sqlite3_column_text(q, 0), *mode = (const char *)sqlite3_column_text(q, 1);
int a = strcmp(arm, "compact") == 0 ? 0 : strcmp(arm, "holdout") == 0 ? 1 : -1, k = 0;
lapse_cmp *c;
if (a < 0) {
small++;
continue;
}
while (k < LAPSE_MODES - 1 && strcmp(mode, lapse_modes[k]) != 0) {
k++;
}
c = &m[k];
if (c->n[a] == c->cap[a]) {
double *grown = realloc(c->cost[a], sizeof(double) * (size_t)(c->cap[a] = c->cap[a] ? c->cap[a] * 2 : 16));
if (!grown) {
goto done;
}
c->cost[a] = grown;
}
c->cost[a][c->n[a]++] = sqlite3_column_double(q, 2);
}
for (int k = 0; k < LAPSE_MODES; k++) {
if (lapse_compare(&m[k]) != 0) {
goto done;
}
compacted += m[k].n[0];
held += m[k].n[1];
}
if (json) {
fprintf(out, "{\"compacted\":%d,\"heldOut\":%d,\"small\":%d,\"modes\":[", compacted, held, small);
} else {
fprintf(out, "cold caches: %d compacted, %d held out, %d under the floor\n", compacted, held, small);
}
for (int k = 0; k < LAPSE_MODES; k++) {
const lapse_cmp *c = &m[k];
if (c->n[0] + c->n[1] == 0) {
continue;
}
if (json) {
fprintf(out, "%s{\"mode\":\"%s\",\"compacted\":%d,\"heldOut\":%d,\"meanCompacted\":%.6f,\"meanHeldOut\":%.6f",
printed ? "," : "", lapse_modes[k], c->n[0], c->n[1], c->mean[0], c->mean[1]);
if (c->enough) {
fprintf(out, ",\"ratio\":%.4f,\"ratioLow\":%.4f,\"ratioHigh\":%.4f,\"saved\":%.4f,\"savedLow\":%.4f,\"savedHigh\":%.4f}",
c->ratio, c->lo_r, c->hi_r, c->saved, c->lo_s, c->hi_s);
} else {
fputs(",\"ratio\":null,\"saved\":null}", out);
}
} else {
fprintf(out, "%s: %d compacted, %d held out\n", lapse_modes[k], c->n[0], c->n[1]);
fprintf(out, "cost from each to the next in its session: compacted $%.4f on average, held out $%.4f\n", c->mean[0],
c->mean[1]);
if (c->enough) {
fprintf(out, "compacted / held out: %.2f (95%% interval %.2f to %.2f)\n", c->ratio, c->lo_r, c->hi_r);
fprintf(out, "saved: $%.2f over %d compactions (95%% interval $%.2f to $%.2f)\n", c->saved, c->n[0], c->lo_s,
c->hi_s);
} else {
fprintf(out, "not enough to compare yet: each arm needs %d (lapseHoldout sets how many are held out)\n",
LAPSE_MIN_ARM);
}
}
printed = 1;
}
if (json) {
fputs("]}\n", out);
}
rc = 0;
done:
sqlite3_finalize(q);
for (int k = 0; k < LAPSE_MODES; k++) {
free(m[k].cost[0]);
free(m[k].cost[1]);
}
return rc;
}