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

@ -6,10 +6,15 @@
// adapter that wires real clients into these ports and turns the result into a
// Response.
//
// Quota: the claim RPC holds one unit of the user's allowance while the request
// is 'processing' (migration 20260928000037). Every path that leaves a claimed
// request unfinished must therefore call markFailed so the unit is released
// immediately instead of waiting for the lease to expire.
// Quota: the claim RPC reserves one unit of the user's LLM allowance through
// the shared reserve_llm_quota lease (migration 20260929020000), the same
// ledger llm-proxy uses, so a running document and a chat request can never
// both take the last unit. commit settles the lease; markFailed releases it.
// Every path that leaves a claimed request unfinished must therefore call
// markFailed so the unit is returned immediately instead of waiting for the
// 10 minute lease to expire. commit can still answer generation_quota_exceeded
// when the lease expired (or the claim predates the lease) and the allowance
// is spent by then; that maps to markFailed('quota_exceeded') + 429.
import { buildMeetingDocumentSystemPrompt } from '../_shared/generative-ai-safety.ts'
import {

View file

@ -0,0 +1,118 @@
// Handler-level regression tests with in-memory ports: no Supabase, no Payple.
import {
createPaypleWebhookHandler,
type IgnoredProviderEvent,
type PaypleWebhookPorts,
type ProviderApplyResult,
} from './index.ts'
import type { CorrelatedPayment, PaypleProviderEventArgs } from './webhook-policy.ts'
import { type PayplePaymentLookupResult, TIER_PRICE } from '../_shared/payple.ts'
function assert(condition: boolean, message: string): asserts condition {
if (!condition) throw new Error(message)
}
const OLD_ORDER = 'D3RO-20260801090000-user-oid1'
const CURRENT_ORDER = 'D3RO-20260901090000-user-oid2'
const PAYER = 'payer-billing-key'
interface FakeState {
applied: Array<PaypleProviderEventArgs & { p_payload_digest: string }>
ignored: IgnoredProviderEvent[]
}
function fakePorts(
state: FakeState,
lookups: Record<string, Partial<PayplePaymentLookupResult>>,
): PaypleWebhookPorts {
// Both orders were registered on the same billing key; oid2 (the renewal)
// funds the current period.
const operations: Record<string, CorrelatedPayment> = {
[OLD_ORDER]: {
user_id: '00000000-0000-4000-8000-000000000001',
tier: 'pro',
operation_id: '00000000-0000-4000-8000-0000000000a1',
payer_id: PAYER,
current_order_id: CURRENT_ORDER,
},
[CURRENT_ORDER]: {
user_id: '00000000-0000-4000-8000-000000000001',
tier: 'pro',
operation_id: '00000000-0000-4000-8000-0000000000a2',
payer_id: PAYER,
current_order_id: CURRENT_ORDER,
},
}
return {
correlatePayment: (orderId) => Promise.resolve(operations[orderId] ?? null),
lookupPayment: ({ orderId, payType }) => Promise.resolve({
PCD_PAY_RST: 'success',
PCD_PAY_CODE: 'PCHK0000',
PCD_PAY_MSG: 'ok',
PCD_PAY_OID: orderId,
PCD_PAY_TYPE: payType,
PCD_PAYER_ID: PAYER,
PCD_PAY_TOTAL: String(TIER_PRICE.pro),
PCD_PAY_TIME: '20260901090000',
...lookups[orderId],
}),
applyProviderEvent: (args): Promise<ProviderApplyResult> => {
state.applied.push(args)
return Promise.resolve({ applied: true, duplicate: false })
},
recordIgnoredEvent: (event) => {
state.ignored.push(event)
return Promise.resolve()
},
now: () => new Date('2026-09-15T00:00:00.000Z'),
}
}
function cancellationRequest(orderId: string): Request {
return new Request('http://localhost/payple-webhook', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
PCD_PAY_RST: 'success',
PCD_PAY_CODE: 'PAYC0000',
PCD_PAYCANCEL_FLAG: 'Y',
PCD_PAY_OID: orderId,
PCD_PAY_TYPE: 'card',
PCD_PAYER_ID: PAYER,
}),
})
}
Deno.test('refund of a past Payple order does not revoke the current paid subscription', async () => {
const state: FakeState = { applied: [], ignored: [] }
const handler = createPaypleWebhookHandler(() => fakePorts(state, {
[OLD_ORDER]: { PCD_PAY_STATE: '승인취소완료', PCD_PAY_TIME: '20260801090000' },
}))
const response = await handler(cancellationRequest(OLD_ORDER))
const body = await response.json() as Record<string, unknown>
assert(response.status === 200, `acknowledged, got ${response.status}`)
assert(body.ignored === 'canceled_order_not_current', `ignored reason, got ${JSON.stringify(body)}`)
assert(state.applied.length === 0, 'no entitlement change is applied')
assert(state.ignored.length === 1, 'the ignored event is recorded')
assert(state.ignored[0].eventId === `cancel:${OLD_ORDER}:승인취소완료`, 'event id recorded')
assert(/^[0-9a-f]{64}$/.test(state.ignored[0].payloadDigest), 'digest recorded')
})
Deno.test('refund of the current Payple order still revokes entitlement', async () => {
const state: FakeState = { applied: [], ignored: [] }
const handler = createPaypleWebhookHandler(() => fakePorts(state, {
[CURRENT_ORDER]: { PCD_PAY_STATE: '승인취소완료' },
}))
const response = await handler(cancellationRequest(CURRENT_ORDER))
assert(response.status === 200, `acknowledged, got ${response.status}`)
assert(state.ignored.length === 0, 'nothing ignored')
assert(state.applied.length === 1, 'revocation applied')
const args = state.applied[0]
assert(args.p_entitled === false && args.p_tier === 'free', 'revokes entitlement')
assert(args.p_provider_order_id === CURRENT_ORDER, 'scoped to the current order')
assert(/^[0-9a-f]{64}$/.test(args.p_payload_digest), 'digest attached')
})

View file

@ -1,12 +1,9 @@
import { createServiceRoleClient } from '../_shared/quota.ts'
import {
calcSubscriptionPeriod,
getPaypleConfig,
parsePaypleTimestamp,
paypleAuth,
paypleLookupPayment,
payplePaymentEventDigest,
payplePaymentEventId,
PaypleConfigurationError,
PaypleVerificationError,
resolvePaypleOrderDate,
@ -14,36 +11,53 @@ import {
TIER_PRICE,
type PayplePaymentLookupResult,
} from '../_shared/payple.ts'
import {
classifyPaypleWebhook,
type CorrelatedPayment,
decideWebhookTransition,
normalizeTier,
type PaypleProviderEventArgs,
type PaypleWebhookPayload,
stringValue,
validateReconciledPaypleEvent,
} from './webhook-policy.ts'
interface PaypleWebhookPayload {
PCD_PAY_RST?: unknown
PCD_PAY_CODE?: unknown
PCD_PAY_MSG?: unknown
PCD_PAY_TYPE?: unknown
PCD_PAY_OID?: unknown
PCD_PAY_TOTAL?: unknown
PCD_PAYER_ID?: unknown
PCD_PAYER_NO?: unknown
PCD_PAY_TIME?: unknown
PCD_PAY_WORK?: unknown
PCD_PAYCANCEL_FLAG?: unknown
PCD_PAY_CARDTRADENUM?: unknown
}
// Re-exported so existing importers of the handler module keep working; the
// rules themselves live in webhook-policy.ts.
export { classifyPaypleWebhook, validateReconciledPaypleEvent }
interface CorrelatedPayment {
user_id: string
tier: 'pro' | 'pro_plus'
operation_id: string | null
payer_id: string
}
interface ProviderApplyResult {
export interface ProviderApplyResult {
applied?: boolean
duplicate?: boolean
reason?: string
}
type WebhookKind = 'payment' | 'cancellation' | 'billing_key_revoked' | 'unsupported'
export interface IgnoredProviderEvent {
userId: string
eventId: string
eventCreatedAt: string
eventType: string
payloadDigest: string
providerResourceId: string
}
/**
* IO port of the webhook handler. The handler orchestrates; adapters talk to
* Supabase and Payple. Tests substitute an in-memory implementation.
*/
export interface PaypleWebhookPorts {
correlatePayment(orderId: string, payerId: string | null): Promise<CorrelatedPayment | null>
lookupPayment(params: {
orderId: string
payType: 'card' | 'transfer'
payTime: string | null
}): Promise<PayplePaymentLookupResult>
applyProviderEvent(
args: PaypleProviderEventArgs & { p_payload_digest: string },
): Promise<ProviderApplyResult | null>
recordIgnoredEvent(event: IgnoredProviderEvent): Promise<void>
now(): Date
}
function jsonResponse(body: Record<string, unknown>, status = 200): Response {
return new Response(JSON.stringify(body), {
@ -52,52 +66,23 @@ function jsonResponse(body: Record<string, unknown>, status = 200): Response {
})
}
function stringValue(value: unknown): string | null {
return typeof value === 'string' && value.length > 0 ? value : null
}
type ServiceClient = ReturnType<typeof createServiceRoleClient>
function normalizeTier(value: unknown): 'pro' | 'pro_plus' | null {
if (value === 'pro') return 'pro'
if (value === 'pro_plus' || value === 'team') return 'pro_plus'
return null
}
export function classifyPaypleWebhook(payload: PaypleWebhookPayload): WebhookKind {
if (payload.PCD_PAY_WORK === 'PUSERDEL') return 'billing_key_revoked'
if (
payload.PCD_PAYCANCEL_FLAG === 'Y'
|| (typeof payload.PCD_PAY_CODE === 'string' && payload.PCD_PAY_CODE.startsWith('PAYC'))
) {
return 'cancellation'
}
if (payload.PCD_PAY_RST === 'success' && payload.PCD_PAY_OID) return 'payment'
return 'unsupported'
}
export function validateReconciledPaypleEvent(
payload: PaypleWebhookPayload,
lookup: PayplePaymentLookupResult,
): void {
const orderId = stringValue(payload.PCD_PAY_OID)
const payType = stringValue(payload.PCD_PAY_TYPE)
const payerId = stringValue(payload.PCD_PAYER_ID)
if (!orderId || lookup.PCD_PAY_OID !== orderId || lookup.PCD_PAY_RST !== 'success') {
throw new PaypleVerificationError('payple_webhook_order_mismatch')
}
if (payType && lookup.PCD_PAY_TYPE !== payType) {
throw new PaypleVerificationError('payple_webhook_type_mismatch')
}
if (payerId && lookup.PCD_PAYER_ID && lookup.PCD_PAYER_ID !== payerId) {
throw new PaypleVerificationError('payple_webhook_payer_mismatch')
}
const payloadTotal = stringValue(payload.PCD_PAY_TOTAL)
if (payloadTotal && lookup.PCD_PAY_TOTAL && Number(payloadTotal) !== Number(lookup.PCD_PAY_TOTAL)) {
throw new PaypleVerificationError('payple_webhook_amount_mismatch')
}
async function readCurrentPaypleOrder(
serviceClient: ServiceClient,
userId: string,
): Promise<string | null> {
const { data, error } = await serviceClient
.from('subscriptions')
.select('payple_pay_oid')
.eq('user_id', userId)
.maybeSingle()
if (error) throw new Error('subscription_lookup_failed')
return stringValue(data?.payple_pay_oid)
}
async function correlatePayment(
serviceClient: ReturnType<typeof createServiceRoleClient>,
serviceClient: ServiceClient,
orderId: string,
payerId: string | null,
): Promise<CorrelatedPayment | null> {
@ -111,11 +96,13 @@ async function correlatePayment(
const operationTier = normalizeTier(operation?.requested_tier)
const operationPayerId = stringValue(operation?.provider_resource_id) ?? payerId
if (operation?.user_id && operationTier && operationPayerId) {
const userId = operation.user_id as string
return {
user_id: operation.user_id as string,
user_id: userId,
tier: operationTier,
operation_id: operation.id as string,
payer_id: operationPayerId,
current_order_id: await readCurrentPaypleOrder(serviceClient, userId),
}
}
@ -133,140 +120,160 @@ async function correlatePayment(
tier: subscriptionTier,
operation_id: null,
payer_id: subscriptionPayerId,
// Matched through payple_pay_oid, so this order is the current one.
current_order_id: orderId,
}
}
export async function paypleWebhookHandler(req: Request): Promise<Response> {
if (req.method !== 'POST') return jsonResponse({ error: 'method_not_allowed' }, 405)
if (!(req.headers.get('content-type') ?? '').toLowerCase().includes('application/json')) {
return jsonResponse({ error: 'unsupported_content_type' }, 415)
}
const rawPayload = await req.text()
if (!rawPayload || rawPayload.length > 64 * 1024) {
return jsonResponse({ error: 'invalid_payload' }, 400)
}
let payload: PaypleWebhookPayload
try {
payload = JSON.parse(rawPayload) as PaypleWebhookPayload
} catch {
return jsonResponse({ error: 'invalid_json' }, 400)
}
const kind = classifyPaypleWebhook(payload)
if (kind === 'unsupported') return jsonResponse({ received: true, ignored: 'unsupported_event' })
if (kind === 'billing_key_revoked') {
// Payple's documented PUSERDEL webhook has no signature and no transaction
// identifier that can be reconciled through PayChkAct. It is therefore not
// authorized to mutate entitlement; payple-manage applies the verified
// result of the server-originated PUSERDEL API call instead.
return jsonResponse({ received: true, ignored: 'non_authoritative_billing_key_event' })
}
const orderId = stringValue(payload.PCD_PAY_OID)
const payType = stringValue(payload.PCD_PAY_TYPE)
if (
!orderId
|| !/^[A-Za-z0-9._-]{8,64}$/.test(orderId)
|| (payType !== 'card' && payType !== 'transfer')
) {
return jsonResponse({ error: 'invalid_payload' }, 400)
}
export function createSupabasePaypleWebhookPorts(): PaypleWebhookPorts {
const serviceClient = createServiceRoleClient()
try {
// Reject unknown order IDs before consuming Payple's authenticated lookup
// rate limit. Every accepted order must have originated in our operation
// ledger or be the current order on an existing Payple subscription.
const correlated = await correlatePayment(
serviceClient,
orderId,
stringValue(payload.PCD_PAYER_ID),
)
if (!correlated) return jsonResponse({ error: 'payment_not_registered' }, 422)
const config = getPaypleConfig()
const payDate = resolvePaypleOrderDate(orderId, stringValue(payload.PCD_PAY_TIME) ?? undefined)
const auth = await paypleAuth(config, { payCheckFlag: true })
const lookup = await paypleLookupPayment(config, auth, { orderId, payType, payDate })
validateReconciledPaypleEvent(payload, lookup)
if (lookup.PCD_PAYER_ID && lookup.PCD_PAYER_ID !== correlated.payer_id) {
return jsonResponse({ error: 'payment_owner_mismatch' }, 401)
}
const expectedAmount = TIER_PRICE[correlated.tier]
const lookupAmount = Number(lookup.PCD_PAY_TOTAL)
if (kind === 'payment' && (!Number.isFinite(lookupAmount) || lookupAmount !== expectedAmount)) {
return jsonResponse({ error: 'payment_amount_mismatch' }, 422)
}
const paymentTime = lookup.PCD_PAY_TIME
? parsePaypleTimestamp(lookup.PCD_PAY_TIME)
: new Date()
const authoritativeCanceled = lookup.PCD_PAY_STATE === '승인취소완료'
|| lookup.PCD_PAY_STATE === 'canceled'
if (kind === 'cancellation' && !authoritativeCanceled) {
return jsonResponse({ error: 'cancellation_not_confirmed' }, 409)
}
const eventTime = kind === 'cancellation' ? new Date() : paymentTime
const eventId = kind === 'cancellation'
? `cancel:${orderId}:${lookup.PCD_PAY_STATE ?? 'confirmed'}`
: payplePaymentEventId(orderId)
const payloadDigest = kind === 'cancellation'
? await sha256Text(JSON.stringify({ payload, lookup }))
: await payplePaymentEventDigest({
orderId,
payerId: correlated.payer_id,
payType: lookup.PCD_PAY_TYPE,
amount: lookupAmount,
})
const { start, end } = calcSubscriptionPeriod(paymentTime)
const { data: applyData, error: applyError } = await serviceClient.rpc(
'apply_payment_provider_event',
{
p_user_id: correlated.user_id,
return {
correlatePayment: (orderId, payerId) => correlatePayment(serviceClient, orderId, payerId),
async lookupPayment({ orderId, payType, payTime }) {
const config = getPaypleConfig()
const payDate = resolvePaypleOrderDate(orderId, payTime ?? undefined)
const auth = await paypleAuth(config, { payCheckFlag: true })
return await paypleLookupPayment(config, auth, { orderId, payType, payDate })
},
async applyProviderEvent(args) {
const { data, error } = await serviceClient.rpc('apply_payment_provider_event', args)
if (error) throw new Error('payple_entitlement_apply_failed')
return data as ProviderApplyResult | null
},
async recordIgnoredEvent(event) {
// Replay-protected audit record that neither touches entitlement nor
// advances the provider ordering cursor.
const { error } = await serviceClient.rpc('record_payment_provider_observation', {
p_user_id: event.userId,
p_provider: 'payple',
p_event_id: eventId,
p_event_created_at: eventTime.toISOString(),
p_event_type: kind === 'cancellation'
? 'webhook.payment_canceled'
: 'payment.completed',
p_payload_digest: payloadDigest,
p_provider_resource_id: correlated.payer_id,
p_tier: kind === 'cancellation' ? 'free' : correlated.tier,
p_status: kind === 'cancellation' ? 'canceled' : 'active',
p_entitled: kind !== 'cancellation',
p_current_period_start: kind === 'cancellation' ? null : start,
p_current_period_end: kind === 'cancellation' ? eventTime.toISOString() : end,
p_cancel_at: kind === 'cancellation' ? eventTime.toISOString() : null,
p_auto_renewing: kind !== 'cancellation',
p_provider_customer_id: correlated.payer_id,
p_provider_order_id: orderId,
p_store_product_id: null,
p_store_purchase_id: null,
p_operation_id: correlated.operation_id,
},
)
if (applyError) throw new Error('payple_entitlement_apply_failed')
const result = applyData as ProviderApplyResult | null
return jsonResponse({
received: true,
applied: result?.applied ?? false,
duplicate: result?.duplicate ?? false,
reason: result?.reason,
})
} catch (error) {
if (error instanceof PaypleConfigurationError) {
return jsonResponse({ error: error.code }, 503)
}
if (error instanceof PaypleVerificationError) {
return jsonResponse({ error: error.code }, 401)
}
return jsonResponse({ error: 'payple_webhook_processing_failed' }, 500)
p_event_id: event.eventId,
p_event_created_at: event.eventCreatedAt,
p_event_type: event.eventType,
p_payload_digest: event.payloadDigest,
p_provider_resource_id: event.providerResourceId,
})
if (error) throw new Error('payple_event_record_failed')
},
now: () => new Date(),
}
}
export function createPaypleWebhookHandler(
makePorts: () => PaypleWebhookPorts,
): (req: Request) => Promise<Response> {
return async (req) => {
if (req.method !== 'POST') return jsonResponse({ error: 'method_not_allowed' }, 405)
if (!(req.headers.get('content-type') ?? '').toLowerCase().includes('application/json')) {
return jsonResponse({ error: 'unsupported_content_type' }, 415)
}
const rawPayload = await req.text()
if (!rawPayload || rawPayload.length > 64 * 1024) {
return jsonResponse({ error: 'invalid_payload' }, 400)
}
let payload: PaypleWebhookPayload
try {
payload = JSON.parse(rawPayload) as PaypleWebhookPayload
} catch {
return jsonResponse({ error: 'invalid_json' }, 400)
}
const kind = classifyPaypleWebhook(payload)
if (kind === 'unsupported') return jsonResponse({ received: true, ignored: 'unsupported_event' })
if (kind === 'billing_key_revoked') {
// Payple's documented PUSERDEL webhook has no signature and no transaction
// identifier that can be reconciled through PayChkAct. It is therefore not
// authorized to mutate entitlement; payple-manage applies the verified
// result of the server-originated PUSERDEL API call instead.
return jsonResponse({ received: true, ignored: 'non_authoritative_billing_key_event' })
}
const orderId = stringValue(payload.PCD_PAY_OID)
const payType = stringValue(payload.PCD_PAY_TYPE)
if (
!orderId
|| !/^[A-Za-z0-9._-]{8,64}$/.test(orderId)
|| (payType !== 'card' && payType !== 'transfer')
) {
return jsonResponse({ error: 'invalid_payload' }, 400)
}
try {
const ports = makePorts()
// Reject unknown order IDs before consuming Payple's authenticated lookup
// rate limit. Every accepted order must have originated in our operation
// ledger or be the current order on an existing Payple subscription.
const correlated = await ports.correlatePayment(orderId, stringValue(payload.PCD_PAYER_ID))
if (!correlated) return jsonResponse({ error: 'payment_not_registered' }, 422)
const lookup = await ports.lookupPayment({
orderId,
payType,
payTime: stringValue(payload.PCD_PAY_TIME),
})
validateReconciledPaypleEvent(payload, lookup)
const transition = decideWebhookTransition({
kind,
orderId,
lookup,
correlated,
expectedAmount: TIER_PRICE[correlated.tier],
now: ports.now(),
})
if (transition.kind === 'reject') {
return jsonResponse({ error: transition.error }, transition.status)
}
if (transition.kind === 'ignore') {
await ports.recordIgnoredEvent({
userId: correlated.user_id,
eventId: transition.eventId,
eventCreatedAt: transition.eventCreatedAt,
eventType: transition.eventType,
payloadDigest: await sha256Text(JSON.stringify({ payload, lookup })),
providerResourceId: transition.providerResourceId,
})
return jsonResponse({
received: true,
applied: false,
duplicate: false,
ignored: transition.reason,
reason: transition.reason,
})
}
const payloadDigest = kind === 'cancellation'
? await sha256Text(JSON.stringify({ payload, lookup }))
: await payplePaymentEventDigest({
orderId,
payerId: correlated.payer_id,
payType: lookup.PCD_PAY_TYPE,
amount: transition.amount,
})
const result = await ports.applyProviderEvent({
...transition.args,
p_payload_digest: payloadDigest,
})
return jsonResponse({
received: true,
applied: result?.applied ?? false,
duplicate: result?.duplicate ?? false,
reason: result?.reason,
})
} catch (error) {
if (error instanceof PaypleConfigurationError) {
return jsonResponse({ error: error.code }, 503)
}
if (error instanceof PaypleVerificationError) {
return jsonResponse({ error: error.code }, 401)
}
return jsonResponse({ error: 'payple_webhook_processing_failed' }, 500)
}
}
}
export const paypleWebhookHandler = createPaypleWebhookHandler(createSupabasePaypleWebhookPorts)
if (import.meta.main) Deno.serve(paypleWebhookHandler)

View file

@ -0,0 +1,160 @@
import {
type CorrelatedPayment,
decideWebhookTransition,
type WebhookTransitionInput,
} from './webhook-policy.ts'
import type { PayplePaymentLookupResult } from '../_shared/payple.ts'
function assert(condition: boolean, message: string): asserts condition {
if (!condition) throw new Error(message)
}
function assertEquals(actual: unknown, expected: unknown, message: string): void {
const a = JSON.stringify(actual)
const e = JSON.stringify(expected)
if (a !== e) throw new Error(`${message}: expected ${e}, got ${a}`)
}
const OLD_ORDER = 'D3RO-20260801090000-user-oid1'
const CURRENT_ORDER = 'D3RO-20260901090000-user-oid2'
const NOW = new Date('2026-09-15T00:00:00.000Z')
function correlated(overrides: Partial<CorrelatedPayment> = {}): CorrelatedPayment {
return {
user_id: '00000000-0000-4000-8000-000000000001',
tier: 'pro',
operation_id: '00000000-0000-4000-8000-0000000000aa',
payer_id: 'payer-billing-key',
current_order_id: CURRENT_ORDER,
...overrides,
}
}
function lookup(orderId: string, overrides: Partial<PayplePaymentLookupResult> = {}): PayplePaymentLookupResult {
return {
PCD_PAY_RST: 'success',
PCD_PAY_CODE: 'PCHK0000',
PCD_PAY_MSG: 'ok',
PCD_PAY_OID: orderId,
PCD_PAY_TYPE: 'card',
PCD_PAYER_ID: 'payer-billing-key',
PCD_PAY_TOTAL: '9900',
PCD_PAY_TIME: '20260901090000',
...overrides,
}
}
function input(overrides: Partial<WebhookTransitionInput>): WebhookTransitionInput {
return {
kind: 'payment',
orderId: CURRENT_ORDER,
lookup: lookup(CURRENT_ORDER),
correlated: correlated(),
expectedAmount: 9900,
now: NOW,
...overrides,
}
}
Deno.test('payment of the current order grants the correlated tier for one period', () => {
const decision = decideWebhookTransition(input({}))
assert(decision.kind === 'apply', `expected apply, got ${decision.kind}`)
assertEquals(decision.amount, 9900, 'amount')
const args = decision.args
assertEquals(args.p_event_id, `payment:${CURRENT_ORDER}`, 'event id')
assertEquals(args.p_event_type, 'payment.completed', 'event type')
assertEquals(args.p_entitled, true, 'entitled')
assertEquals(args.p_tier, 'pro', 'tier')
assertEquals(args.p_status, 'active', 'status')
assertEquals(args.p_auto_renewing, true, 'auto renewing')
assertEquals(args.p_provider_order_id, CURRENT_ORDER, 'order id')
assertEquals(args.p_provider_resource_id, 'payer-billing-key', 'resource id')
// 20260901090000 KST = 2026-09-01T00:00:00Z
assertEquals(args.p_event_created_at, '2026-09-01T00:00:00.000Z', 'event time is payment time')
assertEquals(args.p_current_period_start, '2026-09-01T00:00:00.000Z', 'period start')
assertEquals(args.p_current_period_end, '2026-10-01T00:00:00.000Z', 'period end')
assertEquals(args.p_cancel_at, null, 'no cancel_at')
})
Deno.test('payment of an older registered order is still applied (ordering is the RPC cursor)', () => {
const decision = decideWebhookTransition(input({
orderId: OLD_ORDER,
lookup: lookup(OLD_ORDER, { PCD_PAY_TIME: '20260801090000' }),
}))
assert(decision.kind === 'apply', 'payments are not order-scoped')
})
Deno.test('payment whose reconciled amount differs from the tier price is rejected', () => {
for (const total of ['29900', 'not-a-number', undefined]) {
const decision = decideWebhookTransition(input({
lookup: lookup(CURRENT_ORDER, { PCD_PAY_TOTAL: total }),
}))
assertEquals(decision, { kind: 'reject', status: 422, error: 'payment_amount_mismatch' }, `total ${total}`)
}
const unpricedTier = decideWebhookTransition(input({ expectedAmount: undefined }))
assertEquals(unpricedTier.kind, 'reject', 'tier without a price cannot be paid')
})
Deno.test('lookup payer different from the correlated payer is rejected', () => {
const decision = decideWebhookTransition(input({
lookup: lookup(CURRENT_ORDER, { PCD_PAYER_ID: 'payer-other' }),
}))
assertEquals(decision, { kind: 'reject', status: 401, error: 'payment_owner_mismatch' }, 'owner')
})
Deno.test('cancellation not confirmed by the Payple lookup is rejected', () => {
for (const state of [undefined, '승인완료']) {
const decision = decideWebhookTransition(input({
kind: 'cancellation',
lookup: lookup(CURRENT_ORDER, { PCD_PAY_STATE: state }),
}))
assertEquals(decision, { kind: 'reject', status: 409, error: 'cancellation_not_confirmed' }, `state ${state}`)
}
})
Deno.test('confirmed cancellation of the current order revokes entitlement now', () => {
for (const state of ['승인취소완료', 'canceled']) {
const decision = decideWebhookTransition(input({
kind: 'cancellation',
lookup: lookup(CURRENT_ORDER, { PCD_PAY_STATE: state, PCD_PAY_TOTAL: '1' }),
}))
assert(decision.kind === 'apply', `expected apply for ${state}`)
const args = decision.args
assertEquals(args.p_event_id, `cancel:${CURRENT_ORDER}:${state}`, 'event id')
assertEquals(args.p_event_type, 'webhook.payment_canceled', 'event type')
assertEquals(args.p_entitled, false, 'not entitled')
assertEquals(args.p_tier, 'free', 'tier')
assertEquals(args.p_status, 'canceled', 'status')
assertEquals(args.p_auto_renewing, false, 'auto renewing')
assertEquals(args.p_event_created_at, NOW.toISOString(), 'event time is now')
assertEquals(args.p_current_period_start, null, 'period start untouched')
assertEquals(args.p_current_period_end, NOW.toISOString(), 'period ends now')
assertEquals(args.p_cancel_at, NOW.toISOString(), 'cancel_at now')
assertEquals(args.p_provider_order_id, CURRENT_ORDER, 'order id')
}
})
Deno.test('confirmed cancellation of an older order is ignored and keeps the paid period', () => {
const decision = decideWebhookTransition(input({
kind: 'cancellation',
orderId: OLD_ORDER,
lookup: lookup(OLD_ORDER, { PCD_PAY_STATE: '승인취소완료', PCD_PAY_TIME: '20260801090000' }),
}))
assertEquals(decision, {
kind: 'ignore',
reason: 'canceled_order_not_current',
eventId: `cancel:${OLD_ORDER}:승인취소완료`,
eventCreatedAt: NOW.toISOString(),
eventType: 'webhook.payment_canceled',
providerResourceId: 'payer-billing-key',
}, 'old order refund must not revoke the current subscription')
})
Deno.test('confirmed cancellation while no current order is on record is ignored', () => {
const decision = decideWebhookTransition(input({
kind: 'cancellation',
correlated: correlated({ current_order_id: null }),
lookup: lookup(CURRENT_ORDER, { PCD_PAY_STATE: '승인취소완료' }),
}))
assertEquals(decision.kind, 'ignore', 'fail safe: unknown current order never revokes')
})

View file

@ -0,0 +1,242 @@
// Pure decision rules for the Payple webhook edge function. No IO lives here:
// index.ts owns the Supabase/Payple calls and asks these functions what a
// reconciled webhook means for the user's entitlement, so the rules (which
// order may revoke a subscription, which amount is acceptable, ...) are
// unit-testable without a network or a database.
import {
calcSubscriptionPeriod,
parsePaypleTimestamp,
payplePaymentEventId,
PaypleVerificationError,
type PayplePaymentLookupResult,
} from '../_shared/payple.ts'
export interface PaypleWebhookPayload {
PCD_PAY_RST?: unknown
PCD_PAY_CODE?: unknown
PCD_PAY_MSG?: unknown
PCD_PAY_TYPE?: unknown
PCD_PAY_OID?: unknown
PCD_PAY_TOTAL?: unknown
PCD_PAYER_ID?: unknown
PCD_PAYER_NO?: unknown
PCD_PAY_TIME?: unknown
PCD_PAY_WORK?: unknown
PCD_PAYCANCEL_FLAG?: unknown
PCD_PAY_CARDTRADENUM?: unknown
}
export type WebhookKind = 'payment' | 'cancellation' | 'billing_key_revoked' | 'unsupported'
/** The webhook kinds that are reconciled against Payple and may change entitlement. */
export type ReconciledWebhookKind = 'payment' | 'cancellation'
export type PaypleTier = 'pro' | 'pro_plus'
export interface CorrelatedPayment {
user_id: string
tier: PaypleTier
operation_id: string | null
payer_id: string
/**
* subscriptions.payple_pay_oid at correlation time: the order that funds the
* current paid period. null when the user has no Payple order on record.
*/
current_order_id: string | null
}
export function stringValue(value: unknown): string | null {
return typeof value === 'string' && value.length > 0 ? value : null
}
export function normalizeTier(value: unknown): PaypleTier | null {
if (value === 'pro') return 'pro'
if (value === 'pro_plus' || value === 'team') return 'pro_plus'
return null
}
export function classifyPaypleWebhook(payload: PaypleWebhookPayload): WebhookKind {
if (payload.PCD_PAY_WORK === 'PUSERDEL') return 'billing_key_revoked'
if (
payload.PCD_PAYCANCEL_FLAG === 'Y'
|| (typeof payload.PCD_PAY_CODE === 'string' && payload.PCD_PAY_CODE.startsWith('PAYC'))
) {
return 'cancellation'
}
if (payload.PCD_PAY_RST === 'success' && payload.PCD_PAY_OID) return 'payment'
return 'unsupported'
}
export function validateReconciledPaypleEvent(
payload: PaypleWebhookPayload,
lookup: PayplePaymentLookupResult,
): void {
const orderId = stringValue(payload.PCD_PAY_OID)
const payType = stringValue(payload.PCD_PAY_TYPE)
const payerId = stringValue(payload.PCD_PAYER_ID)
if (!orderId || lookup.PCD_PAY_OID !== orderId || lookup.PCD_PAY_RST !== 'success') {
throw new PaypleVerificationError('payple_webhook_order_mismatch')
}
if (payType && lookup.PCD_PAY_TYPE !== payType) {
throw new PaypleVerificationError('payple_webhook_type_mismatch')
}
if (payerId && lookup.PCD_PAYER_ID && lookup.PCD_PAYER_ID !== payerId) {
throw new PaypleVerificationError('payple_webhook_payer_mismatch')
}
const payloadTotal = stringValue(payload.PCD_PAY_TOTAL)
if (payloadTotal && lookup.PCD_PAY_TOTAL && Number(payloadTotal) !== Number(lookup.PCD_PAY_TOTAL)) {
throw new PaypleVerificationError('payple_webhook_amount_mismatch')
}
}
/** Payple's PayChkAct state is the only authority that an order was canceled. */
export function isAuthoritativeCancellation(lookup: PayplePaymentLookupResult): boolean {
return lookup.PCD_PAY_STATE === '승인취소완료' || lookup.PCD_PAY_STATE === 'canceled'
}
/**
* apply_payment_provider_event arguments, minus p_payload_digest (the digest
* is an async hash computed by the IO layer from the event it forwards).
*/
export type PaypleProviderEventArgs = {
p_user_id: string
p_provider: 'payple'
p_event_id: string
p_event_created_at: string
p_event_type: 'payment.completed' | 'webhook.payment_canceled'
p_provider_resource_id: string
p_tier: 'free' | PaypleTier
p_status: 'active' | 'canceled'
p_entitled: boolean
p_current_period_start: string | null
p_current_period_end: string
p_cancel_at: string | null
p_auto_renewing: boolean
p_provider_customer_id: string
p_provider_order_id: string
p_store_product_id: null
p_store_purchase_id: null
p_operation_id: string | null
}
export interface WebhookTransitionInput {
kind: ReconciledWebhookKind
orderId: string
lookup: PayplePaymentLookupResult
correlated: CorrelatedPayment
/** Payple price of the correlated tier; undefined when the tier has no price. */
expectedAmount: number | undefined
now: Date
}
export type IgnoredWebhookReason = 'canceled_order_not_current'
export type WebhookTransition =
| { kind: 'reject'; status: 401 | 409 | 422; error: string }
| {
kind: 'ignore'
reason: IgnoredWebhookReason
eventId: string
eventCreatedAt: string
eventType: 'webhook.payment_canceled'
providerResourceId: string
}
| { kind: 'apply'; amount: number; args: PaypleProviderEventArgs }
function cancellationEventId(orderId: string, lookup: PayplePaymentLookupResult): string {
return `cancel:${orderId}:${lookup.PCD_PAY_STATE ?? 'confirmed'}`
}
/**
* Decides what a reconciled Payple webhook does to the subscription.
*
* - The Payple lookup's payer must be the correlated payer (401).
* - A payment must match the correlated tier's price exactly (422).
* - A cancellation must be confirmed by Payple's own lookup state (409).
* - A confirmed cancellation revokes entitlement only when the canceled order
* is the one that funds the current period (subscriptions.payple_pay_oid).
* A refund of an older order (last month's checkout, a duplicate charge) —
* or of any order while no current order is on record — is ignored, because
* every order on the same billing key shares the payer id and would
* otherwise pass the database's resource-ownership check.
*/
export function decideWebhookTransition(input: WebhookTransitionInput): WebhookTransition {
const { kind, orderId, lookup, correlated, now } = input
if (lookup.PCD_PAYER_ID && lookup.PCD_PAYER_ID !== correlated.payer_id) {
return { kind: 'reject', status: 401, error: 'payment_owner_mismatch' }
}
const amount = Number(lookup.PCD_PAY_TOTAL)
if (kind === 'payment' && (!Number.isFinite(amount) || amount !== input.expectedAmount)) {
return { kind: 'reject', status: 422, error: 'payment_amount_mismatch' }
}
const paymentTime = lookup.PCD_PAY_TIME ? parsePaypleTimestamp(lookup.PCD_PAY_TIME) : now
if (kind === 'cancellation') {
if (!isAuthoritativeCancellation(lookup)) {
return { kind: 'reject', status: 409, error: 'cancellation_not_confirmed' }
}
const eventId = cancellationEventId(orderId, lookup)
const eventCreatedAt = now.toISOString()
if (correlated.current_order_id !== orderId) {
return {
kind: 'ignore',
reason: 'canceled_order_not_current',
eventId,
eventCreatedAt,
eventType: 'webhook.payment_canceled',
providerResourceId: correlated.payer_id,
}
}
return {
kind: 'apply',
amount,
args: {
...baseArgs(correlated, orderId),
p_event_id: eventId,
p_event_created_at: eventCreatedAt,
p_event_type: 'webhook.payment_canceled',
p_tier: 'free',
p_status: 'canceled',
p_entitled: false,
p_current_period_start: null,
p_current_period_end: eventCreatedAt,
p_cancel_at: eventCreatedAt,
p_auto_renewing: false,
},
}
}
const { start, end } = calcSubscriptionPeriod(paymentTime)
return {
kind: 'apply',
amount,
args: {
...baseArgs(correlated, orderId),
p_event_id: payplePaymentEventId(orderId),
p_event_created_at: paymentTime.toISOString(),
p_event_type: 'payment.completed',
p_tier: correlated.tier,
p_status: 'active',
p_entitled: true,
p_current_period_start: start,
p_current_period_end: end,
p_cancel_at: null,
p_auto_renewing: true,
},
}
}
function baseArgs(correlated: CorrelatedPayment, orderId: string) {
return {
p_user_id: correlated.user_id,
p_provider: 'payple' as const,
p_provider_resource_id: correlated.payer_id,
p_provider_customer_id: correlated.payer_id,
p_provider_order_id: orderId,
p_store_product_id: null,
p_store_purchase_id: null,
p_operation_id: correlated.operation_id,
}
}

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;

View file

@ -0,0 +1,307 @@
\set ON_ERROR_STOP on
-- Regression for 20260929030000_knowledge_chunks_vector_index.sql.
-- match_knowledge_chunks must return the caller's exact top-k chunks (own
-- documents + documents of teams they belong to), even when other tenants own
-- almost every row of knowledge_chunks and the planner is pushed towards
-- index scans. Before the fix an IVFFlat index trained on an empty table was
-- scanned across all tenants with probes = 1 and filtered by tenant only
-- afterwards, so the caller usually got 0-1 rows although exact matches
-- existed.
BEGIN;
CREATE OR REPLACE FUNCTION pg_temp.assert_true(condition boolean, message text)
RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
IF condition IS NOT TRUE THEN
RAISE EXCEPTION 'assertion_failed: %', message;
END IF;
END;
$$;
CREATE OR REPLACE FUNCTION pg_temp.act_as(uid uuid)
RETURNS void
LANGUAGE sql
AS $$
SELECT set_config(
'request.jwt.claims',
json_build_object('sub', uid, 'role', 'authenticated')::text,
true
);
$$;
-- Uniform random direction in [-1, 1]^1536 (deterministic after setseed).
CREATE OR REPLACE FUNCTION pg_temp.rand_vec()
RETURNS public.vector
LANGUAGE sql
VOLATILE
AS $$
SELECT array_agg(random() * 2 - 1 ORDER BY i)::public.vector
FROM generate_series(1, 1536) AS g(i);
$$;
-- base plus a small random perturbation (still very similar to base).
CREATE OR REPLACE FUNCTION pg_temp.near_vec(base public.vector, eps double precision)
RETURNS public.vector
LANGUAGE sql
VOLATILE
AS $$
SELECT array_agg(x + eps * (random() * 2 - 1) ORDER BY i)::public.vector
FROM unnest(base::real[]) WITH ORDINALITY AS t(x, i);
$$;
-- Ids returned by match_knowledge_chunks, in result order.
CREATE OR REPLACE FUNCTION pg_temp.match_ids(q public.vector, k integer, threshold double precision)
RETURNS uuid[]
LANGUAGE sql
VOLATILE
AS $$
SELECT coalesce(array_agg(m.id ORDER BY m.ord), ARRAY[]::uuid[])
FROM public.match_knowledge_chunks(q, k, threshold)
WITH ORDINALITY AS m(id, document_id, chunk_index, content, similarity, ord);
$$;
-- ── 0) the broken IVFFlat index is gone ──────────────────────────────────
SELECT pg_temp.assert_true(
NOT EXISTS (
SELECT 1 FROM pg_indexes
WHERE schemaname = 'public'
AND tablename = 'knowledge_chunks'
AND indexdef ILIKE '%ivfflat%'
),
'knowledge_chunks has no IVFFlat index trained on an empty table'
);
-- ── fixtures (as postgres) ───────────────────────────────────────────────
SELECT setseed(0.4242);
INSERT INTO auth.users (
id, aud, role, email, encrypted_password, email_confirmed_at,
raw_app_meta_data, raw_user_meta_data, created_at, updated_at
) VALUES
(
'39000000-0000-4000-8000-00000000000a', 'authenticated', 'authenticated',
'rag-searcher@example.invalid', crypt('fixture-password', gen_salt('bf')), now(),
'{"provider":"email","providers":["email"]}'::jsonb, '{"name":"Searcher"}'::jsonb, now(), now()
),
(
'39000000-0000-4000-8000-00000000000b', 'authenticated', 'authenticated',
'rag-other-tenant@example.invalid', crypt('fixture-password', gen_salt('bf')), now(),
'{"provider":"email","providers":["email"]}'::jsonb, '{"name":"Other"}'::jsonb, now(), now()
),
(
'39000000-0000-4000-8000-00000000000c', 'authenticated', 'authenticated',
'rag-teammate@example.invalid', crypt('fixture-password', gen_salt('bf')), now(),
'{"provider":"email","providers":["email"]}'::jsonb, '{"name":"Teammate"}'::jsonb, now(), now()
);
-- Team T: searcher + teammate. Team T2: other tenant only.
INSERT INTO public.teams (id, name, owner_id) VALUES
('39100000-0000-4000-8000-00000000000a', 'RAG Team', '39000000-0000-4000-8000-00000000000c'),
('39100000-0000-4000-8000-00000000000b', 'Other Team', '39000000-0000-4000-8000-00000000000b');
INSERT INTO public.team_members (team_id, user_id, role) VALUES
('39100000-0000-4000-8000-00000000000a', '39000000-0000-4000-8000-00000000000c', 'owner'),
('39100000-0000-4000-8000-00000000000a', '39000000-0000-4000-8000-00000000000a', 'member'),
('39100000-0000-4000-8000-00000000000b', '39000000-0000-4000-8000-00000000000b', 'owner');
INSERT INTO public.knowledge_documents (id, user_id, team_id, title) VALUES
-- visible to the searcher
('39200000-0000-4000-8000-00000000000a', '39000000-0000-4000-8000-00000000000a', NULL,
'Searcher personal doc'),
('39200000-0000-4000-8000-00000000000c', '39000000-0000-4000-8000-00000000000c',
'39100000-0000-4000-8000-00000000000a', 'Teammate shared doc'),
-- invisible to the searcher
('39200000-0000-4000-8000-00000000000b', '39000000-0000-4000-8000-00000000000b', NULL,
'Other tenant personal doc'),
('39200000-0000-4000-8000-0000000000bb', '39000000-0000-4000-8000-00000000000b',
'39100000-0000-4000-8000-00000000000b', 'Other tenant team doc');
CREATE TEMP TABLE fixture_query ON COMMIT DROP AS
SELECT pg_temp.rand_vec() AS q;
GRANT SELECT ON fixture_query TO authenticated;
-- Searcher: 60 random chunks + chunk 60 identical to the query.
INSERT INTO public.knowledge_chunks (document_id, chunk_index, content, embedding)
SELECT '39200000-0000-4000-8000-00000000000a', g, 'searcher chunk ' || g, pg_temp.rand_vec()
FROM generate_series(0, 59) AS g;
INSERT INTO public.knowledge_chunks (id, document_id, chunk_index, content, embedding)
SELECT '39300000-0000-4000-8000-00000000000a', '39200000-0000-4000-8000-00000000000a', 60,
'searcher exact match', q
FROM fixture_query;
-- Team doc: 4 random chunks + one close to the query.
INSERT INTO public.knowledge_chunks (document_id, chunk_index, content, embedding)
SELECT '39200000-0000-4000-8000-00000000000c', g, 'team chunk ' || g, pg_temp.rand_vec()
FROM generate_series(0, 3) AS g;
INSERT INTO public.knowledge_chunks (id, document_id, chunk_index, content, embedding)
SELECT '39300000-0000-4000-8000-00000000000c', '39200000-0000-4000-8000-00000000000c', 4,
'team near match', pg_temp.near_vec(q, 0.05)
FROM fixture_query;
-- Other tenant owns almost the whole table, including an exact match of its
-- own and near matches in a team the searcher is not in.
INSERT INTO public.knowledge_chunks (document_id, chunk_index, content, embedding)
SELECT '39200000-0000-4000-8000-00000000000b', g, 'other chunk ' || g, pg_temp.rand_vec()
FROM generate_series(0, 1999) AS g;
INSERT INTO public.knowledge_chunks (id, document_id, chunk_index, content, embedding)
SELECT '39300000-0000-4000-8000-00000000000b', '39200000-0000-4000-8000-00000000000b', 2000,
'other exact match', q
FROM fixture_query;
INSERT INTO public.knowledge_chunks (document_id, chunk_index, content, embedding)
SELECT '39200000-0000-4000-8000-0000000000bb', g, 'other team near ' || g, pg_temp.near_vec(q, 0.02)
FROM fixture_query, generate_series(0, 9) AS g;
-- A chunk without an embedding must never be returned.
INSERT INTO public.knowledge_chunks (document_id, chunk_index, content)
VALUES ('39200000-0000-4000-8000-00000000000a', 61, 'searcher unembedded');
ANALYZE public.knowledge_chunks;
ANALYZE public.knowledge_documents;
-- Exact brute-force ranking over the searcher's visible chunks.
CREATE TEMP TABLE fixture_expected ON COMMIT DROP AS
SELECT
(SELECT array_agg(r.id ORDER BY r.distance, r.id) FROM (
SELECT kc.id, kc.embedding <=> f.q AS distance
FROM public.knowledge_chunks kc, fixture_query f
WHERE kc.embedding IS NOT NULL
AND kc.document_id IN ('39200000-0000-4000-8000-00000000000a',
'39200000-0000-4000-8000-00000000000c')
ORDER BY 2, 1
LIMIT 5
) r) AS top5,
(SELECT array_agg(r.id ORDER BY r.distance, r.id) FROM (
SELECT kc.id, kc.embedding <=> f.q AS distance
FROM public.knowledge_chunks kc, fixture_query f
WHERE kc.embedding IS NOT NULL
AND kc.document_id IN ('39200000-0000-4000-8000-00000000000a',
'39200000-0000-4000-8000-00000000000c')
ORDER BY 2, 1
LIMIT 20
) r) AS top20;
GRANT SELECT ON fixture_expected TO authenticated;
SELECT pg_temp.assert_true(
(SELECT top5[1:2] FROM fixture_expected)
= ARRAY['39300000-0000-4000-8000-00000000000a',
'39300000-0000-4000-8000-00000000000c']::uuid[],
'fixture sanity: exact match then team near match rank first'
);
-- ── 1) searcher gets the exact top-k of their visible chunks ─────────────
CREATE OR REPLACE FUNCTION pg_temp.assert_searcher_results(label text)
RETURNS void
LANGUAGE plpgsql
AS $$
DECLARE
q public.vector := (SELECT f.q FROM fixture_query f);
got uuid[];
BEGIN
got := pg_temp.match_ids(q, 5, -1);
PERFORM pg_temp.assert_true(
got = (SELECT top5 FROM fixture_expected),
format('%s: top-5 equals exact ranking (got %s)', label, got)
);
got := pg_temp.match_ids(q, 20, -1);
PERFORM pg_temp.assert_true(
got = (SELECT top20 FROM fixture_expected),
format('%s: top-20 equals exact ranking (got %s rows)', label, cardinality(got))
);
-- default threshold (0.5) as used by search-knowledge: only the two
-- planted matches qualify; the other tenant's exact/near matches never leak.
got := pg_temp.match_ids(q, 20, 0.5);
PERFORM pg_temp.assert_true(
got = ARRAY['39300000-0000-4000-8000-00000000000a',
'39300000-0000-4000-8000-00000000000c']::uuid[],
format('%s: threshold keeps only the caller''s planted matches (got %s)', label, got)
);
PERFORM pg_temp.assert_true(
NOT EXISTS (
SELECT 1 FROM public.match_knowledge_chunks(q, 50, -1) m
WHERE m.document_id NOT IN ('39200000-0000-4000-8000-00000000000a',
'39200000-0000-4000-8000-00000000000c')
OR m.content = 'searcher unembedded'
),
format('%s: only visible, embedded chunks are returned', label)
);
-- match_count is clamped: 66 visible embedded chunks, cap 50.
PERFORM pg_temp.assert_true(
cardinality(pg_temp.match_ids(q, 1000, -1)) = 50,
format('%s: match_count is capped at 50', label)
);
PERFORM pg_temp.assert_true(
cardinality(pg_temp.match_ids(q, NULL, -1)) = 5,
format('%s: NULL match_count falls back to 5 instead of unlimited', label)
);
PERFORM pg_temp.assert_true(
cardinality(pg_temp.match_ids(q, 0, -1)) = 0
AND cardinality(pg_temp.match_ids(q, -3, -1)) = 0,
format('%s: non-positive match_count returns nothing', label)
);
END;
$$;
SET LOCAL ROLE authenticated;
SELECT pg_temp.act_as('39000000-0000-4000-8000-00000000000a');
-- Push the planner towards index-ordered scans, the worst case for recall:
-- with seq scans and explicit sorts penalised, an ORDER BY distance LIMIT k
-- query is planned as an ANN index scan whenever one is available (what
-- happens in production once knowledge_chunks is large).
SET LOCAL enable_seqscan = off;
SET LOCAL enable_sort = off;
SELECT pg_temp.assert_searcher_results('no ANN index');
-- ── 2) still exact when an ANN index exists and is attractive ────────────
-- A properly trained IVFFlat index scanned with probes = 1 visits ~2% of all
-- rows across tenants. The function must not let the planner use it for the
-- ranking (the pre-fix shape did).
RESET ROLE;
CREATE INDEX knowledge_chunks_embedding_probe_test
ON public.knowledge_chunks
USING ivfflat (embedding public.vector_cosine_ops)
WITH (lists = 50);
SET LOCAL ivfflat.probes = 1;
SET LOCAL ROLE authenticated;
SELECT pg_temp.act_as('39000000-0000-4000-8000-00000000000a');
SELECT pg_temp.assert_searcher_results('trained IVFFlat index present');
-- ── 3) the other tenant sees only their own chunks ───────────────────────
SELECT pg_temp.act_as('39000000-0000-4000-8000-00000000000b');
SELECT pg_temp.assert_true(
(SELECT pg_temp.match_ids(f.q, 1, 0.5) FROM fixture_query f)
= ARRAY['39300000-0000-4000-8000-00000000000b']::uuid[],
'other tenant gets their own exact match first'
);
SELECT pg_temp.assert_true(
NOT EXISTS (
SELECT 1 FROM fixture_query f, public.match_knowledge_chunks(f.q, 50, -1) m
WHERE m.document_id NOT IN ('39200000-0000-4000-8000-00000000000b',
'39200000-0000-4000-8000-0000000000bb')
),
'other tenant never sees the searcher''s or team T''s chunks'
);
-- ── 4) anonymous callers get nothing ─────────────────────────────────────
SELECT set_config('request.jwt.claims', '', true);
SELECT pg_temp.assert_true(
(SELECT cardinality(pg_temp.match_ids(f.q, 50, -1)) FROM fixture_query f) = 0,
'caller without a user id sees no chunks'
);
ROLLBACK;

View file

@ -6,6 +6,13 @@
-- provider call before commit rejected N-1 of them. A 'processing' request now
-- holds one unit of the allowance until it is failed, committed or its lease
-- expires.
--
-- Regression (red-team r3-13, 20260929020000): the held unit lived in a second
-- ledger ('processing' rows) under a second advisory-lock key, so llm-proxy's
-- reserve_llm_quota could take the same last unit while a document was being
-- generated, and commit then threw the paid generation away with
-- generation_quota_exceeded. The claim now reserves through
-- reserve_llm_quota; commit/fail settle that reservation.
BEGIN;
@ -34,6 +41,26 @@ EXCEPTION WHEN OTHERS THEN
END;
$$;
-- Returns the commit payload, or {"error": SQLERRM} when the commit raises.
CREATE OR REPLACE FUNCTION pg_temp.try_commit(p_actor uuid, p_key uuid)
RETURNS jsonb
LANGUAGE plpgsql
AS $$
BEGIN
RETURN public.commit_meeting_document_generation_v1(p_actor, p_key, 'Generated body', 10, 1, 1);
EXCEPTION WHEN OTHERS THEN
RETURN jsonb_build_object('error', SQLERRM);
END;
$$;
CREATE OR REPLACE FUNCTION pg_temp.usage_today(p_actor uuid, p_feature text)
RETURNS integer
LANGUAGE sql
AS $$
SELECT coalesce(sum(count), 0)::integer FROM public.daily_usage
WHERE user_id = p_actor AND date = CURRENT_DATE AND feature = p_feature;
$$;
INSERT INTO auth.users (
id, aud, role, email, encrypted_password, email_confirmed_at,
raw_app_meta_data, raw_user_meta_data, created_at, updated_at
@ -47,19 +74,28 @@ INSERT INTO auth.users (
'37000000-0000-4000-8000-000000000002', 'authenticated', 'authenticated',
'meeting-doc-quota-unlimited@example.invalid', crypt('fixture-password', gen_salt('bf')), now(),
'{"provider":"email","providers":["email"]}'::jsonb, '{}'::jsonb, now(), now()
),
(
'37000000-0000-4000-8000-000000000003', 'authenticated', 'authenticated',
'meeting-doc-quota-pro@example.invalid', crypt('fixture-password', gen_salt('bf')), now(),
'{"provider":"email","providers":["email"]}'::jsonb, '{}'::jsonb, now(), now()
);
UPDATE public.subscriptions SET tier = 'free', status = 'active', overage_credits = 0
WHERE user_id = '37000000-0000-4000-8000-000000000001';
UPDATE public.subscriptions SET tier = 'pro_plus', status = 'active', overage_credits = 0
WHERE user_id = '37000000-0000-4000-8000-000000000002';
UPDATE public.subscriptions SET tier = 'pro', status = 'active', overage_credits = 0
WHERE user_id = '37000000-0000-4000-8000-000000000003';
INSERT INTO public.meetings (id, user_id, title, status, raw_transcript)
VALUES
('37100000-0000-4000-8000-000000000001', '37000000-0000-4000-8000-000000000001',
'Quota fixture meeting', 'completed', 'Speaker one talked about the roadmap.'),
('37100000-0000-4000-8000-000000000002', '37000000-0000-4000-8000-000000000002',
'Unlimited fixture meeting', 'completed', 'Speaker two talked about hiring.');
'Unlimited fixture meeting', 'completed', 'Speaker two talked about hiring.'),
('37100000-0000-4000-8000-000000000003', '37000000-0000-4000-8000-000000000003',
'Pro fixture meeting', 'completed', 'Speaker three talked about the launch.');
INSERT INTO public.user_templates (
id, user_id, template_kind, name, template_type, system_prompt, is_builtin
@ -67,7 +103,9 @@ INSERT INTO public.user_templates (
('37200000-0000-4000-8000-000000000001', '37000000-0000-4000-8000-000000000001',
'meeting_document', 'Quota fixture template', 'custom', 'Summarize the meeting.', false),
('37200000-0000-4000-8000-000000000002', '37000000-0000-4000-8000-000000000002',
'meeting_document', 'Unlimited fixture template', 'custom', 'Summarize the meeting.', false);
'meeting_document', 'Unlimited fixture template', 'custom', 'Summarize the meeting.', false),
('37200000-0000-4000-8000-000000000003', '37000000-0000-4000-8000-000000000003',
'meeting_document', 'Pro fixture template', 'custom', 'Summarize the meeting.', false);
-- One weekly Haiku unit left for the free user.
INSERT INTO public.daily_usage (user_id, date, feature, count)
@ -83,6 +121,7 @@ DECLARE
parallel jsonb;
replay jsonb;
after_release jsonb;
committed jsonb;
after_commit jsonb;
overage_claim jsonb;
overage_parallel jsonb;
@ -105,17 +144,21 @@ BEGIN
replay->>'error' IS NULL AND NOT (replay->>'claimed')::boolean AND replay->>'status' = 'processing',
'replaying the in-flight key reports processing: ' || replay::text
);
PERFORM pg_temp.assert_true(pg_temp.usage_today(actor, 'llm_haiku') = 250,
'a replay takes no additional unit');
-- A failed request releases the unit it held.
PERFORM public.fail_meeting_document_generation_v1(actor, '37300000-0000-4000-8000-000000000001', 'provider_timeout');
PERFORM pg_temp.assert_true(pg_temp.usage_today(actor, 'llm_haiku') = 249,
'failure gives the held unit back to the ledger');
after_release := pg_temp.try_claim(actor, '37300000-0000-4000-8000-000000000003', meeting, template, haiku);
PERFORM pg_temp.assert_true((after_release->>'claimed')::boolean,
'failure releases the in-flight unit: ' || after_release::text);
-- Commit converts the held unit into recorded usage; the allowance is spent.
PERFORM public.commit_meeting_document_generation_v1(
actor, '37300000-0000-4000-8000-000000000003', 'Generated body', 10, 1, 1
);
committed := pg_temp.try_commit(actor, '37300000-0000-4000-8000-000000000003');
PERFORM pg_temp.assert_true(committed->>'consumedFrom' = 'base',
'commit reports the unit the claim held: ' || committed::text);
SELECT count INTO usage_count FROM public.daily_usage
WHERE user_id = actor AND date = CURRENT_DATE AND feature = 'llm_haiku';
PERFORM pg_temp.assert_true(usage_count = 250, 'commit records exactly one unit');
@ -132,10 +175,13 @@ BEGIN
PERFORM pg_temp.assert_true(overage_parallel->>'error' = 'generation_quota_exceeded',
'a single overage credit is not spent twice by parallel claims: ' || overage_parallel::text);
-- A crashed request stops holding its unit once its lease expires.
UPDATE public.meeting_document_generation_requests
SET created_at = now() - interval '11 minutes'
WHERE user_id = actor AND idempotency_key = '37300000-0000-4000-8000-000000000005';
-- A crashed request stops holding its unit once its reservation lease expires.
UPDATE public.llm_quota_reservations AS reservation
SET lease_expires_at = now() - interval '1 minute'
FROM public.meeting_document_generation_requests AS request
WHERE request.user_id = actor
AND request.idempotency_key = '37300000-0000-4000-8000-000000000005'
AND reservation.id = request.llm_reservation_id;
after_lease := pg_temp.try_claim(actor, '37300000-0000-4000-8000-000000000007', meeting, template, haiku);
PERFORM pg_temp.assert_true((after_lease->>'claimed')::boolean,
'an expired in-flight lease no longer holds a unit: ' || after_lease::text);
@ -159,4 +205,146 @@ BEGIN
END;
$$;
-- Cross-path (r3-13): a meeting document and llm-proxy share one ledger.
DO $$
DECLARE
actor constant uuid := '37000000-0000-4000-8000-000000000003';
meeting constant uuid := '37100000-0000-4000-8000-000000000003';
template constant uuid := '37200000-0000-4000-8000-000000000003';
opus constant text := 'claude-opus-4-6';
claim jsonb;
proxy jsonb;
committed jsonb;
blocked jsonb;
legacy jsonb;
proxy_reservation constant uuid := '37600000-0000-4000-8000-000000000001';
credits integer;
BEGIN
-- One Opus unit left today (Pro: 50/day).
INSERT INTO public.daily_usage (user_id, date, feature, count)
VALUES (actor, CURRENT_DATE, 'llm_opus', 49);
-- 1) Document first, then a Talk/command request through llm-proxy.
claim := pg_temp.try_claim(actor, '37500000-0000-4000-8000-000000000001', meeting, template, opus);
PERFORM pg_temp.assert_true((claim->>'claimed')::boolean,
'the document claim takes the last Opus unit: ' || claim::text);
PERFORM pg_temp.assert_true(pg_temp.usage_today(actor, 'llm_opus') = 50,
'the claimed unit is visible in daily_usage while the provider call runs');
proxy := public.reserve_llm_quota(actor, gen_random_uuid(), 'llm_opus', 50, 'daily');
PERFORM pg_temp.assert_true((proxy->>'allowed')::boolean IS FALSE,
'llm-proxy cannot take the unit held by an in-flight document: ' || proxy::text);
PERFORM pg_temp.assert_true(
(SELECT count(*) FROM public.meeting_documents WHERE user_id = actor) = 0,
'no document exists before commit'
);
committed := pg_temp.try_commit(actor, '37500000-0000-4000-8000-000000000001');
PERFORM pg_temp.assert_true(
committed->>'error' IS NULL AND committed->>'consumedFrom' = 'base',
'the paid Opus generation is committed with the base unit the claim held: ' || committed::text
);
PERFORM pg_temp.assert_true(pg_temp.usage_today(actor, 'llm_opus') = 50,
'commit does not count the unit a second time');
-- consume_quota sees the same ledger.
PERFORM pg_temp.assert_true(
(public.consume_quota(actor, 'llm_opus', 50, 'daily')->>'allowed')::boolean IS FALSE,
'consume_quota counts document units'
);
-- 2) llm-proxy first, then a document: the claim sees the proxy's unit.
UPDATE public.daily_usage SET count = 49
WHERE user_id = actor AND date = CURRENT_DATE AND feature = 'llm_opus';
proxy := public.reserve_llm_quota(actor, proxy_reservation, 'llm_opus', 50, 'daily');
PERFORM pg_temp.assert_true((proxy->>'allowed')::boolean, 'llm-proxy takes the last unit');
blocked := pg_temp.try_claim(actor, '37500000-0000-4000-8000-000000000002', meeting, template, opus);
PERFORM pg_temp.assert_true(blocked->>'error' = 'generation_quota_exceeded',
'a document claim cannot take the unit held by llm-proxy: ' || blocked::text);
PERFORM public.finalize_llm_quota(proxy_reservation, false);
-- 3) Overage is taken at claim and refunded when the generation fails.
UPDATE public.daily_usage SET count = 50
WHERE user_id = actor AND date = CURRENT_DATE AND feature = 'llm_opus';
UPDATE public.subscriptions SET overage_credits = 1 WHERE user_id = actor;
claim := pg_temp.try_claim(actor, '37500000-0000-4000-8000-000000000003', meeting, template, opus);
PERFORM pg_temp.assert_true((claim->>'claimed')::boolean, 'an overage credit covers the claim');
SELECT overage_credits INTO credits FROM public.subscriptions WHERE user_id = actor;
PERFORM pg_temp.assert_true(credits = 0, 'the credit is held at claim time');
proxy := public.reserve_llm_quota(actor, gen_random_uuid(), 'llm_opus', 50, 'daily');
PERFORM pg_temp.assert_true((proxy->>'allowed')::boolean IS FALSE,
'llm-proxy cannot spend the credit held by an in-flight document');
PERFORM public.fail_meeting_document_generation_v1(actor, '37500000-0000-4000-8000-000000000003', 'provider_timeout');
SELECT overage_credits INTO credits FROM public.subscriptions WHERE user_id = actor;
PERFORM pg_temp.assert_true(credits = 1, 'a failed generation refunds the overage credit');
PERFORM pg_temp.assert_true(pg_temp.usage_today(actor, 'llm_opus') = 50,
'a failed generation gives its unit back');
-- 4) A row claimed before this migration (no reservation) is still charged
-- once, at commit, through the same ledger.
UPDATE public.daily_usage SET count = 49
WHERE user_id = actor AND date = CURRENT_DATE AND feature = 'llm_opus';
UPDATE public.subscriptions SET overage_credits = 0 WHERE user_id = actor;
claim := pg_temp.try_claim(actor, '37500000-0000-4000-8000-000000000004', meeting, template, opus);
PERFORM pg_temp.assert_true((claim->>'claimed')::boolean, 'legacy fixture claim');
-- Simulate the pre-migration shape: no reservation, unit not in daily_usage.
PERFORM public.finalize_llm_quota(
(SELECT llm_reservation_id FROM public.meeting_document_generation_requests
WHERE user_id = actor AND idempotency_key = '37500000-0000-4000-8000-000000000004'),
false
);
UPDATE public.meeting_document_generation_requests SET llm_reservation_id = NULL
WHERE user_id = actor AND idempotency_key = '37500000-0000-4000-8000-000000000004';
legacy := pg_temp.try_commit(actor, '37500000-0000-4000-8000-000000000004');
PERFORM pg_temp.assert_true(legacy->>'consumedFrom' = 'base',
'a legacy in-flight row is charged at commit: ' || legacy::text);
PERFORM pg_temp.assert_true(pg_temp.usage_today(actor, 'llm_opus') = 50,
'a legacy commit charges exactly one unit');
PERFORM pg_temp.assert_true(
(SELECT llm_reservation_id IS NOT NULL FROM public.meeting_document_generation_requests
WHERE user_id = actor AND idempotency_key = '37500000-0000-4000-8000-000000000004'),
'the legacy commit records the reservation that charged it'
);
END;
$$;
-- One lock key for the whole ledger: every quota path takes it through
-- daily_usage_lock_v1 and no quota function hardcodes an advisory-lock key.
-- (fail_meeting_document_generation_v1 locks inside finalize_llm_quota.)
DO $$
DECLARE
offenders text;
BEGIN
SELECT string_agg(p.proname, ', ' ORDER BY p.proname)
INTO offenders
FROM pg_proc AS p
JOIN pg_namespace AS n ON n.oid = p.pronamespace
WHERE n.nspname = 'public'
AND p.proname IN (
'reserve_llm_quota', 'finalize_llm_quota', 'consume_quota',
'claim_meeting_document_generation_v1', 'commit_meeting_document_generation_v1',
'fail_meeting_document_generation_v1'
)
AND (
p.prosrc LIKE '%pg_advisory%'
OR (
p.proname <> 'fail_meeting_document_generation_v1'
AND p.prosrc NOT LIKE '%daily_usage_lock_v1%'
)
OR (
p.proname = 'fail_meeting_document_generation_v1'
AND p.prosrc NOT LIKE '%finalize_llm_quota%'
)
);
PERFORM pg_temp.assert_true(offenders IS NULL,
'quota functions must lock only through daily_usage_lock_v1: ' || coalesce(offenders, ''));
PERFORM pg_temp.assert_true(
NOT has_function_privilege('anon', 'public.daily_usage_lock_v1(uuid, text)', 'EXECUTE')
AND NOT has_function_privilege('authenticated', 'public.daily_usage_lock_v1(uuid, text)', 'EXECUTE'),
'the ledger lock is not callable by clients'
);
END;
$$;
ROLLBACK;

View file

@ -0,0 +1,341 @@
\set ON_ERROR_STOP on
-- Regression (red-team r3-10): meeting-document claims and llm-proxy
-- reservations used two separate quota ledgers. A claim held its unit only as
-- a 'processing' row in meeting_document_generation_requests (advisory lock
-- seed 0), while reserve_llm_quota counted only daily_usage (seed 20260928).
-- An llm-proxy request could therefore take the unit a running document
-- generation already held; the document was paid for and then rejected by
-- commit with generation_quota_exceeded.
--
-- Since 20260929020000_unify_llm_quota_inflight a claim takes a
-- reserve_llm_quota lease, so both paths share one ledger (daily_usage +
-- llm_quota_reservations) and one lock (daily_usage_lock_v1). This file covers
-- the cross-path interleavings (document <-> llm-proxy in both orders, a mixed
-- burst at the limit, late commit after lease reclaim, legacy claims);
-- meeting-document-generation-quota.integration.sql covers the single path.
--
-- Local only: psql against the local Supabase stack. Runs in a transaction and
-- rolls back.
BEGIN;
CREATE OR REPLACE FUNCTION pg_temp.assert_true(condition boolean, message text)
RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
IF condition IS NOT TRUE THEN
RAISE EXCEPTION 'assertion_failed: %', message;
END IF;
END;
$$;
-- Returns the claim payload, or {"error": SQLERRM} when the claim raises.
CREATE OR REPLACE FUNCTION pg_temp.try_claim(p_actor uuid, p_key uuid, p_meeting uuid, p_template uuid, p_model text)
RETURNS jsonb
LANGUAGE plpgsql
AS $$
BEGIN
RETURN public.claim_meeting_document_generation_v1(
p_actor, p_key, p_meeting, p_template, 'Lease fixture document', p_model
);
EXCEPTION WHEN OTHERS THEN
RETURN jsonb_build_object('error', SQLERRM);
END;
$$;
-- Returns the commit payload, or {"error": SQLERRM} when the commit raises.
CREATE OR REPLACE FUNCTION pg_temp.try_commit(p_actor uuid, p_key uuid)
RETURNS jsonb
LANGUAGE plpgsql
AS $$
BEGIN
RETURN public.commit_meeting_document_generation_v1(p_actor, p_key, 'Generated body', 10, 1, 1);
EXCEPTION WHEN OTHERS THEN
RETURN jsonb_build_object('error', SQLERRM);
END;
$$;
CREATE OR REPLACE FUNCTION pg_temp.usage_of(p_actor uuid, p_feature text)
RETURNS integer
LANGUAGE sql
AS $$
SELECT coalesce(sum(count), 0)::integer FROM public.daily_usage
WHERE user_id = p_actor AND feature = p_feature AND date = CURRENT_DATE;
$$;
INSERT INTO auth.users (
id, aud, role, email, encrypted_password, email_confirmed_at,
raw_app_meta_data, raw_user_meta_data, created_at, updated_at
) VALUES
(
'38000000-0000-4000-8000-000000000001', 'authenticated', 'authenticated',
'meeting-doc-lease-pro@example.invalid', crypt('fixture-password', gen_salt('bf')), now(),
'{"provider":"email","providers":["email"]}'::jsonb, '{}'::jsonb, now(), now()
),
(
'38000000-0000-4000-8000-000000000002', 'authenticated', 'authenticated',
'meeting-doc-lease-free@example.invalid', crypt('fixture-password', gen_salt('bf')), now(),
'{"provider":"email","providers":["email"]}'::jsonb, '{}'::jsonb, now(), now()
),
(
'38000000-0000-4000-8000-000000000003', 'authenticated', 'authenticated',
'meeting-doc-lease-unlimited@example.invalid', crypt('fixture-password', gen_salt('bf')), now(),
'{"provider":"email","providers":["email"]}'::jsonb, '{}'::jsonb, now(), now()
);
UPDATE public.subscriptions SET tier = 'pro', status = 'active', overage_credits = 0
WHERE user_id = '38000000-0000-4000-8000-000000000001';
UPDATE public.subscriptions SET tier = 'free', status = 'active', overage_credits = 0
WHERE user_id = '38000000-0000-4000-8000-000000000002';
UPDATE public.subscriptions SET tier = 'pro_plus', status = 'active', overage_credits = 0
WHERE user_id = '38000000-0000-4000-8000-000000000003';
INSERT INTO public.meetings (id, user_id, title, status, raw_transcript)
VALUES
('38100000-0000-4000-8000-000000000001', '38000000-0000-4000-8000-000000000001',
'Lease fixture meeting', 'completed', 'Speaker one talked about the roadmap.'),
('38100000-0000-4000-8000-000000000002', '38000000-0000-4000-8000-000000000002',
'Lease fixture meeting', 'completed', 'Speaker two talked about hiring.'),
('38100000-0000-4000-8000-000000000003', '38000000-0000-4000-8000-000000000003',
'Lease fixture meeting', 'completed', 'Speaker three talked about budgets.');
INSERT INTO public.user_templates (
id, user_id, template_kind, name, template_type, system_prompt, is_builtin
) VALUES
('38200000-0000-4000-8000-000000000001', '38000000-0000-4000-8000-000000000001',
'meeting_document', 'Lease fixture template', 'custom', 'Summarize the meeting.', false),
('38200000-0000-4000-8000-000000000002', '38000000-0000-4000-8000-000000000002',
'meeting_document', 'Lease fixture template', 'custom', 'Summarize the meeting.', false),
('38200000-0000-4000-8000-000000000003', '38000000-0000-4000-8000-000000000003',
'meeting_document', 'Lease fixture template', 'custom', 'Summarize the meeting.', false);
-- Pro user, one daily Opus unit left (49/50).
INSERT INTO public.daily_usage (user_id, date, feature, count)
VALUES ('38000000-0000-4000-8000-000000000001', CURRENT_DATE, 'llm_opus', 49);
-- 1. A running document holds the last unit against llm-proxy, and its commit
-- is not thrown away afterwards (the reported bug).
DO $$
DECLARE
actor constant uuid := '38000000-0000-4000-8000-000000000001';
meeting constant uuid := '38100000-0000-4000-8000-000000000001';
template constant uuid := '38200000-0000-4000-8000-000000000001';
opus constant text := 'claude-opus-4-6';
claim jsonb;
proxy jsonb;
committed jsonb;
request_row public.meeting_document_generation_requests;
BEGIN
claim := pg_temp.try_claim(actor, '38300000-0000-4000-8000-000000000001', meeting, template, opus);
PERFORM pg_temp.assert_true((claim->>'claimed')::boolean, 'last Opus unit can be claimed: ' || claim::text);
SELECT * INTO request_row FROM public.meeting_document_generation_requests
WHERE user_id = actor AND idempotency_key = '38300000-0000-4000-8000-000000000001';
PERFORM pg_temp.assert_true(request_row.llm_reservation_id IS NOT NULL,
'the claim records the LLM quota lease it holds');
PERFORM pg_temp.assert_true(pg_temp.usage_of(actor, 'llm_opus') = 50,
'the in-flight claim is visible in the shared ledger');
-- The bug: llm-proxy used to see 49/50 here and reserve a second paid call.
proxy := public.reserve_llm_quota(actor, gen_random_uuid(), 'llm_opus', 50, 'daily');
PERFORM pg_temp.assert_true(NOT (proxy->>'allowed')::boolean,
'llm-proxy cannot take the unit a running document holds: ' || proxy::text);
committed := pg_temp.try_commit(actor, '38300000-0000-4000-8000-000000000001');
PERFORM pg_temp.assert_true(committed->>'error' IS NULL AND committed->'document' IS NOT NULL,
'the paid document is committed, not rejected: ' || committed::text);
PERFORM pg_temp.assert_true(committed->>'consumedFrom' = 'base', 'commit reports the base allowance');
PERFORM pg_temp.assert_true(pg_temp.usage_of(actor, 'llm_opus') = 50,
'commit completes the lease without charging a second unit');
PERFORM pg_temp.assert_true(
(SELECT status FROM public.llm_quota_reservations WHERE id = request_row.llm_reservation_id) = 'completed',
'commit completes the lease');
-- Idempotent commit replay does not charge again.
committed := pg_temp.try_commit(actor, '38300000-0000-4000-8000-000000000001');
PERFORM pg_temp.assert_true((committed->>'idempotent')::boolean, 'commit replay is idempotent');
PERFORM pg_temp.assert_true(pg_temp.usage_of(actor, 'llm_opus') = 50, 'commit replay charges nothing');
END;
$$;
-- 2. The reverse order: an llm-proxy reservation holds the last unit, so the
-- document claim is rejected before any provider work.
UPDATE public.daily_usage SET count = 49
WHERE user_id = '38000000-0000-4000-8000-000000000001' AND date = CURRENT_DATE AND feature = 'llm_opus';
DO $$
DECLARE
actor constant uuid := '38000000-0000-4000-8000-000000000001';
meeting constant uuid := '38100000-0000-4000-8000-000000000001';
template constant uuid := '38200000-0000-4000-8000-000000000001';
proxy_id constant uuid := '38500000-0000-4000-8000-000000000001';
proxy jsonb;
claim jsonb;
BEGIN
proxy := public.reserve_llm_quota(actor, proxy_id, 'llm_opus', 50, 'daily');
PERFORM pg_temp.assert_true((proxy->>'allowed')::boolean, 'llm-proxy takes the last unit');
claim := pg_temp.try_claim(actor, '38300000-0000-4000-8000-000000000002', meeting, template, 'claude-opus-4-6');
PERFORM pg_temp.assert_true(claim->>'error' = 'generation_quota_exceeded',
'a document claim cannot take the unit llm-proxy holds: ' || claim::text);
PERFORM pg_temp.assert_true(NOT EXISTS (
SELECT 1 FROM public.meeting_document_generation_requests
WHERE user_id = actor AND idempotency_key = '38300000-0000-4000-8000-000000000002'
), 'a rejected claim leaves no request row');
-- Once llm-proxy releases its lease, the document can be claimed.
PERFORM public.finalize_llm_quota(proxy_id, false);
claim := pg_temp.try_claim(actor, '38300000-0000-4000-8000-000000000002', meeting, template, 'claude-opus-4-6');
PERFORM pg_temp.assert_true((claim->>'claimed')::boolean, 'released unit can be claimed: ' || claim::text);
-- Replaying the in-flight key neither reserves again nor errors.
claim := pg_temp.try_claim(actor, '38300000-0000-4000-8000-000000000002', meeting, template, 'claude-opus-4-6');
PERFORM pg_temp.assert_true(
claim->>'error' IS NULL AND NOT (claim->>'claimed')::boolean AND claim->>'status' = 'processing',
'replaying the in-flight key reports processing: ' || claim::text);
PERFORM pg_temp.assert_true(pg_temp.usage_of(actor, 'llm_opus') = 50, 'a replay holds no extra unit');
-- Failure releases the unit back to the shared ledger, once.
PERFORM public.fail_meeting_document_generation_v1(actor, '38300000-0000-4000-8000-000000000002', 'provider_timeout');
PERFORM public.fail_meeting_document_generation_v1(actor, '38300000-0000-4000-8000-000000000002', 'provider_timeout');
PERFORM pg_temp.assert_true(pg_temp.usage_of(actor, 'llm_opus') = 49,
'failing a claim releases exactly one unit');
proxy := public.reserve_llm_quota(actor, gen_random_uuid(), 'llm_opus', 50, 'daily');
PERFORM pg_temp.assert_true((proxy->>'allowed')::boolean, 'the released unit is usable by llm-proxy');
END;
$$;
-- 3. Interleaved burst: document claims and llm-proxy reservations together
-- never exceed the remaining allowance, and one overage credit is spent once.
UPDATE public.daily_usage SET count = 45
WHERE user_id = '38000000-0000-4000-8000-000000000001' AND date = CURRENT_DATE AND feature = 'llm_opus';
UPDATE public.llm_quota_reservations SET status = 'completed'
WHERE user_id = '38000000-0000-4000-8000-000000000001' AND status = 'reserved';
UPDATE public.subscriptions SET overage_credits = 1
WHERE user_id = '38000000-0000-4000-8000-000000000001';
DO $$
DECLARE
actor constant uuid := '38000000-0000-4000-8000-000000000001';
meeting constant uuid := '38100000-0000-4000-8000-000000000001';
template constant uuid := '38200000-0000-4000-8000-000000000001';
granted integer := 0;
outcome jsonb;
i integer;
BEGIN
FOR i IN 1..10 LOOP
IF i % 2 = 0 THEN
outcome := public.reserve_llm_quota(actor, gen_random_uuid(), 'llm_opus', 50, 'daily');
IF (outcome->>'allowed')::boolean THEN granted := granted + 1; END IF;
ELSE
outcome := pg_temp.try_claim(actor, gen_random_uuid(), meeting, template, 'claude-opus-4-6');
IF coalesce((outcome->>'claimed')::boolean, false) THEN granted := granted + 1; END IF;
END IF;
END LOOP;
PERFORM pg_temp.assert_true(granted = 6,
'5 base units + 1 overage credit admit exactly 6 paid calls, got ' || granted);
PERFORM pg_temp.assert_true(pg_temp.usage_of(actor, 'llm_opus') = 51, 'shared ledger records every admitted call');
PERFORM pg_temp.assert_true(
(SELECT overage_credits FROM public.subscriptions WHERE user_id = actor) = 0,
'the overage credit is spent once');
END;
$$;
-- 4. Lease handling: an expired claim lease stops holding its unit, and a late
-- commit re-checks the allowance instead of charging past it.
DO $$
DECLARE
actor constant uuid := '38000000-0000-4000-8000-000000000002';
meeting constant uuid := '38100000-0000-4000-8000-000000000002';
template constant uuid := '38200000-0000-4000-8000-000000000002';
haiku constant text := 'claude-haiku-4-5-20251001';
claim jsonb;
proxy jsonb;
committed jsonb;
late_id uuid;
BEGIN
INSERT INTO public.daily_usage (user_id, date, feature, count)
VALUES (actor, CURRENT_DATE - 3, 'llm_haiku', 249);
claim := pg_temp.try_claim(actor, '38300000-0000-4000-8000-000000000010', meeting, template, haiku);
PERFORM pg_temp.assert_true((claim->>'claimed')::boolean, 'last weekly Haiku unit can be claimed');
-- Crashed worker: its lease expires, and the next reservation reclaims it.
SELECT llm_reservation_id INTO late_id FROM public.meeting_document_generation_requests
WHERE user_id = actor AND idempotency_key = '38300000-0000-4000-8000-000000000010';
UPDATE public.llm_quota_reservations SET lease_expires_at = now() - interval '1 minute' WHERE id = late_id;
proxy := public.reserve_llm_quota(actor, gen_random_uuid(), 'llm_haiku', 250, 'weekly');
PERFORM pg_temp.assert_true((proxy->>'allowed')::boolean,
'an expired document lease no longer holds a unit: ' || proxy::text);
-- The late commit finds its lease released and the allowance spent: reject
-- rather than charge a unit that is no longer there.
committed := pg_temp.try_commit(actor, '38300000-0000-4000-8000-000000000010');
PERFORM pg_temp.assert_true(committed->>'error' = 'generation_quota_exceeded',
'a late commit past the allowance is rejected: ' || committed::text);
-- With an overage credit the late commit is charged again and succeeds.
UPDATE public.subscriptions SET overage_credits = 1 WHERE user_id = actor;
committed := pg_temp.try_commit(actor, '38300000-0000-4000-8000-000000000010');
PERFORM pg_temp.assert_true(committed->>'error' IS NULL AND committed->>'consumedFrom' = 'overage',
'a late commit re-charges through the shared ledger: ' || committed::text);
PERFORM pg_temp.assert_true(
(SELECT overage_credits FROM public.subscriptions WHERE user_id = actor) = 0,
'the late commit spent the overage credit');
PERFORM pg_temp.assert_true(
(SELECT sum(count) FROM public.daily_usage WHERE user_id = actor AND feature = 'llm_haiku') = 251,
'the late commit is recorded once');
END;
$$;
-- 5. Claims made before this migration (no lease) still commit through the
-- shared ledger, and fail without touching it.
DO $$
DECLARE
actor constant uuid := '38000000-0000-4000-8000-000000000003';
meeting constant uuid := '38100000-0000-4000-8000-000000000003';
template constant uuid := '38200000-0000-4000-8000-000000000003';
lease uuid;
claim jsonb;
committed jsonb;
BEGIN
claim := pg_temp.try_claim(actor, '38300000-0000-4000-8000-000000000020', meeting, template, 'claude-sonnet-4-6');
PERFORM pg_temp.assert_true((claim->>'claimed')::boolean, 'pro_plus Sonnet claim');
-- Turn it into a legacy claim: no lease, nothing recorded yet.
SELECT llm_reservation_id INTO lease FROM public.meeting_document_generation_requests
WHERE user_id = actor AND idempotency_key = '38300000-0000-4000-8000-000000000020';
UPDATE public.meeting_document_generation_requests SET llm_reservation_id = NULL
WHERE user_id = actor AND idempotency_key = '38300000-0000-4000-8000-000000000020';
PERFORM public.finalize_llm_quota(lease, false);
PERFORM pg_temp.assert_true(pg_temp.usage_of(actor, 'llm_sonnet') = 0, 'legacy claim holds nothing');
committed := pg_temp.try_commit(actor, '38300000-0000-4000-8000-000000000020');
PERFORM pg_temp.assert_true(committed->>'error' IS NULL AND committed->>'consumedFrom' = 'base',
'a legacy claim commits: ' || committed::text);
PERFORM pg_temp.assert_true(pg_temp.usage_of(actor, 'llm_sonnet') = 1, 'a legacy commit records one unit');
-- Legacy failure is a no-op on the ledger.
claim := pg_temp.try_claim(actor, '38300000-0000-4000-8000-000000000021', meeting, template, 'claude-sonnet-4-6');
SELECT llm_reservation_id INTO lease FROM public.meeting_document_generation_requests
WHERE user_id = actor AND idempotency_key = '38300000-0000-4000-8000-000000000021';
UPDATE public.meeting_document_generation_requests SET llm_reservation_id = NULL
WHERE user_id = actor AND idempotency_key = '38300000-0000-4000-8000-000000000021';
PERFORM public.finalize_llm_quota(lease, false);
PERFORM public.fail_meeting_document_generation_v1(actor, '38300000-0000-4000-8000-000000000021', 'provider_timeout');
PERFORM pg_temp.assert_true(pg_temp.usage_of(actor, 'llm_sonnet') = 1, 'a legacy failure changes nothing');
-- Unlimited allowances are never throttled and still release on failure.
claim := pg_temp.try_claim(actor, '38300000-0000-4000-8000-000000000022', meeting, template, 'claude-haiku-4-5-20251001');
PERFORM pg_temp.assert_true((claim->>'claimed')::boolean, 'unlimited Haiku claim');
claim := pg_temp.try_claim(actor, '38300000-0000-4000-8000-000000000023', meeting, template, 'claude-haiku-4-5-20251001');
PERFORM pg_temp.assert_true((claim->>'claimed')::boolean, 'unlimited allowances are not throttled');
PERFORM public.fail_meeting_document_generation_v1(actor, '38300000-0000-4000-8000-000000000023', 'provider_timeout');
PERFORM pg_temp.assert_true(pg_temp.usage_of(actor, 'llm_haiku') = 1, 'unlimited failure releases its unit');
END;
$$;
ROLLBACK;

View file

@ -0,0 +1,341 @@
\set ON_ERROR_STOP on
-- A re-record that fails after upload restores the meeting it re-records
-- (migration 20260929040000). Local only: psql against the local Supabase
-- stack. Runs in a transaction and rolls back.
BEGIN;
CREATE OR REPLACE FUNCTION pg_temp.assert_true(condition boolean, message text)
RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
IF condition IS NOT TRUE THEN
RAISE EXCEPTION 'assertion_failed: %', message;
END IF;
END;
$$;
INSERT INTO auth.users (
id, aud, role, email, encrypted_password, email_confirmed_at,
raw_app_meta_data, raw_user_meta_data, created_at, updated_at
) VALUES (
'91000000-0000-4000-8000-000000000001', 'authenticated', 'authenticated',
'rerecord-failure-owner@example.invalid', crypt('fixture-password', gen_salt('bf')), now(),
'{"provider":"email","providers":["email"]}'::jsonb, '{}'::jsonb, now(), now()
);
-- M1: completed by a mobile capture (A1, job J1).
-- M2: first recording, no content yet.
-- M3: content from elsewhere (desktop): transcript rows, no mobile job, no audio row.
INSERT INTO public.meetings (
id, user_id, title, status, raw_transcript, minutes_markdown,
duration_ms, audio_storage_key
) VALUES
(
'92000000-0000-4000-8000-000000000001',
'91000000-0000-4000-8000-000000000001',
'Completed meeting', 'completed', 'old transcript', 'old minutes',
1000, '91000000-0000-4000-8000-000000000001/imports/a1.wav'
),
(
'92000000-0000-4000-8000-000000000002',
'91000000-0000-4000-8000-000000000001',
'First recording', 'recording', NULL, NULL, NULL, NULL
),
(
'92000000-0000-4000-8000-000000000003',
'91000000-0000-4000-8000-000000000001',
'Desktop meeting', 'completed', 'desktop transcript', NULL,
5000, 'desktop/original.wav'
);
INSERT INTO public.transcripts (meeting_id, segment_index, timestamp_ms, duration_ms, text)
VALUES
('92000000-0000-4000-8000-000000000001', 0, 0, 1000, 'old transcript'),
('92000000-0000-4000-8000-000000000003', 0, 0, 2000, 'desktop segment 0'),
('92000000-0000-4000-8000-000000000003', 1, 2000, 3000, 'desktop segment 1');
INSERT INTO public.audio_files (
id, user_id, meeting_id, source, original_name, storage_key, mime_type,
size_bytes, duration_ms, sha256, upload_status
) VALUES
(
'93000000-0000-4000-8000-000000000001',
'91000000-0000-4000-8000-000000000001',
'92000000-0000-4000-8000-000000000001',
'recording', 'a1.wav',
'91000000-0000-4000-8000-000000000001/imports/a1.wav',
'audio/wav', 32044, 1000, repeat('1', 64), 'uploaded'
),
(
'93000000-0000-4000-8000-000000000002',
'91000000-0000-4000-8000-000000000001',
'92000000-0000-4000-8000-000000000001',
'recording', 'a2.wav',
'91000000-0000-4000-8000-000000000001/imports/a2.wav',
'audio/wav', 64044, 2000, repeat('2', 64), 'uploaded'
),
(
'93000000-0000-4000-8000-000000000003',
'91000000-0000-4000-8000-000000000001',
'92000000-0000-4000-8000-000000000001',
'recording', 'a3.wav',
'91000000-0000-4000-8000-000000000001/imports/a3.wav',
'audio/wav', 96044, 3000, repeat('3', 64), 'uploaded'
),
(
'93000000-0000-4000-8000-000000000004',
'91000000-0000-4000-8000-000000000001',
'92000000-0000-4000-8000-000000000002',
'recording', 'first.wav',
'91000000-0000-4000-8000-000000000001/imports/first.wav',
'audio/wav', 32044, 1000, repeat('4', 64), 'uploaded'
),
(
'93000000-0000-4000-8000-000000000005',
'91000000-0000-4000-8000-000000000001',
'92000000-0000-4000-8000-000000000003',
'recording', 'desktop-rerecord.wav',
'91000000-0000-4000-8000-000000000001/imports/desktop-rerecord.wav',
'audio/wav', 32044, 9000, repeat('5', 64), 'failed'
);
INSERT INTO public.processing_jobs (
user_id, audio_file_id, meeting_id, kind, status, progress, attempt_count,
idempotency_key, result, started_at, completed_at
) VALUES (
'91000000-0000-4000-8000-000000000001',
'93000000-0000-4000-8000-000000000001',
'92000000-0000-4000-8000-000000000001',
'transcription', 'succeeded', 100, 1,
'mobile-meeting:m1:' || repeat('1', 64),
jsonb_build_object('audio_file_id', '93000000-0000-4000-8000-000000000001', 'duration_ms', 1000),
now() - interval '1 day', now() - interval '1 day'
);
SET LOCAL ROLE authenticated;
SELECT set_config(
'request.jwt.claims',
'{"sub":"91000000-0000-4000-8000-000000000001","role":"authenticated"}',
true
);
-- 1) Re-record M1 with A2; STT fails terminally after upload.
SELECT public.mobile_begin_meeting_recording('92000000-0000-4000-8000-000000000001');
SELECT public.mobile_queue_meeting_recording('92000000-0000-4000-8000-000000000001', 2000);
SELECT public.mobile_begin_meeting_processing(
'92000000-0000-4000-8000-000000000001',
'93000000-0000-4000-8000-000000000002',
'mobile-meeting:m1:' || repeat('2', 64)
);
SELECT pg_temp.assert_true(
(SELECT audio_storage_key FROM public.meetings
WHERE id = '92000000-0000-4000-8000-000000000001')
= '91000000-0000-4000-8000-000000000001/imports/a2.wav',
'precondition: processing points the meeting at the new capture'
);
SELECT public.mobile_mark_meeting_processing_failure(
'92000000-0000-4000-8000-000000000001',
'mobile-meeting:m1:' || repeat('2', 64),
'transcription', 'STT failed', true
);
SELECT pg_temp.assert_true(
EXISTS (
SELECT 1 FROM public.meetings
WHERE id = '92000000-0000-4000-8000-000000000001'
AND status = 'completed'
AND error_message IS NULL
AND raw_transcript = 'old transcript'
AND minutes_markdown = 'old minutes'
AND duration_ms = 1000
AND audio_storage_key = '91000000-0000-4000-8000-000000000001/imports/a1.wav'
),
'terminal failure of a re-record restores the completed meeting and its audio'
);
SELECT pg_temp.assert_true(
EXISTS (
SELECT 1 FROM public.processing_jobs
WHERE idempotency_key = 'mobile-meeting:m1:' || repeat('2', 64)
AND status = 'failed' AND error_message = 'STT failed'
),
'the failed job still records the failure'
);
RESET ROLE;
SELECT pg_temp.assert_true(
EXISTS (
SELECT 1 FROM public.audio_files
WHERE id = '93000000-0000-4000-8000-000000000002'
AND meeting_id IS NULL AND upload_status = 'deleted'
),
'the failed capture audio is detached'
);
SELECT pg_temp.assert_true(
EXISTS (
SELECT 1 FROM public.audio_purge_queue
WHERE user_id = '91000000-0000-4000-8000-000000000001'
AND storage_key = '91000000-0000-4000-8000-000000000001/imports/a2.wav'
),
'the failed capture audio is queued for purge'
);
SELECT pg_temp.assert_true(
EXISTS (
SELECT 1 FROM public.audio_files
WHERE id = '93000000-0000-4000-8000-000000000001'
AND meeting_id = '92000000-0000-4000-8000-000000000001'
AND upload_status = 'uploaded'
),
'the audio behind the kept transcript stays linked'
);
SELECT pg_temp.assert_true(
(SELECT meeting_id FROM public.audio_files
WHERE id = '93000000-0000-4000-8000-000000000003')
= '92000000-0000-4000-8000-000000000001',
'uploaded audio no failed job owns is not detached by an unrelated failure'
);
-- 2) Re-record M1 with A3; the user discards the queued item.
SET LOCAL ROLE authenticated;
SELECT set_config(
'request.jwt.claims',
'{"sub":"91000000-0000-4000-8000-000000000001","role":"authenticated"}',
true
);
SELECT public.mobile_begin_meeting_recording('92000000-0000-4000-8000-000000000001');
SELECT public.mobile_queue_meeting_recording('92000000-0000-4000-8000-000000000001', 3000);
SELECT public.mobile_begin_meeting_processing(
'92000000-0000-4000-8000-000000000001',
'93000000-0000-4000-8000-000000000003',
'mobile-meeting:m1:' || repeat('3', 64)
);
SELECT pg_temp.assert_true(
(SELECT status FROM public.mobile_fail_meeting_recording(
'92000000-0000-4000-8000-000000000001', 'Queued audio processing was cancelled'
)) = 'completed',
'fail_recording reports the restored status'
);
SELECT pg_temp.assert_true(
EXISTS (
SELECT 1 FROM public.meetings
WHERE id = '92000000-0000-4000-8000-000000000001'
AND status = 'completed'
AND error_message IS NULL
AND duration_ms = 1000
AND audio_storage_key = '91000000-0000-4000-8000-000000000001/imports/a1.wav'
),
'a discarded re-record restores the completed meeting and its audio'
);
RESET ROLE;
SELECT pg_temp.assert_true(
(SELECT meeting_id FROM public.audio_files
WHERE id = '93000000-0000-4000-8000-000000000003') IS NULL,
'the discarded capture audio is detached'
);
-- 3) A first recording keeps the error outcome and its audio for retry.
SET LOCAL ROLE authenticated;
SELECT set_config(
'request.jwt.claims',
'{"sub":"91000000-0000-4000-8000-000000000001","role":"authenticated"}',
true
);
SELECT public.mobile_queue_meeting_recording('92000000-0000-4000-8000-000000000002', 1000);
SELECT public.mobile_begin_meeting_processing(
'92000000-0000-4000-8000-000000000002',
'93000000-0000-4000-8000-000000000004',
'mobile-meeting:m2:' || repeat('4', 64)
);
SELECT public.mobile_mark_meeting_processing_failure(
'92000000-0000-4000-8000-000000000002',
'mobile-meeting:m2:' || repeat('4', 64),
'transcription', 'STT failed', true
);
SELECT pg_temp.assert_true(
EXISTS (
SELECT 1 FROM public.meetings
WHERE id = '92000000-0000-4000-8000-000000000002'
AND status = 'error'
AND error_message = 'STT failed'
),
'terminal failure of a first recording still reports an error'
);
SELECT pg_temp.assert_true(
(SELECT status FROM public.mobile_fail_meeting_recording(
'92000000-0000-4000-8000-000000000002', 'Recording failed'
)) = 'error',
'fail_recording of a first recording still reports an error'
);
RESET ROLE;
SELECT pg_temp.assert_true(
EXISTS (
SELECT 1 FROM public.audio_files
WHERE id = '93000000-0000-4000-8000-000000000004'
AND meeting_id = '92000000-0000-4000-8000-000000000002'
AND upload_status = 'uploaded'
),
'a failed first recording keeps its audio linked for retry'
);
-- 4) Content from elsewhere: a re-record whose upload failed (no job) keeps the
-- original playback key and restores the duration from the transcript span.
SET LOCAL ROLE authenticated;
SELECT set_config(
'request.jwt.claims',
'{"sub":"91000000-0000-4000-8000-000000000001","role":"authenticated"}',
true
);
SELECT public.mobile_begin_meeting_recording('92000000-0000-4000-8000-000000000003');
SELECT public.mobile_queue_meeting_recording('92000000-0000-4000-8000-000000000003', 9000);
SELECT public.mobile_fail_meeting_recording(
'92000000-0000-4000-8000-000000000003', 'Audio upload failed'
);
SELECT pg_temp.assert_true(
EXISTS (
SELECT 1 FROM public.meetings
WHERE id = '92000000-0000-4000-8000-000000000003'
AND status = 'completed'
AND error_message IS NULL
AND raw_transcript = 'desktop transcript'
AND duration_ms = 5000
AND audio_storage_key = 'desktop/original.wav'
),
'a failed re-record of foreign content keeps its key and transcript duration'
);
RESET ROLE;
SELECT pg_temp.assert_true(
(SELECT meeting_id FROM public.audio_files
WHERE id = '93000000-0000-4000-8000-000000000005') IS NULL,
'the failed upload row of the re-record is detached'
);
-- 5) Cancel before processing keeps the 20260929002700 behavior.
SET LOCAL ROLE authenticated;
SELECT set_config(
'request.jwt.claims',
'{"sub":"91000000-0000-4000-8000-000000000001","role":"authenticated"}',
true
);
SELECT public.mobile_begin_meeting_recording('92000000-0000-4000-8000-000000000001');
SELECT pg_temp.assert_true(
(SELECT status FROM public.mobile_cancel_meeting_recording(
'92000000-0000-4000-8000-000000000001'
)) = 'completed',
'cancel of a re-record still returns to completed'
);
-- 6) The helpers are not reachable through the API roles.
RESET ROLE;
SELECT pg_temp.assert_true(
NOT has_function_privilege('authenticated', 'public.mobile_meeting_has_content_v1(uuid)', 'EXECUTE')
AND NOT has_function_privilege('anon', 'public.mobile_meeting_has_content_v1(uuid)', 'EXECUTE')
AND NOT has_function_privilege(
'authenticated', 'public.mobile_restore_meeting_after_failed_capture_v1(uuid, uuid, uuid)', 'EXECUTE'
)
AND NOT has_function_privilege(
'anon', 'public.mobile_restore_meeting_after_failed_capture_v1(uuid, uuid, uuid)', 'EXECUTE'
),
'restore helpers are internal'
);
ROLLBACK;

View file

@ -0,0 +1,207 @@
\set ON_ERROR_STOP on
-- Regression: a confirmed refund of an older Payple order (same billing key)
-- must not revoke the period funded by the current order.
-- Covers apply_payment_provider_event from
-- 20260929100011_payple_cancellation_order_scope.sql.
BEGIN;
CREATE OR REPLACE FUNCTION pg_temp.assert_true(condition boolean, message text)
RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
IF condition IS NOT TRUE THEN
RAISE EXCEPTION 'assertion_failed: %', message;
END IF;
END;
$$;
INSERT INTO auth.users (
id, aud, role, email, encrypted_password, email_confirmed_at,
raw_app_meta_data, raw_user_meta_data, created_at, updated_at
) VALUES (
'20000000-0000-4000-8000-000000000031', 'authenticated', 'authenticated',
'payple-order-scope@example.invalid', crypt('fixture-password', gen_salt('bf')), now(),
'{"provider":"email","providers":["email"]}'::jsonb, '{}'::jsonb, now(), now()
);
DO $$
DECLARE
c_user constant uuid := '20000000-0000-4000-8000-000000000031';
c_payer constant text := 'payer-order-scope';
c_oid1 constant text := 'D3RO-20260801090000-scope01';
c_oid2 constant text := 'D3RO-20260901090000-scope02';
v_result jsonb;
v_period_end timestamptz;
v_cursor_before timestamptz;
v_cursor_after timestamptz;
v_sub public.subscriptions%ROWTYPE;
v_disposition text;
BEGIN
-- Month 1: checkout order oid1.
v_result := public.apply_payment_provider_event(
p_user_id => c_user,
p_provider => 'payple',
p_event_id => 'payment:' || c_oid1,
p_event_created_at => now() - interval '40 days',
p_event_type => 'payment.completed',
p_payload_digest => repeat('a', 64),
p_provider_resource_id => c_payer,
p_tier => 'pro',
p_status => 'active',
p_entitled => true,
p_current_period_start => now() - interval '40 days',
p_current_period_end => now() - interval '10 days',
p_auto_renewing => true,
p_provider_customer_id => c_payer,
p_provider_order_id => c_oid1
);
PERFORM pg_temp.assert_true((v_result->>'applied')::boolean, 'month 1 applied');
-- Month 2: renewal order oid2 on the same billing key.
v_period_end := now() + interval '20 days';
v_result := public.apply_payment_provider_event(
p_user_id => c_user,
p_provider => 'payple',
p_event_id => 'payment:' || c_oid2,
p_event_created_at => now() - interval '10 days',
p_event_type => 'payment.completed',
p_payload_digest => repeat('b', 64),
p_provider_resource_id => c_payer,
p_tier => 'pro',
p_status => 'active',
p_entitled => true,
p_current_period_start => now() - interval '10 days',
p_current_period_end => v_period_end,
p_auto_renewing => true,
p_provider_customer_id => c_payer,
p_provider_order_id => c_oid2
);
PERFORM pg_temp.assert_true((v_result->>'applied')::boolean, 'month 2 applied');
SELECT last_event_created_at INTO v_cursor_before
FROM public.payment_provider_cursors
WHERE user_id = c_user AND provider = 'payple';
-- Support refunds oid1; Payple confirms the cancellation webhook.
v_result := public.apply_payment_provider_event(
p_user_id => c_user,
p_provider => 'payple',
p_event_id => 'cancel:' || c_oid1 || ':승인취소완료',
p_event_created_at => now(),
p_event_type => 'webhook.payment_canceled',
p_payload_digest => repeat('c', 64),
p_provider_resource_id => c_payer,
p_tier => 'free',
p_status => 'canceled',
p_entitled => false,
p_current_period_start => NULL,
p_current_period_end => now(),
p_cancel_at => now(),
p_auto_renewing => false,
p_provider_customer_id => c_payer,
p_provider_order_id => c_oid1
);
PERFORM pg_temp.assert_true(
NOT (v_result->>'applied')::boolean
AND v_result->>'reason' = 'canceled_order_not_current',
'refund of an older order is ignored, got ' || v_result::text
);
SELECT * INTO v_sub FROM public.subscriptions WHERE user_id = c_user;
PERFORM pg_temp.assert_true(
v_sub.tier = 'pro'
AND v_sub.provider = 'payple'
AND v_sub.auto_renewing
AND v_sub.payple_pay_oid = c_oid2
AND v_sub.current_period_end = v_period_end
AND v_sub.provider_resource_id = c_payer,
'current paid period and renewals are preserved'
);
SELECT disposition INTO v_disposition
FROM public.payment_provider_events
WHERE provider = 'payple' AND event_id = 'cancel:' || c_oid1 || ':승인취소완료';
PERFORM pg_temp.assert_true(v_disposition = 'ignored', 'ignored event is recorded');
SELECT last_event_created_at INTO v_cursor_after
FROM public.payment_provider_cursors
WHERE user_id = c_user AND provider = 'payple';
PERFORM pg_temp.assert_true(
v_cursor_after = v_cursor_before,
'ignored refund does not advance the ordering cursor'
);
-- Refunding the current order still revokes entitlement.
v_result := public.apply_payment_provider_event(
p_user_id => c_user,
p_provider => 'payple',
p_event_id => 'cancel:' || c_oid2 || ':승인취소완료',
p_event_created_at => now(),
p_event_type => 'webhook.payment_canceled',
p_payload_digest => repeat('d', 64),
p_provider_resource_id => c_payer,
p_tier => 'free',
p_status => 'canceled',
p_entitled => false,
p_current_period_start => NULL,
p_current_period_end => now(),
p_cancel_at => now(),
p_auto_renewing => false,
p_provider_customer_id => c_payer,
p_provider_order_id => c_oid2
);
PERFORM pg_temp.assert_true(
(v_result->>'applied')::boolean,
'refund of the current order is applied, got ' || v_result::text
);
SELECT * INTO v_sub FROM public.subscriptions WHERE user_id = c_user;
PERFORM pg_temp.assert_true(
v_sub.tier = 'free' AND v_sub.provider = 'none' AND NOT v_sub.auto_renewing,
'current order refund revokes the subscription'
);
-- Revocations that name no order (scheduled expiry, manage) are unaffected.
v_result := public.apply_payment_provider_event(
p_user_id => c_user,
p_provider => 'payple',
p_event_id => 'payment:D3RO-20260910090000-scope03',
p_event_created_at => now() + interval '1 second',
p_event_type => 'payment.completed',
p_payload_digest => repeat('e', 64),
p_provider_resource_id => c_payer,
p_tier => 'pro',
p_status => 'active',
p_entitled => true,
p_current_period_start => now(),
p_current_period_end => now() + interval '1 month',
p_auto_renewing => false,
p_provider_customer_id => c_payer,
p_provider_order_id => 'D3RO-20260910090000-scope03'
);
PERFORM pg_temp.assert_true((v_result->>'applied')::boolean, 're-entitled');
v_result := public.apply_payment_provider_event(
p_user_id => c_user,
p_provider => 'payple',
p_event_id => 'scheduled-expire:order-scope',
p_event_created_at => now() + interval '2 seconds',
p_event_type => 'subscription.scheduled_expiry',
p_payload_digest => repeat('f', 64),
p_provider_resource_id => c_payer,
p_tier => 'free',
p_status => 'expired',
p_entitled => false,
p_provider_order_id => NULL
);
PERFORM pg_temp.assert_true(
(v_result->>'applied')::boolean,
'order-less revocation still applies, got ' || v_result::text
);
END;
$$;
ROLLBACK;
SELECT 'payple_cancellation_order_scope_ok' AS result;

View file

@ -0,0 +1,338 @@
\set ON_ERROR_STOP on
-- Regression: team management RPCs must reject callers that hold no membership
-- row in the target team (see migrations/20260929010000_team_rpc_null_role_guard.sql).
--
-- Before that migration each RPC read the caller role with
-- SELECT role INTO caller_role FROM team_members WHERE ... user_id = auth.uid()
-- and compared it with `<>` / `NOT IN`. For a non-member caller_role is NULL,
-- every guard evaluated to NULL, plpgsql skipped the RAISE, and any signed-in
-- user who knew a team id could mint an admin invite for a second account,
-- change member roles, remove members and cancel invites.
--
-- Local only: psql against the local Supabase stack. Runs in a transaction and
-- rolls back.
BEGIN;
CREATE OR REPLACE FUNCTION pg_temp.assert_true(condition boolean, message text)
RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
IF condition IS NOT TRUE THEN
RAISE EXCEPTION 'assertion_failed: %', message;
END IF;
END;
$$;
CREATE OR REPLACE FUNCTION pg_temp.act_as(user_id uuid)
RETURNS void
LANGUAGE sql
AS $$
SELECT set_config(
'request.jwt.claims',
pg_catalog.json_build_object('sub', user_id, 'role', 'authenticated')::text,
true
);
$$;
-- Runs `statement` and requires it to fail with SQLSTATE 42501 and the given
-- error message. Anything else (success, another error) fails the test.
CREATE OR REPLACE FUNCTION pg_temp.expect_forbidden(
statement text,
expected_message text,
label text
)
RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
BEGIN
EXECUTE statement;
EXCEPTION
WHEN insufficient_privilege THEN
IF SQLERRM <> expected_message THEN
RAISE EXCEPTION 'assertion_failed: % raised % instead of %',
label, SQLERRM, expected_message;
END IF;
RETURN;
END;
RAISE EXCEPTION 'assertion_failed: % was allowed', label;
END;
$$;
-- ---------------------------------------------------------------------------
-- 1. Pure role policy: a missing role (NULL) never satisfies any requirement.
-- ---------------------------------------------------------------------------
SELECT pg_temp.assert_true(
public.team_role_at_least_v1(NULL, 'member') IS FALSE,
'no membership does not satisfy member'
);
SELECT pg_temp.assert_true(
public.team_role_at_least_v1(NULL, 'owner') IS FALSE,
'no membership does not satisfy owner'
);
SELECT pg_temp.assert_true(
public.team_role_at_least_v1('owner', NULL) IS FALSE,
'an unknown requirement is never satisfied'
);
SELECT pg_temp.assert_true(
public.team_role_at_least_v1('superuser', 'member') IS FALSE,
'an unknown role does not satisfy member'
);
SELECT pg_temp.assert_true(
public.team_role_at_least_v1('owner', 'admin')
AND public.team_role_at_least_v1('owner', 'owner')
AND public.team_role_at_least_v1('admin', 'admin')
AND public.team_role_at_least_v1('admin', 'member')
AND public.team_role_at_least_v1('member', 'member'),
'role hierarchy owner > admin > member is honoured'
);
SELECT pg_temp.assert_true(
NOT public.team_role_at_least_v1('admin', 'owner')
AND NOT public.team_role_at_least_v1('member', 'admin'),
'lower roles do not satisfy higher requirements'
);
SELECT pg_temp.assert_true(
NOT has_function_privilege('authenticated', 'public.require_team_role_v1(uuid, text)', 'EXECUTE')
AND NOT has_function_privilege('anon', 'public.require_team_role_v1(uuid, text)', 'EXECUTE'),
'role guard helper is internal to the team RPCs'
);
-- ---------------------------------------------------------------------------
-- 2. Fixtures: team T with owner O, admin A, member M; outsider X with a second
-- account X2; a pending invite for I.
-- ---------------------------------------------------------------------------
INSERT INTO auth.users (
id, aud, role, email, encrypted_password, email_confirmed_at,
raw_app_meta_data, raw_user_meta_data, created_at, updated_at
)
SELECT
fixture.id, 'authenticated', 'authenticated', fixture.email,
crypt('fixture-password', gen_salt('bf')), now(),
'{"provider":"email","providers":["email"]}'::jsonb, '{}'::jsonb, now(), now()
FROM (VALUES
('43100000-0000-4000-8000-000000000001'::uuid, 'null-guard-owner@example.invalid'),
('43100000-0000-4000-8000-000000000002'::uuid, 'null-guard-admin@example.invalid'),
('43100000-0000-4000-8000-000000000003'::uuid, 'null-guard-member@example.invalid'),
('43100000-0000-4000-8000-000000000004'::uuid, 'null-guard-outsider@example.invalid'),
('43100000-0000-4000-8000-000000000005'::uuid, 'null-guard-outsider-2@example.invalid'),
('43100000-0000-4000-8000-000000000006'::uuid, 'null-guard-invitee@example.invalid')
) AS fixture(id, email);
SET LOCAL ROLE authenticated;
SELECT pg_temp.act_as('43100000-0000-4000-8000-000000000001');
SELECT (public.create_team('Null Role Guard Team')->>'id')::uuid AS team_id \gset
SELECT set_config('test.team_id', :'team_id', true);
SELECT public.create_team_invite(:'team_id', 'null-guard-admin@example.invalid', 'admin')
->>'token' AS admin_token \gset
SELECT public.create_team_invite(:'team_id', 'null-guard-member@example.invalid', 'member')
->>'token' AS member_token \gset
SELECT (public.create_team_invite(:'team_id', 'null-guard-invitee@example.invalid', 'member')
->>'id')::uuid AS pending_invite_id \gset
SELECT set_config('test.pending_invite_id', :'pending_invite_id', true);
SELECT pg_temp.act_as('43100000-0000-4000-8000-000000000002');
SELECT public.accept_team_invite(:'admin_token');
SELECT pg_temp.act_as('43100000-0000-4000-8000-000000000003');
SELECT public.accept_team_invite(:'member_token');
-- ---------------------------------------------------------------------------
-- 3. Non-member X: every management RPC is refused.
-- ---------------------------------------------------------------------------
SELECT pg_temp.act_as('43100000-0000-4000-8000-000000000004');
SELECT pg_temp.expect_forbidden(
format(
'SELECT public.create_team_invite(%L::uuid, %L, %L)',
:'team_id', 'null-guard-outsider-2@example.invalid', 'admin'
),
'team_admin_required',
'non-member minting an admin invite'
);
SELECT pg_temp.expect_forbidden(
format(
'SELECT public.create_team_invite(%L::uuid, %L, %L)',
:'team_id', 'null-guard-outsider-2@example.invalid', 'member'
),
'team_admin_required',
'non-member minting a member invite'
);
SELECT pg_temp.expect_forbidden(
format(
'SELECT public.update_team_member_role(%L::uuid, %L::uuid, %L)',
:'team_id', '43100000-0000-4000-8000-000000000003', 'admin'
),
'team_owner_required',
'non-member promoting a member'
);
SELECT pg_temp.expect_forbidden(
format(
'SELECT public.update_team_member_role(%L::uuid, %L::uuid, %L)',
:'team_id', '43100000-0000-4000-8000-000000000002', 'member'
),
'team_owner_required',
'non-member demoting an admin'
);
SELECT pg_temp.expect_forbidden(
format(
'SELECT public.remove_team_member(%L::uuid, %L::uuid)',
:'team_id', '43100000-0000-4000-8000-000000000003'
),
'team_admin_required',
'non-member removing a member'
);
SELECT pg_temp.expect_forbidden(
format(
'SELECT public.remove_team_member(%L::uuid, %L::uuid)',
:'team_id', '43100000-0000-4000-8000-000000000002'
),
'team_admin_required',
'non-member removing an admin'
);
SELECT pg_temp.expect_forbidden(
format(
'SELECT public.remove_team_member(%L::uuid, %L::uuid)',
:'team_id', '43100000-0000-4000-8000-000000000099'
),
'team_admin_required',
'non-member probing membership of an unknown user'
);
SELECT pg_temp.expect_forbidden(
format('SELECT public.cancel_team_invite(%L::uuid)', :'pending_invite_id'),
'team_admin_required',
'non-member cancelling a pending invite'
);
-- The second attacker account has nothing to accept.
SELECT pg_temp.act_as('43100000-0000-4000-8000-000000000005');
SELECT pg_temp.assert_true(
(SELECT count(*) FROM public.list_team_members(:'team_id')) = 0,
'second outsider account sees no team members'
);
-- ---------------------------------------------------------------------------
-- 4. Existing role rules still hold for members.
-- ---------------------------------------------------------------------------
SELECT pg_temp.act_as('43100000-0000-4000-8000-000000000003');
SELECT pg_temp.expect_forbidden(
format(
'SELECT public.create_team_invite(%L::uuid, %L, %L)',
:'team_id', 'null-guard-outsider-2@example.invalid', 'member'
),
'team_admin_required',
'regular member inviting'
);
SELECT pg_temp.expect_forbidden(
format(
'SELECT public.update_team_member_role(%L::uuid, %L::uuid, %L)',
:'team_id', '43100000-0000-4000-8000-000000000002', 'member'
),
'team_owner_required',
'regular member demoting an admin'
);
SELECT pg_temp.expect_forbidden(
format(
'SELECT public.remove_team_member(%L::uuid, %L::uuid)',
:'team_id', '43100000-0000-4000-8000-000000000002'
),
'team_admin_required',
'regular member removing an admin'
);
SELECT pg_temp.expect_forbidden(
format('SELECT public.cancel_team_invite(%L::uuid)', :'pending_invite_id'),
'team_admin_required',
'regular member cancelling another user''s invite'
);
SELECT pg_temp.act_as('43100000-0000-4000-8000-000000000002');
SELECT pg_temp.expect_forbidden(
format(
'SELECT public.create_team_invite(%L::uuid, %L, %L)',
:'team_id', 'null-guard-outsider-2@example.invalid', 'admin'
),
'owner_required_for_admin_invite',
'admin minting another admin invite'
);
SELECT pg_temp.expect_forbidden(
format(
'SELECT public.update_team_member_role(%L::uuid, %L::uuid, %L)',
:'team_id', '43100000-0000-4000-8000-000000000003', 'admin'
),
'team_owner_required',
'admin changing roles'
);
SELECT pg_temp.assert_true(
(public.create_team_invite(:'team_id', 'null-guard-outsider-2@example.invalid', 'member')
->>'role') = 'member',
'admin can still invite a member'
);
SELECT pg_temp.act_as('43100000-0000-4000-8000-000000000001');
SELECT pg_temp.assert_true(
public.update_team_member_role(
:'team_id', '43100000-0000-4000-8000-000000000003', 'admin'
)->>'role' = 'admin'
AND public.update_team_member_role(
:'team_id', '43100000-0000-4000-8000-000000000003', 'member'
)->>'role' = 'member',
'owner can still change roles'
);
SELECT pg_temp.assert_true(
(public.cancel_team_invite(:'pending_invite_id')->>'cancelled')::boolean,
'owner can still cancel an invite'
);
-- A member can still leave on their own; leaving twice reports not found.
SELECT pg_temp.act_as('43100000-0000-4000-8000-000000000003');
SELECT pg_temp.assert_true(
(public.remove_team_member(:'team_id', '43100000-0000-4000-8000-000000000003')
->>'removed')::boolean,
'member can leave the team'
);
DO $$
BEGIN
PERFORM public.remove_team_member(
current_setting('test.team_id')::uuid,
'43100000-0000-4000-8000-000000000003'
);
RAISE EXCEPTION 'assertion_failed: leaving twice succeeded';
EXCEPTION
WHEN no_data_found THEN NULL;
END;
$$;
RESET ROLE;
-- ---------------------------------------------------------------------------
-- 5. State: the outsider changed nothing.
-- ---------------------------------------------------------------------------
SELECT pg_temp.assert_true(
NOT EXISTS (
SELECT 1 FROM public.team_invites
WHERE invited_by = '43100000-0000-4000-8000-000000000004'
),
'outsider created no invite'
);
SELECT pg_temp.assert_true(
(SELECT role FROM public.team_members
WHERE team_id = :'team_id'
AND user_id = '43100000-0000-4000-8000-000000000002') = 'admin',
'admin role is unchanged'
);
SELECT pg_temp.assert_true(
NOT EXISTS (
SELECT 1 FROM public.team_members
WHERE team_id = :'team_id'
AND user_id IN (
'43100000-0000-4000-8000-000000000004',
'43100000-0000-4000-8000-000000000005'
)
),
'neither outsider account joined the team'
);
ROLLBACK;