#!/usr/bin/env bash
# How much PostgreSQL work does the engine do (a) sitting idle and (b) per workflow?
# Uses pg_stat_statements, which the lab's postgres already preloads.
set -euo pipefail
LAB=$(cd "$(dirname "$0")" && pwd)
q() { "$LAB/psql.sh" -At -c "$1"; }
stats() { q "SELECT coalesce(sum(calls),0) || ' statements, ' || coalesce(sum(calls) FILTER (WHERE query ILIKE '%partition_leases%'),0) || ' touching partition_leases' FROM pg_stat_statements WHERE query NOT ILIKE '%pg_stat_statements%'"; }
rows() { q "SELECT 'history=' || (SELECT count(*) FROM engine.transition_history WHERE workflow_id LIKE '$1%') || ' outbox=' || (SELECT count(*) FROM engine.outbox WHERE workflow_id LIKE '$1%') || ' inbox=' || (SELECT count(*) FROM engine.event_inbox i JOIN engine.outbox o USING (event_id) WHERE o.workflow_id LIKE '$1%') || ' attempts=' || (SELECT count(*) FROM engine.activity_attempts WHERE workflow_id LIKE '$1%')"; }

N=${1:-50}; RUN=cost$(date +%s)
q "SELECT pg_stat_statements_reset()" >/dev/null
sleep 30
echo "idle, 30s, zero workflows in flight: $(stats)"
echo "lease epochs (sum over 16 partitions): $(q 'SELECT sum(epoch) FROM engine.partition_leases')"

q "SELECT pg_stat_statements_reset()" >/dev/null
START=$(date +%s)
for i in $(seq 1 "$N"); do "$LAB/submit.sh" "$RUN-$i" lab-add pure.add '[1,2,3]' >/dev/null; done
until [ "$(q "SELECT count(*) FROM engine.workflow_executions WHERE workflow_id LIKE '$RUN-%' AND state='SUCCEEDED'")" = "$N" ]; do sleep 0.5; done
sleep 3
echo "$N two-step workflows, $(( $(date +%s) - START ))s wall clock: $(stats)"
echo "rows left behind for those $N workflows: $(rows "$RUN-")"
"$LAB/psql.sh" -c "SELECT calls, round(total_exec_time::numeric,1) AS total_ms, left(regexp_replace(query, '\s+', ' ', 'g'), 90) AS statement FROM pg_stat_statements WHERE query NOT ILIKE '%pg_stat_statements%' ORDER BY calls DESC LIMIT 8"
