#!/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_LAPSE_HOLDOUT=0 # no random holdouts except where a case sets one
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
[ "$(lapses)" = 0 ] || fail "lapse fired while off"
printf 'PASS: lapse compaction stays off 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 --lapse-floor 1000
[ "$(lapses)" = 0 ] || fail "lapse fired inside the long cache's hour"
age 3700
next
pic --json --lapse on --lapse-floor 1000 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'
# ---- on by default, the holdout and pic usage --lapse --------------------------
DB="$T/holdout.sqlite"
# Each cold cache is the context policy's journaled answer to PreRequest, with its arm.
arms() { sqlite3 "$DB" "SELECT group_concat(arm, ',') FROM (SELECT json_extract(context, '\$.arm') AS arm FROM pic_hook_run
WHERE event = 'PreRequest' AND reason = 'lapse' ORDER BY submission_id, ref)"; }
pic submit h0 "$(big A)" > /dev/null
run --lapse off
s=$(pic sessions | awk '{print $1}')
next "$(big B)"
run --lapse off
next "$(big C)"
run --lapse off
age 400
next
run # on by default, but 30000 tokens is under the default floor of 100000
[ "$(lapses)" = 0 ] || fail "lapse fired under the default floor"
[ "$(arms)" = small ] || fail "the cold cache under the floor was not kept: $(arms)"
age 400
next "$(big D)"
(export PIC_LAPSE_HOLDOUT=1; run --lapse-floor 1000)
[ "$(lapses)" = 0 ] || fail "a held-out lapse compacted"
[ "$(arms)" = small,holdout ] || fail "arms after a holdout: $(arms)"
age 400
next "$(big E)"
run --lapse-floor 1000
[ "$(lapses)" = 1 ] || fail "no lapse by default above the floor"
[ "$(arms)" = small,holdout,compact ] || fail "arms after a compaction: $(arms)"
next
run --lapse-floor 1000
[ "$(arms)" = small,holdout,compact ] || fail "a warm cache was kept as a cold one: $(arms)"
pic usage --lapse > "$T/lapse.txt" || fail "usage --lapse"
grep -q '^cold caches: 1 compacted, 1 held out, 1 under the floor$' "$T/lapse.txt" || fail "usage --lapse: $(cat "$T/lapse.txt")"
grep -q '^trim: 1 compacted, 1 held out$' "$T/lapse.txt" || fail "usage --lapse names the mode: $(cat "$T/lapse.txt")"
grep -q '^not enough to compare yet' "$T/lapse.txt" || fail "usage --lapse compared too soon: $(cat "$T/lapse.txt")"
pic usage --lapse --json | grep -q '"modes":\[{"mode":"trim","compacted":1,"heldOut":1,.*"ratio":null,"saved":null}\]}$' ||
fail "usage --lapse --json: $(pic usage --lapse --json)"
pic check > /dev/null || fail "integrity"
PIC_LAPSE_HOLDOUT=2 "$PIC" --db "$DB" dump > /dev/null 2>&1 && fail "PIC_LAPSE_HOLDOUT=2 accepted"
PIC_LAPSE_HOLDOUT=some "$PIC" --db "$DB" dump > /dev/null 2>&1 && fail "PIC_LAPSE_HOLDOUT=some accepted"
(unset PIC_LAPSE_HOLDOUT; pic settings lapseHoldout 0.5 > /dev/null; pic dump > /dev/null) || fail "lapseHoldout 0.5 refused"
pic settings lapseHoldout -1 > /dev/null
(unset PIC_LAPSE_HOLDOUT; pic dump > /dev/null 2>&1) && fail "lapseHoldout -1 accepted"
pic settings --unset lapseHoldout > /dev/null
printf 'PASS: lapse compaction is on by default above 100000 tokens; held-out and small cold caches are kept\n'
# The comparison: ten cold caches, five compacted whose windows cost 1 and
# five held out whose windows cost 2, and one under the floor that closes
# the last window before a request costing 7.
DB="$T/report.sqlite"
pic submit r1 one > /dev/null
run --lapse off
s=$(pic sessions | awk '{print $1}')
k=1
while [ "$k" -lt 12 ]; do next; run --lapse off; k=$((k + 1)); done
sqlite3 "$DB" "UPDATE pic_generation SET usage = json_set(coalesce(usage, '{}'), '\$.pic_cost.total',
CASE WHEN submission_id <= 5 THEN 1 WHEN submission_id <= 10 THEN 2 ELSE 7 END) WHERE state = 'done'"
# Five compacted in trim mode and five held out, as the policy journals them.
sqlite3 "$DB" "INSERT INTO pic_hook_run(event, session_id, submission_id, ref, command, duration_ms, state, reason, context, created_ms)
SELECT 'PreRequest', u.session_id, u.id, (SELECT min(turn) FROM pic_generation WHERE submission_id = u.id), 'pic:compact', 0, 'done', 'lapse',
json_object('arm', CASE WHEN u.id <= 5 THEN 'compact' WHEN u.id <= 10 THEN 'holdout' ELSE 'small' END, 'mode', 'trim'), 0
FROM pic_submission u WHERE u.id <= 11"
want='{"compacted":5,"heldOut":5,"small":1,"modes":[{"mode":"trim","compacted":5,"heldOut":5,"meanCompacted":1.000000,"meanHeldOut":2.000000,"ratio":0.5000,"ratioLow":0.5000,"ratioHigh":0.5000,"saved":5.0000,"savedLow":5.0000,"savedHigh":5.0000}]}'
[ "$(pic usage --lapse --json)" = "$want" ] || fail "usage --lapse --json: $(pic usage --lapse --json)"
pic usage --lapse | grep -q '^saved: \$5.00 over 5 compactions (95% interval \$5.00 to \$5.00)$' || fail "usage --lapse: $(pic usage --lapse)"
# A journal from before the answers were journaled keeps its pic_lapse rows: summaries.
sqlite3 "$DB" "CREATE TABLE pic_lapse(submission_id INTEGER NOT NULL, turn INTEGER NOT NULL, session_id TEXT NOT NULL,
decided_ms INTEGER NOT NULL, idle_seconds INTEGER NOT NULL, context_tokens INTEGER NOT NULL, arm TEXT NOT NULL,
PRIMARY KEY(submission_id, turn));
INSERT INTO pic_lapse SELECT id, 99, session_id, 0, 400, 200000, 'compact' FROM pic_submission WHERE id = 1"
pic usage --lapse --json | grep -q '"compacted":6,"heldOut":5,"small":1,"modes":\[{"mode":"trim","compacted":5,.*},{"mode":"summary","compacted":1,"heldOut":0,' ||
fail "usage --lapse with old rows: $(pic usage --lapse --json)"
printf 'PASS: pic usage --lapse compares the cost from each cold cache to the next, compacted against held out\n'
# usage --lapse --all pools every registered workspace's journal (no --db): two workspaces each
# with the report fixture's ten cold caches give twenty; one whose journal is gone and one whose
# journal is not a database are skipped and counted, not an error.
home1=$HOME
export HOME="$T/home-all" # its own list of workspaces
mkdir "$HOME"
wspic() { w=$1; shift; "$PIC" --workspace "$w" "$@"; }
lapse_fixture() { # WORKSPACE: five compacted lapses whose windows cost 1, five held out costing 2, one small
w=$1
mkdir -p "$w"
wspic "$w" submit r1 one > /dev/null
wspic "$w" --lapse off run --script "$T/done.txt" 2>> "$T/stderr" || fail "all: run: $(tail -2 "$T/stderr")"
sid=$(wspic "$w" sessions | awk '{print $1}')
k=1
while [ "$k" -lt 12 ]; do
wspic "$w" submit "r$((k + 1))" "go on" --session "$sid" > /dev/null
wspic "$w" --lapse off run --script "$T/done.txt" 2>> "$T/stderr" || fail "all: run: $(tail -2 "$T/stderr")"
k=$((k + 1))
done
sqlite3 "$w/.pic/journal.sqlite" "UPDATE pic_generation SET usage = json_set(coalesce(usage, '{}'), '\$.pic_cost.total',
CASE WHEN submission_id <= 5 THEN 1 WHEN submission_id <= 10 THEN 2 ELSE 7 END) WHERE state = 'done';
INSERT INTO pic_hook_run(event, session_id, submission_id, ref, command, duration_ms, state, reason, context, created_ms)
SELECT 'PreRequest', u.session_id, u.id, (SELECT min(turn) FROM pic_generation WHERE submission_id = u.id), 'pic:compact', 0, 'done', 'lapse',
json_object('arm', CASE WHEN u.id <= 5 THEN 'compact' WHEN u.id <= 10 THEN 'holdout' ELSE 'small' END, 'mode', 'trim'), 0
FROM pic_submission u WHERE u.id <= 11"
}
lapse_fixture "$T/wa"
lapse_fixture "$T/wb"
for gone in wc wd; do
mkdir "$T/$gone"
wspic "$T/$gone" submit g1 hello > /dev/null
done
rm -f "$T/wc/.pic/journal.sqlite" "$T/wc/.pic/journal.sqlite-wal" "$T/wc/.pic/journal.sqlite-shm"
rm -f "$T/wd/.pic/journal.sqlite-wal" "$T/wd/.pic/journal.sqlite-shm"
printf 'this is not a database\n' > "$T/wd/.pic/journal.sqlite"
all=$(cd "$T" && "$PIC" usage --lapse --all --json) || fail "usage --lapse --all"
case $all in
'{"compacted":10,"heldOut":10,"small":2,"modes":[{"mode":"trim","compacted":10,"heldOut":10,'*'"saved":10.0000,'*'"workspaces":2,"skipped":2}') ;;
*) fail "usage --lapse --all --json: $all" ;;
esac
[ "$("$PIC" usage --json --all --lapse)" = "$all" ] || fail "usage --json --all --lapse: flags in another order"
"$PIC" usage --lapse --all | grep -q '^saved: \$10.00 over 10 compactions' || fail "usage --lapse --all: $("$PIC" usage --lapse --all)"
"$PIC" usage --lapse --all | grep -q '^2 workspaces pooled, 2 skipped' || fail "usage --lapse --all: no skipped count"
export HOME=$home1
printf 'PASS: pic usage --lapse --all pools every registered workspace and skips the ones it cannot read\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-policy-answer:1 "$PIC" --db "$DB" --workspace "$WS" --lapse on --lapse-floor 1000 run --script "$T/done.txt" > /dev/null 2>&1 || rc=$?
[ "$rc" = 77 ] || fail "lapse crash: expected exit 77, got $rc"
[ "$(sqlite3 "$DB" "SELECT json_extract(context, '\$.compact') FROM pic_hook_run WHERE event = 'PreRequest' AND reason = 'lapse'")" = trim ] ||
fail "lapse crash: the answer was not journaled"
[ "$(lapses)" = 0 ] || fail "lapse crash: compacted before the crash"
run --lapse off # the journaled answer stands, whatever this run's settings
[ "$(lapses)" = 1 ] || fail "lapse crash: recovery dropped the answer"
[ "$(pic dump | grep -c '^entry .* compaction ')" = 1 ] || fail "lapse crash: compactions"
[ "$(sqlite3 "$DB" "SELECT count(*) FROM pic_hook_run WHERE event = 'PreRequest'")" = 1 ] || fail "lapse crash: asked again"
[ "$(pic dump | grep -c '^submission .* answered ')" = 4 ] || fail "lapse crash: not answered"
pic check > /dev/null || fail "lapse crash: integrity"
# In summary mode, a crash once its summary request is journaled.
pic settings lapseMode summary > /dev/null
age 400
next "$(big D)"
rc=0
PIC_CRASH_AT=after-compaction-started:1 "$PIC" --db "$DB" --workspace "$WS" --lapse-floor 1000 run --script "$T/done.txt" > /dev/null 2>&1 || rc=$?
[ "$rc" = 77 ] || fail "summary lapse crash: expected exit 77, got $rc"
run --lapse off
[ "$(lapses)" -ge 2 ] || fail "summary lapse crash: recovery dropped the answer"
[ "$(pic dump | grep -c '^entry .* compaction ')" = 2 ] || fail "summary lapse crash: compactions"
[ "$(sqlite3 "$DB" "SELECT group_concat(state, ',') FROM (SELECT state FROM pic_generation WHERE reason = 'lapse'
AND submission_id = (SELECT max(submission_id) FROM pic_generation WHERE reason = 'lapse') ORDER BY attempt)")" = failed,done ] ||
fail "summary lapse crash: the summary request was not asked again"
sqlite3 "$DB" "SELECT body FROM pic_entry WHERE kind = 'compaction' ORDER BY seq DESC LIMIT 1" | grep -q 'no summary was made' &&
fail "summary lapse crash: trimmed instead of summarized"
pic settings --unset lapseMode > /dev/null
pic check > /dev/null || fail "summary 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")"
[ "$(head -1 "$T/usage.txt")" = "$(printf '%-24s %11s %8s %12s %12s %12s %12s %12s' trial submissions requests input output cacheRead cacheWrite cost)" ] ||
fail "text header with no verify command: $(head -1 "$T/usage.txt")"
pic log | grep -q '(verify' && fail "a verdict with no verify command: $(pic log)"
"$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'
# ---- a verdict per request: the trusted workspace's verify command ------------
# Two arms over the same two tasks; the verify command passes while the file pass exists.
VWS="$T/vws"
mkdir -p "$VWS/.pic"
printf '{"command":"echo ran >> %s; test -f pass"}\n' "$T/vledger" > "$VWS/.pic/verify.json"
ran() { [ -f "$T/vledger" ] && wc -l < "$T/vledger" | tr -d ' ' || echo 0; }
DB="$T/verdict-untrusted.sqlite"
vpic() { "$PIC" --db "$DB" --workspace "$VWS" "$@"; }
vpic --model fake/priced --trial arm-a ask 'untrusted' > /dev/null 2>> "$T/stderr" || fail "ask: $(tail -2 "$T/stderr")"
[ "$(ran)" = 0 ] || fail "the verify command ran in an untrusted workspace"
[ "$(sqlite3 "$DB" 'SELECT count(*) FROM pic_verdict')" = 0 ] || fail "a verdict untrusted"
vpic trust yes > /dev/null
DB="$T/verdict.sqlite"
task() { # ARM PASS TEXT
if [ "$2" = pass ]; then touch "$VWS/pass"; else rm -f "$VWS/pass"; fi
vpic --model fake/priced --trial "$1" ask "$3" > /dev/null 2>> "$T/stderr" || fail "ask $3: $(tail -2 "$T/stderr")"
}
task arm-a pass 'task one'
task arm-a fail 'task two'
task arm-b pass 'task one'
rm -f "$VWS/pass"
vpic --json --model fake/priced --trial arm-b ask 'task two' > "$T/verdict.jsonl" 2>> "$T/stderr" || fail "ask: $(tail -2 "$T/stderr")"
[ "$(ran)" = 4 ] || fail "the verify command ran $(ran) times for 4 requests"
grep -q '"type":"agent_end",.*"status":"answered".*"verdict":"fail"' "$T/verdict.jsonl" || fail "agent_end verdict: $(grep agent_end "$T/verdict.jsonl")"
[ "$(sqlite3 "$DB" "SELECT group_concat(outcome || ':' || exit_code, ',') FROM (SELECT outcome, exit_code FROM pic_verdict ORDER BY submission_id)")" = 'pass:0,fail:1,pass:0,fail:1' ] ||
fail "verdicts: $(sqlite3 "$DB" 'SELECT * FROM pic_verdict')"
vpic usage --by-trial --json > "$T/vusage.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,"passed":1,"failed":1}' "$T/vusage.json" ||
fail "arm-a: $(cat "$T/vusage.json")"
grep -qx '{"trial":"arm-b","submissions":2,"requests":2,"input":50,"output":24,"cacheRead":200,"cacheWrite":80,"cost":0.00087,"passed":1,"failed":1}' "$T/vusage.json" ||
fail "arm-b: $(cat "$T/vusage.json")"
vpic usage --by-trial > "$T/vusage.txt" || fail "usage --by-trial (text)"
head -1 "$T/vusage.txt" | grep -q ' cost *passed *failed$' || fail "text header: $(head -1 "$T/vusage.txt")"
grep -q '^arm-a *2 *2 *50 *24 *200 *80 *0.000870 *1 *1$' "$T/vusage.txt" || fail "text: $(cat "$T/vusage.txt")"
for c in $(vpic sessions | awk '{print $1}'); do vpic log "$c"; done > "$T/vlog"
[ "$(grep -c '(verify: passed)' "$T/vlog")" = 2 ] && [ "$(grep -c '(verify: failed, exit 1)' "$T/vlog")" = 2 ] || fail "log: $(cat "$T/vlog")"
vpic check > /dev/null || fail "verdict: integrity"
printf 'PASS: two trials over the same tasks report requests, tokens, cost, passed and failed per arm\n'
if [ "$FAULTS" = yes ]; then
# A crash after the command ran, before its verdict commits: unknown, not run again.
# A crash after the verdict commits, before the request is answered: nothing lost.
touch "$VWS/pass"
for point in after-verdict-started after-verdict-run after-verdict; do
DB="$T/verdict-${point}.sqlite"
before=$(ran)
rc=0
PIC_CRASH_AT=$point:1 vpic --model fake/priced ask go > /dev/null 2>&1 || rc=$?
[ "$rc" = 77 ] || fail "$point: expected exit 77, got $rc"
vpic --model fake/priced run 2>> "$T/stderr" || fail "$point: recovery: $(tail -2 "$T/stderr")"
[ "$(sqlite3 "$DB" 'SELECT status FROM pic_submission')" = answered ] || fail "$point: not answered"
v=$(sqlite3 "$DB" "SELECT state || ' ' || coalesce(outcome, '-') FROM pic_verdict")
case $point in
after-verdict-started) [ "$v" = 'unknown -' ] && [ "$(ran)" = "$before" ] || fail "$point: $v, ran $(ran) after $before" ;;
after-verdict-run) [ "$v" = 'unknown -' ] && [ "$(ran)" = $((before + 1)) ] || fail "$point: $v, ran $(ran) after $before" ;;
*) [ "$v" = 'done pass' ] && [ "$(ran)" = $((before + 1)) ] || fail "$point: $v, ran $(ran) after $before" ;;
esac
vpic dump | grep -q "^verdict 1 entry=[0-9]* ${v%% *}" || fail "$point: dump: $(vpic dump | grep '^verdict')"
vpic check > /dev/null || fail "$point: integrity"
done
vpic usage --by-trial --json | grep -qx '{"trial":null,"submissions":1,"requests":1,.*"passed":1,"failed":0}' ||
fail "after a crash: $(vpic usage --by-trial --json)"
DB="$T/verdict-after-verdict-run.sqlite"
vpic usage --by-trial --json | grep -qx '{"trial":null,.*"passed":0,"failed":0,"unknown":1}' ||
fail "unknown: $(vpic usage --by-trial --json)"
vpic log | grep -q '(verify: unknown, interrupted; not run again)' || fail "unknown log: $(vpic log)"
printf 'PASS: a crash at the verdict never runs the verify command again and loses no verdict\n'
fi
kill "$spid" 2>/dev/null || :
spid=
# ---- pic usage --by-tool: calls, failures and the requests that called them ------
# Two requests call write (one into the workspace, one under the first's file, which cannot be made) and one calls nothing.
sed 's|notes.txt|notes.txt/inside.txt|' "$here/streams/tool_use.sse" > "$T/tool_bad.sse"
grep -q 'notes.txt/inside.txt' "$T/tool_bad.sse" || fail "fixture"
rm -f "$T/port" "$T"/log/*
"$SERVER" "$T/port" "$T/log" 120 "sse:$here/streams/tool_use.sse" "sse:$here/streams/text.sse" "sse:$T/tool_bad.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":"priced","cost":{"input":3,"output":15,"cacheRead":0.3,"cacheWrite":3.75}}]}}}' "$(cat "$T/port")" > "$T/models.json"
DB="$T/tool.sqlite"
pic --model fake/priced ask 'write notes' > /dev/null 2>> "$T/stderr" || fail "ask: $(tail -2 "$T/stderr")"
pic --model fake/priced ask 'write elsewhere' > /dev/null 2>> "$T/stderr" || fail "ask: $(tail -2 "$T/stderr")"
[ "$(sqlite3 "$DB" "SELECT group_concat(tool || ':' || is_error, ',') FROM (SELECT tool, is_error FROM pic_effect ORDER BY id)")" = 'write:0,write:1' ] ||
fail "effects: $(sqlite3 "$DB" 'SELECT tool, is_error, substr(result, 1, 80) FROM pic_effect')"
# Each calling request: 25*3 + 40*15 = 675 per million.
pic usage --by-tool --json > "$T/tools.json" || fail "usage --by-tool"
[ "$(cat "$T/tools.json")" = '{"tool":"write","calls":2,"failures":1,"requests":2,"input":50,"output":80,"cacheRead":0,"cacheWrite":0,"cost":0.00135}' ] ||
fail "by-tool json: $(cat "$T/tools.json")"
pic usage --by-tool > "$T/tools.txt" || fail "usage --by-tool (text)"
grep -q '^write *2 *1 *2 *50 *80 *0 *0 *0.001350$' "$T/tools.txt" || fail "by-tool text: $(cat "$T/tools.txt")"
pic usage --by-tool extra > /dev/null 2>&1 && fail "usage --by-tool took an argument"
printf 'PASS: pic usage --by-tool counts each tool'"'"'s calls and failures and sums the requests that called it\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