A session file was written as if it were a chat: role and text, nothing
else. Reading it back kept "user" and "assistant" and dropped everything
else - and nearly every line of an agent transcript is an observation.
Measured on three real sessions: 21 of 1507 messages came back, 8 of 1356,
3 of 317. --resume then sent 1% of the conversation and the model had no
idea what it was continuing.
Three writers had to change with the loader:
- A turn that asked for tools wrote no line at all (agent.c only wrote
when ncalls == 0). It now goes out with its tool_calls, and each result
with the name of its tool and its call id; a provider rejects a tool
message without them.
- {"role":"user","text":""} came from the steer path and showed the model
a blank human turn it answered. sp_session_append_rec writes nothing
when text and calls are both empty.
- A record from the old format has no name and no call id. It is paired
with the next unanswered call of its pending assistant turn, or given a
synthetic one (recovered-N). Dropping it is what emptied every resume;
keeping it unpaired is what a provider answers with 400.
The same pass gives the core its own compactor (compact.c): a thread digest
- one line per dropped message, OPERATOR: 800 chars, assistant: 300, tool
result 160 - so the model keeps the story, not a count. lcm stays a plugin
that runs after it; sp_core_compactor() is the fallback only when no plugin
registered one, because running both eats the conversation before lcm sees
work to do.
Two bugs fell out of the same area:
- The plugin host was only built when a plugin was configured, so a
plugin-less run had no compactor at all: over max_bytes the turn was
refused instead of compacted (90 KB session, budget 8000, "nothing
sent").
- lcm walked *forward* past tool results at the tail boundary, which
silently shrank the tail: a turn with two results kept four messages
where keep_tail says six. Walking back to the assistant that carries
the call keeps six and no orphan.
And the .meta sidecar is shared now: the core rewrote it with only the keys
it knew, so anything a plugin put there was gone on the next open. It
carries unknown lines through (extra[8][160]), which is what lets a plugin
mark a session in the core's own file.
Tests: tests/test_corecompact.c (10 checks, no plugin), the resume cases in
tests/test_session.c, and the tail-size check in tests/test_compactor.c.
Each was seen red on the old code before it was green on the new.
541 lines
17 KiB
C
541 lines
17 KiB
C
/*
|
|
* splinter -- compact: the compactor the core owns.
|
|
*
|
|
* Copyright (c) 2026 Konrad Lother
|
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
*
|
|
* Compaction used to live only in the lcm plugin, which made `compact_threshold`
|
|
* and `compact_target` dead settings: the agent read them, built a budget from
|
|
* them, and handed it to a compactor list that was empty unless a plugin had
|
|
* been loaded. A harness whose own configuration does nothing is worse than one
|
|
* that has no such configuration, because the operator believes it is working.
|
|
*
|
|
* So the core carries a compactor of its own, and it runs when no plugin does.
|
|
*
|
|
* Two things were learned the hard way, and they shape everything below.
|
|
*
|
|
* 1. A cut that leaves only a statistic line loses the thread. lcm replaced the
|
|
* dropped range with "[lcm] 42 messages compacted out (user 12, ...)" and
|
|
* quoted 120 characters of the oldest one. The model then no longer knew what
|
|
* the work was, re-asked, and the operator called it "losing the fade" - a
|
|
* correct complaint. What has to survive is not a count, it is the story:
|
|
* who asked what, in order.
|
|
*
|
|
* 2. Tool output is where the bytes are, and the head of an observation is the
|
|
* part that matters. Trimming bodies saves most of the budget before any
|
|
* message has to go.
|
|
*
|
|
* So the order of work is:
|
|
*
|
|
* 1. trim every tool body outside the verbatim tail
|
|
* 2. still over budget: build a THREAD DIGEST of the dropped range. Every user
|
|
* message survives nearly whole; every assistant turn keeps its opening;
|
|
* every observation is reduced to a line. The digest is one system message.
|
|
* 3. the newest real user message is pinned after the digest, so the question
|
|
* being answered is never something the model has to infer.
|
|
* 4. if the digest plus the tail still exceeds the budget, the caps shrink
|
|
* step by step, cheapest role first. The digest is never dropped whole.
|
|
*
|
|
* Nothing here calls a second model: a summary that costs a request and makes a
|
|
* run unreproducible is a different feature, not a flag on this one.
|
|
*
|
|
* The tail boundary never lands on a "tool" message: its assistant turn carries
|
|
* the tool_call, and a provider rejects an orphaned tool result with a 400.
|
|
*/
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
#include "splinter.h"
|
|
#include "splinter_plugin.h"
|
|
|
|
#define COMPACT_KEEP_TAIL 6 /* messages always kept verbatim */
|
|
#define COMPACT_KEEP_HEAD 8 /* leading system messages never digested */
|
|
#define COMPACT_TOOL_TRIM 2048 /* a tool body outside the tail */
|
|
|
|
/* Per-role caps inside the digest. User text is the thread: keep it nearly
|
|
* whole. An assistant turn is mostly restating its tool call, so its opening
|
|
* is enough. An observation is already trimmed by then. */
|
|
#define CAP_USER 800
|
|
#define CAP_ASSISTANT 300
|
|
#define CAP_TOOL 160
|
|
#define CAP_MIN_USER 120
|
|
#define CAP_MIN_ASSISTANT 40
|
|
#define CAP_MIN_TOOL 0
|
|
|
|
struct caps {
|
|
size_t user;
|
|
size_t assistant;
|
|
size_t tool;
|
|
};
|
|
|
|
static size_t
|
|
msg_bytes(const struct sp_msg *m)
|
|
{
|
|
size_t n = 16; /* JSON scaffolding, estimated */
|
|
|
|
n += m->role != NULL ? strlen(m->role) : 0;
|
|
n += m->name != NULL ? strlen(m->name) : 0;
|
|
n += m->content != NULL ? strlen(m->content) : 0;
|
|
n += m->calls != NULL ? strlen(m->calls) : 0;
|
|
return n;
|
|
}
|
|
|
|
static int
|
|
is_role(const struct sp_msg *m, const char *role)
|
|
{
|
|
return m->role != NULL && strcmp(m->role, role) == 0;
|
|
}
|
|
|
|
/*
|
|
* The engine's own continuation prompt ("Continue with the task ...") arrives as
|
|
* a user message but is not the question. Pinning it keeps the keystroke and
|
|
* loses the task it was meant to continue - measured on a session resumed after
|
|
* a rate limit, which woke up with the prompt, one tool call and no task.
|
|
*/
|
|
static int
|
|
is_continuation(const struct sp_msg *m)
|
|
{
|
|
static const char *prefix[] = {
|
|
"Continue with the task",
|
|
"Setze die Aufgabe",
|
|
NULL
|
|
};
|
|
size_t i;
|
|
|
|
if (m->content == NULL)
|
|
return 0;
|
|
for (i = 0; prefix[i] != NULL; i++)
|
|
if (strncmp(m->content, prefix[i], strlen(prefix[i])) == 0)
|
|
return 1;
|
|
return 0;
|
|
}
|
|
|
|
/*
|
|
* Cut long tool outputs in [from, to). The head of an observation is the part
|
|
* worth keeping: a tool prints its answer, then a stack of context. The marker
|
|
* says the cut happened, so a model does not read a trimmed result as complete.
|
|
*/
|
|
static int
|
|
trim_tools(struct sp_conv *conv, size_t from, size_t to, size_t limit)
|
|
{
|
|
size_t i;
|
|
int trimmed = 0;
|
|
|
|
for (i = from; i < to; i++) {
|
|
struct sp_msg *m = &conv->v[i];
|
|
size_t len;
|
|
char *cut;
|
|
|
|
if (!is_role(m, "tool") || m->content == NULL)
|
|
continue;
|
|
len = strlen(m->content);
|
|
if (len <= limit)
|
|
continue;
|
|
cut = malloc(limit + 96);
|
|
if (cut == NULL)
|
|
return trimmed;
|
|
memcpy(cut, m->content, limit);
|
|
snprintf(cut + limit, 96, "\n[... %zu bytes trimmed by compaction]",
|
|
len - limit);
|
|
free(m->content);
|
|
m->content = cut;
|
|
trimmed++;
|
|
}
|
|
return trimmed;
|
|
}
|
|
|
|
/* Append text with newlines flattened to spaces: the digest is a transcript of
|
|
* one message, not a document with its own layout. */
|
|
static void
|
|
append_flat(struct sp_buf *b, const char *s, size_t cap)
|
|
{
|
|
size_t i;
|
|
|
|
if (s == NULL)
|
|
return;
|
|
for (i = 0; i < cap && s[i] != '\0'; i++) {
|
|
char c = s[i];
|
|
|
|
if (c == '\n' || c == '\r' || c == '\t')
|
|
c = ' ';
|
|
sp_buf_add(b, &c, 1);
|
|
}
|
|
if (s[i] != '\0')
|
|
sp_buf_puts(b, "...");
|
|
}
|
|
|
|
/*
|
|
* The thread: one line per dropped message, in order. A user turn gets its
|
|
* opening nearly whole - that is the task and the corrections to it. An
|
|
* assistant turn gets its opening, which is what it claimed to be doing. An
|
|
* observation gets enough to recognise it.
|
|
*/
|
|
/*
|
|
* Does the registry offer history_search? Passed in rather than looked up here,
|
|
* because build_digest runs inside the shrink loop and the answer never changes.
|
|
*/
|
|
static int
|
|
build_digest(struct sp_conv *conv, size_t from, size_t to, struct caps caps,
|
|
int searchable, struct sp_buf *out)
|
|
{
|
|
size_t i;
|
|
size_t users = 0, assistants = 0, tools = 0, other = 0;
|
|
|
|
if (sp_buf_init(out) != 0)
|
|
return -1;
|
|
for (i = from; i < to; i++) {
|
|
if (is_role(&conv->v[i], "user"))
|
|
users++;
|
|
else if (is_role(&conv->v[i], "assistant"))
|
|
assistants++;
|
|
else if (is_role(&conv->v[i], "tool"))
|
|
tools++;
|
|
else
|
|
other++;
|
|
}
|
|
sp_buf_puts(out, "[thread so far - compacted] ");
|
|
sp_buf_printf(out, "%zu earlier messages: %zu from the operator, %zu "
|
|
"assistant turns, %zu tool results", to - from, users, assistants,
|
|
tools);
|
|
if (other > 0)
|
|
sp_buf_printf(out, ", %zu other", other);
|
|
sp_buf_puts(out, ". In order:\n");
|
|
/*
|
|
* Say where the rest went. Without this line the model reads a summary
|
|
* that stops mid-thought and believes that is all there ever was: it
|
|
* re-asks the operator what the operator already answered, which is the
|
|
* exact complaint ("losing the fade") this digest exists to fix. The
|
|
* tool is named only when it is really registered - a prompt pointing at
|
|
* a missing tool teaches the model to call nothing.
|
|
*/
|
|
if (searchable)
|
|
sp_buf_puts(out, "\n[The full transcript is still on disk. "
|
|
"Call history_search with the words of what you are looking "
|
|
"for to get it back: it searches this whole session by "
|
|
"meaning, not just what is quoted here.]\n");
|
|
|
|
for (i = from; i < to; i++) {
|
|
struct sp_msg *m = &conv->v[i];
|
|
|
|
if (is_role(m, "user")) {
|
|
sp_buf_puts(out, "\nOPERATOR: ");
|
|
append_flat(out, m->content, caps.user);
|
|
} else if (is_role(m, "assistant")) {
|
|
if (m->content == NULL && m->calls != NULL)
|
|
continue; /* a bare tool call says nothing yet */
|
|
sp_buf_puts(out, "\n assistant: ");
|
|
append_flat(out, m->content, caps.assistant);
|
|
} else if (is_role(m, "tool")) {
|
|
if (caps.tool == 0)
|
|
continue;
|
|
sp_buf_puts(out, "\n ");
|
|
if (m->name != NULL) {
|
|
sp_buf_puts(out, m->name);
|
|
sp_buf_puts(out, " -> ");
|
|
} else
|
|
sp_buf_puts(out, "tool -> ");
|
|
append_flat(out, m->content, caps.tool);
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/* Free the strings of [from, to) and close the gap. The vector, not the count. */
|
|
static void
|
|
drop_range(struct sp_conv *conv, size_t from, size_t to)
|
|
{
|
|
size_t i;
|
|
|
|
for (i = from; i < to; i++) {
|
|
free(conv->v[i].role);
|
|
free(conv->v[i].name);
|
|
free(conv->v[i].call_id);
|
|
free(conv->v[i].content);
|
|
free(conv->v[i].calls);
|
|
}
|
|
memmove(&conv->v[from], &conv->v[to],
|
|
(conv->n - to) * sizeof(*conv->v));
|
|
conv->n = from + (conv->n - to);
|
|
}
|
|
|
|
/* Bytes that [from, to) currently costs. */
|
|
static size_t
|
|
range_bytes(struct sp_conv *conv, size_t from, size_t to)
|
|
{
|
|
size_t i, total = 0;
|
|
|
|
for (i = from; i < to; i++)
|
|
total += msg_bytes(&conv->v[i]);
|
|
return total;
|
|
}
|
|
|
|
static int
|
|
core_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
|
|
unsigned turn)
|
|
{
|
|
struct sp_buf digest;
|
|
struct sp_registry *reg;
|
|
int searchable;
|
|
struct caps caps;
|
|
size_t bytes, drop_bytes, tail_bytes;
|
|
char *best_p = NULL;
|
|
size_t best_len = 0;
|
|
size_t first, keep_from;
|
|
long pin_at = -1;
|
|
char *pin_content = NULL;
|
|
char *pin_name = NULL;
|
|
size_t pin_extra = 0;
|
|
int trimmed, pinned = 0;
|
|
int attempt;
|
|
|
|
(void)turn;
|
|
/*
|
|
* Whether the escape hatch exists decides whether the digest advertises
|
|
* it. The embedding index is on by default, but `embed = off` is a
|
|
* supported choice and the prompt must not lie about it.
|
|
*/
|
|
reg = h != NULL ? sp_host_registry(h) : NULL;
|
|
searchable = reg != NULL && sp_registry_find(reg, "history_search") != NULL;
|
|
if (conv == NULL || conv->n == 0 || budget == 0)
|
|
return 0;
|
|
bytes = sp_conv_bytes(conv);
|
|
|
|
if (bytes <= budget)
|
|
return 0; /* fits: nothing to do */
|
|
if (conv->n <= COMPACT_KEEP_TAIL + 1)
|
|
return 0; /* too short to cut anything meaningful */
|
|
|
|
/*
|
|
* The leading system messages stay. Plural, because a compactor plugin
|
|
* that ran before this one put its own summary there - lcm's "[lcm] 42
|
|
* messages compacted out", cps' plan. That message is the result of work
|
|
* somebody already paid for, and digesting it away would replace the
|
|
* plugin's summary with a worse one. The cap keeps a pathological lead of
|
|
* system messages from eating the whole budget.
|
|
*/
|
|
for (first = 0; first < conv->n && first < COMPACT_KEEP_HEAD &&
|
|
is_role(&conv->v[first], "system"); first++)
|
|
;
|
|
keep_from = conv->n - COMPACT_KEEP_TAIL;
|
|
/*
|
|
* The tail must not begin with a tool result: its assistant turn, the
|
|
* one carrying the tool_call, would be cut away and a provider answers
|
|
* an orphaned tool message with a 400. Walk BACK to that assistant
|
|
* rather than forward past the results.
|
|
*
|
|
* Forward was the first try and it quietly broke the promise this
|
|
* constant makes: a turn with two tool results in the tail boundary
|
|
* kept four messages instead of six, because each result pushed the
|
|
* start further in. Measured on system + user + [assistant, tool, tool]
|
|
* x4 + user: 15 messages, tail of six, result was a tail of four. Going
|
|
* back costs the bytes of one call record and keeps the size.
|
|
*/
|
|
while (keep_from < conv->n && keep_from > first &&
|
|
is_role(&conv->v[keep_from], "tool"))
|
|
keep_from--;
|
|
if (keep_from >= conv->n || keep_from <= first)
|
|
return 0;
|
|
|
|
/* 1. trim every tool body outside the verbatim tail */
|
|
trimmed = trim_tools(conv, first, conv->n, COMPACT_TOOL_TRIM);
|
|
bytes = sp_conv_bytes(conv);
|
|
if (bytes <= budget)
|
|
return trimmed > 0 ? 1 : 0;
|
|
|
|
/* 2. the question being answered, pinned after the digest */
|
|
{
|
|
size_t i;
|
|
|
|
for (i = conv->n; i > first; i--) {
|
|
if (!is_role(&conv->v[i - 1], "user"))
|
|
continue;
|
|
if (is_continuation(&conv->v[i - 1]))
|
|
continue;
|
|
pin_at = (long)(i - 1);
|
|
break;
|
|
}
|
|
}
|
|
if (pin_at >= 0 && (size_t)pin_at >= keep_from) {
|
|
/* it is already in the verbatim tail: nothing to pin */
|
|
pin_at = -1;
|
|
}
|
|
if (pin_at >= 0) {
|
|
pin_content = strdup(conv->v[pin_at].content != NULL ?
|
|
conv->v[pin_at].content : "");
|
|
if (conv->v[pin_at].name != NULL)
|
|
pin_name = strdup(conv->v[pin_at].name);
|
|
pinned = pin_content != NULL;
|
|
if (pinned)
|
|
pin_extra = strlen(pin_content) +
|
|
(pin_name != NULL ? strlen(pin_name) : 0) + 20;
|
|
}
|
|
|
|
caps.user = CAP_USER;
|
|
caps.assistant = CAP_ASSISTANT;
|
|
caps.tool = CAP_TOOL;
|
|
|
|
/*
|
|
* What the digest has to beat is not the budget - it is what it replaces.
|
|
* If it costs more than the range it stands in for, the rewrite makes the
|
|
* conversation bigger and the next request pays for nothing. Shrink the
|
|
* caps until the digest is smaller than the range, user text last: that is
|
|
* the thread.
|
|
*
|
|
* The digest may also take at most its share of the budget, unless the
|
|
* verbatim tail alone already leaves less room than that.
|
|
*/
|
|
/*
|
|
* The digest has two hard limits, and it must satisfy both:
|
|
*
|
|
* a) smaller than the range it replaces, or the rewrite grows the
|
|
* conversation and the next request pays for nothing
|
|
* b) small enough that the digest plus the verbatim tail fits the
|
|
* budget, or the turn is refused for exceeding it anyway
|
|
*
|
|
* (b) is the one that was missing: with a budget of 900 and a tail of
|
|
* 1000 the digest could satisfy (a) all day and the request still went
|
|
* out at 3776 bytes. When the tail alone already exceeds the budget,
|
|
* (b) has no answer and (a) is the only rule left.
|
|
*
|
|
* Beyond those, the caps decide how much of the thread survives.
|
|
* Shrinking them is a last resort: the thread IS the point, and a digest
|
|
* that fits but says nothing is the failure this file exists to avoid.
|
|
*/
|
|
drop_bytes = range_bytes(conv, first, keep_from);
|
|
tail_bytes = range_bytes(conv, keep_from, conv->n);
|
|
{
|
|
size_t room = drop_bytes > pin_extra + 64 ?
|
|
drop_bytes - pin_extra - 64 : 0;
|
|
size_t fit = budget > tail_bytes + pin_extra ?
|
|
budget - tail_bytes - pin_extra : 0;
|
|
|
|
if (fit > 0 && fit < room)
|
|
room = fit;
|
|
|
|
/*
|
|
* Shrink until it fits, but keep the best attempt: when even the
|
|
* smallest caps overshoot, the smallest digest is still worth more
|
|
* than no thread at all. The best one is copied out as a plain
|
|
* buffer, so ownership stays in one place.
|
|
*/
|
|
best_p = NULL;
|
|
best_len = 0;
|
|
for (attempt = 0; attempt < 16; attempt++) {
|
|
if (build_digest(conv, first, keep_from, caps,
|
|
searchable, &digest) != 0) {
|
|
free(best_p);
|
|
free(pin_content);
|
|
free(pin_name);
|
|
return -1;
|
|
}
|
|
if (digest.len == 0) {
|
|
sp_buf_free(&digest);
|
|
break;
|
|
}
|
|
if (best_p == NULL || digest.len < best_len) {
|
|
char *copy = malloc(digest.len + 1);
|
|
|
|
if (copy != NULL) {
|
|
memcpy(copy, digest.p, digest.len + 1);
|
|
free(best_p);
|
|
best_p = copy;
|
|
best_len = digest.len;
|
|
}
|
|
}
|
|
if (digest.len <= room) {
|
|
sp_buf_free(&digest);
|
|
break;
|
|
}
|
|
sp_buf_free(&digest);
|
|
if (caps.tool > CAP_MIN_TOOL) {
|
|
caps.tool = caps.tool / 2;
|
|
continue;
|
|
}
|
|
if (caps.assistant > CAP_MIN_ASSISTANT) {
|
|
caps.assistant = caps.assistant / 2;
|
|
continue;
|
|
}
|
|
if (caps.user > CAP_MIN_USER) {
|
|
caps.user = caps.user * 3 / 4;
|
|
continue;
|
|
}
|
|
break; /* nothing left to shrink */
|
|
}
|
|
if (best_p == NULL) {
|
|
free(pin_content);
|
|
free(pin_name);
|
|
return trimmed > 0 ? 1 : 0;
|
|
}
|
|
/*
|
|
* Rule (a), enforced rather than merely computed. The shrink loop
|
|
* stops at the minimum caps and keeps the smallest attempt even
|
|
* when that attempt is still too big - and then the rewrite went
|
|
* out anyway, replacing a short range with a longer digest plus a
|
|
* pinned question. Measured on the case /resume produced: 317
|
|
* bytes in, 476 bytes out, on a budget of 217. A compactor that
|
|
* grows the conversation is worse than none, because the next
|
|
* request pays for it and the turn is refused for size.
|
|
*
|
|
* There is nothing else to try at this point, so the honest
|
|
* answer is "I could not help": the tool bodies were already
|
|
* trimmed above, which is where the easy bytes were.
|
|
*/
|
|
if (best_len + pin_extra >= drop_bytes) {
|
|
free(best_p);
|
|
free(pin_content);
|
|
free(pin_name);
|
|
return trimmed > 0 ? 1 : 0;
|
|
}
|
|
if (sp_buf_init(&digest) != 0) {
|
|
free(best_p);
|
|
free(pin_content);
|
|
free(pin_name);
|
|
return -1;
|
|
}
|
|
sp_buf_add(&digest, best_p, best_len);
|
|
free(best_p);
|
|
}
|
|
|
|
drop_range(conv, first, keep_from);
|
|
{
|
|
struct sp_msg m;
|
|
|
|
memset(&m, 0, sizeof(m));
|
|
m.role = "system";
|
|
m.content = digest.p;
|
|
if (sp_conv_insert(conv, first, &m) != 0) {
|
|
sp_buf_free(&digest);
|
|
free(pin_content);
|
|
free(pin_name);
|
|
return -1;
|
|
}
|
|
}
|
|
if (pinned && pin_content != NULL && pin_content[0] != '\0') {
|
|
struct sp_msg m;
|
|
|
|
memset(&m, 0, sizeof(m));
|
|
m.role = "user";
|
|
m.name = pin_name;
|
|
m.content = pin_content;
|
|
if (sp_conv_insert(conv, first + 1, &m) != 0) {
|
|
sp_buf_free(&digest);
|
|
free(pin_content);
|
|
free(pin_name);
|
|
return -1;
|
|
}
|
|
}
|
|
sp_buf_free(&digest);
|
|
free(pin_content);
|
|
free(pin_name);
|
|
return 1;
|
|
}
|
|
|
|
static const struct sp_compactor compact = { "compact", core_compact };
|
|
|
|
const struct sp_compactor *
|
|
sp_core_compactor(void)
|
|
{
|
|
return &compact;
|
|
}
|