diff --git a/Makefile b/Makefile index f8b1115..888fd8e 100644 --- a/Makefile +++ b/Makefile @@ -340,6 +340,7 @@ check: $(LIB) $(BIN) $(CLIENT) $(PLUGIN) $(TESTS) tests/test_junction echo "== tests/test_protocol.sh"; sh tests/test_protocol.sh; \ echo "== tests/test_attach.sh"; sh tests/test_attach.sh; \ echo "== tests/test_gateway_openai.sh"; sh tests/test_gateway_openai.sh; \ + echo "== tests/test_usage_request.sh"; sh tests/test_usage_request.sh; \ echo "== tests/test_reconnect.sh"; sh tests/test_reconnect.sh; \ echo "== tests/test_junction.sh"; sh tests/test_junction.sh; \ echo "== tests/test_mcpsession.sh"; sh tests/test_mcpsession.sh; \ diff --git a/README.md b/README.md index c7f11a1..b5aa52a 100644 --- a/README.md +++ b/README.md @@ -629,17 +629,22 @@ message, and a piece Telegram refuses to parse is sent as plain text instead. `SPLINTER_TG_MARKDOWN=0` turns the rendering off. `/compact [tokens]` runs the compactors now (default target: `compact_target`, -else 8000 tokens) and reports messages/bytes before and after. The `lcm` -widget in the sidebar keeps the running numbers (context, compactions, +else 8000 tokens) and reports messages/bytes before and after. Typing it while +a turn runs does not lose it: the request is queued and applied when that turn +ends, which is exactly the moment a large context makes you reach for it. The +`lcm` widget in the sidebar keeps the running numbers (context, compactions, messages cut, last cut in messages and bytes, trimmed tool outputs), and the status line carries a `compact N` segment. With `compact_threshold` set, the harness compacts automatically once the last request was larger than that: the conversation is cut to `compact_target` -before the next turn, so the context never grows without bound. Compaction -rewrites the prompt prefix, which invalidates the provider's prompt cache - the -threshold is the knob that trades cache hits for a smaller context. What was -dropped stays in the session log, and the `recall` tool searches it: the model -can look an earlier turn up instead of guessing. +before the next turn, so the context never grows without bound. The size it +judges is the `prompt_tokens` the provider reports, so every streamed turn +sends `stream_options.include_usage` - a provider that follows the OpenAI +contract returns no `usage` otherwise and the threshold would never fire. +Compaction rewrites the prompt prefix, which invalidates the provider's prompt +cache - the threshold is the knob that trades cache hits for a smaller context. +What was dropped stays in the session log, and the `recall` tool searches it: +the model can look an earlier turn up instead of guessing. The `session` plugin reaches further back: `session_search` finds text in the logs of earlier sessions that ran in this working directory (with date, session diff --git a/docs/CONFIG.md b/docs/CONFIG.md index f80ddaa..ffa2a16 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -253,7 +253,7 @@ lies about what it does. | `autonomous` | `1` runs mutating/destructive tools without asking | | `steps` | tool rounds per turn (default 150) | | `max_bytes` | conversation budget in bytes, `0` = no limit | -| `compact_threshold` | context tokens past which the next request is compacted (`0` = off) | +| `compact_threshold` | context tokens past which the next request is compacted (`0` = off); judged by the prompt size the provider reports, which every streamed turn asks for | | `compact_target` | the size compaction aims for, in tokens; `/compact [tokens]` forces it now | | `embed` | the session's search index: `local` (default, built-in CPU encoder, no model and no key), `openai` (posts to `embed_endpoint`), `off` | | `embed_dims` | vector size, 8..4096, default 256; only meaningful for `local`, and `openai` must match what the model returns | diff --git a/src/backend/transport_openai.c b/src/backend/transport_openai.c index 06c6ba7..9628cf7 100644 --- a/src/backend/transport_openai.c +++ b/src/backend/transport_openai.c @@ -558,11 +558,36 @@ openai_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out, sp_buf_puts(err, sp_td("openai.oom", "openai: out of memory")); goto out; } - if (sp_openai_request_opts(conv, c->model, c->reg, 1, - c->have_gen ? &c->gen : NULL, &body) != 0) { - sp_buf_puts(err, sp_td("openai.build_request", - "openai: cannot build the request")); - goto out; + /* + * Every streamed turn asks for the usage chunk, not only the ones a + * caller configured. + * + * `usage` is what compact_threshold judges: agent.c keeps the prompt + * size in stats.last_in, and only a reported prompt_tokens fills it. + * A strict provider - OpenAI among them - sends usage on a stream only + * when stream_options.include_usage asks for it, so a plain turn left + * last_in at 0 and automatic compaction never fired at all. + * + * Measured on one process, one 82-message session, only the endpoint + * differing: usage always -> the second turn went out at 8 messages; + * usage on request only -> the second turn had grown to 84. + * + * The caller's own options win where it set them; include_usage is the + * transport's business because the transport is what needs the number. + */ + { + struct sp_gen_opts gen; + + memset(&gen, 0, sizeof(gen)); + if (c->have_gen) + gen = c->gen; + gen.include_usage = 1; + if (sp_openai_request_opts(conv, c->model, c->reg, 1, + &gen, &body) != 0) { + sp_buf_puts(err, sp_td("openai.build_request", + "openai: cannot build the request")); + goto out; + } } temp_template(path, sizeof(path), "sse"); diff --git a/tests/fake_strict_usage.py b/tests/fake_strict_usage.py new file mode 100644 index 0000000..980a4da --- /dev/null +++ b/tests/fake_strict_usage.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +"""A chat endpoint that behaves like those that follow the OpenAI contract. + +OpenAI's streaming API sends the `usage` chunk only when the request asked for +it with stream_options.include_usage. This endpoint does the same, so a client +that forgets the field gets no token counts at all - which is the shape that +left splinter's stats.last_in at 0 and stopped automatic compaction. + +It answers /v1/models so a caller can wait for it, and appends one line per +completion request to the log: REQ bytes= msgs= include_usage= +""" +import http.server +import json +import sys + + +PORT = int(sys.argv[1]) +LOG = sys.argv[2] + +# The prompt size it reports. Past a realistic compact_threshold on purpose. +PROMPT_TOKENS = 90000 + + +class Handler(http.server.BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def do_GET(self): + body = json.dumps({"data": [{"id": "m", "object": "model"}]}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.send_header("Connection", "close") + self.end_headers() + self.close_connection = True + self.wfile.write(body) + + def do_POST(self): + n = int(self.headers.get("content-length") or 0) + raw = self.rfile.read(n) + try: + req = json.loads(raw) + except ValueError: + req = {} + asked = bool((req.get("stream_options") or {}).get("include_usage")) + with open(LOG, "a") as log: + log.write("REQ bytes=%d msgs=%d include_usage=%s\n" + % (len(raw), len(req.get("messages") or []), asked)) + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Connection", "close") + self.end_headers() + # No keep-alive: a client waits for the close after [DONE], and a + # lingering connection would keep the turn "running" forever. + self.close_connection = True + + def event(obj): + self.wfile.write(b"data: " + json.dumps(obj).encode() + b"\n\n") + self.wfile.flush() + + event({"choices": [{"delta": {"content": "ok"}, "index": 0}]}) + final = {"choices": [{"delta": {}, "finish_reason": "stop", + "index": 0}]} + if asked: + final["usage"] = {"prompt_tokens": PROMPT_TOKENS, + "completion_tokens": 5} + event(final) + self.wfile.write(b"data: [DONE]\n\n") + self.wfile.flush() + + def log_message(self, *args): + pass + + +http.server.HTTPServer(("127.0.0.1", PORT), Handler).serve_forever() diff --git a/tests/test_usage_request.sh b/tests/test_usage_request.sh new file mode 100755 index 0000000..a19ff67 --- /dev/null +++ b/tests/test_usage_request.sh @@ -0,0 +1,120 @@ +#!/bin/sh +# +# splinter -- every streamed turn asks for the usage chunk. +# +# What it guards: automatic compaction is judged by the prompt size the +# provider reports (stats.last_in), and a plain turn used to send no +# stream_options.include_usage. A provider that follows the OpenAI contract +# then sends no `usage` at all, last_in stayed 0, and compact_threshold never +# fired - the conversation grew until the provider cut it (measured: a 253 KB +# request against compact_threshold = 128000, 2026-11-22). +# +# The fake endpoint here behaves like that contract: usage only when asked for. +# Two turns in ONE process, because compaction needs the previous turn's size. +# Without the fix the second request carries the whole conversation; with it +# the second is compacted down to the target. +set -u +cd "$(dirname "$0")/.." || exit 1 +. "$(dirname "$0")/sh/port.sh" +D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-usage-XXXXXX") || exit 1 +P=$(free_port) +F= +S= +fails=0 +cleanup() { + [ -n "$F" ] && kill "$F" 2>/dev/null + [ -n "$S" ] && kill "$S" 2>/dev/null + rm -rf "$D" +} +trap cleanup EXIT + +fail() { echo "FAIL $*"; fails=$((fails + 1)); } + +mkdir -p "$D/home" "$D/sess" + +# A session past the threshold: 40 turns of 1400 bytes plus answers, ~59 kB. +# compact_threshold is in tokens and the byte budget is threshold * 4. +python3 -I - "$D/sess/sess-u.jsonl" <<'PY' +import json, sys +out = [] +for i in range(1, 41): + out.append({"role": "user", "text": "frage %d %s" % (i, "y" * 1400)}) + out.append({"role": "assistant", "text": "antwort %d" % i}) +open(sys.argv[1], "w").write("".join(json.dumps(l) + "\n" for l in out)) +PY + +cat > "$D/conf" < "$D/fake.log" 2>&1 & +F=$! +if ! wait_listen "$P" "$F"; then + echo "FAIL the fake endpoint did not start" + cat "$D/fake.log" + exit 1 +fi + +HOME="$D/home" ./splinter --config "$D/conf" \ + --serve --socket "$D/s.sock" \ + --endpoint "http://127.0.0.1:$P/v1" --model m \ + --session-id sess-u --resume \ + > "$D/serve.log" 2>&1 & +S=$! +i=0 +while [ "$i" -lt 60 ]; do + [ -S "$D/s.sock" ] && break + i=$((i + 1)) + sleep 0.2 +done +if [ ! -S "$D/s.sock" ]; then + echo "FAIL the server did not start" + cat "$D/serve.log" + exit 1 +fi + +./splinterctl --socket "$D/s.sock" --say "turn eins" > /dev/null 2>&1 +./splinterctl --socket "$D/s.sock" --say "turn zwei" > /dev/null 2>&1 + +if [ ! -s "$D/requests.log" ]; then + echo "FAIL no request reached the endpoint" + cat "$D/serve.log" + exit 1 +fi + +# every streamed turn must have asked; a provider that only answers on request +# is exactly the case that used to leave last_in at 0 +n=$(wc -l < "$D/requests.log") +asks=$(grep -c 'include_usage=True' "$D/requests.log") +if [ "$asks" -ne "$n" ]; then + fail "only $asks of $n requests asked for usage" +fi + +msgs=$(tail -1 "$D/requests.log" | + sed -n 's/.*msgs=\([0-9]*\).*/\1/p') +bytes=$(tail -1 "$D/requests.log" | + sed -n 's/.*bytes=\([0-9]*\).*/\1/p') +if [ -z "$msgs" ] || [ -z "$bytes" ]; then + fail "cannot read the second request" + cat "$D/requests.log" +elif [ "$msgs" -ge 40 ]; then + fail "the second turn still carried $msgs messages" \ + "(compaction did not fire; request was $bytes bytes)" +else + echo "ok second turn: $bytes bytes, $msgs messages (compacted)" +fi + +if [ "$fails" -ne 0 ]; then + cat "$D/requests.log" + cat "$D/serve.log" + exit 1 +fi +echo "test_usage_request: ok" +exit 0