43 lines
2.7 KiB
Bash
Executable file
43 lines
2.7 KiB
Bash
Executable file
#!/usr/bin/env bash
|
|
# P8-REVIEW, axis 1 (money): reconcile balance / ledger / open holds by TWO INDEPENDENT paths.
|
|
#
|
|
# Path A — what the platform's own code answers (tmplatformctl reads the account_balances cache
|
|
# that every ledger write updates in the same transaction; /v0/usage is the wire view).
|
|
# Path B — the RAW ledger, summed by SQL that shares no code with path A.
|
|
#
|
|
# The invariant under test is the one credits.go states in prose (credits.go:68-70, :354-356):
|
|
# balance cache == sum(credit_ledger), always, and a hold is a DEBIT at the moment it is taken,
|
|
# so the balance already excludes open holds.
|
|
#
|
|
# Usage: reconcile-two-ways.sh <user-id> (env: PSQL, PGDATABASE, CTL, TM_PLATFORM_DSN)
|
|
set -u
|
|
U="${1:?user id}"
|
|
PSQL="${PSQL:-$HOME/.local/pgsql/bin/psql}"
|
|
CTL="${CTL:-$HOME/tmstand-work/tmplatformctl}"
|
|
q() { "$PSQL" -tAX -c "$1"; }
|
|
|
|
echo "=== PATH A: what the platform answers ==="
|
|
"$CTL" balance --user "$U"
|
|
|
|
echo
|
|
echo "=== PATH B: raw ledger, independent SQL ==="
|
|
echo "ledger rows by kind:"
|
|
q "select kind, count(*), sum(amount_micro_usd) from credit_ledger where user_id='$U' group by kind order by kind"
|
|
echo "sum(credit_ledger) = $(q "select coalesce(sum(amount_micro_usd),0) from credit_ledger where user_id='$U'") micro-USD"
|
|
echo "account_balances cache = $(q "select balance_micro_usd from account_balances where user_id='$U'") micro-USD"
|
|
echo "open holds (reservations) = $(q "select coalesce(sum(amount_micro_usd),0) from reservations where user_id='$U' and state='open'") micro-USD"
|
|
echo "open holds (ledger-derived) = $(q "select coalesce(-sum(l.amount_micro_usd),0) from credit_ledger l join reservations r on r.engine_run_id = l.source_id and l.source='run' where l.user_id='$U' and l.kind='hold' and r.state='open'") micro-USD"
|
|
|
|
echo
|
|
echo "=== VERDICT ==="
|
|
q "select case when (select coalesce(sum(amount_micro_usd),0) from credit_ledger where user_id='$U')
|
|
= (select balance_micro_usd from account_balances where user_id='$U')
|
|
then 'AGREE: cache == raw ledger'
|
|
else 'DISAGREE by ' || ((select balance_micro_usd from account_balances where user_id='$U')
|
|
- (select coalesce(sum(amount_micro_usd),0) from credit_ledger where user_id='$U'))::text || ' micro-USD'
|
|
end"
|
|
q "select case when (select coalesce(sum(amount_micro_usd),0) from reservations where user_id='$U' and state='open')
|
|
= (select coalesce(-sum(l.amount_micro_usd),0) from credit_ledger l join reservations r on r.engine_run_id=l.source_id and l.source='run' where l.user_id='$U' and l.kind='hold' and r.state='open')
|
|
then 'AGREE: open holds == hold rows of open reservations'
|
|
else 'DISAGREE on open holds'
|
|
end"
|