#!/bin/sh
# Benchmark pieces: lapse compaction (a conversation idle past the prompt
# cache's lifetime and above a floor compacts before its next request), the
# trial label and pic usage --by-trial, and the request cap per ask.
# --no-faults skips the crash cases (the release build has no crash hooks).
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
FAULTS=yes
[ "${1:-}" = --no-faults ] && FAULTS=no
here=$(cd "$(dirname "$0")" && pwd)
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-bench.XXXXXX")
export HOME="$T/home"
mkdir -p "$HOME"
spid=
cleanup() { [ -n "$spid" ] && kill "$spid" 2>/dev/null || :; [ -n "${KEEP:-}" ] && { echo "kept $T" >&2; return; }; rm -rf -- "$T"; }
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
unset PIC_TRIAL PIC_MAX_REQUESTS PIC_LAPSE PIC_LAPSE_SECONDS PIC_LAPSE_FLOOR PI_CACHE_RETENTION
export PIC_MODEL_CATALOG=offline PIC_PI_EXPORT=0
big() { yes "$1$1$1$1" | head -c 50000 | tr -d '\n'; } # 40000 characters: 10000 tokens by chars/4
WS="$T/ws"
mkdir "$WS" "$T/log"
printf 'text done\n' > "$T/done.txt"
# ---- lapse compaction, with the scripted provider --------------------------
DB="$T/lapse.sqlite"
pic() { "$PIC" --db "$DB" --workspace "$WS" "$@"; }
run() { pic "$@" run --script "$T/done.txt" 2>> "$T/stderr" || fail "run $*: $(tail -2 "$T/stderr")"; }
# Moves every entry SECONDS into the past: the conversation has been idle.
age() { sqlite3 "$DB" "UPDATE pic_entry SET created_ms = created_ms - $1 * 1000"; }
n=0
next() { n=$((n + 1)); pic submit "k$n" "${1:-go on}" --session "$s" > /dev/null; }
lapses() { pic dump | grep -c '^generation .* compaction reason=lapse' || :; }
pic submit k0 "$(big A)" > /dev/null
run --lapse on
s=$(pic sessions | awk '{print $1}')
next "$(big B)"
run --lapse on
next "$(big C)" # 30000 tokens: past the 20000 kept, so there is history to summarize
run --lapse on
[ "$(lapses)" = 0 ] || fail "lapse while the cache is warm"
age 400
next
run --lapse off
next
run # lapseCompaction defaults to off
[ "$(lapses)" = 0 ] || fail "lapse fired while off"
printf 'PASS: lapse compaction is off by default and with --lapse off\n'
age 400
next
run --lapse on --lapse-floor 1000000
[ "$(lapses)" = 0 ] || fail "lapse fired under the floor"
next
(export PIC_LAPSE=on PIC_LAPSE_FLOOR=1000000; run) # a subshell: sh keeps assignments made for a function
[ "$(lapses)" = 0 ] || fail "lapse fired under the floor (env)"
printf 'PASS: lapse compaction waits for the context floor\n'
pic settings cacheRetention long > /dev/null
age 400
next
run --lapse on
[ "$(lapses)" = 0 ] || fail "lapse fired inside the long cache's hour"
age 3700
next
pic --json --lapse on run --script "$T/done.txt" > "$T/lapse.jsonl" 2>> "$T/stderr" || fail "run: $(tail -2 "$T/stderr")"
[ "$(lapses)" = 1 ] || fail "no lapse past the long cache's hour: $(pic dump | grep '^generation')"
pic settings --unset cacheRetention > /dev/null
grep -q '"type":"compaction_start","reason":"lapse"' "$T/lapse.jsonl" || fail "event: $(grep compaction "$T/lapse.jsonl")"
grep -q '"type":"compaction_end","reason":"lapse","result":{"summary":' "$T/lapse.jsonl" || fail "end event"
idle=$(sqlite3 "$DB" "SELECT idle_seconds FROM pic_generation WHERE reason = 'lapse'")
tokens=$(sqlite3 "$DB" "SELECT context_tokens FROM pic_generation WHERE reason = 'lapse'")
[ "$idle" -ge 3700 ] && [ "$idle" -lt 3800 ] || fail "idle seconds journaled: $idle"
[ "$tokens" -gt 20000 ] || fail "context tokens journaled: $tokens"
[ "$(sqlite3 "$DB" "SELECT e.kind FROM pic_generation g JOIN pic_entry e ON e.seq = g.entry_seq WHERE g.reason = 'lapse'")" = compaction ] ||
fail "the lapse generation has no compaction entry"
pic check > /dev/null || fail "integrity"
printf 'PASS: the default lifetime follows cacheRetention (long: an hour)\n'
next "$(big D)"
run --lapse on
[ "$(lapses)" = 1 ] || fail "lapse fired again with a warm cache"
age 400
next "$(big E)" # each lapse below has new history to summarize
run --lapse on --lapse-floor 1000
[ "$(lapses)" = 2 ] || fail "no lapse past the short cache's 5 minutes"
age 100
next
run --lapse on --lapse-floor 1000
[ "$(lapses)" = 2 ] || fail "lapse fired at 100s with the 300s default"
age 100
next "$(big F)"
(export PIC_LAPSE_SECONDS=60; run --lapse on --lapse-floor 1000)
[ "$(lapses)" = 3 ] || fail "PIC_LAPSE_SECONDS did not shorten the lifetime"
age 100
next "$(big G)"
pic settings lapseCompaction on > /dev/null
pic settings lapseSeconds 60 > /dev/null
pic settings lapseFloorTokens 1000 > /dev/null
run
[ "$(lapses)" = 4 ] || fail "the lapse settings did not apply"
age 100
next
run --lapse-seconds 3600
[ "$(lapses)" = 4 ] || fail "--lapse-seconds did not override the setting"
pic settings --unset lapseCompaction > /dev/null
pic settings --unset lapseSeconds > /dev/null
pic settings --unset lapseFloorTokens > /dev/null
[ "$(pic dump | grep -c '^generation .* compaction reason=lapse idle=[0-9]* tokens=[0-9]*')" = 4 ] ||
fail "dump: $(pic dump | grep compaction)"
pic check > /dev/null || fail "integrity"
printf 'PASS: past the lifetime and above the floor, lapse compacts; flags, env and settings set both\n'
"$PIC" --lapse maybe dump > /dev/null 2>&1 && fail "--lapse maybe accepted"
PIC_LAPSE=maybe "$PIC" --db "$DB" dump > /dev/null 2>&1 && fail "PIC_LAPSE=maybe accepted"
"$PIC" --lapse-floor -1 dump > /dev/null 2>&1 && fail "a negative floor accepted"
printf 'PASS: bad lapse values are refused\n'
if [ "$FAULTS" = yes ]; then
DB="$T/lapse-crash.sqlite"
pic submit c0 "$(big A)" > /dev/null
run
s=$(pic sessions | awk '{print $1}')
next "$(big B)"
run
next "$(big C)"
run
age 400
next
rc=0
PIC_CRASH_AT=after-lapse:1 "$PIC" --db "$DB" --workspace "$WS" --lapse on run --script "$T/done.txt" > /dev/null 2>&1 || rc=$?
[ "$rc" = 77 ] || fail "lapse crash: expected exit 77, got $rc"
[ "$(sqlite3 "$DB" "SELECT count(*) FROM pic_generation WHERE reason = 'lapse' AND state = 'started'")" = 1 ] ||
fail "lapse crash: the decision was not journaled"
run --lapse off # the journaled decision stands, whatever this run's settings
[ "$(lapses)" -ge 1 ] || fail "lapse crash: recovery dropped the decision"
[ "$(pic dump | grep -c '^entry .* compaction ')" = 1 ] || fail "lapse crash: compactions"
[ "$(pic dump | grep -c '^submission .* answered ')" = 4 ] || fail "lapse crash: not answered"
pic check > /dev/null || fail "lapse crash: integrity"
printf 'PASS: a crash at the lapse decision recovers to one lapse compaction\n'
fi
# ---- the trial label and pic usage --by-trial, at a fake server -------------
# A reply with cache reads and writes: input 25, output 12, cacheRead 100, cacheWrite 40.
sed 's/"usage":{"input_tokens":25,"output_tokens":1}/"usage":{"input_tokens":25,"cache_read_input_tokens":100,"cache_creation_input_tokens":40,"output_tokens":1}/' \
"$here/streams/text.sse" > "$T/cached.sse"
grep -q cache_read_input_tokens "$T/cached.sse" || fail "fixture"
"$SERVER" "$T/port" "$T/log" 120 "sse:$T/cached.sse" &
spid=$!
i=0
while [ ! -s "$T/port" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "server did not start"; sleep 0.05; done
printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"k","models":[
{"id":"priced","cost":{"input":3,"output":15,"cacheRead":0.3,"cacheWrite":3.75}}]}}}' "$(cat "$T/port")" > "$T/models.json"
export PIC_MODELS_FILE="$T/models.json"
DB="$T/trial.sqlite"
pic --model fake/priced --trial arm-a ask one > /dev/null 2>> "$T/stderr" || fail "ask: $(tail -2 "$T/stderr")"
PIC_TRIAL=arm-a "$PIC" --db "$DB" --workspace "$WS" --model fake/priced ask -c two > /dev/null 2>> "$T/stderr" || fail "ask: $(tail -2 "$T/stderr")"
PIC_TRIAL=ignored "$PIC" --db "$DB" --workspace "$WS" --model fake/priced --trial 'arm b' ask three > /dev/null 2>> "$T/stderr" || fail "ask: $(tail -2 "$T/stderr")"
pic --model fake/priced ask four > /dev/null 2>> "$T/stderr" || fail "ask: $(tail -2 "$T/stderr")"
[ "$(sqlite3 "$DB" "SELECT group_concat(coalesce(trial, 'NULL'), ',') FROM (SELECT trial FROM pic_submission ORDER BY id)")" = 'arm-a,arm-a,arm b,NULL' ] ||
fail "trial labels: $(sqlite3 "$DB" 'SELECT id, trial FROM pic_submission')"
# Each reply: 25*3 + 12*15 + 100*0.3 + 40*3.75 = 435 per million.
pic usage --by-trial --json > "$T/usage.json" || fail "usage --by-trial"
grep -qx '{"trial":"arm-a","submissions":2,"requests":2,"input":50,"output":24,"cacheRead":200,"cacheWrite":80,"cost":0.00087}' "$T/usage.json" ||
fail "arm-a: $(cat "$T/usage.json")"
grep -qx '{"trial":"arm b","submissions":1,"requests":1,"input":25,"output":12,"cacheRead":100,"cacheWrite":40,"cost":0.000435}' "$T/usage.json" ||
fail "arm b: $(cat "$T/usage.json")"
grep -qx '{"trial":null,"submissions":1,"requests":1,"input":25,"output":12,"cacheRead":100,"cacheWrite":40,"cost":0.000435}' "$T/usage.json" ||
fail "unlabelled: $(cat "$T/usage.json")"
[ "$(wc -l < "$T/usage.json" | tr -d ' ')" = 3 ] || fail "arms: $(cat "$T/usage.json")"
pic usage --by-trial > "$T/usage.txt" || fail "usage --by-trial (text)"
grep -q '^arm-a *2 *2 *50 *24 *200 *80 *0.000870$' "$T/usage.txt" || fail "text: $(cat "$T/usage.txt")"
grep -q '^(none) *1 *1 *25 ' "$T/usage.txt" || fail "text unlabelled: $(cat "$T/usage.txt")"
"$PIC" --trial "$(printf '%065d' 0)" dump > /dev/null 2>&1 && fail "a 65-byte label accepted"
"$PIC" --trial "$(printf 'a\tb')" dump > /dev/null 2>&1 && fail "a label with a tab accepted"
PIC_TRIAL="$(printf 'a\nb')" "$PIC" --db "$DB" dump > /dev/null 2>&1 && fail "PIC_TRIAL with a newline accepted"
pic check > /dev/null || fail "integrity"
printf 'PASS: the trial label is kept per request and pic usage --by-trial sums cost and tokens by arm\n'
kill "$spid" 2>/dev/null || :
spid=
# ---- the request cap ----------------------------------------------------------
rm -f "$T/port" "$T"/log/*
"$SERVER" "$T/port" "$T/log" 120 "sse:$here/streams/tool_use.sse" "sse:$here/streams/tool_use.sse" \
"sse:$here/streams/tool_use.sse" "sse:$here/streams/text.sse" &
spid=$!
i=0
while [ ! -s "$T/port" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "server did not start"; sleep 0.05; done
printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"k","models":[{"id":"m"}]}}}' \
"$(cat "$T/port")" > "$T/models.json"
DB="$T/cap.sqlite"
pic --json --model fake/m --max-requests 2 ask 'write notes' > "$T/cap.jsonl" 2> "$T/stderr" || fail "capped ask: $(tail -2 "$T/stderr")"
[ "$(ls "$T/log" | grep -c '\.req$')" = 2 ] || fail "cap: $(ls "$T/log" | grep -c '\.req$') requests sent"
[ "$(sqlite3 "$DB" "SELECT status || ' ' || stop_reason || ' ' || max_requests FROM pic_submission")" = 'stopped request_cap 2' ] ||
fail "cap: $(sqlite3 "$DB" 'SELECT * FROM pic_submission')"
grep -q '"type":"agent_end",.*"status":"stopped","stopReason":"request_cap"' "$T/cap.jsonl" || fail "cap event: $(grep agent_end "$T/cap.jsonl")"
grep -q '"errorMessage"' "$T/cap.jsonl" && fail "cap: reported as an error"
pic dump | grep -q '^submission .* stopped stop=request_cap ' || fail "cap dump: $(pic dump | grep '^submission')"
pic log | grep -q 'request stopped: request_cap' || fail "cap log: $(pic log)"
pic check > /dev/null || fail "cap: integrity"
PIC_MAX_REQUESTS=1 "$PIC" --db "$DB" --workspace "$WS" --model fake/m ask -c 'go on' > "$T/out" 2>> "$T/stderr" || fail "continue: $(tail -2 "$T/stderr")"
[ "$(ls "$T/log" | grep -c '\.req$')" = 3 ] || fail "continue: requests sent"
[ "$(sqlite3 "$DB" "SELECT status || ' ' || coalesce(stop_reason, '-') FROM pic_submission ORDER BY id DESC LIMIT 1")" = 'stopped request_cap' ] ||
fail "PIC_MAX_REQUESTS: $(sqlite3 "$DB" 'SELECT * FROM pic_submission')"
pic --model fake/m ask -c 'finish' > "$T/out" 2>> "$T/stderr" || fail "continue: $(tail -2 "$T/stderr")"
grep -q 'Hello' "$T/out" || fail "continue: no answer: $(cat "$T/out")"
grep -q '"text":"finish"' "$T/log/4.req" || fail "continue: the new message was not sent"
grep -q '"tool_result"' "$T/log/4.req" || fail "continue: the capped turn's tool results were not sent"
[ "$(sqlite3 "$DB" "SELECT group_concat(status, ',') FROM (SELECT status FROM pic_submission ORDER BY id)")" = 'stopped,stopped,answered' ] ||
fail "continue: statuses"
pic check > /dev/null || fail "continue: integrity"
printf 'PASS: --max-requests stops before request N+1, as request_cap, and ask -c continues\n'
kill "$spid" 2>/dev/null || :
spid=
if [ "$FAULTS" = yes ]; then
# A crash with the first request in flight: its retry counts as the same
# request, so the cap of 1 still stops before a second.
for point in after-generation-started:1 after-request-cap:1; do
rm -f "$T/port" "$T"/log/*
"$SERVER" "$T/port" "$T/log" 120 "sse:$here/streams/tool_use.sse" &
spid=$!
i=0
while [ ! -s "$T/port" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "server did not start"; sleep 0.05; done
printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"k","models":[{"id":"m"}]}}}' \
"$(cat "$T/port")" > "$T/models.json"
DB="$T/cap-crash-${point%%:*}.sqlite"
rc=0
PIC_CRASH_AT=$point "$PIC" --db "$DB" --workspace "$WS" --model fake/m --max-requests 1 ask 'write notes' > /dev/null 2>&1 || rc=$?
[ "$rc" = 77 ] || fail "cap crash $point: expected exit 77, got $rc"
sent=$(ls "$T/log" | grep -c '\.req$' || :)
pic --model fake/m run 2>> "$T/stderr" || fail "cap crash $point: recovery: $(tail -2 "$T/stderr")"
[ "$(sqlite3 "$DB" "SELECT status || ' ' || stop_reason FROM pic_submission")" = 'stopped request_cap' ] ||
fail "cap crash $point: $(sqlite3 "$DB" 'SELECT * FROM pic_submission')"
[ "$(sqlite3 "$DB" "SELECT count(*) FROM pic_generation WHERE state = 'done'")" = 1 ] || fail "cap crash $point: replies"
case $point in
after-generation-started:*) [ "$(ls "$T/log" | grep -c '\.req$')" = $((sent + 1)) ] || fail "cap crash $point: not retried once" ;;
*) [ "$(ls "$T/log" | grep -c '\.req$')" = "$sent" ] || fail "cap crash $point: a request after the cap" ;;
esac
pic check > /dev/null || fail "cap crash $point: integrity"
kill "$spid" 2>/dev/null || :
spid=
done
printf 'PASS: a crash in flight or at the cap keeps the count from the journal\n'
fi