#!/bin/sh
# Remote control file uploads, get_changes diffs, images, and large journal scaling.
# Usage: test/pic/remote_files.sh [--no-faults]
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
RELAY=${RELAY:?set RELAY to the fake_relay binary}
PHONE=${PHONE:?set PHONE to the fake_phone binary}
SQLITE3=${SQLITE3:-sqlite3}
FAULTS=1
[ "${1:-}" = --no-faults ] && FAULTS=0
here=$(cd "$(dirname "$0")" && pwd)
S=$here/streams
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-remote-files.XXXXXX")
export HOME="$T/home"
. "$here/remote_lib.sh"
init_paired 2
serve "sse:$S/text.sse"
pic ask 'first question' > /dev/null 2> "$T/ask.err" || fail "ask: $(cat "$T/ask.err")"
SID=$(q "SELECT id FROM pic_session ORDER BY updated_ms DESC LIMIT 1")
SESS="$DB/$SID"
remote
# get_changes (pic's own): the files a conversation's write and edit calls changed, each from before
# the first of them to what it holds now, with its lines added and removed and its diff's hunks; a
# file put back as it was is left out, one whose earlier bytes are not text says so; a fork shows
# its origin's changes too.
printf 'v0\nkeep\n' > "$WS/ch-mod.txt"
printf 'gone\n' > "$WS/ch-del.txt"
printf 'same\n' > "$WS/ch-back.txt"
printf 'a\000b' > "$WS/ch-bin.dat"
TAB=$(printf '\t')
chedit() { printf 'raw edit {"path":"%s","edits":[{"oldText":"%s","newText":"%s"}]}' "$1" "$2" "$3"; }
printf '%s\n' "tool write ch-new.txt n1${TAB}$(chedit ch-mod.txt v0 v1)${TAB}write ch-del.txt x${TAB}$(chedit ch-back.txt same other)${TAB}write ch-bin.dat text" \
"tool $(chedit ch-back.txt other same)" "text done" > "$T/changes.script"
pic submit k-changes-1 'change some files' > /dev/null || fail "changes: submit"
CSID=$(q "SELECT session_id FROM pic_submission WHERE request_key = 'k-changes-1'")
pic run --script "$T/changes.script" > /dev/null 2> "$T/changes.err" || fail "changes: run: $(cat "$T/changes.err")"
rm "$WS/ch-del.txt"
cl() { # SELECT [WHERE]: of the files the last get_changes listed
"$SQLITE3" :memory: "SELECT $1 FROM json_each(json_extract(CAST(readfile('$T/changes.json') AS TEXT), '\$.payload.data.files')) ${2:-}"
}
script "$T/ph1" <<EOS
cmd k-changes-00000001 {"type":"command","session":"$DB/$CSID","key":"k-changes-00000001","payload":{"type":"get_changes"}}
expect "key":"k-changes-00000001","payload":{"type":"response","command":"get_changes","success":true
cmd k-changes-00000002 {"type":"command","session":"$SESS","key":"k-changes-00000002","payload":{"type":"get_changes"}}
expect "key":"k-changes-00000002","payload":{"type":"response","command":"get_changes","success":true,"data":{"files":[]}}
EOS
done_ok $PR "get_changes"
grep -F '"key":"k-changes-00000001"' "$T/ph1.run" | tail -1 | sed 's/^<- //' > "$T/changes.json"
[ "$(cl "group_concat(json_extract(value, '\$.path') || ' ' || json_extract(value, '\$.status') || ' ' ||
coalesce(json_extract(value, '\$.added') || '+' || json_extract(value, '\$.removed') || '-', json_extract(value, '\$.why')), '|')")" = \
"ch-bin.dat modified binary|ch-del.txt deleted 0+1-|ch-mod.txt modified 1+1-|ch-new.txt added 1+0-" ] ||
fail "get_changes: files: $(cat "$T/changes.json")"
[ "$(cl "json_extract(value, '\$.diff')" "WHERE json_extract(value, '\$.path') = 'ch-del.txt'" | head -1)" = "@@ -1,1 +0,0 @@" ] || fail "get_changes: the deleted file's diff: $(cat "$T/changes.json")"
cl "json_extract(value, '\$.diff')" "WHERE json_extract(value, '\$.path') = 'ch-mod.txt'" > "$T/ch-mod.diff"
grep -qx -- '-v0' "$T/ch-mod.diff" && grep -qx -- '+v1' "$T/ch-mod.diff" && grep -qx -- ' keep' "$T/ch-mod.diff" ||
fail "get_changes: the edit's diff: $(cat "$T/ch-mod.diff")"
FORK=$(pic fork "$CSID" 2> "$T/chfork.err" | tail -1) || fail "changes: fork: $(cat "$T/chfork.err")"
FCSID=$(q "SELECT id FROM pic_session WHERE forked_from = '$CSID'")
[ -n "$FCSID" ] || fail "changes: no fork: $FORK"
script "$T/ph1" <<EOS
cmd k-changes-00000003 {"type":"command","session":"$DB/$FCSID","key":"k-changes-00000003","payload":{"type":"get_changes"}}
expect "key":"k-changes-00000003","payload":{"type":"response","command":"get_changes","success":true,"data":{"files":[{"path":"ch-bin.dat"
EOS
done_ok $PR "get_changes, a fork"
printf 'PASS: get_changes lists the files a conversation changed with their diffs, leaving out what was put back; a fork shows its origin'"'"'s\n'
# The limits, each counted as the bytes go out (JSON-escaped), so the answer fits a message: a
# file over 4 MiB now is too large; one whose earlier bytes were over rewindMaxBytes is not kept;
# a diff of control bytes (escaped six times over) over 256 KiB is too large, as are the diffs
# past 1 MiB together; none of these says lines added or removed. A helper the conversation
# started in this journal has its edits shown with the conversation's.
head -c 1572864 /dev/zero | tr '\0' 'o' > "$WS/ch-notkept.txt"
for f in big a b c d e f g h; do printf 'x\n' > "$WS/ch-esc-$f.txt"; done
printf '%s\n' "tool write ch-notkept.txt small${TAB}write ch-esc-big.txt y${TAB}write ch-esc-a.txt y${TAB}write ch-esc-b.txt y${TAB}write ch-esc-c.txt y${TAB}write ch-esc-d.txt y${TAB}write ch-esc-e.txt y${TAB}write ch-esc-f.txt y${TAB}write ch-esc-g.txt y${TAB}write ch-esc-h.txt y" \
"text done" > "$T/limits.script"
pic submit k-limits-1 'change big files' > /dev/null || fail "limits: submit"
LSID=$(q "SELECT session_id FROM pic_submission WHERE request_key = 'k-limits-1'")
pic run --script "$T/limits.script" > /dev/null 2> "$T/limits.err" || fail "limits: run: $(cat "$T/limits.err")"
head -c 5242880 /dev/zero | tr '\0' 'z' > "$WS/ch-esc-big.txt"
esc() { awk -v n="$1" 'BEGIN { for (i = 0; i < n; i++) { for (j = 0; j < 29; j++) printf "\033"; printf "\n" } }'; }
esc 1800 > "$WS/ch-esc-a.txt" # 52 KiB, over 300 KiB escaped
for f in b c d e f g h; do esc 1024 > "$WS/ch-esc-$f.txt"; done # 30 KiB, about 177 KiB escaped each
LRDB="$(cd "$(dirname "$DB")" && pwd -P)/$(basename "$DB")"
printf '%s\n' "tool write ch-helper.txt h1" "text done" > "$T/helper.script"
env PIC_ORIGIN=agent PIC_PARENT="$LRDB/$LSID" "$PIC" --db "$DB" --workspace "$WS" --model fake/m submit k-limits-h 'a helper' > /dev/null || fail "limits: helper submit"
pic run --script "$T/helper.script" > /dev/null 2> "$T/helper.err" || fail "limits: helper run: $(cat "$T/helper.err")"
[ "$(q "SELECT parent FROM pic_session_origin WHERE session_id = (SELECT session_id FROM pic_submission WHERE request_key = 'k-limits-h')")" = "$LRDB/$LSID" ] ||
fail "limits: the helper's origin: $(q "SELECT * FROM pic_session_origin")"
script "$T/ph1" <<EOS
cmd k-changes-00000004 {"type":"command","session":"$DB/$LSID","key":"k-changes-00000004","payload":{"type":"get_changes"}}
expect "key":"k-changes-00000004","payload":{"type":"response","command":"get_changes","success":true
EOS
done_ok $PR "get_changes, limits"
grep -F '"key":"k-changes-00000004"' "$T/ph1.run" | tail -1 | sed 's/^<- //' > "$T/changes.json"
[ "$(wc -c < "$T/changes.json")" -lt 2097152 ] || fail "get_changes: limits: the answer is $(wc -c < "$T/changes.json") bytes"
[ "$(cl "group_concat(json_extract(value, '\$.path') || ' ' || coalesce(json_extract(value, '\$.why'), 'diff') ||
coalesce(' ' || json_extract(value, '\$.added'), ''), '|')")" = \
"ch-esc-a.txt too large|ch-esc-b.txt diff 1024|ch-esc-big.txt too large|ch-esc-c.txt diff 1024|ch-esc-d.txt diff 1024|ch-esc-e.txt diff 1024|ch-esc-f.txt diff 1024|ch-esc-g.txt too large|ch-esc-h.txt too large|ch-helper.txt diff 1|ch-notkept.txt not kept" ] ||
fail "get_changes: limits: $(cl "group_concat(json_extract(value, '\$.path') || ' ' || coalesce(json_extract(value, '\$.why'), length(json_extract(value, '\$.diff'))), '|')")"
grep -qF '"cut"' "$T/changes.json" && fail "get_changes: limits: cut"
printf 'PASS: get_changes keeps to its limits as the bytes go out: too large and not kept, with no counts; a helper'"'"'s edits shown with its conversation'"'"'s\n'
# Past 200 files the list is cut, and says so.
i=0 calls=
: > "$T/many.script"
while [ $i -lt 201 ]; do # ten calls a turn
calls="$calls${calls:+$TAB}write many/f$i.txt n$i"
i=$((i + 1))
if [ $((i % 10)) = 0 ] || [ $i = 201 ]; then
printf 'tool %s\n' "$calls" >> "$T/many.script"
calls=
fi
done
printf 'text done\n' >> "$T/many.script"
pic submit k-many-files 'write many files' > /dev/null || fail "many: submit"
MSID=$(q "SELECT session_id FROM pic_submission WHERE request_key = 'k-many-files'")
pic run --script "$T/many.script" > /dev/null 2> "$T/many.err" || fail "many: run: $(cat "$T/many.err")"
script "$T/ph1" <<EOS
cmd k-changes-00000005 {"type":"command","session":"$DB/$MSID","key":"k-changes-00000005","payload":{"type":"get_changes"}}
expect "key":"k-changes-00000005","payload":{"type":"response","command":"get_changes","success":true
EOS
done_ok $PR "get_changes, 201 files"
grep -F '"key":"k-changes-00000005"' "$T/ph1.run" | tail -1 | sed 's/^<- //' > "$T/changes.json"
[ "$(cl "count(*)")" = 200 ] && [ "$("$SQLITE3" :memory: "SELECT json_extract(CAST(readfile('$T/changes.json') AS TEXT), '\$.payload.data.cut')")" = 1 ] ||
fail "get_changes: 201 files: $(cl "count(*)") listed, cut $(grep -o '"cut":[a-z]*' "$T/changes.json")"
printf 'PASS: get_changes lists 200 files at most, and says the list is cut\n'
# A FIFO, an oversized regular file (> 256 MiB), and invalid UTF-8 (surrogates/overlongs) at
# touched paths: get_changes answers within its budget, never blocks, and classifies each honestly.
printf 'ok\n' > "$WS/ch-fifo.txt"
printf 'ok\n' > "$WS/ch-huge.bin"
printf 'ok\n' > "$WS/ch-badutf8.txt"
printf '%s\n' "tool write ch-fifo.txt x${TAB}write ch-huge.bin x${TAB}write ch-badutf8.txt x${TAB}write ch-good.txt hi" "text done" > "$T/edge.script"
pic submit k-edge-files 'edge changes' > /dev/null || fail "edge: submit"
ESID=$(q "SELECT session_id FROM pic_submission WHERE request_key = 'k-edge-files'")
pic run --script "$T/edge.script" > /dev/null 2> "$T/edge.err" || fail "edge: run: $(cat "$T/edge.err")"
rm -f "$WS/ch-fifo.txt"
mkfifo "$WS/ch-fifo.txt"
dd if=/dev/zero of="$WS/ch-huge.bin" bs=1048576 count=0 seek=257 2>/dev/null
printf '\355\240\200\n' > "$WS/ch-badutf8.txt"
script "$T/ph1" <<EOS
timed 1500 k-changes-edge-0001 {"type":"command","session":"$DB/$ESID","key":"k-changes-edge-0001","payload":{"type":"get_changes"}}
expect "key":"k-changes-edge-0001","payload":{"type":"response","command":"get_changes","success":true
EOS
done_ok $PR "get_changes, fifo and oversized"
grep -F '"key":"k-changes-edge-0001"' "$T/ph1.run" | tail -1 | sed 's/^<- //' > "$T/changes.json"
[ "$(cl "group_concat(json_extract(value, '\$.path') || ' ' || coalesce(json_extract(value, '\$.why'), 'diff'), '|')")" = \
"ch-badutf8.txt binary|ch-fifo.txt not a file|ch-good.txt diff|ch-huge.bin too large" ] ||
fail "get_changes: edge files: $(cat "$T/changes.json")"
rm -f "$WS/ch-fifo.txt" "$WS/ch-huge.bin"
printf 'PASS: get_changes handles a FIFO, >256 MiB file, and UTF-8 surrogate without hanging\n'
if [ "$FAULTS" = 1 ]; then
# Out of memory in rw_diff is reported as an error, never mislabelled "binary".
kill "$RP"
gone "$RP"
nr=$((nr + 1))
RO="$T/remote$nr.out"
PIC_TEST_DIFF_OOM=1 "$PIC" remote > "$RO" 2> "$T/remote$nr.err" &
RP=$!
bg $RP
await "$RO" 'pic remote: connected'
script "$T/ph1" <<EOS
cmd k-changes-oom-00001 {"type":"command","session":"$DB/$CSID","key":"k-changes-oom-00001","payload":{"type":"get_changes"}}
expect "key":"k-changes-oom-00001","payload":{"type":"response","command":"get_changes","success":false
EOS
done_ok $PR "get_changes, diff oom"
grep -F '"key":"k-changes-oom-00001"' "$T/ph1.run" | tail -1 | grep -qF '"error":"out of memory"' ||
fail "get_changes: diff oom: $(grep -F k-changes-oom-00001 "$T/ph1.run")"
printf 'PASS: get_changes does not misreport diff OOM as binary\n'
# Out of time (each file slow to read, a dev build's seam): the files read in time, honestly
# labelled, and cut, well before the phone would be told busy; the workspace's next command
# is answered at once.
kill "$RP"
gone "$RP"
nr=$((nr + 1))
RO="$T/remote$nr.out"
PIC_TEST_CHANGES_FILE_MS=100 "$PIC" remote > "$RO" 2> "$T/remote$nr.err" &
RP=$!
bg $RP
await "$RO" 'pic remote: connected'
script "$T/ph1" <<EOS
cmd k-changes-00000006 {"type":"command","session":"$DB/$MSID","key":"k-changes-00000006","payload":{"type":"get_changes"}}
expect "key":"k-changes-00000006","payload":{"type":"response","command":"get_changes","success":true
timed 1000 k-changes-00000007 {"type":"command","session":"$DB/$MSID","key":"k-changes-00000007","payload":{"type":"get_state"}}
expect "key":"k-changes-00000007","payload":{"type":"response","command":"get_state","success":true
EOS
done_ok $PR "get_changes, out of time"
grep -F '"key":"k-changes-00000006"' "$T/ph1.run" | tail -1 | sed 's/^<- //' > "$T/changes.json"
n6=$(cl "count(*)")
[ "$n6" -gt 0 ] && [ "$n6" -lt 200 ] && [ "$(cl "count(*)" "WHERE json_extract(value, '\$.diff') IS NULL")" = 0 ] &&
[ "$("$SQLITE3" :memory: "SELECT json_extract(CAST(readfile('$T/changes.json') AS TEXT), '\$.payload.data.cut')")" = 1 ] ||
fail "get_changes: out of time: $n6 listed: $(head -c 600 "$T/changes.json")"
grep -q '^answered k-changes-00000007 in [0-9]* ms$' "$T/ph1.run" || fail "get_changes: out of time: the next command waited: $(grep -F k-changes-00000007 "$T/ph1.run")"
grep -F 'k-changes-0000000' "$T/ph1.run" | grep -qF '"busy"' && fail "get_changes: out of time: told busy: $(grep -F busy "$T/ph1.run")"
printf 'PASS: get_changes out of time answers the files read so far, cut, and never holds the workspace past its budget\n'
kill "$RP"
gone "$RP"
remote
fi
# Files from the phone (#109): upload_begin, upload_chunk and upload_end over the lanes write the
# file under the workspace's .pic/uploads, synced, answered uploaded with its path; the same name
# and content again is the same file, other content a new name; a name with a path, a size over the
# cap, a wrong sha256 and a chunk out of order are refused and leave nothing; a device has at most 4
# uploads open; a prompt names its files, which must be uploads of that workspace.
UP="$(cd "$WS" && pwd -P)/.pic/uploads"
D1=$(printf 'hello, ' | base64); D2=$(printf 'phone file\n' | base64); D3=$(printf 'other text\n' | base64)
SUM=$(printf 'hello, phone file\n' | shasum -a 256 | cut -d' ' -f1)
SUM3=$(printf 'other text\n' | shasum -a 256 | cut -d' ' -f1)
pic submit files-1 "files turn" > /dev/null 2>&1 || fail "files: submit"
pic cancel files-1 > /dev/null 2>&1 || fail "files: cancel"
FID=$(q "SELECT session_id FROM pic_submission WHERE request_key = 'files-1'")
script "$T/ph1" <<EOS
send {"type":"upload_begin","session":"$DB/$FID","payload":{"id":"up-notes-0000000001","name":"notes.txt","size":18,"mime":"text/plain"}}
send {"type":"upload_chunk","payload":{"id":"up-notes-0000000001","n":0,"data":"$D1"}}
send {"type":"upload_chunk","payload":{"id":"up-notes-0000000001","n":1,"data":"$D2"}}
send {"type":"upload_end","payload":{"id":"up-notes-0000000001","sha256":"$SUM"}}
expect {"type":"uploaded","payload":{"id":"up-notes-0000000001","path":".pic/uploads/notes.txt"}}
send {"type":"upload_begin","session":"$DB/$FID","payload":{"id":"up-notes-0000000002","name":"notes.txt","size":18,"mime":"text/plain"}}
send {"type":"upload_chunk","payload":{"id":"up-notes-0000000002","n":0,"data":"$D1"}}
send {"type":"upload_chunk","payload":{"id":"up-notes-0000000002","n":1,"data":"$D2"}}
send {"type":"upload_end","payload":{"id":"up-notes-0000000002","sha256":"$SUM"}}
expect {"type":"uploaded","payload":{"id":"up-notes-0000000002","path":".pic/uploads/notes.txt"}}
send {"type":"upload_begin","session":"$DB/$FID","payload":{"id":"up-notes-0000000003","name":"notes.txt","size":11,"mime":"text/plain"}}
send {"type":"upload_chunk","payload":{"id":"up-notes-0000000003","n":0,"data":"$D3"}}
send {"type":"upload_end","payload":{"id":"up-notes-0000000003","sha256":"$SUM3"}}
expect {"type":"uploaded","payload":{"id":"up-notes-0000000003","path":".pic/uploads/notes-2.txt"}}
send {"type":"upload_begin","session":"$DB/$FID","payload":{"id":"up-bad-00000000001","name":"../escape.txt","size":3,"mime":"text/plain"}}
expect "key":"up-bad-00000000001","payload":{"code":"bad_message"
send {"type":"upload_begin","session":"$DB/$FID","payload":{"id":"up-bad-00000000002","name":"big.bin","size":999999999,"mime":"application/octet-stream"}}
expect "key":"up-bad-00000000002","payload":{"code":"too_large"
send {"type":"upload_begin","session":"$DB/$FID","payload":{"id":"up-bad-00000000003","name":"wrong.txt","size":11,"mime":"text/plain"}}
send {"type":"upload_chunk","payload":{"id":"up-bad-00000000003","n":0,"data":"$D3"}}
send {"type":"upload_end","payload":{"id":"up-bad-00000000003","sha256":"$SUM"}}
expect "key":"up-bad-00000000003","payload":{"code":"bad_upload"
send {"type":"upload_begin","session":"$DB/$FID","payload":{"id":"up-bad-00000000004","name":"order.txt","size":18,"mime":"text/plain"}}
send {"type":"upload_chunk","payload":{"id":"up-bad-00000000004","n":1,"data":"$D2"}}
expect "key":"up-bad-00000000004","payload":{"code":"bad_upload"
send {"type":"upload_begin","session":"$DB/$FID","payload":{"id":"up-many-0000000001","name":"a.txt","size":1,"mime":"text/plain"}}
send {"type":"upload_begin","session":"$DB/$FID","payload":{"id":"up-many-0000000002","name":"b.txt","size":1,"mime":"text/plain"}}
send {"type":"upload_begin","session":"$DB/$FID","payload":{"id":"up-many-0000000003","name":"c.txt","size":1,"mime":"text/plain"}}
send {"type":"upload_begin","session":"$DB/$FID","payload":{"id":"up-many-0000000004","name":"d.txt","size":1,"mime":"text/plain"}}
send {"type":"upload_begin","session":"$DB/$FID","payload":{"id":"up-many-0000000005","name":"e.txt","size":1,"mime":"text/plain"}}
expect "key":"up-many-0000000005","payload":{"code":"quota"
cmd k-files-0000000001 {"type":"command","session":"$DB/$FID","key":"k-files-0000000001","payload":{"type":"prompt","message":"look","files":["../../etc/passwd"]}}
expect "key":"k-files-0000000001","payload":{"code":"bad_command"
cmd k-files-0000000002 {"type":"command","session":"$DB/$FID","key":"k-files-0000000002","payload":{"type":"prompt","message":"look at it","files":[".pic/uploads/notes.txt"]}}
expect "command":"prompt","success":true
EOS
done_ok $PR "files"
[ "$(cat "$UP/notes.txt")" = "hello, phone file" ] || fail "files: notes.txt: $(cat "$UP/notes.txt" 2>&1)"
[ "$(cat "$UP/notes-2.txt")" = "other text" ] || fail "files: notes-2.txt"
for f in escape.txt big.bin wrong.txt order.txt; do [ ! -e "$UP/$f" ] && [ ! -e "$UP/../$f" ] || fail "files: $f was written"; done
[ "$(ls -A "$UP" | grep -c 'up-bad\|up-notes')" = 0 ] || fail "files: a partial file is left: $(ls -A "$UP")"
q "SELECT content FROM pic_submission WHERE request_key = 'rc:$DEV1B:k-files-0000000002'" | grep -qF '[attached: .pic/uploads/notes.txt]' ||
fail "files: the prompt does not name its file: $(q "SELECT content FROM pic_submission WHERE request_key LIKE 'rc:%k-files%'")"
i=0; until pic sessions delete "$FID" > /dev/null 2>&1; do i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "files: cannot delete"; sleep 0.05; done
printf 'PASS: files from the phone: chunked, synced, de-duplicated, bounded and named by the prompt\n'
kill "$spid" 2>/dev/null || :
export PIC_MODELS_FILE="$T/models$n.json"
# Images from the phone: pic says it takes them; a prompt with an image is admitted with it (the
# model gets it, the journal keeps it as a pasted one); the phone's events carry each image without
# its bytes, which it asks for by entry and index; a steer carries its image through the inbox; an
# image over several records arrives whole, and pic acknowledges what it read, so the relay is not
# left holding it; a new conversation starts with one; and what is not an image is refused.
spid=
serve "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/bash_hold.sse" "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse"
sed 's/{"id":"m"}/{"id":"m","input":["text","image"]}/' "$PIC_MODELS_FILE" > "$T/models-see.json"
export PIC_MODELS_FILE="$T/models-see.json"
pic ask 'image first' > /dev/null 2> "$T/aski.err" || fail "ask: $(cat "$T/aski.err")"
SIDI=$(q "SELECT id FROM pic_session")
SESSI="$DB/$SIDI"
kill "$RP"
gone "$RP"
remote
PNG_B64='iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=='
GIF_B64='R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "features":["images","asks","permissions"]
send {"type":"sync","session":"$SESSI","seq":-1}
expect "running":false
cmd k-img-bad-00000001 {"type":"command","session":"$SESSI","key":"k-img-bad-00000001","payload":{"type":"prompt","message":"not one","images":[{"type":"image","data":"aGVsbG8=","mimeType":"image/png"}]}}
expect {"type":"error","key":"k-img-bad-00000001","payload":{"code":"bad_command"
cmd k-img-0000000000001 {"type":"command","session":"$SESSI","key":"k-img-0000000000001","payload":{"type":"prompt","message":"look at this","images":[{"type":"image","data":"$PNG_B64","mimeType":"image/png"}]}}
expect {"type":"text","text":"look at this"},{"type":"image","mimeType":"image/png","index":0,"bytes":70}]
seen "command":"prompt","success":true
seen :k-img-0000000000001","status":"answered"
sleep 300
EOS
done_ok $PR "image prompt"
grep -qF "$PNG_B64" "$LOG/2.req" || fail "image prompt: the model did not get the image"
ISEQ=$(q "SELECT seq FROM pic_entry WHERE kind = 'user' AND body = 'look at this'")
[ -n "$ISEQ" ] || fail "image prompt: no entry"
[ "$(q "SELECT count(*) FROM pic_attachment a JOIN pic_image i ON i.hash = a.image WHERE a.entry_seq = $ISEQ AND i.mime = 'image/png' AND i.width = 1")" = 1 ] ||
fail "image prompt: attachments: $(q 'SELECT entry_seq, queued_id, ordinal FROM pic_attachment')"
[ "$(q "SELECT count(*) FROM pic_submission WHERE request_key LIKE 'rc:%:k-img-bad-00000001'")" = 0 ] || fail "bad image: admitted"
grep '^<- ' "$T/ph1.run" | grep -qF "$PNG_B64" && fail "image prompt: an event carried the image's bytes"
script "$T/ph1" <<EOS
send {"type":"image","session":"$SESSI","seq":$ISEQ,"payload":{"index":0}}
expect {"type":"image","session":"$SESSI","seq":$ISEQ,"payload":{"index":0,"mimeType":"image/png","data":"$PNG_B64"}}
send {"type":"image","session":"$SESSI","seq":$ISEQ,"payload":{"index":3}}
expect "payload":{"index":3,"error":"no_image"}
send {"type":"image","session":"$SESSI","seq":1,"payload":{"index":0}}
expect "payload":{"index":0,"error":"no_image"}
EOS
done_ok $PR "image fetch"
"$PIC" --db "$DB" attach --session "$SIDI" --no-follow > "$T/attachi.out" 2> "$T/attachi.err" || fail "attach: $(cat "$T/attachi.err")"
grep -qF '{"type":"text","text":"look at this"},{"type":"image","data":"'"$PNG_B64"'","mimeType":"image/png"}]' "$T/attachi.out" ||
fail "attach: the image is not in the user message: $(grep -F 'look at this' "$T/attachi.out" | head -c 400)"
printf 'PASS: a prompt from the phone with an image: the model gets it, the journal keeps it; events name it, the phone asks for its bytes; not an image is refused\n'
rm -f "$WS/started" "$WS/release"
pic ask --session "$SIDI" 'hold on' > "$T/holdi.out" 2> "$T/holdi.err" &
HP=$!
bg $HP
i=0
until [ -e "$WS/started" ]; do i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "hold: did not start: $(cat "$T/holdi.err")"; sleep 0.05; done
script "$T/ph1" <<EOS
send {"type":"sync","session":"$SESSI","seq":-1}
expect "running":true
cmd k-img-steer-000001 {"type":"command","session":"$SESSI","key":"k-img-steer-000001","payload":{"type":"prompt","message":"and this","streamingBehavior":"steer","images":[{"type":"image","data":"$GIF_B64","mimeType":"image/gif"}]}}
expect {"type":"ack","key":"k-img-steer-000001"
mark go-release
expect "status":"answered"
EOS
i=0
until [ -e "$T/ph1/go-release" ]; do i=$((i + 1)); [ "$i" -lt $TRIES ] || fail "image steer: no ack: $(cat "$T/ph1.run")"; sleep 0.05; done
touch "$WS/release"
done_ok $PR "image steer"
gone $HP
grep -qF "$GIF_B64" "$LOG/4.req" || fail "image steer: the model did not get the image"
[ "$(q "SELECT count(*) FROM pic_attachment a JOIN pic_entry e ON e.seq = a.entry_seq WHERE e.body = 'and this'")" = 1 ] ||
fail "image steer: attachments: $(q 'SELECT entry_seq, queued_id, ordinal FROM pic_attachment')"
printf 'PASS: a steer from the phone with an image reaches the running request with it\n'
# Over 300 KB: about thirty records, posted while pic reads; it acknowledges them as it goes.
B64CMD=$(command -v base64)
{ printf '%s' "$PNG_B64" | "$B64CMD" -d 2> /dev/null || printf '%s' "$PNG_B64" | "$B64CMD" -D; } > "$T/dot.png"
{ cat "$T/dot.png"; head -c 320000 /dev/zero | tr '\0' 'x'; } > "$T/big.png"
printf '{"type":"command","session":"%s","key":"k-img-big-00000001","payload":{"type":"prompt","message":"big one","images":[{"type":"image","data":"%s","mimeType":"image/png"}]}}\n' \
"$SESSI" "$("$B64CMD" < "$T/big.png" | tr -d '\n')" > "$T/big.json"
script "$T/ph1" <<EOS
cmdfile k-img-big-00000001 $T/big.json
expect "key":"k-img-big-00000001","session":"$SESSI","payload":{"type":"response","command":"prompt","success":true
EOS
done_ok $PR "big image"
until_sql "SELECT status FROM pic_submission WHERE request_key LIKE 'rc:%:k-img-big-00000001'" answered
[ "$(q "SELECT i.sz FROM pic_attachment a JOIN pic_image i ON i.hash = a.image JOIN pic_entry e ON e.seq = a.entry_seq WHERE e.body = 'big one'")" = "$(wc -c < "$T/big.png" | tr -d ' ')" ] ||
fail "big image: stored: $(q 'SELECT a.entry_seq, i.sz FROM pic_attachment a JOIN pic_image i ON i.hash = a.image')"
i=0
until state | grep -qF ' up 0"'; do
i=$((i + 1))
[ "$i" -lt $TRIES ] || fail "big image: the relay still holds what pic read: $(state)"
sleep 0.05
done
printf 'PASS: an image over many records arrives whole, and pic acknowledges what it read\n'
W3=$DB
script "$T/ph1" <<EOS
cmd k-img-new-00000001 {"type":"command","session":"+$W3","key":"k-img-new-00000001","payload":{"type":"prompt","message":"","images":[{"type":"image","data":"$PNG_B64","mimeType":"image/png"}]}}
expect "key":"k-img-new-00000001","session":"$W3/
EOS
done_ok $PR "image new conversation"
grep -F '"key":"k-img-new-00000001"' "$T/ph1.run" | grep -qF '"command":"prompt","success":true' || fail "image new conversation: $(cat "$T/ph1.run")"
[ "$(q "SELECT count(*) FROM pic_attachment a JOIN pic_entry e ON e.seq = a.entry_seq JOIN pic_submission u ON u.id = e.submission_id
WHERE u.request_key LIKE 'rc:%:k-img-new-00000001'")" = 1 ] || fail "image new conversation: attachments"
printf 'PASS: a new conversation from the phone starts with an image and no text\n'
kill "$spid" 2> /dev/null
# A large journal written while phones are served: 60 conversations over 50,000 entries, the most
# recent of them holding nearly all, and a worker adding entries all along. Each part of the list
# is built again only when its journal changes, with work that does not grow with the entries (its
# statements' steps: a walk of pic_entry would take millions; the clock of a loaded machine is no
# measure), and the loop keeps answering pings.
kill "$RP"
gone "$RP"
mkdir "$T/bigws"
BIG="$T/big.sqlite"
"$PIC" --db "$BIG" --workspace "$T/bigws" check > /dev/null 2>&1 || fail "big: check"
pad=$(head -c 600 /dev/zero | tr '\0' x)
"$SQLITE3" "$BIG" "BEGIN;
INSERT INTO pic_session(id, created_ms, updated_ms) SELECT printf('b%04d', value), 1, 1 FROM generate_series(1, 60);
INSERT INTO pic_submission(id, request_key, content, status, session_id)
SELECT value, 'big-' || value, 'question ' || value, 'answered', printf('b%04d', value) FROM generate_series(1, 60);
INSERT INTO pic_entry(submission_id, kind, body) SELECT 1 + (value % 59), 'user', 'early $pad' FROM generate_series(1, 2000);
INSERT INTO pic_entry(submission_id, kind, body) SELECT 60, iif(value % 2, 'user', 'assistant'),
iif(value % 2, 'late $pad', json_array(json_object('type', 'text', 'text', 'late $pad'))) FROM generate_series(1, 48000);
INSERT INTO pic_generation(submission_id, turn, attempt, state, entry_seq, usage)
SELECT 60, seq, 1, 'done', seq, json_object('input_tokens', 1000, 'output_tokens', 10, 'attribution', '$pad$pad$pad')
FROM pic_entry WHERE submission_id = 60 AND kind = 'assistant';
COMMIT" || fail "big: rows"
[ "$("$SQLITE3" "$BIG" "SELECT count(*) FROM pic_entry WHERE submission_id = 60")" -ge 48000 ] || fail "big: entries"
nr=$((nr + 1))
RO="$T/remote$nr.out"
PIC_TEST_RC_LIST_TIMES=1 PIC_TEST_RC_MESSAGE_STEPS=1 "$PIC" remote > "$RO" 2> "$T/remote$nr.err" &
RP=$!
bg $RP
await "$RO" 'pic remote: connected'
( i=0; while [ $i -lt 60 ] && [ ! -e "$T/big.stop" ]; do
"$SQLITE3" -cmd ".timeout 10000" "$BIG" "INSERT INTO pic_entry(submission_id, kind, body) VALUES(60, 'user', 'more')" 2> /dev/null
sleep 0.05; i=$((i + 1)); done ) &
bg $!
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "session":"$BIG/b0060"
send {"type":"ping"}
expect {"type":"pong"}
sleep 1000
send {"type":"ping"}
expect {"type":"pong"}
sleep 1000
send {"type":"ping"}
expect {"type":"pong"}
EOS
done_ok $PR "big journal"
touch "$T/big.stop"
await "$RO" "pic remote: listed $BIG in "
heavy=$(sed -n "s|^pic remote: listed $BIG in [0-9]* ms, \([0-9]*\) steps\$|\1|p" "$RO" | awk '$1 >= 100000' | head -3)
[ -z "$heavy" ] || fail "big: list parts took $heavy steps: $(grep -F 'listed' "$RO" | tail -5)"
grep -q "^pic remote: listed $BIG in [0-9]* ms, [0-9]* steps\$" "$RO" || fail "big: no step count: $(grep -F listed "$RO")"
# A phone's questions about its 48,000-entry conversation read only the newest of it: each takes
# work far below what reading the conversation whole would (the steps its statements ran), and the
# loop answers a ping right after.
BS="$BIG/b0060"
script "$T/ph1" <<EOS
cmd k-big-state-000001 {"type":"command","session":"$BS","key":"k-big-state-000001","payload":{"type":"get_state"}}
expect "command":"get_state","success":true
cmd k-big-stats-000001 {"type":"command","session":"$BS","key":"k-big-stats-000001","payload":{"type":"get_session_stats"}}
expect "command":"get_session_stats","success":true
seen "tokens":{"input":24000000,"output":240000,"cacheRead":0,"cacheWrite":0,"total":24240000}
cmd k-big-msgs-0000001 {"type":"command","session":"$BS","key":"k-big-msgs-0000001","payload":{"type":"get_messages"}}
expect "command":"get_messages","success":true
cmd k-big-wakes-000001 {"type":"command","session":"$BS","key":"k-big-wakes-000001","payload":{"type":"get_wakes"}}
expect "command":"get_wakes"
send {"type":"ping"}
expect {"type":"pong"}
send {"type":"sync","session":"$BS","seq":-1,"key":"k-big-sync-0000001"}
expect {"type":"sync","session":"$BS"
EOS
done_ok $PR "big: questions"
for what in "command get_state" "command get_session_stats" "command get_messages" "command get_wakes" "sync"; do
n=$(sed -n "s|^pic remote: answered $what in \([0-9]*\) steps\$|\1|p" "$RO" | sort -n | tail -1)
[ -n "$n" ] || fail "big: no step count for $what: $(grep -F answered "$RO" | tail -8)"
[ "$n" -lt 2000000 ] || fail "big: $what took $n steps: $(grep -F answered "$RO" | tail -8)"
printf ' %s: %s steps\n' "$what" "$n"
done
[ "$(grep -c "listed $BIG in " "$RO")" -ge 2 ] || fail "big: built once only, though the journal changed: $(grep -F listed "$RO")"
printf 'PASS: a large journal written all along: each list part a bounded amount of work, built again only on a change; the loop keeps answering (%s parts, at most %s steps)\n' \
"$(grep -c "listed $BIG in " "$RO")" "$(sed -n "s|^pic remote: listed $BIG in [0-9]* ms, \([0-9]*\) steps\$|\1|p" "$RO" | sort -n | tail -1)"
# Its stats count the tokens of the whole conversation, not of the newest entries read: totals
# kept as replies are written. Without them (a journal from before) the entries' own usage is
# summed, to the same totals; a reply written after starts the totals again.
"$SQLITE3" "$BIG" "DELETE FROM pic_path_usage" || fail "big: totals not kept: $("$SQLITE3" "$BIG" "SELECT count(*) FROM pic_path_usage")"
# The sum over every entry is the slow path: on a slower machine, still working through the big
# journal, the computer may answer busy, which the protocol says to try again; the phone does.
for try in 2 3 4 5; do
k=k-big-stats-00000$try
script "$T/ph1" <<EOS
cmd $k {"type":"command","session":"$BS","key":"$k","payload":{"type":"get_session_stats"}}
seen "key":"$k"
EOS
done_ok $PR "big: stats without the totals"
grep -F "\"key\":\"$k\"" "$T/ph1.run" | grep -qF '"code":"busy"' || break
sleep 2
done
grep -F "\"key\":\"$k\"" "$T/ph1.run" | grep -qF '"tokens":{"input":24000000,"output":240000,' ||
fail "big: stats without the totals: $(grep -F "\"key\":\"$k\"" "$T/ph1.run" | cut -c1-400)"
"$SQLITE3" "$BIG" "BEGIN; INSERT INTO pic_entry(submission_id, kind, body) VALUES(60, 'assistant', '[]');
INSERT INTO pic_generation(submission_id, turn, attempt, state, entry_seq, usage)
VALUES(60, 999999, 1, 'done', last_insert_rowid(), json_object('input_tokens', 5, 'output_tokens', 1, 'attribution',
json_object('items', json_object('fc_1', json_object('input_tokens', 5)))));
COMMIT" || fail "big: a new reply"
[ "$("$SQLITE3" "$BIG" "SELECT input || ' ' || output FROM pic_path_usage ORDER BY seq DESC LIMIT 1")" = "24000005 240001" ] ||
fail "big: the new reply's totals: $("$SQLITE3" "$BIG" "SELECT * FROM pic_path_usage")"
[ "$("$SQLITE3" "$BIG" "SELECT usage FROM pic_generation WHERE turn = 999999")" = '{"input_tokens":5,"output_tokens":1,"attribution":{}}' ] ||
fail "big: the usage is not trimmed: $("$SQLITE3" "$BIG" "SELECT usage FROM pic_generation WHERE turn = 999999")"
printf 'PASS: a phone'"'"'s stats count the whole conversation from totals kept as replies are written, and without them\n'
# A phone asking get_state of 20 conversations at once (each asked twice, each 150 ms slow): the
# second asking of a question still queued is answered with the first, and a second phone's ping
# and get_state on the same journal are each answered within a second, its turn coming between
# the first phone's.
kill "$RP"
gone "$RP"
nr=$((nr + 1))
RO="$T/remote$nr.out"
PIC_TEST_RC_JOB_MS="command get_state:150" PIC_TEST_RC_MESSAGE_STEPS=1 "$PIC" remote > "$RO" 2> "$T/remote$nr.err" &
RP=$!
bg $RP
await "$RO" 'pic remote: connected'
{
printf 'send {"type":"ping"}\nexpect {"type":"pong"}\n'
for n in 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21; do
printf 'send {"type":"command","session":"%s/b00%s","key":"k-burst-a-000000%s","payload":{"type":"get_state"}}\n' "$BIG" $n $n
printf 'send {"type":"command","session":"%s/b00%s","key":"k-burst-b-000000%s","payload":{"type":"get_state"}}\n' "$BIG" $n $n
done
printf 'mark burst-sent\nwaitcount "key":"k-burst- 40\n'
} > "$T/burst.script"
script "$T/ph1" < "$T/burst.script"
P1=$PR
script "$T/ph4" <<EOS
send {"type":"ping"}
expect {"type":"pong"}
waitfor $T/ph1/burst-sent
ping 1000
timed 1000 k-burst-other-0001 {"type":"command","session":"$BIG/b0060","key":"k-burst-other-0001","payload":{"type":"get_state"}}
expect "key":"k-burst-other-0001"
EOS
P4=$PR
done_ok $P4 "burst: the other phone"
done_ok $P1 "burst"
grep -q '^pong [0-9]* ms$' "$T/ph4.run" || fail "burst: the other phone's ping waited: $(grep -i pong "$T/ph4.run")"
grep -q '^answered k-burst-other-0001 in [0-9]* ms$' "$T/ph4.run" || fail "burst: the other phone's get_state waited: $(grep -F k-burst-other "$T/ph4.run")"
for k in $(grep -o '"key":"k-burst-[ab]-[0-9]*"' "$T/ph1.run" | sort | uniq -d); do fail "burst: two answers for $k"; done
ran=$(grep -c '^pic remote: answered command get_state in' "$RO")
[ "$ran" -lt 40 ] || fail "burst: every repeat ran its own job ($ran)"
printf 'PASS: a burst of questions about 20 conversations: repeats answered together (%s jobs for 40 questions), another phone answered within a second\n' "$ran"
# Out of time (a budget of 0 ms, a dev build's seam): the part is given up, said once, and the
# phone is still answered at once.
kill "$RP"
gone "$RP"
nr=$((nr + 1))
RO="$T/remote$nr.out"
PIC_TEST_RC_LIST_BUDGET_MS=0 "$PIC" remote > "$RO" 2> "$T/remote$nr.err" &
RP=$!
bg $RP
await "$RO" 'pic remote: connected'
script "$T/ph1" <<EOS
send {"type":"sessions"}
expect "type":"sessions"
send {"type":"ping"}
expect {"type":"pong"}
EOS
done_ok $PR "big journal, no time"
await "$RO" "pic remote: listing $BIG took over"
[ "$(grep -c "listing $BIG took over" "$RO")" = 1 ] || fail "big: said more than once: $(grep -F 'took over' "$RO")"
printf 'PASS: a list part out of time is given up and said once; the phone is still answered\n'
kill "$RP"
gone "$RP"
remote