From 1d4ed644f8756da070bd5b103d2e78a7b6425e23 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Sat, 10 Oct 2026 16:41:59 -0400 Subject: [PATCH 1/5] Add shared credit reservations on the existing wallet AI work needs to authorize capacity before paid calls start and settle the actual charge exactly once afterwards (app#2105 milestone 1, which Context accounting app#2123 reuses). The existing preflight only reads the balance, so concurrent requests can each pass it and overspend. Holds live in a new credit_reservations table; they are claims, never temporary debits, so refill, top-up and auto-top-up never see them as consumption. Reserve, settle and release lock the owner's single wallet row first and compute spendable = remaining_credits - outstanding holds. Settlement charges through record_credit_charge_once with the same operation key, so reservation and charge share one retry-stable identity. Service role only; no price, ceiling, expiry, top-up or caller is added, and legacy debit writers still ignore holds. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/credit-reservations.yml | 32 +++ .../20261010210500_credit_reservations.sql | 195 ++++++++++++++ tests/CREDIT-RESERVATIONS.md | 75 ++++++ tests/test_credit_reservations.py | 247 ++++++++++++++++++ 4 files changed, 549 insertions(+) create mode 100644 .github/workflows/credit-reservations.yml create mode 100644 supabase/migrations/20261010210500_credit_reservations.sql create mode 100644 tests/CREDIT-RESERVATIONS.md create mode 100644 tests/test_credit_reservations.py diff --git a/.github/workflows/credit-reservations.yml b/.github/workflows/credit-reservations.yml new file mode 100644 index 0000000..dba2827 --- /dev/null +++ b/.github/workflows/credit-reservations.yml @@ -0,0 +1,32 @@ +name: Credit reservation transactions + +on: + pull_request: + branches: [main] + push: + branches: [main] + +permissions: + contents: read + +jobs: + credit-reservations: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + strategy: + fail-fast: false + matrix: + postgres: [15, 16] + steps: + - uses: actions/checkout@v4 + - name: Install PostgreSQL + run: | + sudo apt-get update + sudo apt-get install -y postgresql-common + sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh -y + sudo apt-get update + sudo apt-get install -y postgresql-${{ matrix.postgres }} + - name: Test isolated credit reservations + run: | + export PATH="/usr/lib/postgresql/${{ matrix.postgres }}/bin:$PATH" + python3 -m unittest discover -s tests -p 'test_credit_reservations.py' diff --git a/supabase/migrations/20261010210500_credit_reservations.sql b/supabase/migrations/20261010210500_credit_reservations.sql new file mode 100644 index 0000000..d2b2108 --- /dev/null +++ b/supabase/migrations/20261010210500_credit_reservations.sql @@ -0,0 +1,195 @@ +-- Shared credit reservations (holds) on the existing wallet for AI work +-- (recoupable/app#2105 milestone 1, reused by Context accounting app#2123). +-- +-- Wallet invariant: confirmed balance = credits_usage.remaining_credits; +-- outstanding holds = sum(credits_held) of this owner's 'held' reservations; +-- spendable = confirmed balance - outstanding holds. A hold is a claim, never a +-- temporary debit, so refill, top-up and auto-top-up logic never see it as use. +-- Settlement charges through record_credit_charge_once with the same operation +-- key, so a reservation and its charge share one retry-stable identity. +-- +-- Not a price, spending ceiling, top-up, expiry policy, or activation of any +-- caller. Legacy debit writers do not consult holds yet. Holds never expire on +-- their own: unknown provider exposure stays held until explicitly reconciled. +BEGIN; + +CREATE TABLE public.credit_reservations ( + id text PRIMARY KEY CHECK (id ~ '^hold-v1-[a-f0-9]{64}$'), + account_id uuid NOT NULL, + operation_key text NOT NULL + CHECK (btrim(operation_key) <> '' AND length(operation_key) <= 200), + credits_held bigint NOT NULL CHECK (credits_held > 0 AND credits_held <= 9007199254740991), + state text NOT NULL DEFAULT 'held' CHECK (state IN ('held','settled','released')), + credits_charged bigint CHECK (credits_charged > 0 AND credits_charged <= credits_held), + charge_event_id text CHECK (charge_event_id ~ '^charge-v1-[a-f0-9]{64}$'), + created_at timestamptz NOT NULL DEFAULT now(), + closed_at timestamptz, + UNIQUE (account_id, operation_key), + CHECK ((state = 'held' AND credits_charged IS NULL AND charge_event_id IS NULL AND closed_at IS NULL) + OR (state = 'settled' AND credits_charged IS NOT NULL AND charge_event_id IS NOT NULL + AND closed_at IS NOT NULL) + OR (state = 'released' AND credits_charged IS NULL AND charge_event_id IS NULL + AND closed_at IS NOT NULL)) +); +CREATE INDEX credit_reservations_open_idx + ON public.credit_reservations (account_id) WHERE state = 'held'; +ALTER TABLE public.credit_reservations ENABLE ROW LEVEL SECURITY; +-- Retained like charge receipts: deleting a row would let a recycled key hold again, +-- so the service role gets no DELETE/TRUNCATE even where default privileges grant it. +REVOKE ALL ON public.credit_reservations FROM PUBLIC, anon, authenticated, service_role; +GRANT SELECT, INSERT, UPDATE ON public.credit_reservations TO service_role; + +CREATE OR REPLACE FUNCTION public.reserve_credits_once( + p_account_id uuid, p_operation_key text, p_credits bigint +) RETURNS jsonb +LANGUAGE plpgsql SECURITY INVOKER SET search_path = public, pg_temp AS $$ +DECLARE + v_id text; + v_held bigint; + v_hold public.credit_reservations%ROWTYPE; + v_wallet public.credits_usage%ROWTYPE; +BEGIN + IF p_account_id IS NULL OR p_operation_key IS NULL OR btrim(p_operation_key) = '' + OR length(p_operation_key) > 200 OR p_credits IS NULL OR p_credits <= 0 + OR p_credits > 9007199254740991 THEN + RAISE EXCEPTION 'Invalid credit reservation' USING ERRCODE = '22023'; + END IF; + -- Every reservation operation locks the owner's single wallet row first, so + -- holds serialize with each other, charge receipts and legacy wallet writers. + BEGIN + SELECT * INTO STRICT v_wallet FROM public.credits_usage + WHERE account_id = p_account_id ORDER BY id FOR UPDATE; + EXCEPTION WHEN no_data_found OR too_many_rows THEN + RAISE EXCEPTION 'Credit wallet is unavailable or ambiguous' USING ERRCODE = '22023'; + END; + IF v_wallet.remaining_credits IS NULL THEN + RAISE EXCEPTION 'Credit wallet is unavailable' USING ERRCODE = '22023'; + END IF; + v_id := 'hold-v1-' || encode(sha256(convert_to( + jsonb_build_array(p_account_id::text,p_operation_key)::text,'UTF8')),'hex'); + SELECT * INTO v_hold FROM public.credit_reservations WHERE id = v_id; + IF FOUND THEN + IF v_hold.account_id IS DISTINCT FROM p_account_id + OR v_hold.operation_key IS DISTINCT FROM p_operation_key + OR v_hold.credits_held IS DISTINCT FROM p_credits THEN + RAISE EXCEPTION 'Credit reservation identity conflict' USING ERRCODE = '22023'; + END IF; + -- A replay reports the saved status; it never re-holds released or settled work. + RETURN jsonb_build_object('state','reused','reservationId',v_id, + 'status',v_hold.state,'creditsHeld',v_hold.credits_held); + END IF; + SELECT coalesce(sum(credits_held),0)::bigint INTO v_held FROM public.credit_reservations + WHERE account_id = p_account_id AND state = 'held'; + IF v_wallet.remaining_credits - v_held < p_credits THEN + -- A definite denial writes nothing; the same key may be retried later. + RETURN jsonb_build_object('state','insufficient','creditsRequested',p_credits, + 'spendableCredits',v_wallet.remaining_credits - v_held); + END IF; + INSERT INTO public.credit_reservations(id,account_id,operation_key,credits_held) + VALUES (v_id,p_account_id,p_operation_key,p_credits); + RETURN jsonb_build_object('state','held','reservationId',v_id,'creditsHeld',p_credits, + 'spendableCredits',v_wallet.remaining_credits - v_held - p_credits); +END; +$$; + +CREATE OR REPLACE FUNCTION public.settle_credit_reservation( + p_account_id uuid, p_operation_key text, p_credits bigint, p_event jsonb +) RETURNS jsonb +LANGUAGE plpgsql SECURITY INVOKER SET search_path = public, pg_temp AS $$ +DECLARE + v_id text; + v_charge jsonb; + v_hold public.credit_reservations%ROWTYPE; + v_wallet public.credits_usage%ROWTYPE; +BEGIN + IF p_account_id IS NULL OR p_operation_key IS NULL OR btrim(p_operation_key) = '' + OR length(p_operation_key) > 200 OR p_credits IS NULL OR p_credits <= 0 + OR p_credits > 9007199254740991 THEN + RAISE EXCEPTION 'Invalid credit settlement' USING ERRCODE = '22023'; + END IF; + BEGIN + SELECT * INTO STRICT v_wallet FROM public.credits_usage + WHERE account_id = p_account_id ORDER BY id FOR UPDATE; + EXCEPTION WHEN no_data_found OR too_many_rows THEN + RAISE EXCEPTION 'Credit wallet is unavailable or ambiguous' USING ERRCODE = '22023'; + END; + v_id := 'hold-v1-' || encode(sha256(convert_to( + jsonb_build_array(p_account_id::text,p_operation_key)::text,'UTF8')),'hex'); + SELECT * INTO v_hold FROM public.credit_reservations WHERE id = v_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Credit reservation not found' USING ERRCODE = '22023'; + END IF; + IF v_hold.state = 'released' THEN + -- Charging released work needs an explicit failure/cancellation policy. + RAISE EXCEPTION 'Credit reservation was released' USING ERRCODE = '22023'; + END IF; + IF p_credits > v_hold.credits_held THEN + RAISE EXCEPTION 'Credit settlement exceeds reservation' USING ERRCODE = '22023'; + END IF; + -- Same owner/key as the reservation: an identical retry reuses the charge + -- receipt; a changed amount or usage payload raises its identity conflict. + v_charge := public.record_credit_charge_once(p_account_id,p_operation_key,p_credits,p_event); + IF v_hold.state = 'held' THEN + UPDATE public.credit_reservations + SET state = 'settled', credits_charged = p_credits, + charge_event_id = v_charge->>'eventId', closed_at = now() + WHERE id = v_id; + ELSIF v_hold.charge_event_id IS DISTINCT FROM v_charge->>'eventId' + OR v_hold.credits_charged IS DISTINCT FROM p_credits THEN + RAISE EXCEPTION 'Credit settlement identity conflict' USING ERRCODE = '22023'; + END IF; + RETURN jsonb_build_object( + 'state',CASE WHEN v_hold.state = 'held' THEN 'settled' ELSE 'reused' END, + 'reservationId',v_id,'eventId',v_charge->>'eventId','creditsHeld',v_hold.credits_held, + 'creditsCharged',p_credits,'creditsReleased',v_hold.credits_held - p_credits); +END; +$$; + +CREATE OR REPLACE FUNCTION public.release_credit_reservation( + p_account_id uuid, p_operation_key text +) RETURNS jsonb +LANGUAGE plpgsql SECURITY INVOKER SET search_path = public, pg_temp AS $$ +DECLARE + v_id text; + v_hold public.credit_reservations%ROWTYPE; + v_wallet public.credits_usage%ROWTYPE; +BEGIN + IF p_account_id IS NULL OR p_operation_key IS NULL OR btrim(p_operation_key) = '' + OR length(p_operation_key) > 200 THEN + RAISE EXCEPTION 'Invalid credit release' USING ERRCODE = '22023'; + END IF; + BEGIN + SELECT * INTO STRICT v_wallet FROM public.credits_usage + WHERE account_id = p_account_id ORDER BY id FOR UPDATE; + EXCEPTION WHEN no_data_found OR too_many_rows THEN + RAISE EXCEPTION 'Credit wallet is unavailable or ambiguous' USING ERRCODE = '22023'; + END; + v_id := 'hold-v1-' || encode(sha256(convert_to( + jsonb_build_array(p_account_id::text,p_operation_key)::text,'UTF8')),'hex'); + SELECT * INTO v_hold FROM public.credit_reservations WHERE id = v_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Credit reservation not found' USING ERRCODE = '22023'; + END IF; + IF v_hold.state = 'settled' THEN + RAISE EXCEPTION 'Credit reservation was settled' USING ERRCODE = '22023'; + END IF; + -- Release writes no usage event and never changes the confirmed balance. + IF v_hold.state = 'held' THEN + UPDATE public.credit_reservations SET state = 'released', closed_at = now() WHERE id = v_id; + END IF; + RETURN jsonb_build_object( + 'state',CASE WHEN v_hold.state = 'held' THEN 'released' ELSE 'reused' END, + 'reservationId',v_id,'creditsHeld',v_hold.credits_held,'creditsReleased',v_hold.credits_held); +END; +$$; + +REVOKE ALL ON FUNCTION public.reserve_credits_once(uuid,text,bigint) + FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.reserve_credits_once(uuid,text,bigint) TO service_role; +REVOKE ALL ON FUNCTION public.settle_credit_reservation(uuid,text,bigint,jsonb) + FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.settle_credit_reservation(uuid,text,bigint,jsonb) TO service_role; +REVOKE ALL ON FUNCTION public.release_credit_reservation(uuid,text) + FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.release_credit_reservation(uuid,text) TO service_role; +COMMIT; diff --git a/tests/CREDIT-RESERVATIONS.md b/tests/CREDIT-RESERVATIONS.md new file mode 100644 index 0000000..4ac7bb3 --- /dev/null +++ b/tests/CREDIT-RESERVATIONS.md @@ -0,0 +1,75 @@ +# Credit reservations (holds) + +`20261010210500_credit_reservations.sql` adds the shared reserve/settle/release +primitive for AI work (recoupable/app#2105 milestone 1, reused by Context accounting +in recoupable/app#2123). It uses the existing `credits_usage` wallet and the +`usage_events` audit log through `record_credit_charge_once`. It adds no wallet, +balance column, price, ceiling, top-up, expiry or caller. + +## Wallet invariant + +- **Confirmed balance:** `credits_usage.remaining_credits`, unchanged by holds. +- **Outstanding holds:** the sum of `credits_held` for the owner's `held` rows. +- **Spendable:** confirmed balance minus outstanding holds. + +A hold is a claim, not a temporary debit followed by a refund, so the monthly +refill, top-ups and auto-top-up never treat it as consumption. Every operation locks +the owner's single wallet row first (rejecting zero or multiple rows like +`record_credit_charge_once`), so holds serialize with each other, with charge +receipts and with the legacy wallet writers. + +## Operations (service role only, security invoker) + +| Function | Result | +| --- | --- | +| `reserve_credits_once(owner, key, credits)` | `held` (new hold), `reused` (same key and amount; reports saved status), or `insufficient` (nothing written). A changed amount conflicts. | +| `settle_credit_reservation(owner, key, credits, event)` | Charges the actual credits through `record_credit_charge_once` with the same key and closes the hold; the remainder is no longer held. An identical retry is `reused`; a changed amount or usage payload conflicts. Charging more than the hold, or a released hold, is rejected. | +| `release_credit_reservation(owner, key)` | Closes an unsettled hold without a charge or usage event; a retry is `reused`. Releasing a settled hold is rejected. | + +The reservation ID (`hold-v1-…`) and the charge receipt ID (`charge-v1-…`) both +derive from the billing owner and operation key. A key identifies one chargeable +attempt: never generate a fresh key on retry and never reuse one for independent work. +A lost reply is ambiguous; replay the same call with the same key to learn the state. + +## Deliberately open + +- **Legacy debit writers do not consult holds.** `deduct_credits_with_audit`, + `deduct_credits` and the API's read-modify-write `deductCredits` still debit the + confirmed balance directly, so spendable credit can fall below zero while a hold + is outstanding. Moving those callers onto reservations is a later slice. +- **No expiry.** Unknown provider exposure stays held until the trusted server + settles or releases it. Do not add a time-based release that turns uncertain + work into spendable credit. +- **Failure and cancellation billing are not decided here.** Release is for work + known not to have incurred a charge (for example, cancelled before dispatch). + Charging released or over-limit work needs an approved policy. +- Request/pilot ceilings, provider-expense versus customer-debit reporting and + pricing versions are not stored here. +- Reservations must be retained like charge receipts. A purge would let a + recycled key hold capacity again, so the service role has no DELETE/TRUNCATE. + +## Verification + +Disposable cluster only (synthetic balances, Unix socket, no hosted credentials): + +```sh +python3 -m unittest discover -s tests -p 'test_credit_reservations.py' +``` + +Eighteen tests cover holds without debit, 12-way concurrent reservations against +one balance, concurrent duplicate reservations and settlements, lost-reply replay, +changed-input conflicts, settlement through the shared charge receipt, over-limit +settlement, release and its state transitions, missing reservations, per-owner +isolation, top-up concurrent with settlement, refill with an outstanding hold, legacy +debit concurrency (documenting that it ignores holds), invalid inputs, +missing/duplicate wallets, denied browser roles, denied service-role deletes and +rollback. Locally passed on +PostgreSQL 15 and 17; CI runs 15 and 16. The fixture is the minimal legacy +schema plus the actual charge-receipt migration, not a replay of every migration. + +## Release + +Apply through the normal database release workflow before deploying the API +adapters. Verify the table and function grants after release (service role only; +no browser grants). Do not exercise these functions against a real wallet to test +deployment. Rolling back the API stops new callers; keep the table and its rows. diff --git a/tests/test_credit_reservations.py b/tests/test_credit_reservations.py new file mode 100644 index 0000000..5d2febe --- /dev/null +++ b/tests/test_credit_reservations.py @@ -0,0 +1,247 @@ +"""Credit reservations (holds) on the existing wallet, against real local transactions.""" +import concurrent.futures +import json +import uuid +from credit_charge_fixture import CreditChargeFixture, ROOT + +MIGRATION = ROOT / 'supabase/migrations/20261010210500_credit_reservations.sql' + + +class CreditReservations(CreditChargeFixture): + @classmethod + def setUpClass(cls): + super().setUpClass() + # Required, never skipped: without the migration the suite must fail. + cls.sql(MIGRATION.read_text()) + + def setUp(self): + self.owner = str(uuid.uuid4()) + self.sql(f"INSERT INTO credits_usage(account_id,remaining_credits) VALUES ('{self.owner}',1000)") + + @staticmethod + def quote(value): + return value.replace("'", "''") + + def reserve_statement(self, key='work-1', credits=300, owner=None, role='service_role'): + return (f"SET ROLE {role}; SELECT public.reserve_credits_once(" + f"'{owner or self.owner}', '{self.quote(key)}', {credits});") + + def settle_statement(self, key='work-1', credits=120, event=None, owner=None): + payload = self.quote(json.dumps(event or {})) + return (f"SET ROLE service_role; SELECT public.settle_credit_reservation(" + f"'{owner or self.owner}', '{self.quote(key)}', {credits}, '{payload}'::jsonb);") + + def release_statement(self, key='work-1', owner=None): + return (f"SET ROLE service_role; SELECT public.release_credit_reservation(" + f"'{owner or self.owner}', '{self.quote(key)}');") + + def run_json(self, statement): + return json.loads(self.sql(statement).stdout) + + def reserve(self, **kwargs): + return self.run_json(self.reserve_statement(**kwargs)) + + def settle(self, **kwargs): + return self.run_json(self.settle_statement(**kwargs)) + + def release(self, **kwargs): + return self.run_json(self.release_statement(**kwargs)) + + def failing(self, statement): + result = self.sql(statement, succeeds=False) + self.assertNotEqual(result.returncode, 0) + return result.stderr + + def balance(self, owner=None): + return int(self.sql(f"SELECT remaining_credits FROM credits_usage " + f"WHERE account_id='{owner or self.owner}'").stdout) + + def holds(self, state='held'): + return int(self.sql(f"SELECT coalesce(sum(credits_held),0) FROM credit_reservations " + f"WHERE account_id='{self.owner}' AND state='{state}'").stdout) + + def usage_events(self): + return int(self.sql(f"SELECT count(*) FROM usage_events WHERE account_id='{self.owner}'").stdout) + + def test_hold_reduces_spendable_without_debit_or_usage_event(self): + receipt = self.reserve() + self.assertEqual(receipt['state'], 'held') + self.assertRegex(receipt['reservationId'], r'^hold-v1-[a-f0-9]{64}$') + self.assertEqual(receipt['creditsHeld'], 300) + self.assertEqual(receipt['spendableCredits'], 700) + # A hold is not a temporary debit: refill/auto-top-up never see it as consumption. + self.assertEqual(self.balance(), 1000) + self.assertEqual(self.usage_events(), 0) + denied = self.reserve(key='work-2', credits=701) + self.assertEqual(denied, {'state': 'insufficient', 'creditsRequested': 701, 'spendableCredits': 700}) + self.assertEqual(self.holds(), 300) + + def test_concurrent_reservations_never_exceed_the_balance(self): + with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool: + receipts = list(pool.map(lambda i: self.reserve(key=f'work-{i}', credits=100), range(12))) + self.assertEqual(sum(r['state'] == 'held' for r in receipts), 10) + self.assertEqual(sum(r['state'] == 'insufficient' for r in receipts), 2) + self.assertEqual(self.holds(), 1000) + self.assertEqual(self.balance(), 1000) + + def test_concurrent_duplicate_reservation_holds_once(self): + with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool: + receipts = list(pool.map(lambda _: self.reserve(), range(12))) + self.assertEqual(sum(r['state'] == 'held' for r in receipts), 1) + self.assertEqual(sum(r['state'] == 'reused' for r in receipts), 11) + self.assertEqual(len({r['reservationId'] for r in receipts}), 1) + self.assertEqual(self.holds(), 300) + + def test_replayed_reservation_reports_current_status_and_changed_amount_conflicts(self): + first = self.reserve() + self.assertEqual(self.reserve(), {'state': 'reused', 'reservationId': first['reservationId'], + 'status': 'held', 'creditsHeld': 300}) + self.assertIn('Credit reservation identity conflict', self.failing(self.reserve_statement(credits=301))) + self.release() + # A replay after release never re-holds capacity for the same work. + self.assertEqual(self.reserve()['status'], 'released') + self.assertEqual(self.holds(), 0) + + def test_settlement_charges_actual_credits_and_releases_the_remainder(self): + held = self.reserve() + receipt = self.settle(event={'model_id': 'fixture', 'output_tokens': 12}) + self.assertEqual(receipt['state'], 'settled') + self.assertEqual(receipt['reservationId'], held['reservationId']) + self.assertRegex(receipt['eventId'], r'^charge-v1-[a-f0-9]{64}$') + self.assertEqual((receipt['creditsHeld'], receipt['creditsCharged'], receipt['creditsReleased']), + (300, 120, 180)) + self.assertEqual(self.balance(), 880) + self.assertEqual(self.holds(), 0) + self.assertEqual(self.holds('settled'), 300) + row = self.sql(f"SELECT credits_deducted, model_id, output_tokens FROM usage_events " + f"WHERE id='{receipt['eventId']}'").stdout.strip() + self.assertEqual(row, '120|fixture|12') + self.assertEqual(self.reserve(key='work-2', credits=880)['state'], 'held') + + def test_settlement_shares_the_charge_receipt_identity(self): + self.reserve() + settled = self.settle() + direct = self.run_json(f"SET ROLE service_role; SELECT public.record_credit_charge_once(" + f"'{self.owner}', 'work-1', 120, '{{}}'::jsonb);") + self.assertEqual(direct['state'], 'reused') + self.assertEqual(direct['eventId'], settled['eventId']) + self.assertEqual(self.balance(), 880) + + def test_lost_and_concurrent_settlement_acknowledgements_charge_once(self): + self.reserve() + with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool: + receipts = list(pool.map(lambda _: self.settle(), range(12))) + self.assertEqual(sum(r['state'] == 'settled' for r in receipts), 1) + self.assertEqual(sum(r['state'] == 'reused' for r in receipts), 11) + self.assertEqual(len({r['eventId'] for r in receipts}), 1) + self.assertEqual(self.settle()['state'], 'reused') + self.assertEqual(self.balance(), 880) + self.assertEqual(self.usage_events(), 1) + + def test_changed_settlement_conflicts_and_keeps_the_first_charge(self): + self.reserve() + self.settle() + for args in [{'credits': 121}, {'event': {'provider': 'different'}}]: + self.assertIn('Credit charge identity conflict', self.failing(self.settle_statement(**args))) + self.assertEqual(self.balance(), 880) + + def test_settlement_above_the_reservation_is_rejected_and_the_hold_remains(self): + self.reserve() + self.assertIn('Credit settlement exceeds reservation', self.failing(self.settle_statement(credits=301))) + self.assertEqual(self.balance(), 1000) + self.assertEqual(self.holds(), 300) + self.assertEqual(self.usage_events(), 0) + + def test_release_returns_capacity_without_charge_and_closes_the_reservation(self): + self.reserve() + receipt = self.release() + self.assertEqual((receipt['state'], receipt['creditsHeld'], receipt['creditsReleased']), + ('released', 300, 300)) + self.assertEqual(self.release()['state'], 'reused') + self.assertEqual((self.balance(), self.holds(), self.usage_events()), (1000, 0, 0)) + self.assertIn('Credit reservation was released', self.failing(self.settle_statement())) + self.reserve(key='work-2') + self.settle(key='work-2') + self.assertIn('Credit reservation was settled', self.failing(self.release_statement(key='work-2'))) + self.assertEqual(self.balance(), 880) + + def test_settle_or_release_without_a_reservation_never_charges(self): + self.assertIn('Credit reservation not found', self.failing(self.settle_statement())) + self.assertIn('Credit reservation not found', self.failing(self.release_statement())) + self.assertEqual((self.balance(), self.usage_events()), (1000, 0)) + + def test_holds_are_isolated_per_billing_owner(self): + other = str(uuid.uuid4()) + self.sql(f"INSERT INTO credits_usage(account_id,remaining_credits) VALUES ('{other}',100)") + mine = self.reserve(credits=1000) + # Same operation key, different billing owner: a separate hold and identity. + foreign = self.reserve(owner=other, credits=100) + self.assertEqual((mine['state'], foreign['state']), ('held', 'held')) + self.assertNotEqual(foreign['reservationId'], mine['reservationId']) + self.assertEqual(self.reserve(owner=other, key='work-2', credits=1)['state'], 'insufficient') + self.assertIn('Credit reservation not found', self.failing(self.release_statement(owner=other, key='absent'))) + + def test_top_up_and_settlement_concurrently_both_survive(self): + self.reserve() + top_up = (f"SET ROLE service_role; UPDATE credits_usage SET remaining_credits = remaining_credits + 500 " + f"WHERE account_id='{self.owner}'") + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + list(pool.map(self.sql, [top_up, self.settle_statement()])) + self.assertEqual(self.balance(), 1380) + + def test_refill_with_an_outstanding_hold_keeps_the_hold(self): + self.sql(f"UPDATE credits_usage SET remaining_credits = 200 WHERE account_id='{self.owner}'") + self.reserve(credits=150) + self.sql(f"UPDATE credits_usage SET remaining_credits = GREATEST(remaining_credits, 1000) " + f"WHERE account_id='{self.owner}'") + self.assertEqual(self.holds(), 150) + self.assertEqual(self.reserve(key='work-2', credits=851)['spendableCredits'], 850) + + def test_legacy_debit_concurrent_with_reservation_is_kept_but_ignores_holds(self): + legacy = (f"SET ROLE service_role; SELECT deduct_credits_with_audit(" + f"'{self.owner}',50::bigint,'legacy-{self.owner}','{{}}'::jsonb)") + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + results = list(pool.map(self.sql, [legacy, self.reserve_statement(credits=960)])) + self.assertEqual(self.balance(), 950) + state = json.loads(results[1].stdout)['state'] + self.assertIn(state, {'held', 'insufficient'}) + # Known limitation: legacy debit callers do not consult holds, so a debit that + # commits after the hold can leave spendable credit below zero until settlement. + self.assertEqual(self.holds(), 960 if state == 'held' else 0) + + def test_invalid_inputs_and_missing_or_duplicate_wallets_never_write(self): + statements = [self.reserve_statement(credits=0), self.reserve_statement(credits=-1), + self.reserve_statement(key=' '), self.reserve_statement(key='k' * 201), + self.reserve_statement(credits=9007199254740992), + self.reserve_statement(owner=str(uuid.uuid4()))] + for statement in statements: + self.failing(statement) + self.reserve() + for statement in [self.settle_statement(credits=0), self.settle_statement(event={'extra': True}), + self.settle_statement(event={'input_tokens': -1}), self.release_statement(key='')]: + self.failing(statement) + self.assertEqual((self.balance(), self.holds(), self.usage_events()), (1000, 300, 0)) + self.sql(f"INSERT INTO credits_usage(account_id,remaining_credits) VALUES ('{self.owner}',700)") + for statement in [self.reserve_statement(key='work-2'), self.settle_statement(), self.release_statement()]: + self.assertIn('Credit wallet is unavailable or ambiguous', self.failing(statement)) + self.assertEqual(self.holds(), 300) + + def test_browser_roles_are_denied_and_holds_cannot_be_deleted(self): + self.reserve() + for role in ['anon', 'authenticated']: + for statement in [self.reserve_statement(key='browser'), self.settle_statement(), + self.release_statement(), 'SELECT * FROM credit_reservations;']: + result = self.sql(statement.replace('service_role', role) if 'SET ROLE' in statement + else f'SET ROLE {role}; {statement}', succeeds=False) + self.assertIn('permission denied', result.stderr) + self.assertEqual((self.balance(), self.holds()), (1000, 300)) + for statement in ['DELETE FROM credit_reservations;', 'TRUNCATE credit_reservations;']: + self.assertIn('permission denied', self.failing(f'SET ROLE service_role; {statement}')) + self.assertEqual(self.holds(), 300) + + def test_transaction_rollback_leaves_no_hold_or_charge(self): + self.sql('BEGIN;' + self.reserve_statement() + 'ROLLBACK;') + self.assertEqual(self.holds(), 0) + self.reserve() + self.sql('BEGIN;' + self.settle_statement() + 'ROLLBACK;') + self.assertEqual((self.balance(), self.holds(), self.usage_events()), (1000, 300, 0)) From e05c45487cc16fe908bfa52ba2e6e78b3789bc57 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Sat, 10 Oct 2026 17:43:21 -0400 Subject: [PATCH 2/5] Freeze hold columns and state activation prerequisites Review follow-up for credit reservations. The service role's UPDATE grant now covers only the closing columns (state, credits_charged, charge_event_id, closed_at), so a hold's owner, key and amount cannot be rewritten outside the functions; a new test checks this and that the service role can still read open holds to reconcile a lost key. The docs now say that connecting any caller requires database#101 and api#1009 (main's API top-up and refill still write an absolute balance read earlier, which can erase a settlement) and database#88. The top-up and refill tests are renamed to say they model atomic writers. The docs also note that every raised rejection is SQLSTATE 22023 and rolled back, and that a held receipt is not an execution lease for duplicate deliveries. Co-Authored-By: Claude Opus 5.5 --- .../20261010210500_credit_reservations.sql | 7 +++- tests/CREDIT-RESERVATIONS.md | 38 ++++++++++++++++--- tests/test_credit_reservations.py | 21 +++++++++- 3 files changed, 58 insertions(+), 8 deletions(-) diff --git a/supabase/migrations/20261010210500_credit_reservations.sql b/supabase/migrations/20261010210500_credit_reservations.sql index d2b2108..cd5b6fd 100644 --- a/supabase/migrations/20261010210500_credit_reservations.sql +++ b/supabase/migrations/20261010210500_credit_reservations.sql @@ -36,8 +36,13 @@ CREATE INDEX credit_reservations_open_idx ALTER TABLE public.credit_reservations ENABLE ROW LEVEL SECURITY; -- Retained like charge receipts: deleting a row would let a recycled key hold again, -- so the service role gets no DELETE/TRUNCATE even where default privileges grant it. +-- UPDATE is limited to the columns settle/release close; a hold's owner, key and +-- amount are immutable once written. The service role may read open holds +-- (state = 'held', by account and created_at) to reconcile lost operation keys. REVOKE ALL ON public.credit_reservations FROM PUBLIC, anon, authenticated, service_role; -GRANT SELECT, INSERT, UPDATE ON public.credit_reservations TO service_role; +GRANT SELECT, INSERT ON public.credit_reservations TO service_role; +GRANT UPDATE (state, credits_charged, charge_event_id, closed_at) + ON public.credit_reservations TO service_role; CREATE OR REPLACE FUNCTION public.reserve_credits_once( p_account_id uuid, p_operation_key text, p_credits bigint diff --git a/tests/CREDIT-RESERVATIONS.md b/tests/CREDIT-RESERVATIONS.md index 4ac7bb3..1201952 100644 --- a/tests/CREDIT-RESERVATIONS.md +++ b/tests/CREDIT-RESERVATIONS.md @@ -30,6 +30,28 @@ The reservation ID (`hold-v1-…`) and the charge receipt ID (`charge-v1-…`) b derive from the billing owner and operation key. A key identifies one chargeable attempt: never generate a fresh key on retry and never reuse one for independent work. A lost reply is ambiguous; replay the same call with the same key to learn the state. +Every rejection these functions raise uses SQLSTATE `22023` and rolls back, so it is +definite for that call: nothing was written, and an unchanged replay fails the same way. + +A `reused` receipt with status `held` goes to every duplicate delivery of the same +key, so a hold permits paid work but is not an execution lease. Duplicate deliveries +must be deduplicated by the caller's own attempt identity before provider dispatch; +settlement charges once either way. + +## Activation prerequisites + +These functions are safe to release with no callers. Do not connect any caller until +these also land: + +- **database#101 and api#1009** (atomic refill and top-up writers). On `main`, the + API top-up (`incrementRemainingCredits`) and monthly refill (`checkAndResetCredits`) + read the balance and later write an absolute value. A settlement that commits between + that read and write is erased from the balance while its `usage_events` row remains. +- **database#88** (one wallet per account). Until then, an account with duplicate + wallet rows is rejected rather than charged. + +The top-up and refill tests here model atomic in-place writers like database#101's; +they do not exercise main's read-modify-write API paths. ## Deliberately open @@ -47,6 +69,12 @@ A lost reply is ambiguous; replay the same call with the same key to learn the s pricing versions are not stored here. - Reservations must be retained like charge receipts. A purge would let a recycled key hold capacity again, so the service role has no DELETE/TRUNCATE. + Its UPDATE grant covers only the closing columns (`state`, `credits_charged`, + `charge_event_id`, `closed_at`); owner, key and amount are immutable. +- **No listing API for open holds.** A worker that loses its key leaves the hold open. + The service role can find open holds by reading `credit_reservations` where + `state = 'held'` (indexed by account, ordered by `created_at`) and then settle or + release them with the recorded key. An API or operator view is a later slice. ## Verification @@ -56,14 +84,14 @@ Disposable cluster only (synthetic balances, Unix socket, no hosted credentials) python3 -m unittest discover -s tests -p 'test_credit_reservations.py' ``` -Eighteen tests cover holds without debit, 12-way concurrent reservations against +Nineteen tests cover holds without debit, 12-way concurrent reservations against one balance, concurrent duplicate reservations and settlements, lost-reply replay, changed-input conflicts, settlement through the shared charge receipt, over-limit settlement, release and its state transitions, missing reservations, per-owner -isolation, top-up concurrent with settlement, refill with an outstanding hold, legacy -debit concurrency (documenting that it ignores holds), invalid inputs, -missing/duplicate wallets, denied browser roles, denied service-role deletes and -rollback. Locally passed on +isolation, an atomic top-up concurrent with settlement, an atomic refill with an +outstanding hold, legacy debit concurrency (documenting that it ignores holds), +invalid inputs, missing/duplicate wallets, denied browser roles, denied service-role +deletes and immutable hold columns, and rollback. Locally passed on PostgreSQL 15 and 17; CI runs 15 and 16. The fixture is the minimal legacy schema plus the actual charge-receipt migration, not a replay of every migration. diff --git a/tests/test_credit_reservations.py b/tests/test_credit_reservations.py index 5d2febe..674154d 100644 --- a/tests/test_credit_reservations.py +++ b/tests/test_credit_reservations.py @@ -181,7 +181,10 @@ def test_holds_are_isolated_per_billing_owner(self): self.assertEqual(self.reserve(owner=other, key='work-2', credits=1)['state'], 'insufficient') self.assertIn('Credit reservation not found', self.failing(self.release_statement(owner=other, key='absent'))) - def test_top_up_and_settlement_concurrently_both_survive(self): + def test_atomic_top_up_and_settlement_concurrently_both_survive(self): + # Models an in-place (atomic) top-up writer such as database#101's. Main's API + # top-up and refill still write an absolute balance read earlier, which can erase + # a settlement that commits in between; callers stay disconnected until that lands. self.reserve() top_up = (f"SET ROLE service_role; UPDATE credits_usage SET remaining_credits = remaining_credits + 500 " f"WHERE account_id='{self.owner}'") @@ -189,7 +192,8 @@ def test_top_up_and_settlement_concurrently_both_survive(self): list(pool.map(self.sql, [top_up, self.settle_statement()])) self.assertEqual(self.balance(), 1380) - def test_refill_with_an_outstanding_hold_keeps_the_hold(self): + def test_atomic_refill_with_an_outstanding_hold_keeps_the_hold(self): + # Models an in-place refill to the plan floor (database#101), not main's API refill. self.sql(f"UPDATE credits_usage SET remaining_credits = 200 WHERE account_id='{self.owner}'") self.reserve(credits=150) self.sql(f"UPDATE credits_usage SET remaining_credits = GREATEST(remaining_credits, 1000) " @@ -239,6 +243,19 @@ def test_browser_roles_are_denied_and_holds_cannot_be_deleted(self): self.assertIn('permission denied', self.failing(f'SET ROLE service_role; {statement}')) self.assertEqual(self.holds(), 300) + def test_service_role_cannot_rewrite_a_hold_owner_key_or_amount(self): + self.reserve() + for column, value in [('credits_held', '1'), ('account_id', f"'{uuid.uuid4()}'"), + ('operation_key', "'other'"), ('id', f"'hold-v1-{'0' * 64}'"), + ('created_at', 'now()')]: + self.assertIn('permission denied', self.failing( + f'SET ROLE service_role; UPDATE credit_reservations SET {column} = {value};')) + open_holds = self.sql(f"SET ROLE service_role; SELECT operation_key, credits_held FROM " + f"credit_reservations WHERE account_id='{self.owner}' AND state='held' " + f"ORDER BY created_at;").stdout.strip() + self.assertEqual(open_holds, 'work-1|300') + self.assertEqual(self.settle()['state'], 'settled') + def test_transaction_rollback_leaves_no_hold_or_charge(self): self.sql('BEGIN;' + self.reserve_statement() + 'ROLLBACK;') self.assertEqual(self.holds(), 0) From 3f2c84903286f0c950faa03bd2cef72f20d5d8ad Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Mon, 26 Oct 2026 02:13:45 -0400 Subject: [PATCH 3/5] Restore recorded migration source identities --- ...009180000_context_evidence_attachments.sql | 186 ++++ ...09180001_context_evidence_receipt_seal.sql | 45 + ...9180002_context_evidence_authorization.sql | 82 ++ ...261009180003_context_evidence_receipts.sql | 48 + .../20261009180004_context_evidence_list.sql | 27 + ...035229_context_evidence_atomic_release.sql | 967 ++++++++++++++++++ ...l => 20261020154953_release_pack_jobs.sql} | 0 ...24002432_professional_artist_accounts.sql} | 0 tests/MIGRATION-HISTORY.md | 24 + tests/README.md | 2 +- tests/RELEASE-PACK-JOBS.md | 2 +- tests/release_pack_fixture.py | 2 +- tests/test_professional_roster.py | 4 +- 13 files changed, 1384 insertions(+), 5 deletions(-) create mode 100644 supabase/migrations/20261009180000_context_evidence_attachments.sql create mode 100644 supabase/migrations/20261009180001_context_evidence_receipt_seal.sql create mode 100644 supabase/migrations/20261009180002_context_evidence_authorization.sql create mode 100644 supabase/migrations/20261009180003_context_evidence_receipts.sql create mode 100644 supabase/migrations/20261009180004_context_evidence_list.sql create mode 100644 supabase/migrations/20261020035229_context_evidence_atomic_release.sql rename supabase/migrations/{20261020150000_release_pack_jobs.sql => 20261020154953_release_pack_jobs.sql} (100%) rename supabase/migrations/{20261023160000_professional_artist_accounts.sql => 20261024002432_professional_artist_accounts.sql} (100%) create mode 100644 tests/MIGRATION-HISTORY.md diff --git a/supabase/migrations/20261009180000_context_evidence_attachments.sql b/supabase/migrations/20261009180000_context_evidence_attachments.sql new file mode 100644 index 0000000..7c170e7 --- /dev/null +++ b/supabase/migrations/20261009180000_context_evidence_attachments.sql @@ -0,0 +1,186 @@ +-- Relevance links for retained evidence, not identity, rights or mandate approval. +begin; +set local lock_timeout='5s'; +set local statement_timeout='30s'; + +alter table public.organization_professionals add constraint organization_professionals_id_owner unique(id,organization_id); +create table public.context_evidence_attachments ( + id uuid primary key default gen_random_uuid(), + owner_id uuid not null references public.accounts(id), + actor_id uuid not null references public.accounts(id), + source_version_id uuid not null, + idempotency_key text not null check(idempotency_key ~ '^[A-Za-z0-9._:-]{1,128}$'), + fingerprint text not null check(fingerprint ~ '^[a-f0-9]{64}$'), + created_at timestamptz not null default now(), + foreign key(source_version_id,owner_id) references public.context_source_versions(id,owner_id), + unique(owner_id,idempotency_key), unique(id,owner_id) +); +create index context_evidence_attachments_version on public.context_evidence_attachments(owner_id,source_version_id,id); +create table public.context_evidence_attachment_targets ( + attachment_id uuid not null, + owner_id uuid not null, + position integer not null check(position between 0 and 99), + artist_id uuid references public.accounts(id), + professional_id uuid, + request_id uuid, + subject_id uuid references public.context_subjects(id), + primary key(attachment_id,position), + foreign key(attachment_id,owner_id) references public.context_evidence_attachments(id,owner_id), + foreign key(professional_id,owner_id) references public.organization_professionals(id,organization_id), + foreign key(request_id,owner_id) references public.context_requests(id,owner_id), + check((artist_id is not null and professional_id is null and request_id is null and subject_id is null) + or (professional_id is not null and artist_id is null and request_id is null and subject_id is null) + or (request_id is not null and subject_id is not null and artist_id is null and professional_id is null)) +); +alter table public.context_evidence_attachments enable row level security; +alter table public.context_evidence_attachment_targets enable row level security; +revoke all on public.context_evidence_attachments,public.context_evidence_attachment_targets from public,anon,authenticated,service_role; +grant select,insert on public.context_evidence_attachments,public.context_evidence_attachment_targets to service_role; + +-- Exact shapes and UUIDs only. Caller order does not change replay identity. +create function public.canonical_context_evidence_targets(p_targets jsonb) +returns jsonb language plpgsql set search_path='' as $$ +declare t jsonb; n integer; canonical jsonb; field text; +begin + if jsonb_typeof(p_targets) is distinct from 'array' then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + if jsonb_array_length(p_targets) not between 1 and 100 then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + for t in select value from jsonb_array_elements(p_targets) loop + if jsonb_typeof(t) is distinct from 'object' then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + select count(*) into n from jsonb_object_keys(t); + if not ((n=1 and (t ? 'artist_id' or t ? 'professional_id')) or (n=2 and t ? 'request_id' and t ? 'subject_id')) + then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + for field in select jsonb_object_keys(t) loop + if jsonb_typeof(t->field) is distinct from 'string' or (t->>field) !~* '^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$' + then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + t:=jsonb_set(t,array[field],to_jsonb((t->>field)::uuid::text)); + end loop; + end loop; + select jsonb_agg(normalized order by normalized::text),count(distinct normalized) into canonical,n + from (select jsonb_object_agg(key,to_jsonb(value::uuid::text)) normalized + from jsonb_array_elements(p_targets) with ordinality a(target,ordinal) + cross join lateral jsonb_each_text(target) e(key,value) group by ordinal) q; + if n<>jsonb_array_length(p_targets) then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + return canonical; +end $$; + +create function public.authorize_context_evidence_source(p_owner uuid,p_version uuid) +returns void language plpgsql set search_path='' as $$ +begin + perform 1 from public.context_sources s join public.context_source_versions v on v.source_id=s.id and v.owner_id=s.owner_id + where v.id=p_version and v.owner_id=p_owner and v.removed_at is null and s.withdrawn_at is null for share of s,v; + if not found then raise exception 'Evidence source unavailable' using errcode='42501'; end if; +end $$; + +-- A global subject UUID never grants access. An owned request plus retained +-- accepted lineage is an independent historical path, even after roster removal. +-- Submitted company/writer candidates retain their original uncertainty. +create function public.authorize_context_evidence_targets(p_owner uuid,p_targets jsonb) +returns void language plpgsql set search_path='' as $$ +declare t jsonb; accessible boolean; +begin + for t in select value from jsonb_array_elements(p_targets) loop + accessible:=false; + if t ? 'artist_id' then + perform 1 from public.account_artist_ids where account_id=p_owner and artist_id=(t->>'artist_id')::uuid for share; + accessible:=found; + perform 1 from public.artist_organization_ids where organization_id=p_owner and artist_id=(t->>'artist_id')::uuid for share; + accessible:=accessible or found; + elsif t ? 'professional_id' then + perform 1 from public.organization_professionals where organization_id=p_owner and id=(t->>'professional_id')::uuid for share; + accessible:=found; + else + -- Source locks precede request/result locks, consistent with withdrawal. + perform 1 from public.context_sources s join public.context_source_versions v on v.source_id=s.id and v.owner_id=s.owner_id + join public.context_result_sources rs on rs.source_version_id=v.id and rs.owner_id=v.owner_id + join public.context_results r on r.id=rs.result_id and r.owner_id=rs.owner_id + join public.context_attempts a on a.id=r.attempt_id and a.owner_id=r.owner_id + where a.request_id=(t->>'request_id')::uuid and r.subject_id=(t->>'subject_id')::uuid and r.owner_id=p_owner + order by s.id,v.id for share of s,v; + perform 1 from public.context_requests where owner_id=p_owner and id=(t->>'request_id')::uuid for share; + perform 1 from public.context_results r join public.context_attempts a on a.id=r.attempt_id and a.owner_id=r.owner_id + where r.owner_id=p_owner and a.request_id=(t->>'request_id')::uuid and r.subject_id=(t->>'subject_id')::uuid for share of r; + select exists(select 1 from public.context_requests req join public.context_attempts a on a.request_id=req.id and a.owner_id=req.owner_id + join public.context_results r on r.attempt_id=a.id and r.owner_id=a.owner_id + where req.owner_id=p_owner and req.id=(t->>'request_id')::uuid and req.status in ('partial','completed') + and jsonb_typeof(req.output->'subjectIds')='array' and req.output->'subjectIds' ? (t->>'subject_id') + and r.subject_id=(t->>'subject_id')::uuid and r.status='accepted' and r.evidence_kind<>'creative_proposal' + and exists(select 1 from public.context_result_sources rs where rs.result_id=r.id and rs.owner_id=p_owner) + and not exists(select 1 from public.context_result_sources rs + join public.context_source_versions v on v.id=rs.source_version_id and v.owner_id=rs.owner_id + join public.context_sources s on s.id=v.source_id and s.owner_id=v.owner_id + where rs.result_id=r.id and rs.owner_id=p_owner and (v.removed_at is not null or s.withdrawn_at is not null))) into accessible; + end if; + if not accessible then raise exception 'Evidence target unavailable' using errcode='42501'; end if; + end loop; +end $$; + +create function public.read_context_evidence_attachment(p_actor uuid,p_owner uuid,p_attachment uuid) +returns jsonb language plpgsql set search_path='' as $$ +declare saved public.context_evidence_attachments; targets jsonb; +begin + perform public.authorize_context_case_actor(p_actor,p_owner); + select * into saved from public.context_evidence_attachments where id=p_attachment and owner_id=p_owner; + if saved.id is null then raise exception 'Evidence attachment unavailable' using errcode='42501'; end if; + perform public.authorize_context_evidence_source(p_owner,saved.source_version_id); + select jsonb_agg(jsonb_strip_nulls(jsonb_build_object('artist_id',artist_id,'professional_id',professional_id, + 'request_id',request_id,'subject_id',subject_id)) order by position) into targets + from public.context_evidence_attachment_targets where attachment_id=saved.id and owner_id=p_owner; + if targets is null then raise exception 'Evidence attachment unavailable' using errcode='42501'; end if; + perform public.authorize_context_evidence_targets(p_owner,targets); + return jsonb_build_object('id',saved.id,'owner_id',saved.owner_id,'actor_id',saved.actor_id,'source_version_id',saved.source_version_id, + 'created_at',saved.created_at,'targets',targets,'assertion','relevance_only','rights_verified',false, + 'policy_version','private-evidence-association-v1'); +end $$; + +create function public.attach_context_evidence(p_actor uuid,p_owner uuid,p_version uuid,p_key text,p_targets jsonb) +returns jsonb language plpgsql set search_path='' as $$ +declare targets jsonb; fingerprint text; saved public.context_evidence_attachments; +begin + perform public.authorize_context_case_actor(p_actor,p_owner); + if p_key is null or p_key !~ '^[A-Za-z0-9._:-]{1,128}$' then raise exception 'Invalid attachment key' using errcode='22023'; end if; + targets:=public.canonical_context_evidence_targets(p_targets); + perform public.authorize_context_evidence_source(p_owner,p_version); + perform public.authorize_context_evidence_targets(p_owner,targets); + fingerprint:=encode(sha256(convert_to(jsonb_build_object('version',p_version,'targets',targets)::text,'UTF8')),'hex'); + insert into public.context_evidence_attachments(owner_id,actor_id,source_version_id,idempotency_key,fingerprint) + values(p_owner,p_actor,p_version,p_key,fingerprint) on conflict(owner_id,idempotency_key) do nothing returning * into saved; + if saved.id is not null then + insert into public.context_evidence_attachment_targets(attachment_id,owner_id,position,artist_id,professional_id,request_id,subject_id) + select saved.id,p_owner,ordinal-1,(value->>'artist_id')::uuid,(value->>'professional_id')::uuid,(value->>'request_id')::uuid,(value->>'subject_id')::uuid + from jsonb_array_elements(targets) with ordinality t(value,ordinal); + else + select * into strict saved from public.context_evidence_attachments where owner_id=p_owner and idempotency_key=p_key; + if saved.fingerprint<>fingerprint then raise exception 'Attachment key already used for different input' using errcode='22023'; end if; + end if; + return public.read_context_evidence_attachment(p_actor,p_owner,saved.id); +end $$; + +-- Version-scoped paging. Inaccessible target receipts are withheld, while the +-- cursor still advances over stored history so a page cannot loop indefinitely. +create function public.list_context_evidence_attachments(p_actor uuid,p_owner uuid,p_version uuid,p_after uuid default null) +returns jsonb language plpgsql set search_path='' as $$ +declare row public.context_evidence_attachments; items jsonb:='[]'; visited integer:=0; cursor_id uuid; more boolean:=false; +begin + perform public.authorize_context_case_actor(p_actor,p_owner); + perform public.authorize_context_evidence_source(p_owner,p_version); + if p_after is not null and not exists(select 1 from public.context_evidence_attachments where id=p_after and owner_id=p_owner and source_version_id=p_version) + then raise exception 'Invalid evidence cursor' using errcode='42501'; end if; + for row in select * from public.context_evidence_attachments where owner_id=p_owner and source_version_id=p_version + and (p_after is null or id>p_after) order by id limit 51 loop + visited:=visited+1; + if visited>50 then more:=true; exit; end if; + cursor_id:=row.id; + begin + items:=items||jsonb_build_array(public.read_context_evidence_attachment(p_actor,p_owner,row.id)); + exception when insufficient_privilege then null; end; + end loop; + return jsonb_build_object('items',items,'next_id',case when more then cursor_id end,'has_more',more); +end $$; + +revoke all on function public.canonical_context_evidence_targets(jsonb),public.authorize_context_evidence_source(uuid,uuid), + public.authorize_context_evidence_targets(uuid,jsonb),public.read_context_evidence_attachment(uuid,uuid,uuid), + public.attach_context_evidence(uuid,uuid,uuid,text,jsonb),public.list_context_evidence_attachments(uuid,uuid,uuid,uuid) from public,anon,authenticated; +grant execute on function public.canonical_context_evidence_targets(jsonb),public.authorize_context_evidence_source(uuid,uuid), + public.authorize_context_evidence_targets(uuid,jsonb),public.read_context_evidence_attachment(uuid,uuid,uuid), + public.attach_context_evidence(uuid,uuid,uuid,text,jsonb),public.list_context_evidence_attachments(uuid,uuid,uuid,uuid) to service_role; +commit; diff --git a/supabase/migrations/20261009180001_context_evidence_receipt_seal.sql b/supabase/migrations/20261009180001_context_evidence_receipt_seal.sql new file mode 100644 index 0000000..446b4fc --- /dev/null +++ b/supabase/migrations/20261009180001_context_evidence_receipt_seal.sql @@ -0,0 +1,45 @@ +-- Forward-only correction: preserve the initial migration already applied in preview. +begin; +set local lock_timeout='5s'; +set local statement_timeout='30s'; +grant update(updated_at) on public.artist_organization_ids to service_role; +alter table public.context_evidence_attachments add column target_count integer; +-- Seal the existing canonical receipt payload, never reinterpret or repair it. +update public.context_evidence_attachments a set target_count=( + select count(*) from public.context_evidence_attachment_targets t where t.attachment_id=a.id and t.owner_id=a.owner_id); +do $$ +begin + if exists(select 1 from public.context_evidence_attachments a where a.target_count not between 1 and 100 or + a.fingerprint<>encode(sha256(convert_to(jsonb_build_object('version',a.source_version_id,'targets', + (select jsonb_agg(jsonb_strip_nulls(jsonb_build_object('artist_id',artist_id,'professional_id',professional_id, + 'request_id',request_id,'subject_id',subject_id)) order by position) + from public.context_evidence_attachment_targets where attachment_id=a.id and owner_id=a.owner_id))::text,'UTF8')),'hex')) + then raise exception 'Inconsistent existing evidence receipt; review required' using errcode='23514'; end if; +end $$; +alter table public.context_evidence_attachments alter column target_count set not null; +alter table public.context_evidence_attachments add constraint context_evidence_target_count check(target_count between 1 and 100); +-- Every slot must be filled in the creation transaction. A receipt cannot be +-- committed with holes, nor appended after its fixed slots have been filled. +create function public.guard_context_evidence_target_slot() +returns trigger language plpgsql set search_path='' as $$ +declare slots integer; +begin + select target_count into slots from public.context_evidence_attachments where id=new.attachment_id and owner_id=new.owner_id; + if slots is null or new.position>=slots then raise exception 'Evidence receipt target count' using errcode='23514'; end if; + return new; +end $$; +create trigger context_evidence_target_slot before insert on public.context_evidence_attachment_targets + for each row execute function public.guard_context_evidence_target_slot(); +create function public.check_context_evidence_receipt_complete() +returns trigger language plpgsql set search_path='' as $$ +begin + if (select count(*) from public.context_evidence_attachment_targets where attachment_id=new.id and owner_id=new.owner_id)<>new.target_count + then raise exception 'Evidence receipt target count' using errcode='23514'; end if; + return new; +end $$; +create constraint trigger context_evidence_receipt_complete after insert on public.context_evidence_attachments + deferrable initially deferred for each row execute function public.check_context_evidence_receipt_complete(); +revoke all on function public.guard_context_evidence_target_slot(),public.check_context_evidence_receipt_complete() from public,anon,authenticated; +grant execute on function public.guard_context_evidence_target_slot(),public.check_context_evidence_receipt_complete() to service_role; + +commit; diff --git a/supabase/migrations/20261009180002_context_evidence_authorization.sql b/supabase/migrations/20261009180002_context_evidence_authorization.sql new file mode 100644 index 0000000..c213203 --- /dev/null +++ b/supabase/migrations/20261009180002_context_evidence_authorization.sql @@ -0,0 +1,82 @@ +-- Validate typed targets and independent retained evidence access. +begin; +-- Exact shapes and UUIDs only. Caller order does not change replay identity. +create or replace function public.canonical_context_evidence_targets(p_targets jsonb) +returns jsonb language plpgsql set search_path='' as $$ +declare t jsonb; n integer; canonical jsonb; field text; +begin + if jsonb_typeof(p_targets) is distinct from 'array' then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + if jsonb_array_length(p_targets) not between 1 and 100 then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + for t in select value from jsonb_array_elements(p_targets) loop + if jsonb_typeof(t) is distinct from 'object' then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + select count(*) into n from jsonb_object_keys(t); + if not ((n=1 and (t ? 'artist_id' or t ? 'professional_id')) or (n=2 and t ? 'request_id' and t ? 'subject_id')) + then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + for field in select jsonb_object_keys(t) loop + if jsonb_typeof(t->field) is distinct from 'string' or (t->>field) !~* '^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$' + then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + t:=jsonb_set(t,array[field],to_jsonb((t->>field)::uuid::text)); + end loop; + end loop; + select jsonb_agg(normalized order by normalized::text),count(distinct normalized) into canonical,n + from (select jsonb_object_agg(key,to_jsonb(value::uuid::text)) normalized + from jsonb_array_elements(p_targets) with ordinality a(target,ordinal) + cross join lateral jsonb_each_text(target) e(key,value) group by ordinal) q; + if n<>jsonb_array_length(p_targets) then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + return canonical; +end $$; + +create or replace function public.authorize_context_evidence_source(p_owner uuid,p_version uuid) +returns void language plpgsql set search_path='' as $$ +begin + perform 1 from public.context_sources s join public.context_source_versions v on v.source_id=s.id and v.owner_id=s.owner_id + where v.id=p_version and v.owner_id=p_owner and v.removed_at is null and s.withdrawn_at is null for share of s,v; + if not found then raise exception 'Evidence source unavailable' using errcode='42501'; end if; +end $$; + +-- A global subject UUID never grants access. An owned request plus retained +-- accepted lineage is an independent historical path, even after roster removal. +-- Submitted company/writer candidates retain their original uncertainty. +create or replace function public.authorize_context_evidence_targets(p_owner uuid,p_targets jsonb) +returns void language plpgsql set search_path='' as $$ +declare t jsonb; accessible boolean; +begin + for t in select value from jsonb_array_elements(p_targets) loop + accessible:=false; + if t ? 'artist_id' then + perform 1 from public.account_artist_ids where account_id=p_owner and artist_id=(t->>'artist_id')::uuid for share; + accessible:=found; + perform 1 from public.artist_organization_ids where organization_id=p_owner and artist_id=(t->>'artist_id')::uuid for share; + accessible:=accessible or found; + elsif t ? 'professional_id' then + perform 1 from public.organization_professionals where organization_id=p_owner and id=(t->>'professional_id')::uuid for share; + accessible:=found; + else + -- Source locks precede request/result locks, consistent with withdrawal. + perform 1 from public.context_sources s join public.context_source_versions v on v.source_id=s.id and v.owner_id=s.owner_id + join public.context_result_sources rs on rs.source_version_id=v.id and rs.owner_id=v.owner_id + join public.context_results r on r.id=rs.result_id and r.owner_id=rs.owner_id + join public.context_attempts a on a.id=r.attempt_id and a.owner_id=r.owner_id + where a.request_id=(t->>'request_id')::uuid and r.subject_id=(t->>'subject_id')::uuid and r.owner_id=p_owner + order by s.id,v.id for share of s,v; + perform 1 from public.context_requests where owner_id=p_owner and id=(t->>'request_id')::uuid for share; + perform 1 from public.context_results r join public.context_attempts a on a.id=r.attempt_id and a.owner_id=r.owner_id + where r.owner_id=p_owner and a.request_id=(t->>'request_id')::uuid and r.subject_id=(t->>'subject_id')::uuid for share of r; + select exists(select 1 from public.context_requests req join public.context_attempts a on a.request_id=req.id and a.owner_id=req.owner_id + join public.context_results r on r.attempt_id=a.id and r.owner_id=a.owner_id + where req.owner_id=p_owner and req.id=(t->>'request_id')::uuid and req.status in ('partial','completed') + and jsonb_typeof(req.output->'subjectIds')='array' and req.output->'subjectIds' ? (t->>'subject_id') + and r.subject_id=(t->>'subject_id')::uuid and r.status='accepted' and r.evidence_kind<>'creative_proposal' + and exists(select 1 from public.context_result_sources rs where rs.result_id=r.id and rs.owner_id=p_owner) + and not exists(select 1 from public.context_result_sources rs + join public.context_source_versions v on v.id=rs.source_version_id and v.owner_id=rs.owner_id + join public.context_sources s on s.id=v.source_id and s.owner_id=v.owner_id + where rs.result_id=r.id and rs.owner_id=p_owner and (v.removed_at is not null or s.withdrawn_at is not null))) into accessible; + end if; + if not accessible then raise exception 'Evidence target unavailable' using errcode='42501'; end if; + end loop; +end $$; + +revoke all on function public.canonical_context_evidence_targets(jsonb),public.authorize_context_evidence_source(uuid,uuid),public.authorize_context_evidence_targets(uuid,jsonb) from public,anon,authenticated; +grant execute on function public.canonical_context_evidence_targets(jsonb),public.authorize_context_evidence_source(uuid,uuid),public.authorize_context_evidence_targets(uuid,jsonb) to service_role; +commit; diff --git a/supabase/migrations/20261009180003_context_evidence_receipts.sql b/supabase/migrations/20261009180003_context_evidence_receipts.sql new file mode 100644 index 0000000..96ef3a7 --- /dev/null +++ b/supabase/migrations/20261009180003_context_evidence_receipts.sql @@ -0,0 +1,48 @@ +-- Save/read immutable, version-specific relevance receipts. +begin; +create or replace function public.read_context_evidence_attachment(p_actor uuid,p_owner uuid,p_attachment uuid) +returns jsonb language plpgsql set search_path='' as $$ +declare saved public.context_evidence_attachments; targets jsonb; +begin + perform public.authorize_context_case_actor(p_actor,p_owner); + select * into saved from public.context_evidence_attachments where id=p_attachment and owner_id=p_owner; + if saved.id is null then raise exception 'Evidence attachment unavailable' using errcode='42501'; end if; + perform public.authorize_context_evidence_source(p_owner,saved.source_version_id); + select jsonb_agg(jsonb_strip_nulls(jsonb_build_object('artist_id',artist_id,'professional_id',professional_id, + 'request_id',request_id,'subject_id',subject_id)) order by position) into targets + from public.context_evidence_attachment_targets where attachment_id=saved.id and owner_id=p_owner; + if targets is null or jsonb_array_length(targets)<>saved.target_count or + encode(sha256(convert_to(jsonb_build_object('version',saved.source_version_id,'targets',targets)::text,'UTF8')),'hex')<>saved.fingerprint + then raise exception 'Evidence attachment unavailable' using errcode='42501'; end if; + perform public.authorize_context_evidence_targets(p_owner,targets); + return jsonb_build_object('id',saved.id,'owner_id',saved.owner_id,'actor_id',saved.actor_id,'source_version_id',saved.source_version_id, + 'created_at',saved.created_at,'targets',targets,'assertion','relevance_only','rights_verified',false, + 'policy_version','private-evidence-association-v1'); +end $$; + +create or replace function public.attach_context_evidence(p_actor uuid,p_owner uuid,p_version uuid,p_key text,p_targets jsonb) +returns jsonb language plpgsql set search_path='' as $$ +declare targets jsonb; fingerprint text; saved public.context_evidence_attachments; +begin + perform public.authorize_context_case_actor(p_actor,p_owner); + if p_key is null or p_key !~ '^[A-Za-z0-9._:-]{1,128}$' then raise exception 'Invalid attachment key' using errcode='22023'; end if; + targets:=public.canonical_context_evidence_targets(p_targets); + perform public.authorize_context_evidence_source(p_owner,p_version); + perform public.authorize_context_evidence_targets(p_owner,targets); + fingerprint:=encode(sha256(convert_to(jsonb_build_object('version',p_version,'targets',targets)::text,'UTF8')),'hex'); + insert into public.context_evidence_attachments(owner_id,actor_id,source_version_id,idempotency_key,fingerprint,target_count) + values(p_owner,p_actor,p_version,p_key,fingerprint,jsonb_array_length(targets)) on conflict(owner_id,idempotency_key) do nothing returning * into saved; + if saved.id is not null then + insert into public.context_evidence_attachment_targets(attachment_id,owner_id,position,artist_id,professional_id,request_id,subject_id) + select saved.id,p_owner,ordinal-1,(value->>'artist_id')::uuid,(value->>'professional_id')::uuid,(value->>'request_id')::uuid,(value->>'subject_id')::uuid + from jsonb_array_elements(targets) with ordinality t(value,ordinal); + else + select * into strict saved from public.context_evidence_attachments where owner_id=p_owner and idempotency_key=p_key; + if saved.fingerprint<>fingerprint then raise exception 'Attachment key already used for different input' using errcode='22023'; end if; + end if; + return public.read_context_evidence_attachment(p_actor,p_owner,saved.id); +end $$; + +revoke all on function public.read_context_evidence_attachment(uuid,uuid,uuid),public.attach_context_evidence(uuid,uuid,uuid,text,jsonb) from public,anon,authenticated; +grant execute on function public.read_context_evidence_attachment(uuid,uuid,uuid),public.attach_context_evidence(uuid,uuid,uuid,text,jsonb) to service_role; +commit; diff --git a/supabase/migrations/20261009180004_context_evidence_list.sql b/supabase/migrations/20261009180004_context_evidence_list.sql new file mode 100644 index 0000000..94b2bc8 --- /dev/null +++ b/supabase/migrations/20261009180004_context_evidence_list.sql @@ -0,0 +1,27 @@ +-- Scope-checked bounded receipt history, withholding inaccessible targets. +begin; +-- Version-scoped paging. Inaccessible target receipts are withheld, while the +-- cursor still advances over stored history so a page cannot loop indefinitely. +create or replace function public.list_context_evidence_attachments(p_actor uuid,p_owner uuid,p_version uuid,p_after uuid default null) +returns jsonb language plpgsql set search_path='' as $$ +declare row public.context_evidence_attachments; items jsonb:='[]'; visited integer:=0; cursor_id uuid; more boolean:=false; +begin + perform public.authorize_context_case_actor(p_actor,p_owner); + perform public.authorize_context_evidence_source(p_owner,p_version); + if p_after is not null and not exists(select 1 from public.context_evidence_attachments where id=p_after and owner_id=p_owner and source_version_id=p_version) + then raise exception 'Invalid evidence cursor' using errcode='42501'; end if; + for row in select * from public.context_evidence_attachments where owner_id=p_owner and source_version_id=p_version + and (p_after is null or id>p_after) order by id limit 51 loop + visited:=visited+1; + if visited>50 then more:=true; exit; end if; + cursor_id:=row.id; + begin + items:=items||jsonb_build_array(public.read_context_evidence_attachment(p_actor,p_owner,row.id)); + exception when insufficient_privilege then null; end; + end loop; + return jsonb_build_object('items',items,'next_id',case when more then cursor_id end,'has_more',more); +end $$; + +revoke all on function public.list_context_evidence_attachments(uuid,uuid,uuid,uuid) from public,anon,authenticated; +grant execute on function public.list_context_evidence_attachments(uuid,uuid,uuid,uuid) to service_role; +commit; diff --git a/supabase/migrations/20261020035229_context_evidence_atomic_release.sql b/supabase/migrations/20261020035229_context_evidence_atomic_release.sql new file mode 100644 index 0000000..9e5fac7 --- /dev/null +++ b/supabase/migrations/20261020035229_context_evidence_atomic_release.sql @@ -0,0 +1,967 @@ +-- REVIEW-ONLY MCP METHOD: five schema changes plus one tool execution record. +-- Target godremdqwajrwazhbrue. apply_migration owns the transaction and generated version. +-- Preserve this exact query as the generated-version source file after authorized execution. +SET LOCAL lock_timeout='5s'; +SET LOCAL statement_timeout='30s'; +SET LOCAL idle_in_transaction_session_timeout='60s'; +DO $recoup_mcp_release$ +DECLARE + installed integer; + checked record; + fn oid; +BEGIN + IF current_database()<>'postgres' OR current_user<>'postgres' THEN + RAISE EXCEPTION 'Release database/role mismatch'; + END IF; + SELECT count(*) INTO installed FROM supabase_migrations.schema_migrations WHERE version IN ('20261009180000','20261009180001','20261009180002','20261009180003','20261009180004'); + IF installed=0 THEN + -- The approved clean installer, including its guards and five records, is unchanged. + EXECUTE $approved_install$DO $recoup_release$ +DECLARE + originals text[] := ARRAY[ +$source0$-- Relevance links for retained evidence, not identity, rights or mandate approval. +begin; +set local lock_timeout='5s'; +set local statement_timeout='30s'; + +alter table public.organization_professionals add constraint organization_professionals_id_owner unique(id,organization_id); +create table public.context_evidence_attachments ( + id uuid primary key default gen_random_uuid(), + owner_id uuid not null references public.accounts(id), + actor_id uuid not null references public.accounts(id), + source_version_id uuid not null, + idempotency_key text not null check(idempotency_key ~ '^[A-Za-z0-9._:-]{1,128}$'), + fingerprint text not null check(fingerprint ~ '^[a-f0-9]{64}$'), + created_at timestamptz not null default now(), + foreign key(source_version_id,owner_id) references public.context_source_versions(id,owner_id), + unique(owner_id,idempotency_key), unique(id,owner_id) +); +create index context_evidence_attachments_version on public.context_evidence_attachments(owner_id,source_version_id,id); +create table public.context_evidence_attachment_targets ( + attachment_id uuid not null, + owner_id uuid not null, + position integer not null check(position between 0 and 99), + artist_id uuid references public.accounts(id), + professional_id uuid, + request_id uuid, + subject_id uuid references public.context_subjects(id), + primary key(attachment_id,position), + foreign key(attachment_id,owner_id) references public.context_evidence_attachments(id,owner_id), + foreign key(professional_id,owner_id) references public.organization_professionals(id,organization_id), + foreign key(request_id,owner_id) references public.context_requests(id,owner_id), + check((artist_id is not null and professional_id is null and request_id is null and subject_id is null) + or (professional_id is not null and artist_id is null and request_id is null and subject_id is null) + or (request_id is not null and subject_id is not null and artist_id is null and professional_id is null)) +); +alter table public.context_evidence_attachments enable row level security; +alter table public.context_evidence_attachment_targets enable row level security; +revoke all on public.context_evidence_attachments,public.context_evidence_attachment_targets from public,anon,authenticated,service_role; +grant select,insert on public.context_evidence_attachments,public.context_evidence_attachment_targets to service_role; + +-- Exact shapes and UUIDs only. Caller order does not change replay identity. +create function public.canonical_context_evidence_targets(p_targets jsonb) +returns jsonb language plpgsql set search_path='' as $$ +declare t jsonb; n integer; canonical jsonb; field text; +begin + if jsonb_typeof(p_targets) is distinct from 'array' then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + if jsonb_array_length(p_targets) not between 1 and 100 then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + for t in select value from jsonb_array_elements(p_targets) loop + if jsonb_typeof(t) is distinct from 'object' then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + select count(*) into n from jsonb_object_keys(t); + if not ((n=1 and (t ? 'artist_id' or t ? 'professional_id')) or (n=2 and t ? 'request_id' and t ? 'subject_id')) + then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + for field in select jsonb_object_keys(t) loop + if jsonb_typeof(t->field) is distinct from 'string' or (t->>field) !~* '^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$' + then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + t:=jsonb_set(t,array[field],to_jsonb((t->>field)::uuid::text)); + end loop; + end loop; + select jsonb_agg(normalized order by normalized::text),count(distinct normalized) into canonical,n + from (select jsonb_object_agg(key,to_jsonb(value::uuid::text)) normalized + from jsonb_array_elements(p_targets) with ordinality a(target,ordinal) + cross join lateral jsonb_each_text(target) e(key,value) group by ordinal) q; + if n<>jsonb_array_length(p_targets) then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + return canonical; +end $$; + +create function public.authorize_context_evidence_source(p_owner uuid,p_version uuid) +returns void language plpgsql set search_path='' as $$ +begin + perform 1 from public.context_sources s join public.context_source_versions v on v.source_id=s.id and v.owner_id=s.owner_id + where v.id=p_version and v.owner_id=p_owner and v.removed_at is null and s.withdrawn_at is null for share of s,v; + if not found then raise exception 'Evidence source unavailable' using errcode='42501'; end if; +end $$; + +-- A global subject UUID never grants access. An owned request plus retained +-- accepted lineage is an independent historical path, even after roster removal. +-- Submitted company/writer candidates retain their original uncertainty. +create function public.authorize_context_evidence_targets(p_owner uuid,p_targets jsonb) +returns void language plpgsql set search_path='' as $$ +declare t jsonb; accessible boolean; +begin + for t in select value from jsonb_array_elements(p_targets) loop + accessible:=false; + if t ? 'artist_id' then + perform 1 from public.account_artist_ids where account_id=p_owner and artist_id=(t->>'artist_id')::uuid for share; + accessible:=found; + perform 1 from public.artist_organization_ids where organization_id=p_owner and artist_id=(t->>'artist_id')::uuid for share; + accessible:=accessible or found; + elsif t ? 'professional_id' then + perform 1 from public.organization_professionals where organization_id=p_owner and id=(t->>'professional_id')::uuid for share; + accessible:=found; + else + -- Source locks precede request/result locks, consistent with withdrawal. + perform 1 from public.context_sources s join public.context_source_versions v on v.source_id=s.id and v.owner_id=s.owner_id + join public.context_result_sources rs on rs.source_version_id=v.id and rs.owner_id=v.owner_id + join public.context_results r on r.id=rs.result_id and r.owner_id=rs.owner_id + join public.context_attempts a on a.id=r.attempt_id and a.owner_id=r.owner_id + where a.request_id=(t->>'request_id')::uuid and r.subject_id=(t->>'subject_id')::uuid and r.owner_id=p_owner + order by s.id,v.id for share of s,v; + perform 1 from public.context_requests where owner_id=p_owner and id=(t->>'request_id')::uuid for share; + perform 1 from public.context_results r join public.context_attempts a on a.id=r.attempt_id and a.owner_id=r.owner_id + where r.owner_id=p_owner and a.request_id=(t->>'request_id')::uuid and r.subject_id=(t->>'subject_id')::uuid for share of r; + select exists(select 1 from public.context_requests req join public.context_attempts a on a.request_id=req.id and a.owner_id=req.owner_id + join public.context_results r on r.attempt_id=a.id and r.owner_id=a.owner_id + where req.owner_id=p_owner and req.id=(t->>'request_id')::uuid and req.status in ('partial','completed') + and jsonb_typeof(req.output->'subjectIds')='array' and req.output->'subjectIds' ? (t->>'subject_id') + and r.subject_id=(t->>'subject_id')::uuid and r.status='accepted' and r.evidence_kind<>'creative_proposal' + and exists(select 1 from public.context_result_sources rs where rs.result_id=r.id and rs.owner_id=p_owner) + and not exists(select 1 from public.context_result_sources rs + join public.context_source_versions v on v.id=rs.source_version_id and v.owner_id=rs.owner_id + join public.context_sources s on s.id=v.source_id and s.owner_id=v.owner_id + where rs.result_id=r.id and rs.owner_id=p_owner and (v.removed_at is not null or s.withdrawn_at is not null))) into accessible; + end if; + if not accessible then raise exception 'Evidence target unavailable' using errcode='42501'; end if; + end loop; +end $$; + +create function public.read_context_evidence_attachment(p_actor uuid,p_owner uuid,p_attachment uuid) +returns jsonb language plpgsql set search_path='' as $$ +declare saved public.context_evidence_attachments; targets jsonb; +begin + perform public.authorize_context_case_actor(p_actor,p_owner); + select * into saved from public.context_evidence_attachments where id=p_attachment and owner_id=p_owner; + if saved.id is null then raise exception 'Evidence attachment unavailable' using errcode='42501'; end if; + perform public.authorize_context_evidence_source(p_owner,saved.source_version_id); + select jsonb_agg(jsonb_strip_nulls(jsonb_build_object('artist_id',artist_id,'professional_id',professional_id, + 'request_id',request_id,'subject_id',subject_id)) order by position) into targets + from public.context_evidence_attachment_targets where attachment_id=saved.id and owner_id=p_owner; + if targets is null then raise exception 'Evidence attachment unavailable' using errcode='42501'; end if; + perform public.authorize_context_evidence_targets(p_owner,targets); + return jsonb_build_object('id',saved.id,'owner_id',saved.owner_id,'actor_id',saved.actor_id,'source_version_id',saved.source_version_id, + 'created_at',saved.created_at,'targets',targets,'assertion','relevance_only','rights_verified',false, + 'policy_version','private-evidence-association-v1'); +end $$; + +create function public.attach_context_evidence(p_actor uuid,p_owner uuid,p_version uuid,p_key text,p_targets jsonb) +returns jsonb language plpgsql set search_path='' as $$ +declare targets jsonb; fingerprint text; saved public.context_evidence_attachments; +begin + perform public.authorize_context_case_actor(p_actor,p_owner); + if p_key is null or p_key !~ '^[A-Za-z0-9._:-]{1,128}$' then raise exception 'Invalid attachment key' using errcode='22023'; end if; + targets:=public.canonical_context_evidence_targets(p_targets); + perform public.authorize_context_evidence_source(p_owner,p_version); + perform public.authorize_context_evidence_targets(p_owner,targets); + fingerprint:=encode(sha256(convert_to(jsonb_build_object('version',p_version,'targets',targets)::text,'UTF8')),'hex'); + insert into public.context_evidence_attachments(owner_id,actor_id,source_version_id,idempotency_key,fingerprint) + values(p_owner,p_actor,p_version,p_key,fingerprint) on conflict(owner_id,idempotency_key) do nothing returning * into saved; + if saved.id is not null then + insert into public.context_evidence_attachment_targets(attachment_id,owner_id,position,artist_id,professional_id,request_id,subject_id) + select saved.id,p_owner,ordinal-1,(value->>'artist_id')::uuid,(value->>'professional_id')::uuid,(value->>'request_id')::uuid,(value->>'subject_id')::uuid + from jsonb_array_elements(targets) with ordinality t(value,ordinal); + else + select * into strict saved from public.context_evidence_attachments where owner_id=p_owner and idempotency_key=p_key; + if saved.fingerprint<>fingerprint then raise exception 'Attachment key already used for different input' using errcode='22023'; end if; + end if; + return public.read_context_evidence_attachment(p_actor,p_owner,saved.id); +end $$; + +-- Version-scoped paging. Inaccessible target receipts are withheld, while the +-- cursor still advances over stored history so a page cannot loop indefinitely. +create function public.list_context_evidence_attachments(p_actor uuid,p_owner uuid,p_version uuid,p_after uuid default null) +returns jsonb language plpgsql set search_path='' as $$ +declare row public.context_evidence_attachments; items jsonb:='[]'; visited integer:=0; cursor_id uuid; more boolean:=false; +begin + perform public.authorize_context_case_actor(p_actor,p_owner); + perform public.authorize_context_evidence_source(p_owner,p_version); + if p_after is not null and not exists(select 1 from public.context_evidence_attachments where id=p_after and owner_id=p_owner and source_version_id=p_version) + then raise exception 'Invalid evidence cursor' using errcode='42501'; end if; + for row in select * from public.context_evidence_attachments where owner_id=p_owner and source_version_id=p_version + and (p_after is null or id>p_after) order by id limit 51 loop + visited:=visited+1; + if visited>50 then more:=true; exit; end if; + cursor_id:=row.id; + begin + items:=items||jsonb_build_array(public.read_context_evidence_attachment(p_actor,p_owner,row.id)); + exception when insufficient_privilege then null; end; + end loop; + return jsonb_build_object('items',items,'next_id',case when more then cursor_id end,'has_more',more); +end $$; + +revoke all on function public.canonical_context_evidence_targets(jsonb),public.authorize_context_evidence_source(uuid,uuid), + public.authorize_context_evidence_targets(uuid,jsonb),public.read_context_evidence_attachment(uuid,uuid,uuid), + public.attach_context_evidence(uuid,uuid,uuid,text,jsonb),public.list_context_evidence_attachments(uuid,uuid,uuid,uuid) from public,anon,authenticated; +grant execute on function public.canonical_context_evidence_targets(jsonb),public.authorize_context_evidence_source(uuid,uuid), + public.authorize_context_evidence_targets(uuid,jsonb),public.read_context_evidence_attachment(uuid,uuid,uuid), + public.attach_context_evidence(uuid,uuid,uuid,text,jsonb),public.list_context_evidence_attachments(uuid,uuid,uuid,uuid) to service_role; +commit; +$source0$, +$source1$-- Forward-only correction: preserve the initial migration already applied in preview. +begin; +set local lock_timeout='5s'; +set local statement_timeout='30s'; +grant update(updated_at) on public.artist_organization_ids to service_role; +alter table public.context_evidence_attachments add column target_count integer; +-- Seal the existing canonical receipt payload, never reinterpret or repair it. +update public.context_evidence_attachments a set target_count=( + select count(*) from public.context_evidence_attachment_targets t where t.attachment_id=a.id and t.owner_id=a.owner_id); +do $$ +begin + if exists(select 1 from public.context_evidence_attachments a where a.target_count not between 1 and 100 or + a.fingerprint<>encode(sha256(convert_to(jsonb_build_object('version',a.source_version_id,'targets', + (select jsonb_agg(jsonb_strip_nulls(jsonb_build_object('artist_id',artist_id,'professional_id',professional_id, + 'request_id',request_id,'subject_id',subject_id)) order by position) + from public.context_evidence_attachment_targets where attachment_id=a.id and owner_id=a.owner_id))::text,'UTF8')),'hex')) + then raise exception 'Inconsistent existing evidence receipt; review required' using errcode='23514'; end if; +end $$; +alter table public.context_evidence_attachments alter column target_count set not null; +alter table public.context_evidence_attachments add constraint context_evidence_target_count check(target_count between 1 and 100); +-- Every slot must be filled in the creation transaction. A receipt cannot be +-- committed with holes, nor appended after its fixed slots have been filled. +create function public.guard_context_evidence_target_slot() +returns trigger language plpgsql set search_path='' as $$ +declare slots integer; +begin + select target_count into slots from public.context_evidence_attachments where id=new.attachment_id and owner_id=new.owner_id; + if slots is null or new.position>=slots then raise exception 'Evidence receipt target count' using errcode='23514'; end if; + return new; +end $$; +create trigger context_evidence_target_slot before insert on public.context_evidence_attachment_targets + for each row execute function public.guard_context_evidence_target_slot(); +create function public.check_context_evidence_receipt_complete() +returns trigger language plpgsql set search_path='' as $$ +begin + if (select count(*) from public.context_evidence_attachment_targets where attachment_id=new.id and owner_id=new.owner_id)<>new.target_count + then raise exception 'Evidence receipt target count' using errcode='23514'; end if; + return new; +end $$; +create constraint trigger context_evidence_receipt_complete after insert on public.context_evidence_attachments + deferrable initially deferred for each row execute function public.check_context_evidence_receipt_complete(); +revoke all on function public.guard_context_evidence_target_slot(),public.check_context_evidence_receipt_complete() from public,anon,authenticated; +grant execute on function public.guard_context_evidence_target_slot(),public.check_context_evidence_receipt_complete() to service_role; + +commit; +$source1$, +$source2$-- Validate typed targets and independent retained evidence access. +begin; +-- Exact shapes and UUIDs only. Caller order does not change replay identity. +create or replace function public.canonical_context_evidence_targets(p_targets jsonb) +returns jsonb language plpgsql set search_path='' as $$ +declare t jsonb; n integer; canonical jsonb; field text; +begin + if jsonb_typeof(p_targets) is distinct from 'array' then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + if jsonb_array_length(p_targets) not between 1 and 100 then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + for t in select value from jsonb_array_elements(p_targets) loop + if jsonb_typeof(t) is distinct from 'object' then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + select count(*) into n from jsonb_object_keys(t); + if not ((n=1 and (t ? 'artist_id' or t ? 'professional_id')) or (n=2 and t ? 'request_id' and t ? 'subject_id')) + then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + for field in select jsonb_object_keys(t) loop + if jsonb_typeof(t->field) is distinct from 'string' or (t->>field) !~* '^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$' + then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + t:=jsonb_set(t,array[field],to_jsonb((t->>field)::uuid::text)); + end loop; + end loop; + select jsonb_agg(normalized order by normalized::text),count(distinct normalized) into canonical,n + from (select jsonb_object_agg(key,to_jsonb(value::uuid::text)) normalized + from jsonb_array_elements(p_targets) with ordinality a(target,ordinal) + cross join lateral jsonb_each_text(target) e(key,value) group by ordinal) q; + if n<>jsonb_array_length(p_targets) then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + return canonical; +end $$; + +create or replace function public.authorize_context_evidence_source(p_owner uuid,p_version uuid) +returns void language plpgsql set search_path='' as $$ +begin + perform 1 from public.context_sources s join public.context_source_versions v on v.source_id=s.id and v.owner_id=s.owner_id + where v.id=p_version and v.owner_id=p_owner and v.removed_at is null and s.withdrawn_at is null for share of s,v; + if not found then raise exception 'Evidence source unavailable' using errcode='42501'; end if; +end $$; + +-- A global subject UUID never grants access. An owned request plus retained +-- accepted lineage is an independent historical path, even after roster removal. +-- Submitted company/writer candidates retain their original uncertainty. +create or replace function public.authorize_context_evidence_targets(p_owner uuid,p_targets jsonb) +returns void language plpgsql set search_path='' as $$ +declare t jsonb; accessible boolean; +begin + for t in select value from jsonb_array_elements(p_targets) loop + accessible:=false; + if t ? 'artist_id' then + perform 1 from public.account_artist_ids where account_id=p_owner and artist_id=(t->>'artist_id')::uuid for share; + accessible:=found; + perform 1 from public.artist_organization_ids where organization_id=p_owner and artist_id=(t->>'artist_id')::uuid for share; + accessible:=accessible or found; + elsif t ? 'professional_id' then + perform 1 from public.organization_professionals where organization_id=p_owner and id=(t->>'professional_id')::uuid for share; + accessible:=found; + else + -- Source locks precede request/result locks, consistent with withdrawal. + perform 1 from public.context_sources s join public.context_source_versions v on v.source_id=s.id and v.owner_id=s.owner_id + join public.context_result_sources rs on rs.source_version_id=v.id and rs.owner_id=v.owner_id + join public.context_results r on r.id=rs.result_id and r.owner_id=rs.owner_id + join public.context_attempts a on a.id=r.attempt_id and a.owner_id=r.owner_id + where a.request_id=(t->>'request_id')::uuid and r.subject_id=(t->>'subject_id')::uuid and r.owner_id=p_owner + order by s.id,v.id for share of s,v; + perform 1 from public.context_requests where owner_id=p_owner and id=(t->>'request_id')::uuid for share; + perform 1 from public.context_results r join public.context_attempts a on a.id=r.attempt_id and a.owner_id=r.owner_id + where r.owner_id=p_owner and a.request_id=(t->>'request_id')::uuid and r.subject_id=(t->>'subject_id')::uuid for share of r; + select exists(select 1 from public.context_requests req join public.context_attempts a on a.request_id=req.id and a.owner_id=req.owner_id + join public.context_results r on r.attempt_id=a.id and r.owner_id=a.owner_id + where req.owner_id=p_owner and req.id=(t->>'request_id')::uuid and req.status in ('partial','completed') + and jsonb_typeof(req.output->'subjectIds')='array' and req.output->'subjectIds' ? (t->>'subject_id') + and r.subject_id=(t->>'subject_id')::uuid and r.status='accepted' and r.evidence_kind<>'creative_proposal' + and exists(select 1 from public.context_result_sources rs where rs.result_id=r.id and rs.owner_id=p_owner) + and not exists(select 1 from public.context_result_sources rs + join public.context_source_versions v on v.id=rs.source_version_id and v.owner_id=rs.owner_id + join public.context_sources s on s.id=v.source_id and s.owner_id=v.owner_id + where rs.result_id=r.id and rs.owner_id=p_owner and (v.removed_at is not null or s.withdrawn_at is not null))) into accessible; + end if; + if not accessible then raise exception 'Evidence target unavailable' using errcode='42501'; end if; + end loop; +end $$; + +revoke all on function public.canonical_context_evidence_targets(jsonb),public.authorize_context_evidence_source(uuid,uuid),public.authorize_context_evidence_targets(uuid,jsonb) from public,anon,authenticated; +grant execute on function public.canonical_context_evidence_targets(jsonb),public.authorize_context_evidence_source(uuid,uuid),public.authorize_context_evidence_targets(uuid,jsonb) to service_role; +commit; +$source2$, +$source3$-- Save/read immutable, version-specific relevance receipts. +begin; +create or replace function public.read_context_evidence_attachment(p_actor uuid,p_owner uuid,p_attachment uuid) +returns jsonb language plpgsql set search_path='' as $$ +declare saved public.context_evidence_attachments; targets jsonb; +begin + perform public.authorize_context_case_actor(p_actor,p_owner); + select * into saved from public.context_evidence_attachments where id=p_attachment and owner_id=p_owner; + if saved.id is null then raise exception 'Evidence attachment unavailable' using errcode='42501'; end if; + perform public.authorize_context_evidence_source(p_owner,saved.source_version_id); + select jsonb_agg(jsonb_strip_nulls(jsonb_build_object('artist_id',artist_id,'professional_id',professional_id, + 'request_id',request_id,'subject_id',subject_id)) order by position) into targets + from public.context_evidence_attachment_targets where attachment_id=saved.id and owner_id=p_owner; + if targets is null or jsonb_array_length(targets)<>saved.target_count or + encode(sha256(convert_to(jsonb_build_object('version',saved.source_version_id,'targets',targets)::text,'UTF8')),'hex')<>saved.fingerprint + then raise exception 'Evidence attachment unavailable' using errcode='42501'; end if; + perform public.authorize_context_evidence_targets(p_owner,targets); + return jsonb_build_object('id',saved.id,'owner_id',saved.owner_id,'actor_id',saved.actor_id,'source_version_id',saved.source_version_id, + 'created_at',saved.created_at,'targets',targets,'assertion','relevance_only','rights_verified',false, + 'policy_version','private-evidence-association-v1'); +end $$; + +create or replace function public.attach_context_evidence(p_actor uuid,p_owner uuid,p_version uuid,p_key text,p_targets jsonb) +returns jsonb language plpgsql set search_path='' as $$ +declare targets jsonb; fingerprint text; saved public.context_evidence_attachments; +begin + perform public.authorize_context_case_actor(p_actor,p_owner); + if p_key is null or p_key !~ '^[A-Za-z0-9._:-]{1,128}$' then raise exception 'Invalid attachment key' using errcode='22023'; end if; + targets:=public.canonical_context_evidence_targets(p_targets); + perform public.authorize_context_evidence_source(p_owner,p_version); + perform public.authorize_context_evidence_targets(p_owner,targets); + fingerprint:=encode(sha256(convert_to(jsonb_build_object('version',p_version,'targets',targets)::text,'UTF8')),'hex'); + insert into public.context_evidence_attachments(owner_id,actor_id,source_version_id,idempotency_key,fingerprint,target_count) + values(p_owner,p_actor,p_version,p_key,fingerprint,jsonb_array_length(targets)) on conflict(owner_id,idempotency_key) do nothing returning * into saved; + if saved.id is not null then + insert into public.context_evidence_attachment_targets(attachment_id,owner_id,position,artist_id,professional_id,request_id,subject_id) + select saved.id,p_owner,ordinal-1,(value->>'artist_id')::uuid,(value->>'professional_id')::uuid,(value->>'request_id')::uuid,(value->>'subject_id')::uuid + from jsonb_array_elements(targets) with ordinality t(value,ordinal); + else + select * into strict saved from public.context_evidence_attachments where owner_id=p_owner and idempotency_key=p_key; + if saved.fingerprint<>fingerprint then raise exception 'Attachment key already used for different input' using errcode='22023'; end if; + end if; + return public.read_context_evidence_attachment(p_actor,p_owner,saved.id); +end $$; + +revoke all on function public.read_context_evidence_attachment(uuid,uuid,uuid),public.attach_context_evidence(uuid,uuid,uuid,text,jsonb) from public,anon,authenticated; +grant execute on function public.read_context_evidence_attachment(uuid,uuid,uuid),public.attach_context_evidence(uuid,uuid,uuid,text,jsonb) to service_role; +commit; +$source3$, +$source4$-- Scope-checked bounded receipt history, withholding inaccessible targets. +begin; +-- Version-scoped paging. Inaccessible target receipts are withheld, while the +-- cursor still advances over stored history so a page cannot loop indefinitely. +create or replace function public.list_context_evidence_attachments(p_actor uuid,p_owner uuid,p_version uuid,p_after uuid default null) +returns jsonb language plpgsql set search_path='' as $$ +declare row public.context_evidence_attachments; items jsonb:='[]'; visited integer:=0; cursor_id uuid; more boolean:=false; +begin + perform public.authorize_context_case_actor(p_actor,p_owner); + perform public.authorize_context_evidence_source(p_owner,p_version); + if p_after is not null and not exists(select 1 from public.context_evidence_attachments where id=p_after and owner_id=p_owner and source_version_id=p_version) + then raise exception 'Invalid evidence cursor' using errcode='42501'; end if; + for row in select * from public.context_evidence_attachments where owner_id=p_owner and source_version_id=p_version + and (p_after is null or id>p_after) order by id limit 51 loop + visited:=visited+1; + if visited>50 then more:=true; exit; end if; + cursor_id:=row.id; + begin + items:=items||jsonb_build_array(public.read_context_evidence_attachment(p_actor,p_owner,row.id)); + exception when insufficient_privilege then null; end; + end loop; + return jsonb_build_object('items',items,'next_id',case when more then cursor_id end,'has_more',more); +end $$; + +revoke all on function public.list_context_evidence_attachments(uuid,uuid,uuid,uuid) from public,anon,authenticated; +grant execute on function public.list_context_evidence_attachments(uuid,uuid,uuid,uuid) to service_role; +commit; +$source4$ +]::text[]; + bodies text[] := ARRAY[ +$body0$-- Relevance links for retained evidence, not identity, rights or mandate approval. +set local lock_timeout='5s'; +set local statement_timeout='30s'; + +alter table public.organization_professionals add constraint organization_professionals_id_owner unique(id,organization_id); +create table public.context_evidence_attachments ( + id uuid primary key default gen_random_uuid(), + owner_id uuid not null references public.accounts(id), + actor_id uuid not null references public.accounts(id), + source_version_id uuid not null, + idempotency_key text not null check(idempotency_key ~ '^[A-Za-z0-9._:-]{1,128}$'), + fingerprint text not null check(fingerprint ~ '^[a-f0-9]{64}$'), + created_at timestamptz not null default now(), + foreign key(source_version_id,owner_id) references public.context_source_versions(id,owner_id), + unique(owner_id,idempotency_key), unique(id,owner_id) +); +create index context_evidence_attachments_version on public.context_evidence_attachments(owner_id,source_version_id,id); +create table public.context_evidence_attachment_targets ( + attachment_id uuid not null, + owner_id uuid not null, + position integer not null check(position between 0 and 99), + artist_id uuid references public.accounts(id), + professional_id uuid, + request_id uuid, + subject_id uuid references public.context_subjects(id), + primary key(attachment_id,position), + foreign key(attachment_id,owner_id) references public.context_evidence_attachments(id,owner_id), + foreign key(professional_id,owner_id) references public.organization_professionals(id,organization_id), + foreign key(request_id,owner_id) references public.context_requests(id,owner_id), + check((artist_id is not null and professional_id is null and request_id is null and subject_id is null) + or (professional_id is not null and artist_id is null and request_id is null and subject_id is null) + or (request_id is not null and subject_id is not null and artist_id is null and professional_id is null)) +); +alter table public.context_evidence_attachments enable row level security; +alter table public.context_evidence_attachment_targets enable row level security; +revoke all on public.context_evidence_attachments,public.context_evidence_attachment_targets from public,anon,authenticated,service_role; +grant select,insert on public.context_evidence_attachments,public.context_evidence_attachment_targets to service_role; + +-- Exact shapes and UUIDs only. Caller order does not change replay identity. +create function public.canonical_context_evidence_targets(p_targets jsonb) +returns jsonb language plpgsql set search_path='' as $$ +declare t jsonb; n integer; canonical jsonb; field text; +begin + if jsonb_typeof(p_targets) is distinct from 'array' then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + if jsonb_array_length(p_targets) not between 1 and 100 then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + for t in select value from jsonb_array_elements(p_targets) loop + if jsonb_typeof(t) is distinct from 'object' then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + select count(*) into n from jsonb_object_keys(t); + if not ((n=1 and (t ? 'artist_id' or t ? 'professional_id')) or (n=2 and t ? 'request_id' and t ? 'subject_id')) + then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + for field in select jsonb_object_keys(t) loop + if jsonb_typeof(t->field) is distinct from 'string' or (t->>field) !~* '^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$' + then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + t:=jsonb_set(t,array[field],to_jsonb((t->>field)::uuid::text)); + end loop; + end loop; + select jsonb_agg(normalized order by normalized::text),count(distinct normalized) into canonical,n + from (select jsonb_object_agg(key,to_jsonb(value::uuid::text)) normalized + from jsonb_array_elements(p_targets) with ordinality a(target,ordinal) + cross join lateral jsonb_each_text(target) e(key,value) group by ordinal) q; + if n<>jsonb_array_length(p_targets) then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + return canonical; +end $$; + +create function public.authorize_context_evidence_source(p_owner uuid,p_version uuid) +returns void language plpgsql set search_path='' as $$ +begin + perform 1 from public.context_sources s join public.context_source_versions v on v.source_id=s.id and v.owner_id=s.owner_id + where v.id=p_version and v.owner_id=p_owner and v.removed_at is null and s.withdrawn_at is null for share of s,v; + if not found then raise exception 'Evidence source unavailable' using errcode='42501'; end if; +end $$; + +-- A global subject UUID never grants access. An owned request plus retained +-- accepted lineage is an independent historical path, even after roster removal. +-- Submitted company/writer candidates retain their original uncertainty. +create function public.authorize_context_evidence_targets(p_owner uuid,p_targets jsonb) +returns void language plpgsql set search_path='' as $$ +declare t jsonb; accessible boolean; +begin + for t in select value from jsonb_array_elements(p_targets) loop + accessible:=false; + if t ? 'artist_id' then + perform 1 from public.account_artist_ids where account_id=p_owner and artist_id=(t->>'artist_id')::uuid for share; + accessible:=found; + perform 1 from public.artist_organization_ids where organization_id=p_owner and artist_id=(t->>'artist_id')::uuid for share; + accessible:=accessible or found; + elsif t ? 'professional_id' then + perform 1 from public.organization_professionals where organization_id=p_owner and id=(t->>'professional_id')::uuid for share; + accessible:=found; + else + -- Source locks precede request/result locks, consistent with withdrawal. + perform 1 from public.context_sources s join public.context_source_versions v on v.source_id=s.id and v.owner_id=s.owner_id + join public.context_result_sources rs on rs.source_version_id=v.id and rs.owner_id=v.owner_id + join public.context_results r on r.id=rs.result_id and r.owner_id=rs.owner_id + join public.context_attempts a on a.id=r.attempt_id and a.owner_id=r.owner_id + where a.request_id=(t->>'request_id')::uuid and r.subject_id=(t->>'subject_id')::uuid and r.owner_id=p_owner + order by s.id,v.id for share of s,v; + perform 1 from public.context_requests where owner_id=p_owner and id=(t->>'request_id')::uuid for share; + perform 1 from public.context_results r join public.context_attempts a on a.id=r.attempt_id and a.owner_id=r.owner_id + where r.owner_id=p_owner and a.request_id=(t->>'request_id')::uuid and r.subject_id=(t->>'subject_id')::uuid for share of r; + select exists(select 1 from public.context_requests req join public.context_attempts a on a.request_id=req.id and a.owner_id=req.owner_id + join public.context_results r on r.attempt_id=a.id and r.owner_id=a.owner_id + where req.owner_id=p_owner and req.id=(t->>'request_id')::uuid and req.status in ('partial','completed') + and jsonb_typeof(req.output->'subjectIds')='array' and req.output->'subjectIds' ? (t->>'subject_id') + and r.subject_id=(t->>'subject_id')::uuid and r.status='accepted' and r.evidence_kind<>'creative_proposal' + and exists(select 1 from public.context_result_sources rs where rs.result_id=r.id and rs.owner_id=p_owner) + and not exists(select 1 from public.context_result_sources rs + join public.context_source_versions v on v.id=rs.source_version_id and v.owner_id=rs.owner_id + join public.context_sources s on s.id=v.source_id and s.owner_id=v.owner_id + where rs.result_id=r.id and rs.owner_id=p_owner and (v.removed_at is not null or s.withdrawn_at is not null))) into accessible; + end if; + if not accessible then raise exception 'Evidence target unavailable' using errcode='42501'; end if; + end loop; +end $$; + +create function public.read_context_evidence_attachment(p_actor uuid,p_owner uuid,p_attachment uuid) +returns jsonb language plpgsql set search_path='' as $$ +declare saved public.context_evidence_attachments; targets jsonb; +begin + perform public.authorize_context_case_actor(p_actor,p_owner); + select * into saved from public.context_evidence_attachments where id=p_attachment and owner_id=p_owner; + if saved.id is null then raise exception 'Evidence attachment unavailable' using errcode='42501'; end if; + perform public.authorize_context_evidence_source(p_owner,saved.source_version_id); + select jsonb_agg(jsonb_strip_nulls(jsonb_build_object('artist_id',artist_id,'professional_id',professional_id, + 'request_id',request_id,'subject_id',subject_id)) order by position) into targets + from public.context_evidence_attachment_targets where attachment_id=saved.id and owner_id=p_owner; + if targets is null then raise exception 'Evidence attachment unavailable' using errcode='42501'; end if; + perform public.authorize_context_evidence_targets(p_owner,targets); + return jsonb_build_object('id',saved.id,'owner_id',saved.owner_id,'actor_id',saved.actor_id,'source_version_id',saved.source_version_id, + 'created_at',saved.created_at,'targets',targets,'assertion','relevance_only','rights_verified',false, + 'policy_version','private-evidence-association-v1'); +end $$; + +create function public.attach_context_evidence(p_actor uuid,p_owner uuid,p_version uuid,p_key text,p_targets jsonb) +returns jsonb language plpgsql set search_path='' as $$ +declare targets jsonb; fingerprint text; saved public.context_evidence_attachments; +begin + perform public.authorize_context_case_actor(p_actor,p_owner); + if p_key is null or p_key !~ '^[A-Za-z0-9._:-]{1,128}$' then raise exception 'Invalid attachment key' using errcode='22023'; end if; + targets:=public.canonical_context_evidence_targets(p_targets); + perform public.authorize_context_evidence_source(p_owner,p_version); + perform public.authorize_context_evidence_targets(p_owner,targets); + fingerprint:=encode(sha256(convert_to(jsonb_build_object('version',p_version,'targets',targets)::text,'UTF8')),'hex'); + insert into public.context_evidence_attachments(owner_id,actor_id,source_version_id,idempotency_key,fingerprint) + values(p_owner,p_actor,p_version,p_key,fingerprint) on conflict(owner_id,idempotency_key) do nothing returning * into saved; + if saved.id is not null then + insert into public.context_evidence_attachment_targets(attachment_id,owner_id,position,artist_id,professional_id,request_id,subject_id) + select saved.id,p_owner,ordinal-1,(value->>'artist_id')::uuid,(value->>'professional_id')::uuid,(value->>'request_id')::uuid,(value->>'subject_id')::uuid + from jsonb_array_elements(targets) with ordinality t(value,ordinal); + else + select * into strict saved from public.context_evidence_attachments where owner_id=p_owner and idempotency_key=p_key; + if saved.fingerprint<>fingerprint then raise exception 'Attachment key already used for different input' using errcode='22023'; end if; + end if; + return public.read_context_evidence_attachment(p_actor,p_owner,saved.id); +end $$; + +-- Version-scoped paging. Inaccessible target receipts are withheld, while the +-- cursor still advances over stored history so a page cannot loop indefinitely. +create function public.list_context_evidence_attachments(p_actor uuid,p_owner uuid,p_version uuid,p_after uuid default null) +returns jsonb language plpgsql set search_path='' as $$ +declare row public.context_evidence_attachments; items jsonb:='[]'; visited integer:=0; cursor_id uuid; more boolean:=false; +begin + perform public.authorize_context_case_actor(p_actor,p_owner); + perform public.authorize_context_evidence_source(p_owner,p_version); + if p_after is not null and not exists(select 1 from public.context_evidence_attachments where id=p_after and owner_id=p_owner and source_version_id=p_version) + then raise exception 'Invalid evidence cursor' using errcode='42501'; end if; + for row in select * from public.context_evidence_attachments where owner_id=p_owner and source_version_id=p_version + and (p_after is null or id>p_after) order by id limit 51 loop + visited:=visited+1; + if visited>50 then more:=true; exit; end if; + cursor_id:=row.id; + begin + items:=items||jsonb_build_array(public.read_context_evidence_attachment(p_actor,p_owner,row.id)); + exception when insufficient_privilege then null; end; + end loop; + return jsonb_build_object('items',items,'next_id',case when more then cursor_id end,'has_more',more); +end $$; + +revoke all on function public.canonical_context_evidence_targets(jsonb),public.authorize_context_evidence_source(uuid,uuid), + public.authorize_context_evidence_targets(uuid,jsonb),public.read_context_evidence_attachment(uuid,uuid,uuid), + public.attach_context_evidence(uuid,uuid,uuid,text,jsonb),public.list_context_evidence_attachments(uuid,uuid,uuid,uuid) from public,anon,authenticated; +grant execute on function public.canonical_context_evidence_targets(jsonb),public.authorize_context_evidence_source(uuid,uuid), + public.authorize_context_evidence_targets(uuid,jsonb),public.read_context_evidence_attachment(uuid,uuid,uuid), + public.attach_context_evidence(uuid,uuid,uuid,text,jsonb),public.list_context_evidence_attachments(uuid,uuid,uuid,uuid) to service_role; +$body0$, +$body1$-- Forward-only correction: preserve the initial migration already applied in preview. +set local lock_timeout='5s'; +set local statement_timeout='30s'; +grant update(updated_at) on public.artist_organization_ids to service_role; +alter table public.context_evidence_attachments add column target_count integer; +-- Seal the existing canonical receipt payload, never reinterpret or repair it. +update public.context_evidence_attachments a set target_count=( + select count(*) from public.context_evidence_attachment_targets t where t.attachment_id=a.id and t.owner_id=a.owner_id); +do $$ +begin + if exists(select 1 from public.context_evidence_attachments a where a.target_count not between 1 and 100 or + a.fingerprint<>encode(sha256(convert_to(jsonb_build_object('version',a.source_version_id,'targets', + (select jsonb_agg(jsonb_strip_nulls(jsonb_build_object('artist_id',artist_id,'professional_id',professional_id, + 'request_id',request_id,'subject_id',subject_id)) order by position) + from public.context_evidence_attachment_targets where attachment_id=a.id and owner_id=a.owner_id))::text,'UTF8')),'hex')) + then raise exception 'Inconsistent existing evidence receipt; review required' using errcode='23514'; end if; +end $$; +alter table public.context_evidence_attachments alter column target_count set not null; +alter table public.context_evidence_attachments add constraint context_evidence_target_count check(target_count between 1 and 100); +-- Every slot must be filled in the creation transaction. A receipt cannot be +-- committed with holes, nor appended after its fixed slots have been filled. +create function public.guard_context_evidence_target_slot() +returns trigger language plpgsql set search_path='' as $$ +declare slots integer; +begin + select target_count into slots from public.context_evidence_attachments where id=new.attachment_id and owner_id=new.owner_id; + if slots is null or new.position>=slots then raise exception 'Evidence receipt target count' using errcode='23514'; end if; + return new; +end $$; +create trigger context_evidence_target_slot before insert on public.context_evidence_attachment_targets + for each row execute function public.guard_context_evidence_target_slot(); +create function public.check_context_evidence_receipt_complete() +returns trigger language plpgsql set search_path='' as $$ +begin + if (select count(*) from public.context_evidence_attachment_targets where attachment_id=new.id and owner_id=new.owner_id)<>new.target_count + then raise exception 'Evidence receipt target count' using errcode='23514'; end if; + return new; +end $$; +create constraint trigger context_evidence_receipt_complete after insert on public.context_evidence_attachments + deferrable initially deferred for each row execute function public.check_context_evidence_receipt_complete(); +revoke all on function public.guard_context_evidence_target_slot(),public.check_context_evidence_receipt_complete() from public,anon,authenticated; +grant execute on function public.guard_context_evidence_target_slot(),public.check_context_evidence_receipt_complete() to service_role; + +$body1$, +$body2$-- Validate typed targets and independent retained evidence access. +-- Exact shapes and UUIDs only. Caller order does not change replay identity. +create or replace function public.canonical_context_evidence_targets(p_targets jsonb) +returns jsonb language plpgsql set search_path='' as $$ +declare t jsonb; n integer; canonical jsonb; field text; +begin + if jsonb_typeof(p_targets) is distinct from 'array' then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + if jsonb_array_length(p_targets) not between 1 and 100 then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + for t in select value from jsonb_array_elements(p_targets) loop + if jsonb_typeof(t) is distinct from 'object' then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + select count(*) into n from jsonb_object_keys(t); + if not ((n=1 and (t ? 'artist_id' or t ? 'professional_id')) or (n=2 and t ? 'request_id' and t ? 'subject_id')) + then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + for field in select jsonb_object_keys(t) loop + if jsonb_typeof(t->field) is distinct from 'string' or (t->>field) !~* '^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$' + then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + t:=jsonb_set(t,array[field],to_jsonb((t->>field)::uuid::text)); + end loop; + end loop; + select jsonb_agg(normalized order by normalized::text),count(distinct normalized) into canonical,n + from (select jsonb_object_agg(key,to_jsonb(value::uuid::text)) normalized + from jsonb_array_elements(p_targets) with ordinality a(target,ordinal) + cross join lateral jsonb_each_text(target) e(key,value) group by ordinal) q; + if n<>jsonb_array_length(p_targets) then raise exception 'Invalid evidence targets' using errcode='22023'; end if; + return canonical; +end $$; + +create or replace function public.authorize_context_evidence_source(p_owner uuid,p_version uuid) +returns void language plpgsql set search_path='' as $$ +begin + perform 1 from public.context_sources s join public.context_source_versions v on v.source_id=s.id and v.owner_id=s.owner_id + where v.id=p_version and v.owner_id=p_owner and v.removed_at is null and s.withdrawn_at is null for share of s,v; + if not found then raise exception 'Evidence source unavailable' using errcode='42501'; end if; +end $$; + +-- A global subject UUID never grants access. An owned request plus retained +-- accepted lineage is an independent historical path, even after roster removal. +-- Submitted company/writer candidates retain their original uncertainty. +create or replace function public.authorize_context_evidence_targets(p_owner uuid,p_targets jsonb) +returns void language plpgsql set search_path='' as $$ +declare t jsonb; accessible boolean; +begin + for t in select value from jsonb_array_elements(p_targets) loop + accessible:=false; + if t ? 'artist_id' then + perform 1 from public.account_artist_ids where account_id=p_owner and artist_id=(t->>'artist_id')::uuid for share; + accessible:=found; + perform 1 from public.artist_organization_ids where organization_id=p_owner and artist_id=(t->>'artist_id')::uuid for share; + accessible:=accessible or found; + elsif t ? 'professional_id' then + perform 1 from public.organization_professionals where organization_id=p_owner and id=(t->>'professional_id')::uuid for share; + accessible:=found; + else + -- Source locks precede request/result locks, consistent with withdrawal. + perform 1 from public.context_sources s join public.context_source_versions v on v.source_id=s.id and v.owner_id=s.owner_id + join public.context_result_sources rs on rs.source_version_id=v.id and rs.owner_id=v.owner_id + join public.context_results r on r.id=rs.result_id and r.owner_id=rs.owner_id + join public.context_attempts a on a.id=r.attempt_id and a.owner_id=r.owner_id + where a.request_id=(t->>'request_id')::uuid and r.subject_id=(t->>'subject_id')::uuid and r.owner_id=p_owner + order by s.id,v.id for share of s,v; + perform 1 from public.context_requests where owner_id=p_owner and id=(t->>'request_id')::uuid for share; + perform 1 from public.context_results r join public.context_attempts a on a.id=r.attempt_id and a.owner_id=r.owner_id + where r.owner_id=p_owner and a.request_id=(t->>'request_id')::uuid and r.subject_id=(t->>'subject_id')::uuid for share of r; + select exists(select 1 from public.context_requests req join public.context_attempts a on a.request_id=req.id and a.owner_id=req.owner_id + join public.context_results r on r.attempt_id=a.id and r.owner_id=a.owner_id + where req.owner_id=p_owner and req.id=(t->>'request_id')::uuid and req.status in ('partial','completed') + and jsonb_typeof(req.output->'subjectIds')='array' and req.output->'subjectIds' ? (t->>'subject_id') + and r.subject_id=(t->>'subject_id')::uuid and r.status='accepted' and r.evidence_kind<>'creative_proposal' + and exists(select 1 from public.context_result_sources rs where rs.result_id=r.id and rs.owner_id=p_owner) + and not exists(select 1 from public.context_result_sources rs + join public.context_source_versions v on v.id=rs.source_version_id and v.owner_id=rs.owner_id + join public.context_sources s on s.id=v.source_id and s.owner_id=v.owner_id + where rs.result_id=r.id and rs.owner_id=p_owner and (v.removed_at is not null or s.withdrawn_at is not null))) into accessible; + end if; + if not accessible then raise exception 'Evidence target unavailable' using errcode='42501'; end if; + end loop; +end $$; + +revoke all on function public.canonical_context_evidence_targets(jsonb),public.authorize_context_evidence_source(uuid,uuid),public.authorize_context_evidence_targets(uuid,jsonb) from public,anon,authenticated; +grant execute on function public.canonical_context_evidence_targets(jsonb),public.authorize_context_evidence_source(uuid,uuid),public.authorize_context_evidence_targets(uuid,jsonb) to service_role; +$body2$, +$body3$-- Save/read immutable, version-specific relevance receipts. +create or replace function public.read_context_evidence_attachment(p_actor uuid,p_owner uuid,p_attachment uuid) +returns jsonb language plpgsql set search_path='' as $$ +declare saved public.context_evidence_attachments; targets jsonb; +begin + perform public.authorize_context_case_actor(p_actor,p_owner); + select * into saved from public.context_evidence_attachments where id=p_attachment and owner_id=p_owner; + if saved.id is null then raise exception 'Evidence attachment unavailable' using errcode='42501'; end if; + perform public.authorize_context_evidence_source(p_owner,saved.source_version_id); + select jsonb_agg(jsonb_strip_nulls(jsonb_build_object('artist_id',artist_id,'professional_id',professional_id, + 'request_id',request_id,'subject_id',subject_id)) order by position) into targets + from public.context_evidence_attachment_targets where attachment_id=saved.id and owner_id=p_owner; + if targets is null or jsonb_array_length(targets)<>saved.target_count or + encode(sha256(convert_to(jsonb_build_object('version',saved.source_version_id,'targets',targets)::text,'UTF8')),'hex')<>saved.fingerprint + then raise exception 'Evidence attachment unavailable' using errcode='42501'; end if; + perform public.authorize_context_evidence_targets(p_owner,targets); + return jsonb_build_object('id',saved.id,'owner_id',saved.owner_id,'actor_id',saved.actor_id,'source_version_id',saved.source_version_id, + 'created_at',saved.created_at,'targets',targets,'assertion','relevance_only','rights_verified',false, + 'policy_version','private-evidence-association-v1'); +end $$; + +create or replace function public.attach_context_evidence(p_actor uuid,p_owner uuid,p_version uuid,p_key text,p_targets jsonb) +returns jsonb language plpgsql set search_path='' as $$ +declare targets jsonb; fingerprint text; saved public.context_evidence_attachments; +begin + perform public.authorize_context_case_actor(p_actor,p_owner); + if p_key is null or p_key !~ '^[A-Za-z0-9._:-]{1,128}$' then raise exception 'Invalid attachment key' using errcode='22023'; end if; + targets:=public.canonical_context_evidence_targets(p_targets); + perform public.authorize_context_evidence_source(p_owner,p_version); + perform public.authorize_context_evidence_targets(p_owner,targets); + fingerprint:=encode(sha256(convert_to(jsonb_build_object('version',p_version,'targets',targets)::text,'UTF8')),'hex'); + insert into public.context_evidence_attachments(owner_id,actor_id,source_version_id,idempotency_key,fingerprint,target_count) + values(p_owner,p_actor,p_version,p_key,fingerprint,jsonb_array_length(targets)) on conflict(owner_id,idempotency_key) do nothing returning * into saved; + if saved.id is not null then + insert into public.context_evidence_attachment_targets(attachment_id,owner_id,position,artist_id,professional_id,request_id,subject_id) + select saved.id,p_owner,ordinal-1,(value->>'artist_id')::uuid,(value->>'professional_id')::uuid,(value->>'request_id')::uuid,(value->>'subject_id')::uuid + from jsonb_array_elements(targets) with ordinality t(value,ordinal); + else + select * into strict saved from public.context_evidence_attachments where owner_id=p_owner and idempotency_key=p_key; + if saved.fingerprint<>fingerprint then raise exception 'Attachment key already used for different input' using errcode='22023'; end if; + end if; + return public.read_context_evidence_attachment(p_actor,p_owner,saved.id); +end $$; + +revoke all on function public.read_context_evidence_attachment(uuid,uuid,uuid),public.attach_context_evidence(uuid,uuid,uuid,text,jsonb) from public,anon,authenticated; +grant execute on function public.read_context_evidence_attachment(uuid,uuid,uuid),public.attach_context_evidence(uuid,uuid,uuid,text,jsonb) to service_role; +$body3$, +$body4$-- Scope-checked bounded receipt history, withholding inaccessible targets. +-- Version-scoped paging. Inaccessible target receipts are withheld, while the +-- cursor still advances over stored history so a page cannot loop indefinitely. +create or replace function public.list_context_evidence_attachments(p_actor uuid,p_owner uuid,p_version uuid,p_after uuid default null) +returns jsonb language plpgsql set search_path='' as $$ +declare row public.context_evidence_attachments; items jsonb:='[]'; visited integer:=0; cursor_id uuid; more boolean:=false; +begin + perform public.authorize_context_case_actor(p_actor,p_owner); + perform public.authorize_context_evidence_source(p_owner,p_version); + if p_after is not null and not exists(select 1 from public.context_evidence_attachments where id=p_after and owner_id=p_owner and source_version_id=p_version) + then raise exception 'Invalid evidence cursor' using errcode='42501'; end if; + for row in select * from public.context_evidence_attachments where owner_id=p_owner and source_version_id=p_version + and (p_after is null or id>p_after) order by id limit 51 loop + visited:=visited+1; + if visited>50 then more:=true; exit; end if; + cursor_id:=row.id; + begin + items:=items||jsonb_build_array(public.read_context_evidence_attachment(p_actor,p_owner,row.id)); + exception when insufficient_privilege then null; end; + end loop; + return jsonb_build_object('items',items,'next_id',case when more then cursor_id end,'has_more',more); +end $$; + +revoke all on function public.list_context_evidence_attachments(uuid,uuid,uuid,uuid) from public,anon,authenticated; +grant execute on function public.list_context_evidence_attachments(uuid,uuid,uuid,uuid) to service_role; +$body4$ +]::text[]; + versions text[] := ARRAY[ +$version0$20261009180000$version0$, +$version1$20261009180001$version1$, +$version2$20261009180002$version2$, +$version3$20261009180003$version3$, +$version4$20261009180004$version4$ +]::text[]; + names text[] := ARRAY[ +$name0$context_evidence_attachments$name0$, +$name1$context_evidence_receipt_seal$name1$, +$name2$context_evidence_authorization$name2$, +$name3$context_evidence_receipts$name3$, +$name4$context_evidence_list$name4$ +]::text[]; + hashes text[] := ARRAY[ +$hash0$e8da77af97583862fc7ae083deab57c17708c0520fe4cd781b1424a92c3db5e1$hash0$, +$hash1$6de9db119f8c3fca29376af6a52356a7c11b725114af9a34cc2294549de29662$hash1$, +$hash2$3a990094055ada83aaf62410d359d23848174df2dd396cf2c8e9c8317d763140$hash2$, +$hash3$30a25384bc726ef613ddafee16c9d76649d2b436033b5632dca42d3225ea84c4$hash3$, +$hash4$27518a7a42bd3e92d3d357dc06119e190fd2ffe14685e4dfa351b00c9eb9eef5$hash4$ +]::text[]; + baseline jsonb; + actual jsonb; + checked record; + fn oid; + step integer; +BEGIN + IF current_database()<>'postgres' OR current_user<>'postgres' THEN + RAISE EXCEPTION 'Release database/role mismatch'; + END IF; + IF EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname='public' AND c.relname IN + ('context_evidence_attachments','context_evidence_attachment_targets')) + OR EXISTS (SELECT 1 FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace + WHERE n.nspname='public' AND p.proname=ANY(ARRAY[ + 'canonical_context_evidence_targets','authorize_context_evidence_source','authorize_context_evidence_targets','read_context_evidence_attachment','attach_context_evidence','list_context_evidence_attachments','guard_context_evidence_target_slot','check_context_evidence_receipt_complete'])) THEN + RAISE EXCEPTION 'Fresh-install evidence objects required; stop and inspect'; + END IF; + IF (SELECT count(*) FROM information_schema.columns + WHERE table_schema='supabase_migrations' AND table_name='schema_migrations' + AND ((column_name IN ('version','name') AND data_type='text') + OR (column_name='statements' AND data_type='ARRAY' AND udt_name='_text')))<>3 THEN + RAISE EXCEPTION 'Migration-history shape must be reviewed before release'; + END IF; + IF EXISTS (SELECT 1 FROM supabase_migrations.schema_migrations + WHERE version IN ('20261009180000','20261009180001','20261009180002','20261009180003','20261009180004')) + OR (SELECT count(*) FROM supabase_migrations.schema_migrations WHERE version IN ('20261009190000','20261009193000','20261010010000','20261010035000','20261010040000','20261010060000','20261010060001','20261010060002','20261010060003','20261010060004','20261010100000','20261015230000','20261019200000'))<>13 + OR (SELECT max(version) FROM supabase_migrations.schema_migrations) IS DISTINCT FROM '20261019200000' THEN + RAISE EXCEPTION 'Migration history changed; do not replay or repair automatically'; + END IF; + IF NOT has_column_privilege('service_role','public.artist_organization_ids','updated_at','UPDATE') THEN + RAISE EXCEPTION 'Previously verified membership-lock privilege changed'; + END IF; + SELECT jsonb_object_agg(proname,encode(sha256(convert_to(pg_get_functiondef(oid),'UTF8')),'hex')) + INTO baseline FROM pg_proc WHERE oid IN ( + 'public.commit_spotify_context(uuid,uuid,uuid,jsonb)'::regprocedure, + 'public.save_context_brief(uuid,text,jsonb)'::regprocedure); + + FOR step IN 1..5 LOOP + -- Reassert for every file; never rely on a preceding file's SET LOCAL. + PERFORM set_config('lock_timeout','5s',true); + PERFORM set_config('statement_timeout','30s',true); + PERFORM set_config('idle_in_transaction_session_timeout','60s',true); + IF encode(sha256(convert_to(originals[step],'UTF8')),'hex')<>hashes[step] THEN + RAISE EXCEPTION 'Pinned source hash mismatch'; + END IF; + EXECUTE bodies[step]; + -- Bookkeeping uses the existing Supabase ledger, after actual SQL success. + -- It commits only with all five changes; this is not a repair/applied-state claim. + INSERT INTO supabase_migrations.schema_migrations(version,name,statements) + VALUES(versions[step],names[step],ARRAY[originals[step]]); + RAISE NOTICE 'Prepared step % (%/5); not committed yet',versions[step],step; + END LOOP; + + FOR checked IN SELECT * FROM (VALUES ('public.canonical_context_evidence_targets(jsonb)','75f3d9cbf75cc774ce164914c97e24d7334d3a6207b08ea81f02b004de57cc09'), +('public.authorize_context_evidence_source(uuid,uuid)','d1f1dd6ace296a05ad48d5b24aafdab8c886b8d07a47cff280d1d19ea6760f8b'), +('public.authorize_context_evidence_targets(uuid,jsonb)','11c326ab113f3d6fff372d3f6a678a261f1689eb31f05a319bed3ae68eaeeec2'), +('public.read_context_evidence_attachment(uuid,uuid,uuid)','7e19b905769bd1dbe4bfc1f53e2e0cf99ba5496667b79ba89f8ce9fe7286fb43'), +('public.attach_context_evidence(uuid,uuid,uuid,text,jsonb)','c8cd5faa93a62ae3e2a2d4ea5919cc9f7349935ca03bc1c9c6cbb430cb2c8589'), +('public.list_context_evidence_attachments(uuid,uuid,uuid,uuid)','3377c9b3c4d2b91b2ec401e6235ddf075eeb4906b24939acbaad2a0ac58a5c0a'), +('public.guard_context_evidence_target_slot()','d0b7abff3c29bb819cb1b5e5f6cabe2976e41e4f33055e1ebeabcdffdd49bc6a'), +('public.check_context_evidence_receipt_complete()','bc75f86456a7e6b612858f56d397ab5bafff863ccd079b66cc69e2c77c770ccf')) v(signature,body_hash) LOOP + fn:=to_regprocedure(checked.signature); + IF fn IS NULL OR NOT EXISTS(SELECT 1 FROM pg_proc WHERE oid=fn AND NOT prosecdef + AND encode(sha256(convert_to(prosrc,'UTF8')),'hex')=checked.body_hash + AND proconfig @> ARRAY['search_path=""']) + OR NOT has_function_privilege('service_role',fn,'EXECUTE') + OR has_function_privilege('anon',fn,'EXECUTE') + OR has_function_privilege('authenticated',fn,'EXECUTE') THEN + RAISE EXCEPTION 'Evidence function/body/permission verification failed'; + END IF; + END LOOP; + IF EXISTS(SELECT 1 FROM (VALUES('public.context_evidence_attachments'), + ('public.context_evidence_attachment_targets')) t(name) WHERE + NOT has_table_privilege('service_role',name,'SELECT') + OR NOT has_table_privilege('service_role',name,'INSERT') + OR has_table_privilege('service_role',name,'UPDATE,DELETE') + OR has_table_privilege('anon',name,'SELECT,INSERT,UPDATE,DELETE') + OR has_table_privilege('authenticated',name,'SELECT,INSERT,UPDATE,DELETE')) THEN + RAISE EXCEPTION 'Evidence table permissions changed'; + END IF; + SELECT jsonb_object_agg(proname,encode(sha256(convert_to(pg_get_functiondef(oid),'UTF8')),'hex')) + INTO actual FROM pg_proc WHERE oid IN ( + 'public.commit_spotify_context(uuid,uuid,uuid,jsonb)'::regprocedure, + 'public.save_context_brief(uuid,text,jsonb)'::regprocedure); + IF actual IS DISTINCT FROM baseline OR (SELECT count(*) FROM jsonb_object_keys(actual))<>2 + OR NOT has_column_privilege('service_role','public.artist_organization_ids','updated_at','UPDATE') THEN + RAISE EXCEPTION 'Existing Context definitions or lock privilege changed'; + END IF; +END +$recoup_release$; +$approved_install$; + RETURN; + END IF; + IF installed<>5 THEN + RAISE EXCEPTION 'Partial evidence history; stop without repair'; + END IF; + -- Canonical replay may contain either the approved complete-file representation + -- or the pinned CLI 2.22.6 parsed array. Neither representation is rewritten. + IF EXISTS(SELECT 1 FROM (VALUES ('20261009180000','context_evidence_attachments','e8da77af97583862fc7ae083deab57c17708c0520fe4cd781b1424a92c3db5e1','70988a8e8502be15ee7468a459aceea9ec5633a87a702abf1c5cd9c1e6c521ff'), +('20261009180001','context_evidence_receipt_seal','6de9db119f8c3fca29376af6a52356a7c11b725114af9a34cc2294549de29662','48cecb816bee52fb38ac78cd3574dc60df5a5f7f3a1498c1d89b5852d3faa286'), +('20261009180002','context_evidence_authorization','3a990094055ada83aaf62410d359d23848174df2dd396cf2c8e9c8317d763140','4c947fe84e01c8935b38c9b464c1748680330d0332f6ea84e992be4985641f97'), +('20261009180003','context_evidence_receipts','30a25384bc726ef613ddafee16c9d76649d2b436033b5632dca42d3225ea84c4','18a668845ee3947c7323a991820a728f1cefff0f2fc36c8399f2733a996eb6b6'), +('20261009180004','context_evidence_list','27518a7a42bd3e92d3d357dc06119e190fd2ffe14685e4dfa351b00c9eb9eef5','59c4892fa4e028d7eefa2a9b1e47bca4d83a53dfc3d91b59c1e2502ebe862e12')) e(version,name,file_hash,array_hash) + LEFT JOIN supabase_migrations.schema_migrations m ON m.version=e.version + WHERE m.name IS DISTINCT FROM e.name OR NOT COALESCE( + (cardinality(m.statements)=1 AND encode(sha256(convert_to(m.statements[1],'UTF8')),'hex')=e.file_hash) + OR encode(sha256(convert_to(to_jsonb(m.statements)::text,'UTF8')),'hex')=e.array_hash,false)) + OR (SELECT count(*) FROM supabase_migrations.schema_migrations WHERE version IN ('20261009190000','20261009193000','20261010010000','20261010035000','20261010040000','20261010060000','20261010060001','20261010060002','20261010060003','20261010060004','20261010100000','20261015230000','20261019200000'))<>13 THEN + RAISE EXCEPTION 'Canonical evidence source history mismatch'; + END IF; + FOR checked IN SELECT * FROM (VALUES ('public.canonical_context_evidence_targets(jsonb)','75f3d9cbf75cc774ce164914c97e24d7334d3a6207b08ea81f02b004de57cc09'), +('public.authorize_context_evidence_source(uuid,uuid)','d1f1dd6ace296a05ad48d5b24aafdab8c886b8d07a47cff280d1d19ea6760f8b'), +('public.authorize_context_evidence_targets(uuid,jsonb)','11c326ab113f3d6fff372d3f6a678a261f1689eb31f05a319bed3ae68eaeeec2'), +('public.read_context_evidence_attachment(uuid,uuid,uuid)','7e19b905769bd1dbe4bfc1f53e2e0cf99ba5496667b79ba89f8ce9fe7286fb43'), +('public.attach_context_evidence(uuid,uuid,uuid,text,jsonb)','c8cd5faa93a62ae3e2a2d4ea5919cc9f7349935ca03bc1c9c6cbb430cb2c8589'), +('public.list_context_evidence_attachments(uuid,uuid,uuid,uuid)','3377c9b3c4d2b91b2ec401e6235ddf075eeb4906b24939acbaad2a0ac58a5c0a'), +('public.guard_context_evidence_target_slot()','d0b7abff3c29bb819cb1b5e5f6cabe2976e41e4f33055e1ebeabcdffdd49bc6a'), +('public.check_context_evidence_receipt_complete()','bc75f86456a7e6b612858f56d397ab5bafff863ccd079b66cc69e2c77c770ccf')) v(signature,body_hash) LOOP + fn:=to_regprocedure(checked.signature); + IF fn IS NULL OR NOT EXISTS(SELECT 1 FROM pg_proc WHERE oid=fn AND NOT prosecdef + AND encode(sha256(convert_to(prosrc,'UTF8')),'hex')=checked.body_hash + AND proconfig @> ARRAY['search_path=""']) + OR NOT has_function_privilege('service_role',fn,'EXECUTE') + OR has_function_privilege('anon',fn,'EXECUTE') + OR has_function_privilege('authenticated',fn,'EXECUTE') THEN + RAISE EXCEPTION 'Evidence function/body/permission verification failed'; + END IF; + END LOOP; + IF EXISTS(SELECT 1 FROM (VALUES('public.context_evidence_attachments'), + ('public.context_evidence_attachment_targets')) t(name) WHERE + NOT has_table_privilege('service_role',name,'SELECT') + OR NOT has_table_privilege('service_role',name,'INSERT') + OR has_table_privilege('service_role',name,'UPDATE,DELETE') + OR has_table_privilege('anon',name,'SELECT,INSERT,UPDATE,DELETE') + OR has_table_privilege('authenticated',name,'SELECT,INSERT,UPDATE,DELETE')) THEN + RAISE EXCEPTION 'Evidence table permissions changed'; + END IF; + IF EXISTS(SELECT 1 FROM (VALUES('public.context_evidence_attachments'), + ('public.context_evidence_attachment_targets')) t(name) LEFT JOIN pg_class c ON c.oid=to_regclass(t.name) + WHERE c.oid IS NULL OR NOT c.relrowsecurity) + OR NOT has_column_privilege('service_role','public.artist_organization_ids','updated_at','UPDATE') THEN + RAISE EXCEPTION 'Canonical evidence table/lock state mismatch'; + END IF; + RAISE NOTICE 'Canonical evidence replay verified; original history and schema unchanged'; +END +$recoup_mcp_release$; diff --git a/supabase/migrations/20261020150000_release_pack_jobs.sql b/supabase/migrations/20261020154953_release_pack_jobs.sql similarity index 100% rename from supabase/migrations/20261020150000_release_pack_jobs.sql rename to supabase/migrations/20261020154953_release_pack_jobs.sql diff --git a/supabase/migrations/20261023160000_professional_artist_accounts.sql b/supabase/migrations/20261024002432_professional_artist_accounts.sql similarity index 100% rename from supabase/migrations/20261023160000_professional_artist_accounts.sql rename to supabase/migrations/20261024002432_professional_artist_accounts.sql diff --git a/tests/MIGRATION-HISTORY.md b/tests/MIGRATION-HISTORY.md new file mode 100644 index 0000000..e8207d8 --- /dev/null +++ b/tests/MIGRATION-HISTORY.md @@ -0,0 +1,24 @@ +# Migration source-history alignment + +This change restores recorded migration identities without changing SQL. Five evidence files match the published source in PR #90 (head 74f7e3eb59c01ba4a48978e149faf22a2d1be88c). The atomic evidence release matches its preserved Git blob and the recorded applied statement byte-for-byte. Release-pack jobs (#119) and professional artist accounts (#121) retain their exact merged SQL under their recorded application timestamps. + +| Recorded version | Source | SHA-256 of unchanged SQL | +| --- | --- | --- | +| 20261009180000 | PR #90 | `e8da77af97583862fc7ae083deab57c17708c0520fe4cd781b1424a92c3db5e1` | +| 20261009180001 | PR #90 | `6de9db119f8c3fca29376af6a52356a7c11b725114af9a34cc2294549de29662` | +| 20261009180002 | PR #90 | `3a990094055ada83aaf62410d359d23848174df2dd396cf2c8e9c8317d763140` | +| 20261009180003 | PR #90 | `30a25384bc726ef613ddafee16c9d76649d2b436033b5632dca42d3225ea84c4` | +| 20261009180004 | PR #90 | `27518a7a42bd3e92d3d357dc06119e190fd2ffe14685e4dfa351b00c9eb9eef5` | +| 20261020035229 | Preserved atomic release; recorded applied statement | `b5b46d803748432bb114bcd36a896d0f306df9b89b70b17de8a69e69929a615c` | +| 20261020154953 | PR #119; formerly 20261020150000 | `3605c64461a5aa5d7ef29fe0893c10d863b51f14044f0098a89ee6b7d1a16aed` | +| 20261024002432 | PR #121; formerly 20261023160000 | `1e3533414fc0101ab26258f1199370978f83395adf31b6c0c5aa9e9bfccea76d` | + +The atomic release's preserved local source is b85a490b0b03803d052544c2445696fc3863e936. That local commit is not asserted to be a merged or remotely published commit; the independently read recorded migration statement is the authoritative byte comparison. No SQL was inferred from migration names and no empty migration was introduced. + +## Merge hold: pending migration is not authorized by this repair + +Read-only version comparison after alignment: 276 recorded remote versions, 277 unique local versions, zero remote-only versions. The sole local-only migration is `20261022120000_context_catalog_cases.sql` from merged PR #120. It is unchanged and absent from the observed remote history; it is not a renamed equivalent of these eight entries. + +Fixing history can unblock the configured main-merge integration and allow that pending catalog-case migration to apply. **Keep this PR draft and do not merge without explicit migration approval or a proven non-applying review-only path.** Source-history repair is not migration-apply permission. No integration setting, remote history, schema or grant is changed here. Metadata comparison is not a live dry-run or hosted SQL qualification; environments with different recorded history require their own review. + +Validation is bounded to byte equality against recorded statements/original Git blobs, unique timestamp identities, migration version-set comparison, unchanged catalog-case source, and updated fixture/document references. No remote migration repair, SQL apply or replay was executed. diff --git a/tests/README.md b/tests/README.md index 074abcf..79df5fd 100644 --- a/tests/README.md +++ b/tests/README.md @@ -44,7 +44,7 @@ Rollout: apply the contact migration before deploying API readers of `contact_id ## Professional artist accounts -Apply `20261023160000_professional_artist_accounts.sql` before deploying the API +Apply `20261024002432_professional_artist_accounts.sql` before deploying the API and app changes that require `professional.artist_id`. This field references `accounts.id`, using the existing artist terminology and workflows. New confirmed professionals use `create_artist_with_roster` in the same transaction as roles and diff --git a/tests/RELEASE-PACK-JOBS.md b/tests/RELEASE-PACK-JOBS.md index 830906d..6143c26 100644 --- a/tests/RELEASE-PACK-JOBS.md +++ b/tests/RELEASE-PACK-JOBS.md @@ -1,6 +1,6 @@ # Private release-pack jobs -Apply `20261020150000_release_pack_jobs.sql` before deploying its API caller. It adds two private, service-only tables, one pack command RPC, a reservation-aware monthly floor, and atomic legacy balance adjustment/topup RPCs. No hosted data is changed by the test fixture. +Apply `20261020154953_release_pack_jobs.sql` before deploying its API caller. It adds two private, service-only tables, one pack command RPC, a reservation-aware monthly floor, and atomic legacy balance adjustment/topup RPCs. No hosted data is changed by the test fixture. ```sh # PostgreSQL 16/17 binaries must be on PATH; macOS example: diff --git a/tests/release_pack_fixture.py b/tests/release_pack_fixture.py index 3520bfd..1dfe714 100644 --- a/tests/release_pack_fixture.py +++ b/tests/release_pack_fixture.py @@ -5,7 +5,7 @@ import unittest ROOT = pathlib.Path(__file__).resolve().parents[1] -MIGRATION = '20261020150000_release_pack_jobs.sql' +MIGRATION = '20261020154953_release_pack_jobs.sql' class ReleasePackFixture(unittest.TestCase): diff --git a/tests/test_professional_roster.py b/tests/test_professional_roster.py index 0f32212..197530d 100644 --- a/tests/test_professional_roster.py +++ b/tests/test_professional_roster.py @@ -29,7 +29,7 @@ def setUpClass(cls): cls.sql((ROOT/'supabase/migrations/20261008030000_onboarding_membership_lock_privilege.sql').read_text()) for migration in sorted((ROOT/'supabase/migrations').glob('20261008050*.sql')): cls.sql(migration.read_text()) - migration = ROOT/'supabase/migrations/20261023160000_professional_artist_accounts.sql' + migration = ROOT/'supabase/migrations/20261024002432_professional_artist_accounts.sql' if migration.exists() and getattr(cls, "apply_account_migration", True): cls.sql(migration.read_text()) @classmethod @@ -186,7 +186,7 @@ def test_backfill_preserves_confirmed_identity_and_old_receipts(self): INSERT INTO organization_professionals(id,organization_id,name,roles,confirmed_by) VALUES ('{sidney_professional}','{sidney_org}','Fixture professional',ARRAY['songwriter','producer'],'{sidney_actor}'); """) - migration = (ROOT/'supabase/migrations/20261023160000_professional_artist_accounts.sql').read_text() + migration = (ROOT/'supabase/migrations/20261024002432_professional_artist_accounts.sql').read_text() self.assertIn('prerequisites changed',self.sql('BEGIN;'+migration+'COMMIT;',fails=True)) self.assertEqual(self.sql("SELECT count(*) FROM information_schema.columns WHERE table_name='organization_professionals' AND column_name='artist_id'"),'0') self.sql(f"INSERT INTO account_artist_ids VALUES ('{sidney_actor}','{sidney_artist}')") From bc8f9636227b89f8734e44b53c473b81b9a51b2c Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:14:20 -0500 Subject: [PATCH 4/5] Protect shared credit reservations across existing wallet writers --- .github/workflows/credit-reservations.yml | 1 + ...1117000000_compose_credit_reservations.sql | 157 ++++++++++++ tests/CREDIT-RESERVATIONS.md | 53 ++-- tests/test_credit_reservation_composition.py | 236 ++++++++++++++++++ 4 files changed, 428 insertions(+), 19 deletions(-) create mode 100644 supabase/migrations/20261117000000_compose_credit_reservations.sql create mode 100644 tests/test_credit_reservation_composition.py diff --git a/.github/workflows/credit-reservations.yml b/.github/workflows/credit-reservations.yml index dba2827..efae730 100644 --- a/.github/workflows/credit-reservations.yml +++ b/.github/workflows/credit-reservations.yml @@ -30,3 +30,4 @@ jobs: run: | export PATH="/usr/lib/postgresql/${{ matrix.postgres }}/bin:$PATH" python3 -m unittest discover -s tests -p 'test_credit_reservations.py' + python3 -m unittest discover -s tests -p 'test_credit_reservation_composition.py' diff --git a/supabase/migrations/20261117000000_compose_credit_reservations.sql b/supabase/migrations/20261117000000_compose_credit_reservations.sql new file mode 100644 index 0000000..d86efd1 --- /dev/null +++ b/supabase/migrations/20261117000000_compose_credit_reservations.sql @@ -0,0 +1,157 @@ +-- Compose the existing shared-reservation candidate with released pack holds and +-- all wallet debit writers. Depends on 20261010210500_credit_reservations and +-- 20261020150000_release_pack_jobs. No balances, prices or callers are changed. +-- Pack holds have already been deducted from remaining_credits. Shared holds +-- have not: protect only the latter at the common wallet-write boundary. +BEGIN; +SET LOCAL lock_timeout = '5s'; +SET LOCAL statement_timeout = '30s'; + +CREATE OR REPLACE FUNCTION public.protect_credit_reservations() +RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER +SET search_path = public, pg_temp AS $$ +DECLARE v_held numeric; +BEGIN + -- Definer visibility is necessary: a permitted legacy writer may not be + -- allowed to read reservation rows. This function grants no read/write API. + SELECT coalesce(sum(credits_held),0) INTO v_held + FROM public.credit_reservations + WHERE account_id = OLD.account_id AND state = 'held'; + IF v_held > 0 THEN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Outstanding credit reservations prevent wallet removal' + USING ERRCODE = '22023'; + END IF; + IF NEW.account_id IS DISTINCT FROM OLD.account_id + OR NEW.remaining_credits IS NULL OR NEW.remaining_credits < v_held THEN + RAISE EXCEPTION 'Outstanding credit reservations exceed available wallet funds' + USING ERRCODE = '22023'; + END IF; + END IF; + IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION public.protect_credit_reservations() + FROM PUBLIC, anon, authenticated, service_role; +CREATE TRIGGER protect_credit_reservations +BEFORE UPDATE OF remaining_credits, account_id OR DELETE ON public.credits_usage +FOR EACH ROW EXECUTE FUNCTION public.protect_credit_reservations(); + +CREATE OR REPLACE FUNCTION public.reserve_credits_once( + p_account_id uuid, p_operation_key text, p_credits bigint +) RETURNS jsonb +LANGUAGE plpgsql SECURITY INVOKER SET search_path = public, pg_temp AS $$ +DECLARE + v_id text; + v_held bigint; + v_hold public.credit_reservations%ROWTYPE; + v_wallet public.credits_usage%ROWTYPE; +BEGIN + IF p_account_id IS NULL OR p_operation_key IS NULL OR btrim(p_operation_key) = '' + OR length(p_operation_key) > 200 OR p_credits IS NULL OR p_credits <= 0 + OR p_credits > 9007199254740991 THEN + RAISE EXCEPTION 'Invalid credit reservation' USING ERRCODE = '22023'; + END IF; + -- Every reservation operation locks the owner's single wallet row first, so + -- holds serialize with each other, charge receipts and legacy wallet writers. + BEGIN + SELECT * INTO STRICT v_wallet FROM public.credits_usage + WHERE account_id = p_account_id ORDER BY id FOR UPDATE; + EXCEPTION WHEN no_data_found OR too_many_rows THEN + RAISE EXCEPTION 'Credit wallet is unavailable or ambiguous' USING ERRCODE = '22023'; + END; + IF v_wallet.remaining_credits IS NULL THEN + RAISE EXCEPTION 'Credit wallet is unavailable' USING ERRCODE = '22023'; + END IF; + v_id := 'hold-v1-' || encode(sha256(convert_to( + jsonb_build_array(p_account_id::text,p_operation_key)::text,'UTF8')),'hex'); + SELECT * INTO v_hold FROM public.credit_reservations WHERE id = v_id; + IF FOUND THEN + IF v_hold.account_id IS DISTINCT FROM p_account_id + OR v_hold.operation_key IS DISTINCT FROM p_operation_key + OR v_hold.credits_held IS DISTINCT FROM p_credits THEN + RAISE EXCEPTION 'Credit reservation identity conflict' USING ERRCODE = '22023'; + END IF; + -- A replay reports the saved status; it never re-holds released or settled work. + RETURN jsonb_build_object('state','reused','reservationId',v_id, + 'status',v_hold.state,'creditsHeld',v_hold.credits_held); + END IF; + SELECT coalesce(sum(credits_held),0)::bigint INTO v_held FROM public.credit_reservations + WHERE account_id = p_account_id AND state = 'held'; + IF v_wallet.remaining_credits - v_held < p_credits THEN + -- A definite denial writes nothing; the same key may be retried later. + RETURN jsonb_build_object('state','insufficient','creditsRequested',p_credits, + 'spendableCredits',v_wallet.remaining_credits - v_held); + END IF; + INSERT INTO public.credit_reservations(id,account_id,operation_key,credits_held) + VALUES (v_id,p_account_id,p_operation_key,p_credits); + -- Version the locked wallet so an older REPEATABLE READ writer cannot miss + -- this new hold. This changes no amount, timestamp, usage event or top-up. + UPDATE public.credits_usage SET remaining_credits = remaining_credits + WHERE id = v_wallet.id; + RETURN jsonb_build_object('state','held','reservationId',v_id,'creditsHeld',p_credits, + 'spendableCredits',v_wallet.remaining_credits - v_held - p_credits); +END; +$$; + +CREATE OR REPLACE FUNCTION public.settle_credit_reservation( + p_account_id uuid, p_operation_key text, p_credits bigint, p_event jsonb +) RETURNS jsonb +LANGUAGE plpgsql SECURITY INVOKER SET search_path = public, pg_temp AS $$ +DECLARE + v_id text; + v_charge jsonb; + v_hold public.credit_reservations%ROWTYPE; + v_wallet public.credits_usage%ROWTYPE; +BEGIN + IF p_account_id IS NULL OR p_operation_key IS NULL OR btrim(p_operation_key) = '' + OR length(p_operation_key) > 200 OR p_credits IS NULL OR p_credits <= 0 + OR p_credits > 9007199254740991 THEN + RAISE EXCEPTION 'Invalid credit settlement' USING ERRCODE = '22023'; + END IF; + BEGIN + SELECT * INTO STRICT v_wallet FROM public.credits_usage + WHERE account_id = p_account_id ORDER BY id FOR UPDATE; + EXCEPTION WHEN no_data_found OR too_many_rows THEN + RAISE EXCEPTION 'Credit wallet is unavailable or ambiguous' USING ERRCODE = '22023'; + END; + v_id := 'hold-v1-' || encode(sha256(convert_to( + jsonb_build_array(p_account_id::text,p_operation_key)::text,'UTF8')),'hex'); + SELECT * INTO v_hold FROM public.credit_reservations WHERE id = v_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Credit reservation not found' USING ERRCODE = '22023'; + END IF; + IF v_hold.state = 'released' THEN + -- Charging released work needs an explicit failure/cancellation policy. + RAISE EXCEPTION 'Credit reservation was released' USING ERRCODE = '22023'; + END IF; + IF p_credits > v_hold.credits_held THEN + RAISE EXCEPTION 'Credit settlement exceeds reservation' USING ERRCODE = '22023'; + END IF; + -- Same owner/key as the reservation: an identical retry reuses the charge + -- receipt; a changed amount or usage payload raises its identity conflict. + IF v_hold.state = 'held' THEN + -- Close only this hold before debiting, so the wallet guard still protects + -- every other reservation. Both writes are one transaction: invalid event, + -- identity conflict or any charge failure restores the original open hold. + -- Hold and charge IDs use the same owner/key digest, with different prefixes. + UPDATE public.credit_reservations + SET state = 'settled', credits_charged = p_credits, + charge_event_id = 'charge-v1-' || substr(v_id,9), closed_at = now() + WHERE id = v_id; + END IF; + v_charge := public.record_credit_charge_once(p_account_id,p_operation_key,p_credits,p_event); + IF v_hold.state = 'settled' AND + (v_hold.charge_event_id IS DISTINCT FROM v_charge->>'eventId' + OR v_hold.credits_charged IS DISTINCT FROM p_credits) THEN + RAISE EXCEPTION 'Credit settlement identity conflict' USING ERRCODE = '22023'; + END IF; + RETURN jsonb_build_object( + 'state',CASE WHEN v_hold.state = 'held' THEN 'settled' ELSE 'reused' END, + 'reservationId',v_id,'eventId',v_charge->>'eventId','creditsHeld',v_hold.credits_held, + 'creditsCharged',p_credits,'creditsReleased',v_hold.credits_held - p_credits); +END; +$$; + +COMMIT; diff --git a/tests/CREDIT-RESERVATIONS.md b/tests/CREDIT-RESERVATIONS.md index 1201952..efaa8eb 100644 --- a/tests/CREDIT-RESERVATIONS.md +++ b/tests/CREDIT-RESERVATIONS.md @@ -8,9 +8,10 @@ balance column, price, ceiling, top-up, expiry or caller. ## Wallet invariant -- **Confirmed balance:** `credits_usage.remaining_credits`, unchanged by holds. +- **Wallet balance:** `credits_usage.remaining_credits`, unchanged by shared holds. + Released pack holds have already been deducted from this balance. - **Outstanding holds:** the sum of `credits_held` for the owner's `held` rows. -- **Spendable:** confirmed balance minus outstanding holds. +- **Spendable:** wallet balance minus outstanding shared holds. Never subtract pack holds twice. A hold is a claim, not a temporary debit followed by a refund, so the monthly refill, top-ups and auto-top-up never treat it as consumption. Every operation locks @@ -40,25 +41,31 @@ settlement charges once either way. ## Activation prerequisites -These functions are safe to release with no callers. Do not connect any caller until -these also land: - -- **database#101 and api#1009** (atomic refill and top-up writers). On `main`, the - API top-up (`incrementRemainingCredits`) and monthly refill (`checkAndResetCredits`) - read the balance and later write an absolute value. A settlement that commits between - that read and write is erased from the balance while its `usage_events` row remains. -- **database#88** (one wallet per account). Until then, an account with duplicate - wallet rows is rejected rather than charged. - -The top-up and refill tests here model atomic in-place writers like database#101's; -they do not exercise main's read-modify-write API paths. +This successor retains Database115's original migration unchanged and adds +`20261117000000_compose_credit_reservations.sql` after the released pack migration. +The added trigger checks all balance/owner updates and wallet deletion against open +shared holds. Unrelated metadata writes and legacy no-hold debit behavior are unchanged. +It uses a narrowly scoped SECURITY DEFINER function with pinned search path and no +direct EXECUTE grant, so a wallet writer cannot hide holds through its own RLS view. + +Settlement closes its own hold before the charge within one transaction; a failed +charge restores that hold. Other holds remain protected. Successful reserve performs +a no-amount-change wallet update: this creates a row version that forces an old +repeatable-read writer to serialize/retry instead of missing a new hold. + +Current released API refill/top-up/deduction callers are already atomic. The pack +migration's refill floor counts unconsumed pack holds. Preserve it; the old +Database101/API1009 prerequisite text is historical, not current implementation state. +Database88's one-wallet constraint remains separate; this migration does not apply it +or repair duplicates. Zero/multiple wallets still reject reservation operations. +No caller activation follows from these source changes. Review/release and verify +actual migrations/grants separately before any live use. ## Deliberately open -- **Legacy debit writers do not consult holds.** `deduct_credits_with_audit`, - `deduct_credits` and the API's read-modify-write `deductCredits` still debit the - confirmed balance directly, so spendable credit can fall below zero while a hold - is outstanding. Moving those callers onto reservations is a later slice. +- **Legacy pre-dispatch authorization is not implemented.** The guard protects + reserved funds at debit time, but legacy callers can already have incurred provider + expense when a debit fails. It does not bound that exposure or activate paid work. - **No expiry.** Unknown provider exposure stays held until the trusted server settles or releases it. Do not add a time-based release that turns uncertain work into spendable credit. @@ -82,9 +89,11 @@ Disposable cluster only (synthetic balances, Unix socket, no hosted credentials) ```sh python3 -m unittest discover -s tests -p 'test_credit_reservations.py' +python3 -m unittest discover -s tests -p 'test_credit_reservation_composition.py' ``` -Nineteen tests cover holds without debit, 12-way concurrent reservations against +The original nineteen-test baseline applies only the original reservation migration +and preserves its historical gap demonstration. It covers holds without debit, 12-way concurrent reservations against one balance, concurrent duplicate reservations and settlements, lost-reply replay, changed-input conflicts, settlement through the shared charge receipt, over-limit settlement, release and its state transitions, missing reservations, per-owner @@ -95,6 +104,12 @@ deletes and immutable hold columns, and rollback. Locally passed on PostgreSQL 15 and 17; CI runs 15 and 16. The fixture is the minimal legacy schema plus the actual charge-receipt migration, not a replay of every migration. +The composition suite replays the actual charge, reservation, pack and corrective +migrations in order on a synthetic minimal schema. It checks shared/pack holds, +legacy and stable debits, actual refill/top-up RPCs, concurrent admission, settlement +with other holds, lost acknowledgements, rollback, owner isolation, wallet lifecycle, +RLS-hidden holds and the repeatable-read race. It is not a full production schema replay. + ## Release Apply through the normal database release workflow before deploying the API diff --git a/tests/test_credit_reservation_composition.py b/tests/test_credit_reservation_composition.py new file mode 100644 index 0000000..723d36d --- /dev/null +++ b/tests/test_credit_reservation_composition.py @@ -0,0 +1,236 @@ +"""Released pack/refill/debit RPCs composed with shared reservations, on local PostgreSQL.""" +import concurrent.futures +import json +import subprocess +import uuid +from credit_charge_fixture import CreditChargeFixture, ROOT + + +class CreditReservationComposition(CreditChargeFixture): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.sql('''CREATE TABLE public.accounts(id uuid PRIMARY KEY); + CREATE TABLE public.account_organization_ids(account_id uuid, organization_id uuid); + ALTER TABLE public.credits_usage ADD COLUMN timestamp timestamp DEFAULT now();''') + # Replay the owning migrations in deployment order, not rewritten model functions. + for name in ['20261010210500_credit_reservations.sql', + '20261020150000_release_pack_jobs.sql', + '20261117000000_compose_credit_reservations.sql']: + cls.sql((ROOT / 'supabase/migrations' / name).read_text()) + + def setUp(self): + self.owner = str(uuid.uuid4()) + self.job = str(uuid.uuid4()) + self.sql(f"INSERT INTO accounts VALUES ('{self.owner}'); INSERT INTO credits_usage" + f"(account_id,remaining_credits) VALUES ('{self.owner}',1000)") + + def rpc(self, function, args, succeeds=True): + result = self.sql(f'SET ROLE service_role; SELECT {function}({args});', succeeds=succeeds) + return json.loads(result.stdout) if succeeds else result + + def reserve(self, amount=600, key='shared'): + return self.rpc('reserve_credits_once', f"'{self.owner}','{key}',{amount}") + + def settle(self, amount=600, key='shared', event=None, succeeds=True): + data = json.dumps(event or {}).replace("'", "''") + return self.rpc('settle_credit_reservation', + f"'{self.owner}','{key}',{amount},'{data}'::jsonb", succeeds) + + def wallet(self): + return int(self.sql(f"SELECT remaining_credits FROM credits_usage WHERE account_id='{self.owner}'").stdout) + + def holds(self): + return int(self.sql(f"SELECT coalesce(sum(credits_held),0) FROM credit_reservations " + f"WHERE account_id='{self.owner}' AND state='held'").stdout) + + def events(self): + return int(self.sql(f"SELECT count(*) FROM usage_events WHERE account_id='{self.owner}'").stdout) + + def command(self, action, data=None, succeeds=True): + payload = json.dumps(data or {}).replace("'", "''") + return self.rpc('release_pack_command', + f"'{self.owner}',null,'{action}','{self.job}','{payload}'::jsonb", succeeds) + + def quote_pack(self): + assets = [{'kind': 'artwork', 'ordinal': 0, 'credits': 100, 'maximum_usd': 0.01}] + self.command('prepare', {'idempotency_key': self.job, 'fingerprint': 'a'*64, + 'brief': {}, 'deliverables': {}, 'status': 'ready_to_quote', 'assets': assets}) + quote = {'id': str(uuid.uuid4()), 'revision': 1, 'credits': 100, + 'maximum_usd': 0.01, 'expires_at': '2099-01-01T00:00:00Z'} + self.command('estimate', {'quote': quote, 'assets': assets}) + return {'quote_id': quote['id'], 'expected_revision': 1, 'approved_max_usd': 0.01} + + def debit_sql(self, amount): + return (f"SET ROLE service_role; SELECT deduct_credits_with_audit('{self.owner}'," + f"{amount}::bigint,'legacy-{uuid.uuid4()}','{{}}'::jsonb);") + + def test_pack_hold_and_shared_hold_protect_the_same_wallet_without_double_counting(self): + self.command('approve', self.quote_pack()) + self.assertEqual(self.reserve()['spendableCredits'], 300) + denied = self.sql(self.debit_sql(301), succeeds=False) + self.assertNotEqual(denied.returncode, 0) + self.assertEqual((self.wallet(), self.holds(), self.events()), (900, 600, 0)) + self.sql(self.debit_sql(300)) + self.command('settle', {'error': 'cancelled before provider dispatch'}) + self.assertEqual(self.wallet(), 700) + self.settle() + self.assertEqual((self.wallet(), self.holds(), self.events()), (100, 0, 2)) + + def test_pack_approval_cannot_consume_a_preexisting_shared_reservation(self): + approval = self.quote_pack() + self.reserve(960) + denied = self.command('approve', approval, succeeds=False) + self.assertNotEqual(denied.returncode, 0) + self.assertEqual(self.command('read')['job']['status'], 'awaiting_approval') + self.assertEqual((self.wallet(), self.holds()), (1000, 960)) + + def test_atomic_adjustment_and_stable_charge_also_cannot_consume_held_funds(self): + self.reserve(960) + for function, args in [ + ('adjust_credit_balance_atomic', f"'{self.owner}',-41"), + ('record_credit_charge_once', f"'{self.owner}','other',41,'{{}}'::jsonb"), + ]: + self.assertNotEqual(self.rpc(function, args, False).returncode, 0) + self.assertEqual((self.wallet(), self.holds(), self.events()), (1000, 960, 0)) + + def test_settlement_excludes_its_own_hold_but_preserves_other_holds(self): + self.reserve(200) + self.reserve(800, 'other') + self.assertEqual(self.settle(150)['creditsReleased'], 50) + self.assertEqual((self.wallet(), self.holds()), (850, 800)) + self.settle(800, 'other') + self.assertEqual((self.wallet(), self.holds(), self.events()), (50, 0, 2)) + + def test_lost_settlement_acknowledgement_reuses_one_charge_and_conflict_rolls_back(self): + self.reserve() + first = self.settle(120) # Committed response is deliberately not used to retry a provider. + replay = self.settle(120) + self.assertEqual(replay['state'], 'reused') + self.assertEqual(replay['eventId'], first['eventId']) + self.assertNotEqual(self.settle(121, succeeds=False).returncode, 0) + self.assertEqual((self.wallet(), self.holds(), self.events()), (880, 0, 1)) + + def test_rejected_charge_restores_open_hold_and_no_event(self): + self.reserve() + self.assertNotEqual(self.settle(120, event={'unexpected': True}, succeeds=False).returncode, 0) + self.assertEqual((self.wallet(), self.holds(), self.events()), (1000, 600, 0)) + self.assertEqual(self.reserve()['status'], 'held') + + def test_actual_refill_counts_pack_hold_once_and_does_not_release_shared_hold(self): + self.sql(f"UPDATE credits_usage SET remaining_credits=150 WHERE account_id='{self.owner}'") + self.command('approve', self.quote_pack()) + self.reserve(40) + stamp = self.sql(f"SELECT timestamp::text FROM credits_usage WHERE account_id='{self.owner}'").stdout.strip() + receipt = self.rpc('refill_credits_to_floor', f"'{self.owner}',200,'{stamp}'::timestamp") + self.assertEqual(receipt['remainingCredits'], 100) + self.assertEqual(self.holds(), 40) + self.settle(30) + stale = self.rpc('refill_credits_to_floor', f"'{self.owner}',200,'{stamp}'::timestamp") + self.assertEqual(stale['state'], 'superseded') + self.command('settle', {'error': 'cancelled'}) + self.assertEqual((self.wallet(), self.holds()), (170, 0)) + + def test_actual_topup_and_settlement_concurrently_both_survive(self): + self.reserve() + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + a = pool.submit(self.rpc, 'increment_credits_atomic', f"'{self.owner}',500") + b = pool.submit(self.settle, 120) + a.result(); b.result() + self.assertEqual((self.wallet(), self.holds(), self.events()), (1380, 0, 1)) + + def test_concurrent_legacy_debit_and_reservation_cannot_both_oversubscribe(self): + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + a = pool.submit(self.reserve, 960) + b = pool.submit(self.sql, self.debit_sql(50), False) + reservation, debit = a.result(), b.result() + if reservation['state'] == 'held': + self.assertNotEqual(debit.returncode, 0) + self.assertEqual((self.wallet(), self.holds(), self.events()), (1000, 960, 0)) + else: + self.assertEqual(reservation['state'], 'insufficient') + self.assertEqual(debit.returncode, 0) + self.assertEqual((self.wallet(), self.holds(), self.events()), (950, 0, 1)) + + def test_existing_no_hold_legacy_debit_behavior_is_unchanged(self): + self.sql(self.debit_sql(1001)) + self.assertEqual((self.wallet(), self.events()), (-1, 1)) + + def test_outstanding_hold_blocks_null_balance_owner_change_and_wallet_deletion(self): + self.reserve() + for statement in [ + f"UPDATE credits_usage SET remaining_credits=NULL WHERE account_id='{self.owner}'", + f"UPDATE credits_usage SET account_id='{uuid.uuid4()}' WHERE account_id='{self.owner}'", + f"DELETE FROM credits_usage WHERE account_id='{self.owner}'", + ]: + self.assertNotEqual(self.sql(statement, succeeds=False).returncode, 0) + self.assertEqual((self.wallet(), self.holds()), (1000, 600)) + + def test_release_keeps_balance_and_makes_capacity_available_to_legacy_debit(self): + self.reserve() + self.rpc('release_credit_reservation', f"'{self.owner}','shared'") + self.sql(self.debit_sql(1000)) + self.assertEqual((self.wallet(), self.holds(), self.events()), (0, 0, 1)) + + def test_old_repeatable_read_snapshot_cannot_miss_a_new_reservation(self): + client = subprocess.Popen(['psql', '-h', self.tmp.name, '-p', '55474', '-d', 'postgres', + '-XAtq', '-v', 'ON_ERROR_STOP=1'], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + self.addCleanup(lambda: client.poll() is None and client.kill()) + client.stdin.write(f"BEGIN ISOLATION LEVEL REPEATABLE READ; SELECT remaining_credits " + f"FROM credits_usage WHERE account_id='{self.owner}';\n") + client.stdin.flush() + self.assertEqual(client.stdout.readline().strip(), '1000') + self.reserve(960) + _, stderr = client.communicate(self.debit_sql(50) + ' COMMIT;', timeout=10) + self.assertNotEqual(client.returncode, 0) + self.assertIn('could not serialize access', stderr) + self.assertEqual((self.wallet(), self.holds(), self.events()), (1000, 960, 0)) + + def test_guard_sees_holds_hidden_from_a_wallet_writer(self): + role = 'wallet_' + uuid.uuid4().hex + self.sql(f"CREATE ROLE {role}; GRANT USAGE ON SCHEMA public TO {role}; " + f"GRANT SELECT, UPDATE, DELETE ON credits_usage TO {role}; " + f"CREATE POLICY {role}_policy ON credits_usage TO {role} USING (true) WITH CHECK (true);") + self.reserve(960) + self.assertNotEqual(self.sql(f'SET ROLE {role}; SELECT * FROM credit_reservations', False).returncode, 0) + # Unrelated metadata updates are not a financial operation. + self.sql(f"SET ROLE {role}; UPDATE credits_usage SET timestamp=now() WHERE account_id='{self.owner}'") + denied = self.sql(f"SET ROLE {role}; UPDATE credits_usage SET remaining_credits=950 " + f"WHERE account_id='{self.owner}'", False) + self.assertNotEqual(denied.returncode, 0) + self.assertIn('Outstanding credit reservations', denied.stderr) + self.assertNotEqual(self.sql(f'SET ROLE {role}; SELECT protect_credit_reservations()', False).returncode, 0) + self.assertEqual((self.wallet(), self.holds()), (1000, 960)) + + def test_concurrent_pack_approval_and_shared_reservation_cannot_both_oversubscribe(self): + approval = self.quote_pack() + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + a = pool.submit(self.reserve, 960) + b = pool.submit(self.command, 'approve', approval, False) + reservation, pack = a.result(), b.result() + if reservation['state'] == 'held': + self.assertNotEqual(pack.returncode, 0) + self.assertEqual((self.wallet(), self.holds()), (1000, 960)) + else: + self.assertEqual(pack.returncode, 0) + self.assertEqual((self.wallet(), self.holds()), (900, 0)) + + def test_failed_usage_insert_restores_hold_and_wallet(self): + name = 'fail_usage_' + uuid.uuid4().hex + self.sql(f"""CREATE FUNCTION {name}() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN IF NEW.provider='fixture_failure' THEN RAISE EXCEPTION 'fixture insert failure'; + END IF; RETURN NEW; END $$; + CREATE TRIGGER {name} BEFORE INSERT ON usage_events FOR EACH ROW EXECUTE FUNCTION {name}();""") + self.reserve() + rejected = self.settle(120, event={'provider': 'fixture_failure'}, succeeds=False) + self.assertIn('fixture insert failure', rejected.stderr) + self.assertEqual((self.wallet(), self.holds(), self.events()), (1000, 600, 0)) + self.assertEqual(self.reserve()['status'], 'held') + + def test_another_owners_holds_do_not_limit_this_wallet(self): + other = str(uuid.uuid4()) + self.sql(f"INSERT INTO credits_usage(account_id,remaining_credits) VALUES ('{other}',1000)") + self.rpc('reserve_credits_once', f"'{other}','other',1000") + self.sql(self.debit_sql(1000)) + self.assertEqual((self.wallet(), self.holds()), (0, 0)) From e1a42e90f24256e0eda92b2bf5c2530c064f8c6f Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:47:17 -0500 Subject: [PATCH 5/5] Use restored pack migration identity in reservation composition fixture --- tests/test_credit_reservation_composition.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test_credit_reservation_composition.py b/tests/test_credit_reservation_composition.py index 723d36d..a74de73 100644 --- a/tests/test_credit_reservation_composition.py +++ b/tests/test_credit_reservation_composition.py @@ -4,6 +4,7 @@ import subprocess import uuid from credit_charge_fixture import CreditChargeFixture, ROOT +from release_pack_fixture import MIGRATION as PACK_MIGRATION class CreditReservationComposition(CreditChargeFixture): @@ -15,7 +16,7 @@ def setUpClass(cls): ALTER TABLE public.credits_usage ADD COLUMN timestamp timestamp DEFAULT now();''') # Replay the owning migrations in deployment order, not rewritten model functions. for name in ['20261010210500_credit_reservations.sql', - '20261020150000_release_pack_jobs.sql', + PACK_MIGRATION, '20261117000000_compose_credit_reservations.sql']: cls.sql((ROOT / 'supabase/migrations' / name).read_text())