fix: red-team round 3 hardening across desktop, mobile, core and server

Batch of red-team r3 fixes that were in the working tree before the
2026-09-28 design overhaul, committed as one unit with their tests.

- desktop main: STT timeouts and sidecar, voice recording store, sync
  (credentials, audio, knowledge reindex, push gates), runtime
  provisioner, update policy, AltGr keybindings, voice-command policy,
  dictionary file codec/limits, meeting transcript condensing and a
  local recording ledger so interrupted-session recovery only closes
  meetings this device recorded (a phone's live meeting is left alone).
- mobile: login CSRF via implicit token callbacks rejected, account
  deletion/retention, durable queue retention, knowledge realtime
  without unfiltered DELETE, meeting re-record failure paths, cloud STT
  client, preferences store/resync.
- core: text chunking splits long unbroken transcripts to fit, template
  field policy, dictionary limits, meeting markdown inline handling.
- server: payple webhook policy and cancellation order scope, meeting
  document generation quota, team RPC null-role guard, unified LLM
  quota in-flight accounting, knowledge chunk vector index, meeting
  re-record failure paths (migrations 20260929*).
- ci: portable/runtime feed gates, update-policy schema, Forgejo file
  delete and alias planning.

Four older tests are updated to the new contracts rather than the old
behavior: token-pair auth callbacks are rejected, knowledge realtime no
longer subscribes to DELETE, long transcript lines are split, and
meeting recovery requires the local recording ledger for empty rows.
This commit is contained in:
Yun Chan 2026-09-28 20:45:52 +09:00
parent 2428ede03d
commit ba9ef9741e
161 changed files with 17056 additions and 2379 deletions

View file

@ -0,0 +1,358 @@
-- ============================================================================
-- 20260929010000_team_rpc_null_role_guard.sql
--
-- Team management RPCs must refuse callers that are not members of the team.
--
-- Bug
-- create_team_invite (20260821000010), update_team_member_role,
-- remove_team_member and cancel_team_invite (20260821000008) read the caller
-- role with
-- SELECT role INTO caller_role FROM team_members
-- WHERE team_id = ... AND user_id = auth.uid();
-- and then guarded with `caller_role <> 'owner'` / `caller_role NOT IN (...)`.
-- For a caller without a membership row caller_role is NULL, every guard
-- evaluates to NULL, and plpgsql skips an IF whose condition is NULL. The
-- functions are SECURITY DEFINER and granted to authenticated, so any
-- signed-in user who knew a team id could mint an admin invite for a second
-- account (and join as admin through accept_team_invite), change member
-- roles, remove members and cancel invites.
--
-- Fix
-- Role policy lives in one place instead of being re-implemented as ad-hoc
-- comparisons in every RPC:
-- * team_role_at_least_v1(role, minimum) pure, NULL-safe hierarchy check
-- (owner > admin > member); a
-- missing role never qualifies.
-- * require_team_role_v1(team, minimum) resolves the caller's membership
-- and raises 42501 unless it meets
-- the minimum; returns the role.
-- The four RPCs are redefined on top of these helpers. Everything else in
-- their bodies (validation, locks, rate limit, idempotency, response shape,
-- error names) is unchanged, with two deliberate ordering changes:
-- * remove_team_member authorizes a caller removing someone else before it
-- looks the target up, so a non-member cannot probe who is in a team.
-- Leaving (removing yourself) keeps its existing behaviour.
-- * NULL inputs (email, role) are rejected by validation instead of
-- slipping through a NULL comparison.
--
-- Both helpers are SECURITY INVOKER and not executable by client roles; the
-- SECURITY DEFINER RPCs call them as their owner. The function-acl allowlist
-- (tests/function-acl.integration.sql) is therefore unaffected.
-- ============================================================================
-- ----------------------------------------------------------------------------
-- 1. Role policy
-- ----------------------------------------------------------------------------
CREATE OR REPLACE FUNCTION public.team_role_at_least_v1(
team_role text,
minimum_role text
)
RETURNS boolean
LANGUAGE sql
IMMUTABLE
PARALLEL SAFE
SET search_path = ''
AS $$
-- Unknown or NULL values rank 0; a requirement that ranks 0 is never met.
SELECT required.rank > 0 AND held.rank >= required.rank
FROM (
SELECT CASE team_role
WHEN 'owner' THEN 3 WHEN 'admin' THEN 2 WHEN 'member' THEN 1 ELSE 0
END AS rank
) AS held
CROSS JOIN (
SELECT CASE minimum_role
WHEN 'owner' THEN 3 WHEN 'admin' THEN 2 WHEN 'member' THEN 1 ELSE 0
END AS rank
) AS required;
$$;
CREATE OR REPLACE FUNCTION public.require_team_role_v1(
target_team_id uuid,
minimum_role text
)
RETURNS text
LANGUAGE plpgsql
STABLE
SET search_path = ''
AS $$
DECLARE
current_user_id uuid := auth.uid();
caller_role text;
BEGIN
IF current_user_id IS NULL THEN
RAISE EXCEPTION 'authentication_required' USING ERRCODE = '42501';
END IF;
SELECT member.role INTO caller_role
FROM public.team_members AS member
WHERE member.team_id = target_team_id AND member.user_id = current_user_id;
IF NOT public.team_role_at_least_v1(caller_role, minimum_role) THEN
RAISE EXCEPTION '%', CASE minimum_role
WHEN 'owner' THEN 'team_owner_required'
WHEN 'admin' THEN 'team_admin_required'
ELSE 'team_member_required'
END
USING ERRCODE = '42501';
END IF;
RETURN caller_role;
END;
$$;
REVOKE ALL ON FUNCTION public.team_role_at_least_v1(text, text) FROM PUBLIC, anon, authenticated;
REVOKE ALL ON FUNCTION public.require_team_role_v1(uuid, text) FROM PUBLIC, anon, authenticated;
-- ----------------------------------------------------------------------------
-- 2. create_team_invite (was 20260821000010)
-- ----------------------------------------------------------------------------
CREATE OR REPLACE FUNCTION public.create_team_invite(
target_team_id uuid,
invited_email text,
invited_role text DEFAULT 'member'
)
RETURNS jsonb
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = ''
AS $$
DECLARE
current_user_id uuid := auth.uid();
current_user_email text;
caller_team_role text;
normalized_email text := lower(btrim(invited_email));
existing_invite public.team_invites;
created_invite public.team_invites;
invite_token text;
BEGIN
IF current_user_id IS NULL THEN
RAISE EXCEPTION 'authentication_required' USING ERRCODE = '42501';
END IF;
IF target_team_id IS NULL
OR normalized_email IS NULL
OR normalized_email !~ '^[^[:space:]@]+@[^[:space:]@]+[.][^[:space:]@]+$'
OR char_length(normalized_email) > 254
OR invited_role IS NULL
OR invited_role NOT IN ('admin', 'member') THEN
RAISE EXCEPTION 'invalid_invite' USING ERRCODE = '22023';
END IF;
SELECT lower(account.email) INTO current_user_email
FROM auth.users AS account
WHERE account.id = current_user_id;
IF current_user_email = normalized_email THEN
RAISE EXCEPTION 'cannot_invite_self' USING ERRCODE = '22023';
END IF;
caller_team_role := public.require_team_role_v1(target_team_id, 'admin');
IF invited_role = 'admin'
AND NOT public.team_role_at_least_v1(caller_team_role, 'owner') THEN
RAISE EXCEPTION 'owner_required_for_admin_invite' USING ERRCODE = '42501';
END IF;
PERFORM pg_advisory_xact_lock(
hashtextextended(target_team_id::text || ':' || normalized_email, 73042)
);
IF (
SELECT count(*)
FROM public.team_invites AS recent_invite
WHERE recent_invite.invited_by = current_user_id
AND recent_invite.created_at >= now() - interval '24 hours'
) >= 50 THEN
RAISE EXCEPTION 'invite_rate_limited' USING ERRCODE = '54000';
END IF;
IF EXISTS (
SELECT 1
FROM public.team_members AS member
JOIN auth.users AS account ON account.id = member.user_id
WHERE member.team_id = target_team_id
AND lower(account.email) = normalized_email
) THEN
RAISE EXCEPTION 'already_team_member' USING ERRCODE = '23505';
END IF;
SELECT active_invite.* INTO existing_invite
FROM public.team_invites AS active_invite
WHERE active_invite.team_id = target_team_id
AND lower(active_invite.email) = normalized_email
AND active_invite.accepted_at IS NULL
ORDER BY active_invite.created_at DESC
LIMIT 1
FOR UPDATE;
IF existing_invite.id IS NOT NULL AND existing_invite.expires_at > now() THEN
IF existing_invite.role <> invited_role THEN
UPDATE public.team_invites
SET role = invited_role
WHERE id = existing_invite.id
RETURNING * INTO existing_invite;
END IF;
RETURN jsonb_build_object(
'id', existing_invite.id,
'team_id', existing_invite.team_id,
'email', existing_invite.email,
'token', existing_invite.token,
'role', existing_invite.role,
'expires_at', existing_invite.expires_at,
'duplicate', true
);
END IF;
IF existing_invite.id IS NOT NULL THEN
DELETE FROM public.team_invites WHERE id = existing_invite.id;
END IF;
invite_token := public.generate_invite_token();
INSERT INTO public.team_invites (
team_id, invited_by, email, role, token
) VALUES (
target_team_id, current_user_id, normalized_email, invited_role, invite_token
)
RETURNING * INTO created_invite;
RETURN jsonb_build_object(
'id', created_invite.id,
'team_id', created_invite.team_id,
'email', created_invite.email,
'token', created_invite.token,
'role', created_invite.role,
'expires_at', created_invite.expires_at,
'duplicate', false
);
END;
$$;
-- ----------------------------------------------------------------------------
-- 3. update_team_member_role (was 20260821000008)
-- ----------------------------------------------------------------------------
CREATE OR REPLACE FUNCTION public.update_team_member_role(
target_team_id uuid,
member_user_id uuid,
new_role text
)
RETURNS jsonb
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = ''
AS $$
DECLARE
current_user_id uuid := auth.uid();
prior_role text;
BEGIN
IF current_user_id IS NULL THEN
RAISE EXCEPTION 'authentication_required' USING ERRCODE = '42501';
END IF;
IF new_role IS NULL OR new_role NOT IN ('admin', 'member') THEN
RAISE EXCEPTION 'invalid_team_role' USING ERRCODE = '22023';
END IF;
PERFORM pg_advisory_xact_lock(hashtextextended(target_team_id::text, 73044));
PERFORM public.require_team_role_v1(target_team_id, 'owner');
SELECT role INTO prior_role FROM public.team_members
WHERE team_id = target_team_id AND user_id = member_user_id
FOR UPDATE;
IF prior_role IS NULL THEN
RAISE EXCEPTION 'team_member_not_found' USING ERRCODE = 'P0002';
END IF;
IF prior_role = 'owner' OR member_user_id = current_user_id THEN
RAISE EXCEPTION 'team_owner_immutable' USING ERRCODE = '42501';
END IF;
UPDATE public.team_members SET role = new_role
WHERE team_id = target_team_id AND user_id = member_user_id;
RETURN jsonb_build_object(
'team_id', target_team_id,
'user_id', member_user_id,
'role', new_role
);
END;
$$;
-- ----------------------------------------------------------------------------
-- 4. remove_team_member (was 20260821000008)
-- ----------------------------------------------------------------------------
CREATE OR REPLACE FUNCTION public.remove_team_member(
target_team_id uuid,
member_user_id uuid
)
RETURNS jsonb
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = ''
AS $$
DECLARE
current_user_id uuid := auth.uid();
is_leaving boolean;
caller_role text;
target_role text;
BEGIN
IF current_user_id IS NULL THEN
RAISE EXCEPTION 'authentication_required' USING ERRCODE = '42501';
END IF;
is_leaving := member_user_id IS NOT DISTINCT FROM current_user_id;
PERFORM pg_advisory_xact_lock(hashtextextended(target_team_id::text, 73045));
-- Removing someone else requires at least admin. Checked before the target
-- lookup so a non-member cannot learn who belongs to the team.
IF NOT is_leaving THEN
caller_role := public.require_team_role_v1(target_team_id, 'admin');
END IF;
SELECT role INTO target_role FROM public.team_members
WHERE team_id = target_team_id AND user_id = member_user_id
FOR UPDATE;
IF target_role IS NULL THEN
RAISE EXCEPTION 'team_member_not_found' USING ERRCODE = 'P0002';
END IF;
IF target_role = 'owner' THEN
RAISE EXCEPTION 'team_owner_cannot_leave' USING ERRCODE = '42501';
END IF;
IF NOT is_leaving
AND target_role = 'admin'
AND NOT public.team_role_at_least_v1(caller_role, 'owner') THEN
RAISE EXCEPTION 'team_admin_required' USING ERRCODE = '42501';
END IF;
DELETE FROM public.team_members
WHERE team_id = target_team_id AND user_id = member_user_id;
RETURN jsonb_build_object(
'team_id', target_team_id,
'user_id', member_user_id,
'removed', true
);
END;
$$;
-- ----------------------------------------------------------------------------
-- 5. cancel_team_invite (was 20260821000008)
-- ----------------------------------------------------------------------------
CREATE OR REPLACE FUNCTION public.cancel_team_invite(invite_id uuid)
RETURNS jsonb
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = ''
AS $$
DECLARE
current_user_id uuid := auth.uid();
invite public.team_invites;
BEGIN
IF current_user_id IS NULL THEN
RAISE EXCEPTION 'authentication_required' USING ERRCODE = '42501';
END IF;
SELECT * INTO invite FROM public.team_invites WHERE id = invite_id FOR UPDATE;
IF invite.id IS NULL OR invite.accepted_at IS NOT NULL THEN
RAISE EXCEPTION 'invite_not_found' USING ERRCODE = 'P0002';
END IF;
-- The inviter may withdraw their own invite; anyone else needs admin.
IF invite.invited_by IS DISTINCT FROM current_user_id THEN
PERFORM public.require_team_role_v1(invite.team_id, 'admin');
END IF;
DELETE FROM public.team_invites WHERE id = invite.id;
RETURN jsonb_build_object('id', invite.id, 'cancelled', true);
END;
$$;
-- CREATE OR REPLACE keeps existing ACLs; restate them so this file is the
-- complete contract for the redefined RPCs.
REVOKE ALL ON FUNCTION public.create_team_invite(uuid, text, text) FROM PUBLIC, anon;
REVOKE ALL ON FUNCTION public.update_team_member_role(uuid, uuid, text) FROM PUBLIC, anon;
REVOKE ALL ON FUNCTION public.remove_team_member(uuid, uuid) FROM PUBLIC, anon;
REVOKE ALL ON FUNCTION public.cancel_team_invite(uuid) FROM PUBLIC, anon;
GRANT EXECUTE ON FUNCTION public.create_team_invite(uuid, text, text) TO authenticated;
GRANT EXECUTE ON FUNCTION public.update_team_member_role(uuid, uuid, text) TO authenticated;
GRANT EXECUTE ON FUNCTION public.remove_team_member(uuid, uuid) TO authenticated;
GRANT EXECUTE ON FUNCTION public.cancel_team_invite(uuid) TO authenticated;

View file

@ -0,0 +1,830 @@
-- ============================================================================
-- 20260929020000_unify_llm_quota_inflight.sql
--
-- One LLM quota ledger and one lock for every path that spends LLM allowance.
--
-- Bug
-- Meeting-document generation held its in-flight unit in a different ledger
-- and under a different lock than llm-proxy / consume_quota:
-- * claim_meeting_document_generation_v1 (20260928000037) locked
-- hashtextextended(user:feature, 0) and counted daily_usage PLUS
-- meeting_document_generation_requests rows in status 'processing';
-- it wrote nothing to daily_usage;
-- * reserve_llm_quota / finalize_llm_quota (20260928020800) and
-- consume_quota (20260928000131) locked hashtextextended(user:feature,
-- 20260928) and counted daily_usage only.
-- So an in-flight document unit was invisible to llm-proxy. With one Opus
-- unit left, a document claim passed (49 < 50), a Talk/command request then
-- reserved the same unit through llm-proxy (daily_usage 49 -> 50), and
-- commit_meeting_document_generation_v1 re-checked the allowance, saw
-- 50 >= 50 and raised generation_quota_exceeded: the paid Opus generation
-- was thrown away (or, with overage credits, a credit the claim promised
-- was covered by the base allowance was spent silently). The two paths also
-- never serialised against each other because the lock keys differed.
--
-- Fix (single source of truth for LLM quota state)
-- 1. public.daily_usage_lock_v1(user, feature) is the only place that knows
-- the per-user/per-feature advisory-lock key for the daily_usage ledger.
-- reserve_llm_quota, finalize_llm_quota, consume_quota and the three
-- meeting-document RPCs all take the lock through it.
-- 2. A meeting-document claim now reserves its unit with reserve_llm_quota
-- (a fresh server-generated reservation id, stored on the request row in
-- llm_reservation_id). The unit is in daily_usage from the moment of the
-- claim, so llm-proxy and consume_quota see it.
-- commit -> finalize_llm_quota(id, true) (the unit stays spent;
-- consumedFrom comes from the reservation)
-- fail -> finalize_llm_quota(id, false) (daily_usage -1, overage
-- credit refunded when the unit came from overage)
-- The separate 'processing'-row in-flight count and commit's allowance
-- re-check / daily_usage insert are gone, so usage is counted once.
-- 3. Crashed workers: the reservation lease (10 minutes) is reclaimed by the
-- next reserve for that user/feature, exactly like llm-proxy. That
-- replaces the old "processing rows older than 10 minutes stop counting"
-- rule.
--
-- Single-path behaviour is unchanged: "allowed" is still
-- usage + in-flight < base limit + overage, because daily_usage now includes
-- in-flight units. What moves: document usage is recorded at claim instead of
-- commit, and an overage credit is taken at claim and refunded on failure
-- (the llm-proxy model).
--
-- Compatibility
-- * RPC signatures and return shapes are unchanged.
-- * Request rows that were already 'processing' when this migration ran have
-- llm_reservation_id NULL. commit charges them through the same ledger at
-- commit time (the previous behaviour), and fail has nothing to release.
-- The same path covers a reservation whose lease expired and was
-- reclaimed before commit arrived.
-- * The reservation id is generated server-side (gen_random_uuid), never the
-- client's idempotency key: idempotency keys are unique only per user,
-- llm_quota_reservations.id is a global primary key.
--
-- Only service_role may call the quota functions. Local verification:
-- tests/meeting-document-generation-quota.integration.sql.
-- ============================================================================
-- ----------------------------------------------------------------------------
-- 1. The single lock for the daily_usage quota ledger.
-- ----------------------------------------------------------------------------
CREATE OR REPLACE FUNCTION public.daily_usage_lock_v1(
p_user_id uuid,
p_feature text
) RETURNS void
LANGUAGE plpgsql
SET search_path = pg_catalog, public
AS $$
BEGIN
IF p_user_id IS NULL OR p_feature IS NULL THEN
RAISE EXCEPTION 'invalid_daily_usage_lock' USING ERRCODE = '22023';
END IF;
-- Seed 20260928 is the key consume_quota and reserve_llm_quota already used,
-- so existing sessions of those functions keep serialising with new ones.
PERFORM pg_advisory_xact_lock(hashtextextended(p_user_id::text || ':' || p_feature, 20260928));
END;
$$;
REVOKE ALL ON FUNCTION public.daily_usage_lock_v1(uuid, text) FROM PUBLIC, anon, authenticated;
GRANT EXECUTE ON FUNCTION public.daily_usage_lock_v1(uuid, text) TO service_role;
COMMENT ON FUNCTION public.daily_usage_lock_v1(uuid, text) IS
'Transaction advisory lock guarding the daily_usage quota ledger for one user/feature. Every quota path (consume_quota, reserve/finalize_llm_quota, meeting-document claim/commit/fail) must take it through this function.';
-- ----------------------------------------------------------------------------
-- 2. Request rows point at the reservation that holds their unit.
-- ----------------------------------------------------------------------------
ALTER TABLE public.meeting_document_generation_requests
ADD COLUMN IF NOT EXISTS llm_reservation_id uuid
REFERENCES public.llm_quota_reservations(id) ON DELETE SET NULL;
CREATE INDEX IF NOT EXISTS meeting_document_generation_llm_reservation_idx
ON public.meeting_document_generation_requests(llm_reservation_id)
WHERE llm_reservation_id IS NOT NULL;
-- The 'processing'-row in-flight count is replaced by the reservation ledger.
DROP INDEX IF EXISTS public.meeting_document_generation_in_flight_idx;
-- ----------------------------------------------------------------------------
-- 3. reserve_llm_quota / finalize_llm_quota / consume_quota: same bodies as
-- 20260928020800 and 20260928000131, lock taken through the helper.
-- ----------------------------------------------------------------------------
CREATE OR REPLACE FUNCTION public.reserve_llm_quota(
p_user_id uuid,
p_reservation_id uuid,
p_feature text,
p_base_limit integer,
p_period text
) RETURNS jsonb
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public, pg_temp
AS $$
DECLARE
existing public.llm_quota_reservations%ROWTYPE;
expired public.llm_quota_reservations%ROWTYPE;
subscription_tier text := 'free';
overage integer := 0;
new_overage integer;
current_count integer := 0;
consumed_from text;
BEGIN
IF p_user_id IS NULL
OR p_reservation_id IS NULL
OR p_feature IS NULL
OR p_feature NOT IN ('llm_haiku', 'llm_sonnet', 'llm_opus')
OR p_base_limit IS NULL
OR p_base_limit < -1
OR p_period IS NULL
OR p_period NOT IN ('daily', 'weekly') THEN
RAISE EXCEPTION 'invalid_llm_quota_reservation' USING ERRCODE = '22023';
END IF;
PERFORM public.daily_usage_lock_v1(p_user_id, p_feature);
SELECT * INTO existing
FROM public.llm_quota_reservations
WHERE id = p_reservation_id
FOR UPDATE;
IF FOUND THEN
IF existing.user_id <> p_user_id OR existing.feature <> p_feature THEN
RAISE EXCEPTION 'llm_quota_reservation_conflict' USING ERRCODE = 'PT409';
END IF;
RETURN jsonb_build_object(
'allowed', existing.status IN ('reserved', 'completed'),
'reservation_id', existing.id,
'status', existing.status,
'current', existing.current_count,
'limit', existing.quota_limit,
'period', existing.quota_period,
'tier', existing.tier,
'overage_credits', existing.overage_after,
'consumed_from', existing.consumed_from
);
END IF;
-- Reclaim crashed requests before calculating the next allowance.
FOR expired IN
SELECT *
FROM public.llm_quota_reservations
WHERE user_id = p_user_id
AND feature = p_feature
AND status = 'reserved'
AND lease_expires_at <= now()
FOR UPDATE
LOOP
UPDATE public.daily_usage
SET count = greatest(count - 1, 0)
WHERE user_id = expired.user_id
AND date = expired.usage_date
AND feature = expired.feature;
IF expired.consumed_from = 'overage' THEN
UPDATE public.subscriptions
SET overage_credits = overage_credits + 1,
updated_at = now()
WHERE user_id = expired.user_id;
END IF;
UPDATE public.llm_quota_reservations
SET status = 'released', finalized_at = now(), release_reason = 'lease_expired'
WHERE id = expired.id;
END LOOP;
SELECT coalesce(tier, 'free'), coalesce(overage_credits, 0)
INTO subscription_tier, overage
FROM public.subscriptions
WHERE user_id = p_user_id
FOR UPDATE;
IF NOT FOUND THEN
subscription_tier := 'free';
overage := 0;
END IF;
-- Not available: never spend credits on a model the tier does not include.
IF p_base_limit = 0 THEN
RETURN jsonb_build_object(
'allowed', false,
'reservation_id', NULL,
'status', 'denied',
'current', 0,
'limit', 0,
'period', p_period,
'tier', subscription_tier,
'overage_credits', overage,
'consumed_from', 'none'
);
END IF;
-- daily_usage already includes units held by in-flight reservations
-- (llm-proxy requests and meeting-document claims alike).
SELECT coalesce(sum(count), 0)::integer INTO current_count
FROM public.daily_usage
WHERE user_id = p_user_id
AND feature = p_feature
AND date >= CASE WHEN p_period = 'weekly' THEN CURRENT_DATE - 6 ELSE CURRENT_DATE END
AND date <= CURRENT_DATE;
IF p_base_limit = -1 THEN
consumed_from := 'unlimited';
ELSIF current_count < p_base_limit THEN
consumed_from := 'base';
ELSE
UPDATE public.subscriptions
SET overage_credits = overage_credits - 1,
updated_at = now()
WHERE user_id = p_user_id
AND overage_credits > 0
RETURNING overage_credits INTO new_overage;
IF NOT FOUND THEN
RETURN jsonb_build_object(
'allowed', false,
'reservation_id', NULL,
'status', 'denied',
'current', current_count,
'limit', p_base_limit,
'period', p_period,
'tier', subscription_tier,
'overage_credits', 0,
'consumed_from', 'none'
);
END IF;
overage := new_overage;
consumed_from := 'overage';
END IF;
INSERT INTO public.daily_usage(user_id, date, feature, count)
VALUES (p_user_id, CURRENT_DATE, p_feature, 1)
ON CONFLICT (user_id, date, feature)
DO UPDATE SET count = public.daily_usage.count + 1;
current_count := current_count + 1;
INSERT INTO public.llm_quota_reservations(
id, user_id, feature, consumed_from, tier, quota_period, quota_limit,
current_count, overage_after, lease_expires_at
) VALUES (
p_reservation_id, p_user_id, p_feature, consumed_from, subscription_tier, p_period, p_base_limit,
current_count, overage, now() + interval '10 minutes'
);
RETURN jsonb_build_object(
'allowed', true,
'reservation_id', p_reservation_id,
'status', 'reserved',
'current', current_count,
'limit', p_base_limit,
'period', p_period,
'tier', subscription_tier,
'overage_credits', overage,
'consumed_from', consumed_from
);
END;
$$;
CREATE OR REPLACE FUNCTION public.finalize_llm_quota(
p_reservation_id uuid,
p_succeeded boolean
) RETURNS jsonb
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public, pg_temp
AS $$
DECLARE
reservation public.llm_quota_reservations%ROWTYPE;
final_status text;
BEGIN
IF p_reservation_id IS NULL OR p_succeeded IS NULL THEN
RAISE EXCEPTION 'invalid_llm_quota_finalize' USING ERRCODE = '22023';
END IF;
SELECT * INTO reservation
FROM public.llm_quota_reservations
WHERE id = p_reservation_id;
IF NOT FOUND THEN
RAISE EXCEPTION 'llm_quota_reservation_not_found' USING ERRCODE = 'P0002';
END IF;
PERFORM public.daily_usage_lock_v1(reservation.user_id, reservation.feature);
SELECT * INTO reservation
FROM public.llm_quota_reservations
WHERE id = p_reservation_id
FOR UPDATE;
IF reservation.status <> 'reserved' THEN
RETURN jsonb_build_object('reservation_id', reservation.id, 'status', reservation.status);
END IF;
IF p_succeeded THEN
final_status := 'completed';
ELSE
UPDATE public.daily_usage
SET count = greatest(count - 1, 0)
WHERE user_id = reservation.user_id
AND date = reservation.usage_date
AND feature = reservation.feature;
IF reservation.consumed_from = 'overage' THEN
UPDATE public.subscriptions
SET overage_credits = overage_credits + 1,
updated_at = now()
WHERE user_id = reservation.user_id;
END IF;
final_status := 'released';
END IF;
UPDATE public.llm_quota_reservations
SET status = final_status,
finalized_at = now(),
release_reason = CASE WHEN p_succeeded THEN NULL ELSE 'provider_failed' END
WHERE id = reservation.id;
RETURN jsonb_build_object('reservation_id', reservation.id, 'status', final_status);
END;
$$;
REVOKE ALL ON FUNCTION public.reserve_llm_quota(uuid, uuid, text, integer, text) FROM PUBLIC, anon, authenticated;
REVOKE ALL ON FUNCTION public.finalize_llm_quota(uuid, boolean) FROM PUBLIC, anon, authenticated;
GRANT EXECUTE ON FUNCTION public.reserve_llm_quota(uuid, uuid, text, integer, text) TO service_role;
GRANT EXECUTE ON FUNCTION public.finalize_llm_quota(uuid, boolean) TO service_role;
CREATE OR REPLACE FUNCTION public.consume_quota(
p_user_id uuid,
p_feature text,
p_base_limit integer,
p_period text DEFAULT 'daily'
) RETURNS jsonb
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public, pg_temp
AS $$
DECLARE
v_window_start date;
v_current integer := 0;
v_overage integer := 0;
v_new_overage integer;
v_consumed_from text;
BEGIN
IF p_user_id IS NULL
OR p_feature IS NULL
OR p_base_limit IS NULL
OR p_base_limit < -1
OR p_period IS NULL
OR p_period NOT IN ('daily', 'weekly') THEN
RAISE EXCEPTION 'invalid_quota_consumption' USING ERRCODE = '22023';
END IF;
-- Serialise read-then-increment for this user/feature.
PERFORM public.daily_usage_lock_v1(p_user_id, p_feature);
SELECT coalesce(overage_credits, 0) INTO v_overage
FROM public.subscriptions
WHERE user_id = p_user_id
FOR UPDATE;
v_overage := coalesce(v_overage, 0);
-- Not available: never spend credits on a feature the tier does not include.
IF p_base_limit = 0 THEN
RETURN jsonb_build_object(
'allowed', false,
'current', 0,
'limit', 0,
'overage_credits', v_overage,
'consumed_from', 'none'
);
END IF;
v_window_start := CASE WHEN p_period = 'weekly' THEN CURRENT_DATE - 6 ELSE CURRENT_DATE END;
SELECT coalesce(sum(count), 0)::integer INTO v_current
FROM public.daily_usage
WHERE user_id = p_user_id
AND feature = p_feature
AND date >= v_window_start
AND date <= CURRENT_DATE;
IF p_base_limit = -1 THEN
v_consumed_from := 'unlimited';
ELSIF v_current < p_base_limit THEN
v_consumed_from := 'base';
ELSE
UPDATE public.subscriptions
SET overage_credits = overage_credits - 1,
updated_at = now()
WHERE user_id = p_user_id
AND overage_credits > 0
RETURNING overage_credits INTO v_new_overage;
IF NOT FOUND THEN
RETURN jsonb_build_object(
'allowed', false,
'current', v_current,
'limit', p_base_limit,
'overage_credits', 0,
'consumed_from', 'none'
);
END IF;
v_overage := v_new_overage;
v_consumed_from := 'overage';
END IF;
INSERT INTO public.daily_usage (user_id, date, feature, count)
VALUES (p_user_id, CURRENT_DATE, p_feature, 1)
ON CONFLICT (user_id, date, feature) DO UPDATE
SET count = public.daily_usage.count + 1;
RETURN jsonb_build_object(
'allowed', true,
'current', v_current + 1,
'limit', p_base_limit,
'overage_credits', v_overage,
'consumed_from', v_consumed_from
);
END;
$$;
REVOKE ALL ON FUNCTION public.consume_quota(uuid, text, integer, text) FROM PUBLIC, anon, authenticated;
GRANT EXECUTE ON FUNCTION public.consume_quota(uuid, text, integer, text) TO service_role;
-- ----------------------------------------------------------------------------
-- 4. Meeting-document claim: reserve the unit in the shared ledger.
-- ----------------------------------------------------------------------------
CREATE OR REPLACE FUNCTION public.claim_meeting_document_generation_v1(
p_actor_id uuid,
p_idempotency_key uuid,
p_meeting_id uuid,
p_template_id uuid,
p_title text,
p_model text
)
RETURNS jsonb
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = pg_catalog, public, auth, extensions
AS $$
DECLARE
meeting_row public.meetings;
template_row public.user_templates;
transcript_value text;
transcript_digest text;
request_digest text;
request_row public.meeting_document_generation_requests;
inserted boolean := false;
tier_value text := 'free';
quota_feature_value text;
quota_limit_value integer;
quota_period_value text;
reservation_id_value uuid;
reservation jsonb;
is_replay boolean := false;
safe_title text := trim(p_title);
BEGIN
IF p_actor_id IS NULL OR p_idempotency_key IS NULL OR p_meeting_id IS NULL OR p_template_id IS NULL THEN
RAISE EXCEPTION 'generation_identifiers_required' USING ERRCODE = '22023';
END IF;
IF char_length(safe_title) NOT BETWEEN 1 AND 160 THEN
RAISE EXCEPTION 'invalid_document_title' USING ERRCODE = '22023';
END IF;
IF p_model NOT IN ('claude-haiku-4-5-20251001', 'claude-sonnet-4-6', 'claude-opus-4-6') THEN
RAISE EXCEPTION 'invalid_generation_model' USING ERRCODE = '22023';
END IF;
SELECT * INTO meeting_row FROM public.meetings WHERE id = p_meeting_id;
IF meeting_row.id IS NULL THEN
RAISE EXCEPTION 'meeting_not_found' USING ERRCODE = 'P0002';
END IF;
IF meeting_row.user_id <> p_actor_id AND NOT (
meeting_row.team_id IS NOT NULL
AND (
EXISTS (
SELECT 1 FROM public.teams
WHERE id = meeting_row.team_id AND owner_id = p_actor_id
)
OR EXISTS (
SELECT 1 FROM public.team_members
WHERE team_id = meeting_row.team_id
AND user_id = p_actor_id
AND role IN ('owner', 'admin')
)
)
) THEN
RAISE EXCEPTION 'meeting_generation_forbidden' USING ERRCODE = '42501';
END IF;
SELECT * INTO template_row
FROM public.user_templates
WHERE id = p_template_id
AND user_id = p_actor_id
AND template_kind = 'meeting_document';
IF template_row.id IS NULL THEN
RAISE EXCEPTION 'meeting_template_not_found' USING ERRCODE = 'P0002';
END IF;
SELECT nullif(string_agg(
CASE WHEN nullif(trim(transcript.speaker), '') IS NULL
THEN transcript.text
ELSE trim(transcript.speaker) || ': ' || transcript.text
END,
E'\n' ORDER BY transcript.segment_index
), '')
INTO transcript_value
FROM public.transcripts AS transcript
WHERE transcript.meeting_id = meeting_row.id;
transcript_value := coalesce(
transcript_value,
nullif(trim(meeting_row.edited_transcript), ''),
nullif(trim(meeting_row.raw_transcript), '')
);
IF transcript_value IS NULL THEN
RAISE EXCEPTION 'meeting_transcript_required' USING ERRCODE = '22023';
END IF;
IF char_length(transcript_value) > 48000 THEN
RAISE EXCEPTION 'meeting_transcript_too_large' USING ERRCODE = '22023';
END IF;
SELECT coalesce(subscription.tier, 'free')
INTO tier_value
FROM public.subscriptions AS subscription
WHERE subscription.user_id = p_actor_id;
tier_value := coalesce(tier_value, 'free');
IF tier_value = 'free' AND p_model <> 'claude-haiku-4-5-20251001' THEN
RAISE EXCEPTION 'generation_model_not_allowed' USING ERRCODE = '42501';
END IF;
quota_feature_value := CASE
WHEN p_model LIKE '%sonnet%' THEN 'llm_sonnet'
WHEN p_model LIKE '%opus%' THEN 'llm_opus'
ELSE 'llm_haiku'
END;
quota_limit_value := CASE
WHEN tier_value = 'free' AND quota_feature_value = 'llm_haiku' THEN 250
WHEN tier_value = 'free' THEN 0
WHEN tier_value = 'pro' AND quota_feature_value = 'llm_haiku' THEN 1500
WHEN tier_value = 'pro' AND quota_feature_value = 'llm_sonnet' THEN 300
WHEN tier_value = 'pro' AND quota_feature_value = 'llm_opus' THEN 50
WHEN tier_value = 'pro_plus' AND quota_feature_value = 'llm_haiku' THEN -1
WHEN tier_value = 'pro_plus' AND quota_feature_value = 'llm_sonnet' THEN 1500
WHEN tier_value = 'pro_plus' AND quota_feature_value = 'llm_opus' THEN 300
WHEN tier_value = 'team' AND quota_feature_value = 'llm_haiku' THEN -1
WHEN tier_value = 'team' AND quota_feature_value = 'llm_sonnet' THEN 3000
WHEN tier_value = 'team' AND quota_feature_value = 'llm_opus' THEN 600
WHEN tier_value = 'enterprise' THEN -1
ELSE 0
END;
quota_period_value := CASE WHEN tier_value = 'free' THEN 'weekly' ELSE 'daily' END;
IF quota_limit_value = 0 THEN
RAISE EXCEPTION 'generation_quota_exceeded' USING ERRCODE = 'P0001';
END IF;
-- The shared ledger lock: claims, commits, fails, llm-proxy reservations and
-- consume_quota for one user/feature all serialise here.
PERFORM public.daily_usage_lock_v1(p_actor_id, quota_feature_value);
SELECT EXISTS (
SELECT 1 FROM public.meeting_document_generation_requests
WHERE user_id = p_actor_id AND idempotency_key = p_idempotency_key
) INTO is_replay;
-- A replay never starts provider work, so it takes no unit.
IF NOT is_replay THEN
reservation_id_value := gen_random_uuid();
reservation := public.reserve_llm_quota(
p_actor_id, reservation_id_value, quota_feature_value, quota_limit_value, quota_period_value
);
IF (reservation->>'allowed')::boolean IS NOT TRUE THEN
RAISE EXCEPTION 'generation_quota_exceeded' USING ERRCODE = 'P0001';
END IF;
END IF;
transcript_digest := encode(extensions.digest(transcript_value, 'sha256'), 'hex');
request_digest := encode(extensions.digest(
jsonb_build_object(
'meeting_id', meeting_row.id,
'template_id', template_row.id,
'template_revision', template_row.revision,
'transcript_hash', transcript_digest,
'title', safe_title,
'model', p_model
)::text,
'sha256'
), 'hex');
INSERT INTO public.meeting_document_generation_requests(
user_id, idempotency_key, meeting_id, template_id, request_hash,
document_title, model, quota_feature, quota_limit, quota_period,
template_revision, template_type, transcript_hash, status, llm_reservation_id
)
VALUES (
p_actor_id, p_idempotency_key, meeting_row.id, template_row.id, request_digest,
safe_title, p_model, quota_feature_value, quota_limit_value, quota_period_value,
template_row.revision, template_row.template_type, transcript_digest, 'processing',
reservation_id_value
)
ON CONFLICT DO NOTHING
RETURNING true INTO inserted;
SELECT * INTO request_row
FROM public.meeting_document_generation_requests
WHERE user_id = p_actor_id AND idempotency_key = p_idempotency_key;
IF NOT coalesce(inserted, false) THEN
IF request_row.request_hash <> request_digest THEN
RAISE EXCEPTION 'generation_idempotency_conflict' USING ERRCODE = '22023';
END IF;
-- A concurrent claim for the same key won the insert; give our unit back.
IF reservation_id_value IS NOT NULL THEN
PERFORM public.finalize_llm_quota(reservation_id_value, false);
END IF;
END IF;
RETURN jsonb_build_object(
'claimed', coalesce(inserted, false),
'status', request_row.status,
'documentId', request_row.document_id,
'meetingTitle', coalesce(meeting_row.title, 'Meeting'),
'documentTitle', request_row.document_title,
'templateType', request_row.template_type,
'systemPrompt', CASE WHEN coalesce(inserted, false) THEN template_row.system_prompt ELSE NULL END,
'transcript', CASE WHEN coalesce(inserted, false) THEN transcript_value ELSE NULL END,
'model', request_row.model
);
END;
$$;
REVOKE ALL ON FUNCTION public.claim_meeting_document_generation_v1(uuid, uuid, uuid, uuid, text, text)
FROM PUBLIC, anon, authenticated;
GRANT EXECUTE ON FUNCTION public.claim_meeting_document_generation_v1(uuid, uuid, uuid, uuid, text, text)
TO service_role;
-- ----------------------------------------------------------------------------
-- 5. Meeting-document fail: release the reserved unit.
-- ----------------------------------------------------------------------------
CREATE OR REPLACE FUNCTION public.fail_meeting_document_generation_v1(
p_actor_id uuid,
p_idempotency_key uuid,
p_error_code text
)
RETURNS boolean
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = pg_catalog, public
AS $$
DECLARE
changed integer;
held_reservation uuid;
BEGIN
IF p_error_code NOT IN (
'provider_unavailable', 'provider_timeout', 'provider_request_failed',
'provider_invalid_response', 'quota_exceeded', 'commit_failed'
) THEN
RAISE EXCEPTION 'invalid_generation_error_code' USING ERRCODE = '22023';
END IF;
UPDATE public.meeting_document_generation_requests
SET status = 'failed', error_code = p_error_code, completed_at = now()
WHERE user_id = p_actor_id
AND idempotency_key = p_idempotency_key
AND status = 'processing'
RETURNING llm_reservation_id INTO held_reservation;
GET DIAGNOSTICS changed = ROW_COUNT;
-- Rows claimed before 20260929020000 hold no reservation: nothing to release.
-- finalize is a no-op for a reservation whose lease was already reclaimed.
IF changed > 0 AND held_reservation IS NOT NULL THEN
PERFORM public.finalize_llm_quota(held_reservation, false);
END IF;
RETURN changed > 0;
END;
$$;
REVOKE ALL ON FUNCTION public.fail_meeting_document_generation_v1(uuid, uuid, text)
FROM PUBLIC, anon, authenticated;
GRANT EXECUTE ON FUNCTION public.fail_meeting_document_generation_v1(uuid, uuid, text)
TO service_role;
-- ----------------------------------------------------------------------------
-- 6. Meeting-document commit: settle the reserved unit, never re-evaluate it.
-- ----------------------------------------------------------------------------
CREATE OR REPLACE FUNCTION public.commit_meeting_document_generation_v1(
p_actor_id uuid,
p_idempotency_key uuid,
p_content text,
p_latency_ms integer,
p_input_tokens integer DEFAULT NULL,
p_output_tokens integer DEFAULT NULL
)
RETURNS jsonb
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = pg_catalog, public
AS $$
DECLARE
request_row public.meeting_document_generation_requests;
document_row public.meeting_documents;
settled jsonb;
reservation jsonb;
charged_reservation uuid;
consumed_from text;
BEGIN
IF char_length(trim(p_content)) NOT BETWEEN 1 AND 100000
OR p_latency_ms NOT BETWEEN 0 AND 600000
OR (p_input_tokens IS NOT NULL AND p_input_tokens < 0)
OR (p_output_tokens IS NOT NULL AND p_output_tokens < 0) THEN
RAISE EXCEPTION 'invalid_generation_result' USING ERRCODE = '22023';
END IF;
SELECT * INTO request_row
FROM public.meeting_document_generation_requests
WHERE user_id = p_actor_id AND idempotency_key = p_idempotency_key
FOR UPDATE;
IF request_row.user_id IS NULL THEN
RAISE EXCEPTION 'generation_request_not_found' USING ERRCODE = 'P0002';
END IF;
IF request_row.status = 'succeeded' THEN
SELECT * INTO document_row FROM public.meeting_documents WHERE id = request_row.document_id;
RETURN jsonb_build_object('idempotent', true, 'document', to_jsonb(document_row));
END IF;
IF request_row.status <> 'processing' THEN
RAISE EXCEPTION 'generation_request_not_committable' USING ERRCODE = '55000';
END IF;
PERFORM public.daily_usage_lock_v1(p_actor_id, request_row.quota_feature);
charged_reservation := request_row.llm_reservation_id;
IF charged_reservation IS NOT NULL THEN
-- The claim already holds the unit: spend it (no allowance re-check).
settled := public.finalize_llm_quota(charged_reservation, true);
END IF;
IF settled->>'status' = 'completed' THEN
SELECT reservation_row.consumed_from
INTO consumed_from
FROM public.llm_quota_reservations AS reservation_row
WHERE reservation_row.id = charged_reservation;
ELSE
-- No unit is held: a row claimed before 20260929020000, or a reservation
-- whose lease expired and was reclaimed before commit arrived. Charge one
-- unit now through the same ledger (the previous commit-time rule).
charged_reservation := gen_random_uuid();
reservation := public.reserve_llm_quota(
p_actor_id, charged_reservation, request_row.quota_feature,
request_row.quota_limit, request_row.quota_period
);
IF (reservation->>'allowed')::boolean IS NOT TRUE THEN
RAISE EXCEPTION 'generation_quota_exceeded' USING ERRCODE = 'P0001';
END IF;
PERFORM public.finalize_llm_quota(charged_reservation, true);
consumed_from := reservation->>'consumed_from';
END IF;
INSERT INTO public.meeting_documents(
meeting_id, user_id, template_type, title, content, prompt_used,
llm_model, llm_latency_ms, template_id, generation_idempotency_key
)
VALUES (
request_row.meeting_id,
p_actor_id,
request_row.template_type,
request_row.document_title,
trim(p_content),
'template:' || request_row.template_id::text || '@' || request_row.template_revision::text,
request_row.model,
p_latency_ms,
request_row.template_id,
p_idempotency_key
)
RETURNING * INTO document_row;
INSERT INTO public.meeting_document_generation_audit(
user_id, meeting_id, template_id, document_id, idempotency_key,
model, template_revision, transcript_hash, input_tokens, output_tokens, latency_ms
)
VALUES (
p_actor_id, request_row.meeting_id, request_row.template_id, document_row.id,
p_idempotency_key, request_row.model, request_row.template_revision,
request_row.transcript_hash, p_input_tokens, p_output_tokens, p_latency_ms
);
UPDATE public.meeting_document_generation_requests
SET status = 'succeeded',
document_id = document_row.id,
llm_reservation_id = charged_reservation,
error_code = NULL,
completed_at = now()
WHERE user_id = p_actor_id AND idempotency_key = p_idempotency_key;
RETURN jsonb_build_object(
'idempotent', false,
'consumedFrom', consumed_from,
'document', to_jsonb(document_row)
);
END;
$$;
REVOKE ALL ON FUNCTION public.commit_meeting_document_generation_v1(uuid, uuid, text, integer, integer, integer)
FROM PUBLIC, anon, authenticated;
GRANT EXECUTE ON FUNCTION public.commit_meeting_document_generation_v1(uuid, uuid, text, integer, integer, integer)
TO service_role;

View file

@ -0,0 +1,102 @@
-- ============================================================================
-- Knowledge vector search: rank exactly within the caller's visible chunks
-- ============================================================================
--
-- Problem (20260410000004_pgvector_knowledge.sql)
-- * idx_knowledge_chunks_embedding was an IVFFlat index (lists = 100) built
-- in the same migration that added the embedding column, so it was
-- trained on zero vectors and its centroids are meaningless. Nothing ever
-- ran the REINDEX that the comment asked for.
-- * match_knowledge_chunks ended with
-- ORDER BY kc.embedding <=> query_embedding LIMIT match_count
-- which lets the planner walk that ANN index across ALL tenants with the
-- default ivfflat.probes = 1, and only then apply the user/team filter,
-- the similarity threshold and RLS. A user whose chunks are a small share
-- of the table usually got 0-1 rows although exact matches existed, so
-- search-knowledge returned `results: []` and answers were generated
-- without the user's documents.
--
-- Fix
-- 1) Drop the broken IVFFlat index. It is not replaced by another ANN index
-- (HNSW etc.): match_knowledge_chunks below never orders the whole table
-- by distance, so an ANN index could not serve it and would only add
-- write cost to embed-chunks. Per-caller candidate sets (own documents +
-- teams the caller belongs to) are small and are reached through
-- idx_knowledge_chunks_document.
-- 2) match_knowledge_chunks first materializes the ids of the documents the
-- caller can see, computes the exact cosine distance for their chunks
-- only, and ranks inside that set. The MATERIALIZED CTEs are an
-- optimization fence: the planner cannot turn the ORDER BY back into a
-- global approximate index scan, so recall is exact regardless of what
-- indexes exist on knowledge_chunks.
-- 3) match_count is clamped to [0, 50] (NULL -> default 5). LIMIT NULL used
-- to mean "no limit". The search-knowledge edge function already caps
-- requests at 20, so it is unaffected.
--
-- Signature, return columns, SECURITY INVOKER (RLS still applies) and the
-- existing EXECUTE grants are unchanged (CREATE OR REPLACE keeps the ACL).
-- ============================================================================
DROP INDEX IF EXISTS public.idx_knowledge_chunks_embedding;
CREATE OR REPLACE FUNCTION public.match_knowledge_chunks(
query_embedding vector(1536),
match_count integer DEFAULT 5,
similarity_threshold double precision DEFAULT 0.5
)
RETURNS TABLE (
id uuid,
document_id uuid,
chunk_index integer,
content text,
similarity double precision
)
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
-- Upper bound on rows one call may return. Keep >= search-knowledge's
-- MAX_MATCH_COUNT (20).
max_match_count CONSTANT integer := 50;
effective_count integer := LEAST(GREATEST(COALESCE(match_count, 5), 0), max_match_count);
BEGIN
IF effective_count = 0 OR query_embedding IS NULL THEN
RETURN;
END IF;
RETURN QUERY
WITH visible_documents AS MATERIALIZED (
SELECT kd.id AS visible_document_id
FROM public.knowledge_documents kd
WHERE
kd.user_id = auth.uid()
OR (
kd.team_id IS NOT NULL
AND kd.team_id IN (
SELECT tm.team_id FROM public.team_members tm WHERE tm.user_id = auth.uid()
)
)
),
candidates AS MATERIALIZED (
SELECT
kc.id AS chunk_id,
kc.document_id AS chunk_document_id,
kc.chunk_index AS chunk_position,
kc.content AS chunk_content,
(kc.embedding <=> query_embedding)::double precision AS distance
FROM visible_documents vd
INNER JOIN public.knowledge_chunks kc ON kc.document_id = vd.visible_document_id
WHERE kc.embedding IS NOT NULL
)
SELECT
c.chunk_id,
c.chunk_document_id,
c.chunk_position,
c.chunk_content,
(1 - c.distance)::double precision AS similarity
FROM candidates c
WHERE (1 - c.distance) > similarity_threshold
ORDER BY c.distance, c.chunk_id
LIMIT effective_count;
END;
$$;

View file

@ -0,0 +1,345 @@
-- A re-record that fails AFTER upload must not break the meeting it re-records.
--
-- 20260929002700 stopped begin from wiping the previous content and taught
-- cancel to fall back to 'completed', but the two post-upload failure paths
-- were left as defined in 20260821000022:
-- * mobile_mark_meeting_processing_failure(p_terminal => true)
-- * mobile_fail_meeting_recording (terminal upload failure, queued item
-- discarded by the user)
-- Both set status = 'error' unconditionally. After mobile_begin_meeting_processing
-- had already pointed meetings.audio_storage_key / duration_ms at the failed
-- capture, a completed meeting was left marked failed on every device, with
-- playback pointing at audio that never produced its transcript, and the failed
-- capture's audio_files row stayed linked (so the retention trigger never
-- queued it for purge).
--
-- One rule now covers every failure path of a meeting that still holds earlier
-- content (mobile_meeting_has_content_v1):
-- status -> 'completed', error_message cleared
-- audio_storage_key, duration_ms
-- -> restored from the capture that produced the content (the
-- audio of the latest succeeded transcription job, or for
-- content that came from elsewhere, the linked audio that
-- no mobile capture job owns / the transcript span)
-- failed capture -> its audio_files row is detached (meeting_id = NULL),
-- which marks it deleted and queues its object for purge
-- (20260929000004). A later retry of the same local item
-- inserts a fresh row for the same content-addressed key,
-- which cancels that purge.
-- A meeting without earlier content keeps the original 'error' outcome and its
-- audio stays linked so the queued item can be retried.
--
-- started_at is deliberately NOT frozen during a re-record: memo offsets taken
-- while re-recording (computeMemoTimestamp) are anchored to it. Restoring the
-- pre-re-record value needs a stored copy, which this schema does not have.
--
-- Signatures, grants and return shapes of the public RPCs are unchanged.
BEGIN;
-- Single definition of "this meeting still holds content from an earlier
-- recording" (previously inlined in mobile_cancel_meeting_recording).
CREATE OR REPLACE FUNCTION public.mobile_meeting_has_content_v1(p_meeting_id uuid)
RETURNS boolean
LANGUAGE sql
STABLE
SET search_path = ''
AS $$
SELECT EXISTS (
SELECT 1
FROM public.meetings m
WHERE m.id = p_meeting_id
AND (
m.raw_transcript IS NOT NULL
OR m.edited_transcript IS NOT NULL
OR m.minutes_markdown IS NOT NULL
OR m.minutes_json IS NOT NULL
)
)
OR EXISTS (
SELECT 1 FROM public.transcripts t WHERE t.meeting_id = p_meeting_id
);
$$;
-- Internal: return a meeting with earlier content to 'completed' after its
-- current capture failed. Only called from the SECURITY DEFINER RPCs below,
-- which have already verified that p_user_id = auth.uid() owns the meeting.
CREATE OR REPLACE FUNCTION public.mobile_restore_meeting_after_failed_capture_v1(
p_meeting_id uuid,
p_user_id uuid,
p_failed_audio_file_id uuid
)
RETURNS public.meetings
LANGUAGE plpgsql
SET search_path = ''
AS $$
DECLARE
kept_job public.processing_jobs;
kept_audio public.audio_files;
failed_key text;
detached_keys text[];
restored_duration bigint;
result public.meetings;
BEGIN
-- 1) The capture that produced the content still on the meeting. A successful
-- completion detaches every older audio row, so the newest succeeded job
-- whose audio is still linked is the live one.
SELECT j.* INTO kept_job
FROM public.processing_jobs j
JOIN public.audio_files a ON a.id = j.audio_file_id
WHERE j.user_id = p_user_id
AND j.meeting_id = p_meeting_id
AND j.kind = 'transcription'
AND j.status = 'succeeded'
AND a.user_id = p_user_id
AND a.meeting_id = p_meeting_id
AND a.upload_status = 'uploaded'
AND a.id IS DISTINCT FROM p_failed_audio_file_id
ORDER BY j.completed_at DESC NULLS LAST, j.updated_at DESC, j.id
LIMIT 1;
IF kept_job.id IS NOT NULL THEN
SELECT * INTO kept_audio
FROM public.audio_files
WHERE id = kept_job.audio_file_id;
ELSE
-- Content that did not come from a mobile capture (desktop sync, import):
-- keep the newest uploaded audio no mobile capture job owns.
SELECT a.* INTO kept_audio
FROM public.audio_files a
WHERE a.user_id = p_user_id
AND a.meeting_id = p_meeting_id
AND a.upload_status = 'uploaded'
AND a.id IS DISTINCT FROM p_failed_audio_file_id
AND NOT EXISTS (
SELECT 1 FROM public.processing_jobs j
WHERE j.audio_file_id = a.id
AND j.meeting_id = p_meeting_id
AND j.kind = 'transcription'
AND j.status <> 'succeeded'
)
ORDER BY a.created_at DESC, a.id
LIMIT 1;
END IF;
SELECT a.storage_key INTO failed_key
FROM public.audio_files a
WHERE a.id = p_failed_audio_file_id
AND a.user_id = p_user_id;
-- 2) Detach the failed capture(s): only rows positively identified as a
-- capture that did not produce the content (the failed job's audio, an
-- upload that never finished, audio of a job that did not succeed).
-- Anything else linked (audio of content from elsewhere) is left alone.
WITH detached AS (
UPDATE public.audio_files a
SET meeting_id = NULL
WHERE a.user_id = p_user_id
AND a.meeting_id = p_meeting_id
AND a.id IS DISTINCT FROM kept_audio.id
AND (
a.id = p_failed_audio_file_id
OR a.upload_status <> 'uploaded'
OR EXISTS (
SELECT 1 FROM public.processing_jobs j
WHERE j.audio_file_id = a.id
AND j.meeting_id = p_meeting_id
AND j.kind = 'transcription'
AND j.status <> 'succeeded'
)
)
RETURNING a.storage_key
)
SELECT COALESCE(array_agg(d.storage_key), ARRAY[]::text[])
INTO detached_keys
FROM detached d;
-- 3) Timing of the live capture: what completion recorded, else the audio,
-- else the transcript span. Unknown -> leave the column as it is.
restored_duration := COALESCE(
CASE
WHEN (kept_job.result ->> 'duration_ms') ~ '^[0-9]{1,18}$'
THEN (kept_job.result ->> 'duration_ms')::bigint
END,
kept_audio.duration_ms,
(
SELECT max(t.timestamp_ms::bigint + COALESCE(t.duration_ms, 0))
FROM public.transcripts t
WHERE t.meeting_id = p_meeting_id
)
);
UPDATE public.meetings m
SET status = 'completed',
error_message = NULL,
ended_at = COALESCE(m.ended_at, now()),
duration_ms = COALESCE(restored_duration, m.duration_ms),
-- Only repoint playback that currently targets the failed capture; a key
-- the failure never touched (upload failed before processing began) stays.
audio_storage_key = CASE
WHEN m.audio_storage_key = ANY (detached_keys)
OR m.audio_storage_key = failed_key
THEN kept_audio.storage_key
ELSE m.audio_storage_key
END
WHERE m.id = p_meeting_id
AND m.user_id = p_user_id
RETURNING m.* INTO result;
RETURN result;
END;
$$;
-- Same as 20260821000022, plus: a terminal failure of a meeting with earlier
-- content restores it instead of marking it 'error'.
CREATE OR REPLACE FUNCTION public.mobile_mark_meeting_processing_failure(
p_meeting_id uuid,
p_idempotency_key text,
p_error_code text,
p_error_message text,
p_terminal boolean DEFAULT false
)
RETURNS public.processing_jobs
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = ''
AS $$
DECLARE
current_user_id uuid := auth.uid();
result public.processing_jobs;
BEGIN
IF current_user_id IS NULL THEN
RAISE EXCEPTION 'authentication required' USING ERRCODE = '42501';
END IF;
IF length(COALESCE(p_error_code, '')) NOT BETWEEN 1 AND 64
OR length(COALESCE(p_error_message, '')) NOT BETWEEN 1 AND 500 THEN
RAISE EXCEPTION 'invalid processing failure' USING ERRCODE = '22023';
END IF;
UPDATE public.processing_jobs
SET status = CASE WHEN p_terminal THEN 'failed' ELSE 'queued' END,
progress = CASE WHEN p_terminal THEN progress ELSE LEAST(progress, 69) END,
error_code = p_error_code,
error_message = p_error_message,
completed_at = CASE WHEN p_terminal THEN now() ELSE NULL END
WHERE user_id = current_user_id
AND meeting_id = p_meeting_id
AND idempotency_key = p_idempotency_key
AND kind = 'transcription'
AND status <> 'succeeded'
RETURNING * INTO result;
IF result.id IS NULL THEN
RAISE EXCEPTION 'processing job not found' USING ERRCODE = '22023';
END IF;
IF p_terminal AND public.mobile_meeting_has_content_v1(p_meeting_id) THEN
PERFORM public.mobile_restore_meeting_after_failed_capture_v1(
p_meeting_id, current_user_id, result.audio_file_id
);
ELSE
UPDATE public.meetings
SET status = CASE WHEN p_terminal THEN 'error' ELSE 'processing' END,
error_message = CASE WHEN p_terminal THEN p_error_message ELSE NULL END
WHERE id = p_meeting_id AND user_id = current_user_id;
END IF;
RETURN result;
END;
$$;
-- Same as 20260821000022, plus the earlier-content restore.
CREATE OR REPLACE FUNCTION public.mobile_fail_meeting_recording(
p_meeting_id uuid,
p_error_message text
)
RETURNS public.meetings
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = ''
AS $$
DECLARE
current_user_id uuid := auth.uid();
result public.meetings;
BEGIN
IF current_user_id IS NULL THEN
RAISE EXCEPTION 'authentication required' USING ERRCODE = '42501';
END IF;
IF length(COALESCE(p_error_message, '')) NOT BETWEEN 1 AND 500 THEN
RAISE EXCEPTION 'invalid recording failure' USING ERRCODE = '22023';
END IF;
-- Ownership first (and lock the row) so the restore helper only ever runs
-- on the caller's own meeting.
PERFORM 1 FROM public.meetings
WHERE id = p_meeting_id AND user_id = current_user_id
FOR UPDATE;
IF NOT FOUND THEN
RAISE EXCEPTION 'meeting not found or not owned' USING ERRCODE = '42501';
END IF;
IF public.mobile_meeting_has_content_v1(p_meeting_id) THEN
RETURN public.mobile_restore_meeting_after_failed_capture_v1(
p_meeting_id, current_user_id, NULL
);
END IF;
UPDATE public.meetings
SET status = 'error',
ended_at = COALESCE(ended_at, now()),
error_message = p_error_message
WHERE id = p_meeting_id AND user_id = current_user_id
RETURNING * INTO result;
RETURN result;
END;
$$;
-- Same behavior as 20260929002700; the content rule now comes from the shared
-- helper instead of an inlined copy.
CREATE OR REPLACE FUNCTION public.mobile_cancel_meeting_recording(p_meeting_id uuid)
RETURNS public.meetings
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = ''
AS $$
DECLARE
current_user_id uuid := auth.uid();
has_content boolean;
result public.meetings;
BEGIN
IF current_user_id IS NULL THEN
RAISE EXCEPTION 'authentication required' USING ERRCODE = '42501';
END IF;
has_content := public.mobile_meeting_has_content_v1(p_meeting_id);
UPDATE public.meetings m
SET status = CASE WHEN has_content THEN 'completed' ELSE 'error' END,
ended_at = now(),
error_message = CASE
WHEN has_content THEN NULL
ELSE 'Recording was cancelled before processing.'
END
WHERE m.id = p_meeting_id
AND m.user_id = current_user_id
AND m.status = 'recording'
RETURNING m.* INTO result;
IF result.id IS NULL THEN
RAISE EXCEPTION 'active meeting recording not found' USING ERRCODE = '22023';
END IF;
RETURN result;
END;
$$;
-- Helpers are internal: never callable through PostgREST.
REVOKE ALL ON FUNCTION public.mobile_meeting_has_content_v1(uuid)
FROM PUBLIC, anon, authenticated;
REVOKE ALL ON FUNCTION public.mobile_restore_meeting_after_failed_capture_v1(uuid, uuid, uuid)
FROM PUBLIC, anon, authenticated;
REVOKE ALL ON FUNCTION public.mobile_mark_meeting_processing_failure(uuid, text, text, text, boolean) FROM PUBLIC, anon;
REVOKE ALL ON FUNCTION public.mobile_fail_meeting_recording(uuid, text) FROM PUBLIC, anon;
REVOKE ALL ON FUNCTION public.mobile_cancel_meeting_recording(uuid) FROM PUBLIC, anon;
GRANT EXECUTE ON FUNCTION public.mobile_mark_meeting_processing_failure(uuid, text, text, text, boolean) TO authenticated;
GRANT EXECUTE ON FUNCTION public.mobile_fail_meeting_recording(uuid, text) TO authenticated;
GRANT EXECUTE ON FUNCTION public.mobile_cancel_meeting_recording(uuid) TO authenticated;
COMMIT;

View file

@ -0,0 +1,380 @@
-- ============================================================================
-- Payple: a refund of an older order must not revoke the current period
--
-- apply_payment_provider_event checked a non-entitled (revoking) event only
-- against subscriptions.provider and provider_resource_id. For Payple that is
-- the billing-key payer id, shared by every order charged on the key, and
-- p_provider_order_id was ignored for revocations. A confirmed cancellation
-- webhook for last month's order (a console refund of a duplicate or courtesy
-- charge) therefore reset the whole subscription to free, dropping the period
-- paid by the current order and stopping renewals.
--
-- The payple-webhook edge function now ignores such cancellations itself
-- (webhook-policy.ts, reason 'canceled_order_not_current'). This migration
-- closes the remaining window where a renewal changes payple_pay_oid between
-- the edge function's read and this function's per-user advisory lock.
--
-- Only the new order-scope guard is added; the body is otherwise identical to
-- 20260821000003_payment_provider_serialization.sql. CREATE OR REPLACE keeps
-- the existing owner and grants (service_role only).
-- ============================================================================
BEGIN;
-- Apply one authoritative provider event. Provider ownership is strict: an
-- event can never overwrite another provider. A cancellation can affect only
-- the exact provider resource currently owning the entitlement.
CREATE OR REPLACE FUNCTION public.apply_payment_provider_event(
p_user_id uuid,
p_provider text,
p_event_id text,
p_event_created_at timestamptz,
p_event_type text,
p_payload_digest text,
p_provider_resource_id text,
p_tier text,
p_status text,
p_entitled boolean,
p_current_period_start timestamptz DEFAULT NULL,
p_current_period_end timestamptz DEFAULT NULL,
p_cancel_at timestamptz DEFAULT NULL,
p_auto_renewing boolean DEFAULT NULL,
p_provider_customer_id text DEFAULT NULL,
p_provider_order_id text DEFAULT NULL,
p_store_product_id text DEFAULT NULL,
p_store_purchase_id uuid DEFAULT NULL,
p_operation_id uuid DEFAULT NULL
) RETURNS jsonb
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public, pg_temp
AS $$
DECLARE
v_event public.payment_provider_events%ROWTYPE;
v_cursor public.payment_provider_cursors%ROWTYPE;
v_subscription public.subscriptions%ROWTYPE;
v_result jsonb;
BEGIN
IF p_user_id IS NULL OR NOT EXISTS (SELECT 1 FROM auth.users WHERE id = p_user_id) THEN
RAISE EXCEPTION 'unknown_user';
END IF;
IF p_provider NOT IN ('stripe', 'payple', 'google_play', 'app_store', 'admin') THEN
RAISE EXCEPTION 'invalid_provider';
END IF;
IF p_event_id IS NULL OR length(trim(p_event_id)) NOT BETWEEN 3 AND 255 THEN
RAISE EXCEPTION 'invalid_event_id';
END IF;
IF p_event_created_at IS NULL OR p_event_created_at > now() + interval '10 minutes' THEN
RAISE EXCEPTION 'invalid_event_created_at';
END IF;
IF p_event_type IS NULL OR length(trim(p_event_type)) NOT BETWEEN 1 AND 100 THEN
RAISE EXCEPTION 'invalid_event_type';
END IF;
IF p_payload_digest IS NULL OR p_payload_digest !~ '^[0-9a-f]{64}$' THEN
RAISE EXCEPTION 'invalid_payload_digest';
END IF;
IF p_provider_resource_id IS NULL
OR length(trim(p_provider_resource_id)) NOT BETWEEN 1 AND 255 THEN
RAISE EXCEPTION 'invalid_provider_resource_id';
END IF;
IF p_tier NOT IN ('free', 'pro', 'pro_plus') THEN
RAISE EXCEPTION 'invalid_tier';
END IF;
IF p_entitled AND p_tier = 'free' THEN
RAISE EXCEPTION 'entitled_tier_must_be_paid';
END IF;
IF p_status IS NULL OR p_status NOT IN (
'active', 'trialing', 'past_due', 'canceled', 'unpaid', 'incomplete',
'incomplete_expired', 'paused', 'on_hold', 'expired', 'refunded', 'pending'
) THEN
RAISE EXCEPTION 'invalid_status';
END IF;
IF p_current_period_start IS NOT NULL
AND p_current_period_end IS NOT NULL
AND p_current_period_end < p_current_period_start THEN
RAISE EXCEPTION 'invalid_subscription_period';
END IF;
IF p_provider_customer_id IS NOT NULL AND length(p_provider_customer_id) > 255 THEN
RAISE EXCEPTION 'invalid_provider_customer_id';
END IF;
IF p_provider_order_id IS NOT NULL AND length(p_provider_order_id) > 255 THEN
RAISE EXCEPTION 'invalid_provider_order_id';
END IF;
PERFORM pg_advisory_xact_lock(hashtextextended(p_user_id::text, 73031));
INSERT INTO public.payment_provider_events (
provider,
event_id,
user_id,
provider_resource_id,
event_type,
event_created_at,
payload_digest
) VALUES (
p_provider,
trim(p_event_id),
p_user_id,
trim(p_provider_resource_id),
trim(p_event_type),
p_event_created_at,
p_payload_digest
)
ON CONFLICT (provider, event_id) DO NOTHING
RETURNING * INTO v_event;
IF v_event.id IS NULL THEN
SELECT *
INTO v_event
FROM public.payment_provider_events
WHERE provider = p_provider
AND event_id = trim(p_event_id)
FOR UPDATE;
IF v_event.user_id <> p_user_id
OR v_event.provider_resource_id <> trim(p_provider_resource_id)
OR v_event.event_type <> trim(p_event_type)
OR v_event.payload_digest <> p_payload_digest THEN
RAISE EXCEPTION 'provider_event_payload_mismatch';
END IF;
RETURN coalesce(
v_event.result,
jsonb_build_object(
'applied', false,
'duplicate', true,
'reason', 'event_processing_in_progress'
)
) || jsonb_build_object('duplicate', true);
END IF;
SELECT *
INTO v_cursor
FROM public.payment_provider_cursors
WHERE user_id = p_user_id
AND provider = p_provider
FOR UPDATE;
IF v_cursor.user_id IS NOT NULL AND (
v_cursor.last_event_created_at > p_event_created_at
OR (
v_cursor.last_event_created_at = p_event_created_at
AND v_cursor.last_event_id >= trim(p_event_id)
)
) THEN
v_result := jsonb_build_object(
'applied', false,
'duplicate', false,
'reason', 'stale_provider_event'
);
UPDATE public.payment_provider_events
SET disposition = 'ignored', result = v_result, processed_at = now()
WHERE id = v_event.id;
RETURN v_result;
END IF;
-- A Payple revocation is order-scoped. Every order charged on one billing
-- key shares provider_resource_id (the payer id), so the resource-ownership
-- check below cannot tell last month's order from the current one. Only a
-- cancellation of the order that funds the current period
-- (subscriptions.payple_pay_oid) may revoke it. This runs before the cursor
-- advances so an ignored refund of an older order cannot make a later
-- legitimate event look stale. Callers that revoke without naming an order
-- (payple-renew scheduled expiry, payple-manage) are unaffected.
IF NOT p_entitled
AND p_provider = 'payple'
AND nullif(trim(p_provider_order_id), '') IS NOT NULL
AND EXISTS (
SELECT 1
FROM public.subscriptions
WHERE user_id = p_user_id
AND provider = 'payple'
AND payple_pay_oid IS DISTINCT FROM trim(p_provider_order_id)
) THEN
v_result := jsonb_build_object(
'applied', false,
'duplicate', false,
'reason', 'canceled_order_not_current'
);
UPDATE public.payment_provider_events
SET disposition = 'ignored', result = v_result, processed_at = now()
WHERE id = v_event.id;
RETURN v_result;
END IF;
INSERT INTO public.payment_provider_cursors (
user_id, provider, last_event_created_at, last_event_id
) VALUES (
p_user_id, p_provider, p_event_created_at, trim(p_event_id)
)
ON CONFLICT (user_id, provider) DO UPDATE
SET last_event_created_at = EXCLUDED.last_event_created_at,
last_event_id = EXCLUDED.last_event_id,
updated_at = now();
SELECT *
INTO v_subscription
FROM public.subscriptions
WHERE user_id = p_user_id
FOR UPDATE;
IF v_subscription.id IS NULL THEN
INSERT INTO public.subscriptions (user_id, tier, status, provider, payment_provider)
VALUES (p_user_id, 'free', 'active', 'none', 'none')
RETURNING * INTO v_subscription;
END IF;
IF p_operation_id IS NOT NULL AND NOT EXISTS (
SELECT 1
FROM public.payment_provider_operations
WHERE id = p_operation_id
AND user_id = p_user_id
AND provider = p_provider
) THEN
RAISE EXCEPTION 'invalid_payment_operation';
END IF;
IF p_entitled AND EXISTS (
SELECT 1
FROM public.payment_provider_operations
WHERE user_id = p_user_id
AND provider <> p_provider
AND state IN ('reserved', 'external_created', 'charged')
AND expires_at > now()
) THEN
v_result := jsonb_build_object(
'applied', false,
'duplicate', false,
'reason', 'other_provider_operation_in_progress'
);
UPDATE public.payment_provider_events
SET disposition = 'rejected', result = v_result, processed_at = now()
WHERE id = v_event.id;
RETURN v_result;
END IF;
IF p_entitled AND v_subscription.provider NOT IN ('none', p_provider) THEN
v_result := jsonb_build_object(
'applied', false,
'duplicate', false,
'reason', 'active_subscription_other_provider',
'owner_provider', v_subscription.provider
);
UPDATE public.payment_provider_events
SET disposition = 'rejected', result = v_result, processed_at = now()
WHERE id = v_event.id;
RETURN v_result;
END IF;
IF NOT p_entitled AND v_subscription.provider <> p_provider THEN
v_result := jsonb_build_object(
'applied', false,
'duplicate', false,
'reason', 'provider_not_owner',
'owner_provider', v_subscription.provider
);
UPDATE public.payment_provider_events
SET disposition = 'ignored', result = v_result, processed_at = now()
WHERE id = v_event.id;
RETURN v_result;
END IF;
IF NOT p_entitled
AND v_subscription.provider_resource_id IS DISTINCT FROM trim(p_provider_resource_id) THEN
v_result := jsonb_build_object(
'applied', false,
'duplicate', false,
'reason', 'provider_resource_not_owner'
);
UPDATE public.payment_provider_events
SET disposition = 'ignored', result = v_result, processed_at = now()
WHERE id = v_event.id;
RETURN v_result;
END IF;
IF p_entitled THEN
UPDATE public.subscriptions
SET tier = p_tier,
status = p_status,
current_period_start = p_current_period_start,
current_period_end = p_current_period_end,
cancel_at = p_cancel_at,
provider = p_provider,
provider_resource_id = trim(p_provider_resource_id),
provider_event_id = trim(p_event_id),
provider_event_created_at = p_event_created_at,
auto_renewing = p_auto_renewing,
stripe_customer_id = CASE
WHEN p_provider = 'stripe' THEN coalesce(nullif(trim(p_provider_customer_id), ''), stripe_customer_id)
ELSE stripe_customer_id
END,
stripe_subscription_id = CASE
WHEN p_provider = 'stripe' THEN trim(p_provider_resource_id)
ELSE stripe_subscription_id
END,
payple_payer_id = CASE
WHEN p_provider = 'payple' AND p_provider_customer_id = '' THEN NULL
WHEN p_provider = 'payple' AND p_provider_customer_id IS NOT NULL
THEN trim(p_provider_customer_id)
ELSE payple_payer_id
END,
payple_pay_oid = CASE
WHEN p_provider = 'payple' THEN coalesce(nullif(trim(p_provider_order_id), ''), payple_pay_oid)
ELSE payple_pay_oid
END,
store_product_id = CASE
WHEN p_provider IN ('google_play', 'app_store') THEN p_store_product_id
ELSE NULL
END,
store_purchase_id = CASE
WHEN p_provider IN ('google_play', 'app_store') THEN p_store_purchase_id
ELSE NULL
END,
renewal_failures = CASE WHEN p_provider = 'payple' THEN 0 ELSE renewal_failures END,
updated_at = now()
WHERE user_id = p_user_id;
ELSE
UPDATE public.subscriptions
SET tier = 'free',
status = p_status,
current_period_start = coalesce(p_current_period_start, current_period_start),
current_period_end = coalesce(p_current_period_end, current_period_end),
cancel_at = coalesce(p_cancel_at, p_current_period_end, now()),
provider = 'none',
provider_resource_id = NULL,
provider_event_id = trim(p_event_id),
provider_event_created_at = p_event_created_at,
auto_renewing = false,
store_product_id = NULL,
store_purchase_id = NULL,
updated_at = now()
WHERE user_id = p_user_id;
END IF;
IF p_operation_id IS NOT NULL THEN
UPDATE public.payment_provider_operations
SET state = 'applied',
external_reference = coalesce(
nullif(trim(p_provider_order_id), ''),
nullif(trim(p_provider_resource_id), ''),
external_reference
),
error_code = NULL,
updated_at = now()
WHERE id = p_operation_id;
END IF;
v_result := jsonb_build_object(
'applied', true,
'duplicate', false,
'provider', CASE WHEN p_entitled THEN p_provider ELSE 'none' END,
'tier', CASE WHEN p_entitled THEN p_tier ELSE 'free' END,
'status', p_status,
'entitled', p_entitled
);
UPDATE public.payment_provider_events
SET disposition = 'applied', result = v_result, processed_at = now()
WHERE id = v_event.id;
RETURN v_result;
END;
$$;
COMMIT;