import { sql, type SQL } from "drizzle-orm"; import type { ConnectionHealth, ConnectionKind, ConnectionOwnership, ProviderId, QuotaBlockClaim, QuotaProviderDetail, SubscriptionConnection, SubscriptionQuota, SubscriptionSettingValues, } from "@opengeni/subscriptions"; import { quotaAfterRateLimitReset, storedQuotaDocument, withSubscriptionCoreModelIdForms, } from "@opengeni/subscriptions"; import { rawRows, type Database } from "./database"; import { subscriptionCoreProvider, subscriptionCoreProviderIds, } from "./subscription-core-providers"; import { subscriptionCoreConnectionKind } from "./subscription-core/provider"; /** * A connection's model list read in every id form of its models (the * provider adapter's `modelIdFormsFor`). A provider this binary does not * register keeps its list as stored. */ function modelIdsInEveryForm(providerId: string, modelIds: readonly string[]): string[] { return subscriptionCoreProviderIds().includes(providerId) ? withSubscriptionCoreModelIdForms(subscriptionCoreProvider(providerId).adapter, modelIds) : [...modelIds]; } export type EffectiveSubscriptionSettingsRow = { values: SubscriptionSettingValues; sources: { rotation: Record; providers: Record; fallbackOrder: Record; crossProviderFailover: "organization" | "workspace"; personalConnectionsAllowed: "organization" | "workspace"; personalFallbackAllowed: "organization" | "workspace"; }; }; /** Typed M2 persistence seam; no production selector calls this repository yet. */ export async function readSubscriptionEffectiveSettings( db: Database, accountId: string, workspaceId: string, ): Promise { const [row] = await rawRows<{ effective: EffectiveSubscriptionSettingsRow }>( db, sql`select subscription_effective_settings(${accountId}::uuid, ${workspaceId}::uuid) as effective`, ); if (!row) throw new Error("Subscription settings were not found"); return withoutRetiredProviderKeys(row.effective); } /** * The resolver still reports the retired per-workspace source keys * (`useOrganizationAccounts`, `inferenceSource`) for binaries that straddle * 0907. Every account that reaches a workspace serves it now (D-50), so a * provider carries only its switch. Null (no settings row yet) stays null. */ export function withoutRetiredProviderKeys(effective: T): T { const providers = (effective as { values?: { providers?: unknown } } | null)?.values?.providers; if (!providers || typeof providers !== "object") return effective; for (const entry of Object.values(providers as Record)) { if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue; delete (entry as Record).useOrganizationAccounts; delete (entry as Record).inferenceSource; } return effective; } /** * The status of `alias`'s connection row as an availability read sees it at * `now`. A timed 403 quarantine is `error` with `health_retry_at` (only the * quarantine writer sets it; any other status or error write drops it). * From that time on the connection reads * `active`, without waiting for a turn to run the recovery routine, which * stores the same transition for the connections that turn may lease. * A quarantine without a deadline remains an error until reconnect. */ export function subscriptionConnectionEffectiveStatus( alias: string, now: SQL = sql`clock_timestamp()`, ): SQL { const row = sql.raw(alias); return sql`case when ${row}.status = 'error' and ${row}.health_retry_at <= ${now} then 'active' else ${row}.status end`; } /** The row's last error as availability reads see it: none once its quarantine ended. */ export function subscriptionConnectionEffectiveLastError( alias: string, now: SQL = sql`clock_timestamp()`, ): SQL { const row = sql.raw(alias); return sql`case when ${row}.status = 'error' and ${row}.health_retry_at <= ${now} then null else ${row}.last_error end`; } /** * Read the provider/workspace-visible connection world for the pure placement * policy. Account and workspace are mandatory; provider and connection kind * may narrow the result (the shared core passes both: a row of another kind * is never placed for a provider, rather than placed and refused at * credential load). * Callers cannot accidentally turn this into a viewer-derived or cross-account pool read. * Credential ciphertext is deliberately never selected here. * * `health` says how an ended quarantine reads. `effective`: healthy, for a * reader that only decides availability (admission, the catalog), which * cannot run the recovery routine. `stored`: still `error`, for placement of * an accepted turn, whose lease and credential reads enforce the stored * status; the turn recovers ended quarantines before it places, and one that * ends after that recovery waits for the turn's next check rather than being * leased and refused at credential load. */ export async function listSubscriptionConnectionsForPlacement( db: Database, input: { accountId: string; workspaceId: string; provider?: ProviderId; kind?: ConnectionKind; now?: Date; health: "effective" | "stored"; }, ): Promise { const now = (input.now ?? new Date()).toISOString(); const rows = await rawRows<{ id: string; provider: ProviderId; kind: ConnectionKind; ownership: "shared" | "personal"; owner_membership_id: string | null; health: string; label: string | null; plan_type: string | null; extra_credits_enabled: boolean; allocator_enabled: boolean; entitled_model_ids: string[] | null; observed_model_slugs: string[] | null; last_observed_model_slugs: string[] | null; model_catalog_observed_at: Date | string | null; model_catalog_expires_at: Date | string | null; excluded_models: string[]; allowed_model_ids: string[] | null; refresh_generation: number | string; scope_kind: "organization" | "workspaces" | "people"; allow_personal_workspaces: boolean; managed_by_workspace_id: string | null; quota: unknown; quota_revision: number | string | null; quota_observed_refresh_generation: number | string | null; quota_updated_at: Date | string | null; }>( db, sql`select connection.id::text as id, connection.provider, connection.kind, connection.ownership, connection.owner_organization_membership_id::text as owner_membership_id, ${ input.health === "effective" ? subscriptionConnectionEffectiveStatus("connection", sql`${now}::timestamptz`) : sql`connection.status` } as health, connection.label, connection.plan_type, connection.allocator_enabled, connection.extra_credits_enabled, null::text[] as entitled_model_ids, connection.excluded_models, case when quota.model_catalog_refresh_generation = connection.refresh_generation and quota.model_catalog_observed_at <= ${now}::timestamptz and quota.model_catalog_expires_at > ${now}::timestamptz then quota.model_catalog_slugs else null end as observed_model_slugs, case when quota.model_catalog_refresh_generation = connection.refresh_generation and quota.model_catalog_observed_at <= ${now}::timestamptz then quota.model_catalog_slugs else null end as last_observed_model_slugs, quota.model_catalog_observed_at, quota.model_catalog_expires_at, connection.allowed_model_ids, connection.refresh_generation, connection.scope_kind, connection.allow_personal_workspaces, connection.managed_by_workspace_id::text as managed_by_workspace_id, quota.quota, quota.revision as quota_revision, quota.observed_refresh_generation as quota_observed_refresh_generation, quota.updated_at as quota_updated_at from subscription_connections connection left join subscription_connection_quota quota on quota.account_id = connection.account_id and quota.connection_id = connection.id where connection.account_id = ${input.accountId}::uuid and (${input.provider ?? null}::text is null or connection.provider = ${input.provider ?? null}) and (${input.kind ?? null}::text is null or connection.kind = ${input.kind ?? null}) order by connection.provider, connection.id`, ); if (rows.length === 0) return []; const workspaceAssignments = await rawRows<{ connection_id: string; workspace_id: string; }>( db, sql`select connection_id::text as connection_id, workspace_id::text as workspace_id from subscription_connection_workspaces where account_id = ${input.accountId}::uuid`, ); const peopleAssignments = await rawRows<{ connection_id: string; membership_id: string; }>( db, sql`select connection_id::text as connection_id, organization_membership_id::text as membership_id from subscription_connection_people where account_id = ${input.accountId}::uuid`, ); const workspacesByConnection = groupStrings( workspaceAssignments, "connection_id", "workspace_id", ); const peopleByConnection = groupStrings(peopleAssignments, "connection_id", "membership_id"); return rows.map((row) => { const health: ConnectionHealth = row.health === "active" ? "healthy" : row.health === "needs_relogin" || row.health === "needs_reconnect" ? "needs_reconnect" : "error"; let ownership: ConnectionOwnership; if (row.ownership === "personal") { if (!row.owner_membership_id) { throw new Error("Personal subscription connection is missing its owner membership"); } ownership = { kind: "personal", ownerMembershipId: row.owner_membership_id }; } else { ownership = { kind: "shared", managedByWorkspaceId: row.managed_by_workspace_id, scope: row.scope_kind === "organization" ? { kind: "organization" } : row.scope_kind === "people" ? { kind: "people", membershipIds: peopleByConnection.get(row.id) ?? [] } : { kind: "workspaces", workspaceIds: workspacesByConnection.get(row.id) ?? [], allowPersonalWorkspaces: row.allow_personal_workspaces, }, }; } return { id: row.id, provider: row.provider, kind: row.kind, ownership, health, ...(subscriptionCoreProviderIds().includes(row.provider) && subscriptionCoreProvider(row.provider).projectWait ? { label: row.label, planType: row.plan_type } : {}), extraCreditsEnabled: row.extra_credits_enabled, allocatorEnabled: row.allocator_enabled, entitledModelIds: row.entitled_model_ids, observedModelSlugs: row.observed_model_slugs, lastObservedModelSlugs: row.last_observed_model_slugs, modelCatalogObservedAt: row.model_catalog_observed_at ? new Date(row.model_catalog_observed_at).getTime() : null, modelCatalogExpiresAt: row.model_catalog_expires_at ? new Date(row.model_catalog_expires_at).getTime() : null, // Read in every id form of their models, so placement and every // catalog reader treat a model listed under one form as listed. excludedModelIds: modelIdsInEveryForm(row.provider, row.excluded_models), allowedModelIds: row.allowed_model_ids === null ? null : modelIdsInEveryForm(row.provider, row.allowed_model_ids), refreshGeneration: Number(row.refresh_generation), quota: decodeSubscriptionQuota(row), }; }); } function groupStrings< T extends Record, Key extends string, ValueKey extends Exclude, >(rows: T[], key: Key, valueKey: ValueKey): Map { const grouped = new Map(); for (const row of rows) { const values = grouped.get(row[key]) ?? []; values.push(row[valueKey]); grouped.set(row[key], values); } return grouped; } export function decodeSubscriptionQuota(row: { quota: unknown; quota_revision: number | string | null; quota_observed_refresh_generation: number | string | null; quota_updated_at: Date | string | null; }): SubscriptionQuota | null { if (row.quota_observed_refresh_generation === null) return null; if (row.quota === null || typeof row.quota !== "object" || Array.isArray(row.quota)) return null; const raw = row.quota as Record; const windows = raw.windows; const cooldowns = raw.modelCooldowns; if (!Array.isArray(windows) || cooldowns === null || typeof cooldowns !== "object") return null; const parsedWindows = []; for (const window of windows) { if (window === null || typeof window !== "object" || Array.isArray(window)) return null; const item = window as Record; if ( typeof item.id !== "string" || !( item.usedPercent === null || (typeof item.usedPercent === "number" && Number.isFinite(item.usedPercent)) ) || !( item.resetsAt === null || (typeof item.resetsAt === "number" && Number.isFinite(item.resetsAt)) ) || (item.status !== "ok" && item.status !== "warning" && item.status !== "exhausted" && item.status !== "unknown") ) return null; parsedWindows.push({ id: item.id, usedPercent: item.usedPercent, resetsAt: item.resetsAt, status: item.status as "ok" | "warning" | "exhausted" | "unknown", }); } const modelCooldowns: Record = {}; for (const [modelId, until] of Object.entries(cooldowns)) { if (typeof until !== "number" || !Number.isFinite(until)) return null; modelCooldowns[modelId] = until; } const exhaustedUntil = raw.exhaustedUntil === undefined ? null : raw.exhaustedUntil; const exhaustedKind = raw.exhaustedKind === undefined ? null : raw.exhaustedKind; const source = raw.source === undefined ? null : raw.source; if ( !( exhaustedUntil === null || (typeof exhaustedUntil === "number" && Number.isFinite(exhaustedUntil)) ) || !(exhaustedKind === null || exhaustedKind === "quota" || exhaustedKind === "rate_limit") || !( source === null || source === "usage_endpoint" || source === "response_headers" || source === "refusal" ) ) return null; const quota: SubscriptionQuota = { windows: parsedWindows, modelCooldowns, exhaustedUntil, exhaustedKind, revision: Number(row.quota_revision ?? 1), observedAt: row.quota_updated_at === null ? null : new Date(row.quota_updated_at).getTime(), observedRefreshGeneration: row.quota_observed_refresh_generation === null ? null : Number(row.quota_observed_refresh_generation), source, }; // Block evidence is optional and fails closed: a malformed claim is // dropped (its block runs to its own deadline), never the quota. const claims = raw.modelCooldownClaims; const causes = raw.modelCooldownCauses; if (causes !== null && typeof causes === "object" && !Array.isArray(causes)) { const parsed: Record[string]> = {}; for (const [modelId, evidence] of Object.entries(causes)) { if (!evidence || typeof evidence !== "object" || Array.isArray(evidence)) continue; const { until, cause } = evidence as Record; if ( typeof until === "number" && until === modelCooldowns[modelId] && (cause === "entitlement" || cause === "rate_limit" || cause === "quota") ) parsed[modelId] = { until, cause }; } if (Object.keys(parsed).length > 0) quota.modelCooldownCauses = parsed; } if (claims !== null && typeof claims === "object" && !Array.isArray(claims)) { const parsed: Record = {}; for (const [modelId, claim] of Object.entries(claims)) { const decoded = decodeQuotaBlockClaim(claim); if (decoded && modelCooldowns[modelId] !== undefined) parsed[modelId] = decoded; } if (Object.keys(parsed).length > 0) quota.modelCooldownClaims = parsed; } const exhaustedClaim = exhaustedUntil === null ? null : decodeQuotaBlockClaim(raw.exhaustedClaim); if (exhaustedClaim) quota.exhaustedClaim = exhaustedClaim; // Reduced service and provider details are optional too: a malformed // value is dropped, never the quota. if (typeof raw.constrainedUntil === "number" && Number.isFinite(raw.constrainedUntil)) quota.constrainedUntil = raw.constrainedUntil; const details = raw.providerDetails; if (details !== null && typeof details === "object" && !Array.isArray(details)) { const parsed: Record = {}; for (const [key, part] of Object.entries(details)) { if (part === null || typeof part !== "object" || Array.isArray(part)) continue; const { observedAt, value } = part as Record; if (typeof observedAt === "number" && Number.isFinite(observedAt) && value !== undefined) parsed[key] = { observedAt, value: value as QuotaProviderDetail["value"] }; } if (Object.keys(parsed).length > 0) quota.providerDetails = parsed; } return quota; } function decodeQuotaBlockClaim(value: unknown): QuotaBlockClaim | null { if (value === null || typeof value !== "object" || Array.isArray(value)) return null; const claim = value as Record; if ( typeof claim.until !== "number" || !Number.isFinite(claim.until) || typeof claim.observedAt !== "number" || !Number.isFinite(claim.observedAt) || !Array.isArray(claim.windowIds) || claim.windowIds.length === 0 || claim.windowIds.length > 16 || !claim.windowIds.every((id) => typeof id === "string" && id.length > 0 && id.length <= 128) ) return null; return { until: claim.until, observedAt: claim.observedAt, windowIds: [...new Set(claim.windowIds as string[])], }; } /** * Record, inside the caller's transaction, that the provider reset a * connection's rate limits at `resetAt` (`quotaAfterRateLimitReset`): the * stored windows and exhaustion deadline are invalidated, so placement no * longer waits on readings taken before the reset. Only a quota observed with * the connection's current refresh generation is rewritten (an observation of * an older credential is left for the generation fence to discard). Returns * whether the stored quota changed. */ export async function recordSubscriptionCoreRateLimitResetInTransaction( tx: Database, input: { accountId: string; provider: ProviderId; connectionId: string; resetAt: Date }, ): Promise { const [row] = await rawRows<{ quota: unknown; quota_revision: number | string | null; quota_observed_refresh_generation: number | string | null; quota_updated_at: Date | string | null; }>( tx, sql`select quota.quota, quota.revision as quota_revision, quota.observed_refresh_generation as quota_observed_refresh_generation, quota.updated_at as quota_updated_at from subscription_connection_quota quota join subscription_connections connection on connection.account_id = quota.account_id and connection.id = quota.connection_id where quota.account_id = ${input.accountId}::uuid and quota.connection_id = ${input.connectionId}::uuid and connection.provider = ${input.provider} and quota.observed_refresh_generation = connection.refresh_generation for update of quota`, ); if (!row) return false; const current = decodeSubscriptionQuota(row); if (!current) return false; const next = quotaAfterRateLimitReset(current, input.resetAt.getTime()); if (next === current) return false; await tx.execute( sql`update subscription_connection_quota set quota = ${JSON.stringify(storedQuotaDocument(next))}::jsonb, revision = revision + 1, updated_at = ${new Date(next.observedAt ?? input.resetAt.getTime()).toISOString()}::timestamptz where account_id = ${input.accountId}::uuid and connection_id = ${input.connectionId}::uuid`, ); return true; } /** Canonical IDs win; otherwise resolve one visible provider-scoped alias. */ export async function resolveSubscriptionConnectionId( db: Database, input: { accountId: string; provider: ProviderId; connectionId: string }, ): Promise { const [row] = await rawRows<{ id: string }>( db, sql`select coalesce( (select direct.id::text from subscription_connections direct where direct.account_id = ${input.accountId}::uuid and direct.provider = ${input.provider} and direct.id = ${input.connectionId}::uuid), (select canonical.id::text from subscription_connection_aliases alias join subscription_connections canonical on canonical.account_id = alias.account_id and canonical.provider = alias.provider and canonical.id = alias.connection_id where alias.account_id = ${input.accountId}::uuid and alias.provider = ${input.provider} and alias.alias_connection_id = ${input.connectionId}::uuid) ) as id`, ); return row?.id ?? null; } export type SubscriptionSessionBinding = { accountId: string; workspaceId: string; sessionId: string; provider: ProviderId; connectionId: string | null; modelId: string; choice: "automatic" | "explicit"; onlyThisModel: boolean; lastModelCallAt: Date | null; lastSwitchReason: | "initial" | "reselected_cold" | "failover_same_provider" | "failover_cross_provider" | "return_to_preferred" | "explicit_choice" | "revoked" | null; version: number; }; /** * The session's binding for one provider (0733, D-32): a session keeps one * binding per provider, and a provider reads and writes only its own. */ export async function readSubscriptionSessionBinding( db: Database, input: { workspaceId: string; sessionId: string; provider: ProviderId; /** * Lock the row until the transaction ends, so a placement compares and * writes the binding it decided from while parallel placements of the * same session wait (SUB-STICK-02). */ forUpdate?: boolean; }, ): Promise { const [row] = await rawRows<{ account_id: string; workspace_id: string; session_id: string; provider: ProviderId; connection_id: string | null; model_id: string; choice: "automatic" | "explicit"; only_this_model: boolean; last_model_call_at: Date | string | null; last_switch_reason: SubscriptionSessionBinding["lastSwitchReason"]; version: number | string; }>( db, sql`select account_id::text as account_id, workspace_id::text as workspace_id, session_id::text as session_id, provider, connection_id::text as connection_id, model_id, choice, only_this_model, last_model_call_at, last_switch_reason, version from subscription_session_bindings where workspace_id = ${input.workspaceId}::uuid and session_id = ${input.sessionId}::uuid and provider = ${input.provider} ${input.forUpdate ? sql`for update` : sql``}`, ); if (!row) return null; return { accountId: row.account_id, workspaceId: row.workspace_id, sessionId: row.session_id, provider: row.provider, connectionId: row.connection_id, modelId: row.model_id, choice: row.choice, onlyThisModel: row.only_this_model, lastModelCallAt: row.last_model_call_at === null ? null : new Date(row.last_model_call_at), lastSwitchReason: row.last_switch_reason, version: Number(row.version), }; } const ROLLING_SESSION_BINDING_INDEX = "subscription_session_bindings_rolling_session_idx"; /** * Whether an error is a concurrent first binding of the session meeting 0733's * rolling `(workspace_id, session_id)` index. That index is not the conflict * target of `writeSubscriptionSessionBinding`, so two first bindings of one * session can race on it as a unique violation instead of a lost * compare-and-swap. Callers treat it as the lost compare-and-swap; the * transaction (or savepoint) is aborted and must be retried in a new one. */ export function isSubscriptionSessionBindingRollingConflict(error: unknown): boolean { for (let current = error, depth = 0; current && depth < 4; depth += 1) { const fields = current as { code?: unknown; constraint_name?: unknown; cause?: unknown }; if (fields.code === "23505" && fields.constraint_name === ROLLING_SESSION_BINDING_INDEX) return true; current = fields.cause; } return false; } /** * Inserts the provider's binding once or compare-and-swaps its version. A * binding never changes provider (the 0733 trigger refuses it). While 0733's * rolling index exists a racing first binding can fail with * `isSubscriptionSessionBindingRollingConflict`. */ export async function writeSubscriptionSessionBinding( db: Database, input: Omit & { expectedVersion?: number | null }, ): Promise { if ( input.expectedVersion != null && (!Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 1) ) throw new Error("Subscription binding expected version must be a positive safe integer"); const [row] = await rawRows<{ version: number | string }>( db, sql`insert into subscription_session_bindings ( account_id, workspace_id, session_id, provider, connection_id, model_id, choice, only_this_model, last_model_call_at, last_switch_reason, version ) values ( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.sessionId}::uuid, ${input.provider}, ${input.connectionId ?? null}::uuid, ${input.modelId}, ${input.choice}, ${input.onlyThisModel}, ${input.lastModelCallAt?.toISOString() ?? null}::timestamptz, ${input.lastSwitchReason ?? null}, 1 ) on conflict (workspace_id, session_id, provider) do update set connection_id = excluded.connection_id, model_id = excluded.model_id, choice = excluded.choice, only_this_model = excluded.only_this_model, last_model_call_at = excluded.last_model_call_at, last_switch_reason = excluded.last_switch_reason, version = subscription_session_bindings.version + 1 where ${input.expectedVersion ?? null}::bigint is not null and subscription_session_bindings.account_id = excluded.account_id and subscription_session_bindings.version = ${input.expectedVersion ?? null}::bigint returning version`, ); return row ? Number(row.version) : null; } /** * Record a use of the bound account's prompt cache on the session binding * (SUB-STICK-04): the clock placement measures warmth from. It moves only * forward and only while the binding still names this provider's connection, * so a use on an account the session has already left never warms the new * one. The clock is not part of the binding's version: the version guards the * account, model and choice, and a clock-only advance must not make a * concurrent placement or pin lose its compare-and-swap. * * A cleared clock (a pin change, or a switch by a writer that stated none) * means the next turn re-runs selection (SUB-STICK-05, D-31). Only a * placement restarts it (`restart: true`); a request or completed call of the * turn already running never does, so removing a pin mid-turn still takes * effect at the next turn. */ export async function advanceSubscriptionBindingCacheClock( db: Database, input: { workspaceId: string; sessionId: string; provider: ProviderId; connectionId: string; at: Date; /** A placement on the account: may start a cleared clock. */ restart?: boolean; }, ): Promise { const at = sql`${input.at.toISOString()}::timestamptz`; const rows = await rawRows<{ advanced: boolean }>( db, sql`update subscription_session_bindings set last_model_call_at = ${at} where workspace_id = ${input.workspaceId}::uuid and session_id = ${input.sessionId}::uuid and provider = ${input.provider} and connection_id = ${input.connectionId}::uuid and ${input.restart === true ? sql`(last_model_call_at is null or last_model_call_at < ${at})` : sql`last_model_call_at < ${at}`} returning true as advanced`, ); return rows.length > 0; } export async function createSubscriptionConnection( db: Database, input: { accountId: string; provider: ProviderId; kind: "subscription" | "api_key"; credentialEncrypted: string; providerAccountId?: string | null; }, ): Promise { const [row] = await rawRows<{ id: string }>( db, sql`insert into subscription_connections ( account_id, provider, kind, credential_encrypted, provider_account_id ) values ( ${input.accountId}::uuid, ${input.provider}, ${input.kind}, ${input.credentialEncrypted}, ${input.providerAccountId ?? null} ) returning id::text as id`, ); if (!row) throw new Error("Subscription connection insert returned no row"); return row.id; } export type SubscriptionTurnLeaseIdentity = { accountId: string; workspaceId: string; sessionId: string; turnId: string; provider: ProviderId; connectionId: string; holderId: string; generation: number; }; export type SubscriptionTurnLease = SubscriptionTurnLeaseIdentity & { leasedUntil: Date; }; /** * Whether a turn lease row still holds its turn: unexpired, and its holder * generation's attempt has neither written its quiescence receipt nor been * closed for worker death (`lease_lost_recoverable`: the activity stopped * heartbeating for its whole heartbeat timeout and the turn was redispatched). * Either way that attempt has lost inference authority for good, so a crashed * or force-stopped worker that never ran its own release must not keep a newer * generation of the same turn waiting for the TTL. Renew, assert and usage * finalization keep the plain expiry fence: the holder may still finish usage * accounting after its receipt, but a newer generation can take the turn over * meanwhile, and a holder that was only partitioned loses its lease at its next * renewal once the newer generation replaced the row. */ export function subscriptionTurnLeaseHeldSql(table = "subscription_leases"): SQL { const lease = sql.identifier(table); return sql`(${lease}.leased_until > clock_timestamp() and not exists ( select 1 from session_turn_attempts holder where holder.account_id = ${lease}.account_id and holder.workspace_id = ${lease}.workspace_id and holder.session_id = ${lease}.session_id and holder.turn_id = ${lease}.turn_id and holder.execution_generation = ${lease}.generation and (holder.quiesced_at is not null or (holder.state = 'closed' and holder.outcome = 'lease_lost_recoverable'))))`; } /** * Acquire the chat-turn lease after core placement and immediately rechecking * current eligibility. Replays by the same holder/connection/generation are * idempotent. A stale holder can be replaced only by a strictly newer * generation for the same turn and session, and only after the lease expired * or the holder generation's attempt wrote its quiescence receipt or was closed * for worker death. */ export async function acquireSubscriptionTurnLease( db: Database, input: SubscriptionTurnLeaseIdentity & { ttlMs: number }, ): Promise { assertPositiveLeaseTtl(input.ttlMs); assertPositiveGeneration(input.generation); if (!input.holderId.trim() || input.holderId.length > 256) throw new Error("Subscription lease holder id must contain 1-256 characters"); const [row] = await rawRows<{ leased_until: Date | string }>( db, sql`insert into subscription_leases ( account_id, workspace_id, session_id, turn_id, connection_id, provider, holder_id, generation, leased_until ) values ( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.sessionId}::uuid, ${input.turnId}::uuid, ${input.connectionId}::uuid, ${input.provider}, ${input.holderId}, ${input.generation}, clock_timestamp() + (${input.ttlMs} * interval '1 millisecond') ) on conflict (workspace_id, turn_id) do update set connection_id = excluded.connection_id, provider = excluded.provider, holder_id = excluded.holder_id, generation = excluded.generation, leased_until = clock_timestamp() + (${input.ttlMs} * interval '1 millisecond') where subscription_leases.account_id = excluded.account_id and subscription_leases.session_id = excluded.session_id and ((subscription_leases.generation = excluded.generation and subscription_leases.connection_id = excluded.connection_id and subscription_leases.provider = excluded.provider and subscription_leases.holder_id = excluded.holder_id and subscription_leases.leased_until > clock_timestamp()) or (subscription_leases.generation < excluded.generation and not ${subscriptionTurnLeaseHeldSql()})) returning leased_until`, ); return row ? { ...turnLeaseIdentity(input), leasedUntil: new Date(row.leased_until) } : null; } /** * Persist one successful token refresh through the private database seam. * Call only inside withSubscriptionCoreRefreshLock for the same provider, * immediately after the provider returns. SQL consumes the one-shot * authorization that begin_subscription_core_refresh minted in the same * transaction and writes * under the refresh lock and refresh-generation compare-and-swap, so a caller * cannot turn the helper into a general credential update API, and a rotated * token is not discarded because the lease or visibility changed meanwhile. */ export async function persistSubscriptionCoreRefresh( db: Database, input: { provider: ProviderId; accountId: string; workspaceId: string; sessionId: string; turnId: string; connectionId: string; expectedRefreshGeneration: number; credentialEncrypted: string; expiresAt: Date | null; lastRefreshAt: Date; }, ): Promise { subscriptionCoreProvider(input.provider); assertPositiveGeneration(input.expectedRefreshGeneration); const [row] = await rawRows<{ persisted: boolean }>( db, sql`select opengeni_private.persist_subscription_core_refresh(${input.provider}, ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.sessionId}::uuid, ${input.turnId}::uuid, ${input.connectionId}::uuid, ${input.expectedRefreshGeneration}::bigint, ${input.credentialEncrypted}, ${input.expiresAt?.toISOString() ?? null}::timestamptz, ${input.lastRefreshAt.toISOString()}::timestamptz ) as persisted`, ); return row?.persisted === true; } /** * persistSubscriptionCoreRefresh plus the plan the rotated credential reports * (M3 PR 2a). Same one-shot authorization, advisory lock and * refresh-generation compare-and-swap; a NULL plan keeps the recorded plan, * and a changed plan clears the connection's model cooldowns. * * Every refresh path persists through it (migration 1367): a chat turn's * refresh names its session and turn and consumes the authorization * begin_subscription_core_refresh minted; a refresh outside a turn * (operations, usage reads, administered connections) passes null for both * and consumes the one begin_subscription_core_connection_refresh or * begin_subscription_core_owned_connection_refresh minted. */ export async function persistSubscriptionCoreRefreshWithPlan( db: Database, input: Omit[1], "sessionId" | "turnId"> & { /** The chat turn's session and turn; both null for a refresh outside a turn. */ sessionId: string | null; turnId: string | null; planType: string | null; }, ): Promise { subscriptionCoreProvider(input.provider); assertPositiveGeneration(input.expectedRefreshGeneration); if ((input.sessionId === null) !== (input.turnId === null)) { throw new Error("A subscription refresh names both its session and turn, or neither"); } const planType = subscriptionRefreshPlanValue(input.planType); const [row] = await rawRows<{ persisted: boolean }>( db, sql`select opengeni_private.persist_subscription_core_refresh_with_plan(${input.provider}, ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.sessionId}::uuid, ${input.turnId}::uuid, ${input.connectionId}::uuid, ${input.expectedRefreshGeneration}::bigint, ${input.credentialEncrypted}, ${input.expiresAt?.toISOString() ?? null}::timestamptz, ${input.lastRefreshAt.toISOString()}::timestamptz, ${planType} ) as persisted`, ); return row?.persisted === true; } /** * An organization administrator's refresh of an organization-managed * connection (an organization usage read). The same refresh write as * persistSubscriptionCoreRefreshWithPlan (migration 1515): the rotated * credential, the plan it reports (null keeps the recorded plan), the * refresh-generation compare-and-swap and the model-cooldown reset on a plan * change. The routine runs with the caller's rights, so the organization * update policy decides whether the write is admitted; the caller holds the * per-connection refresh lock and has locked the row it may refresh. */ export async function persistSubscriptionCoreAdministratorRefresh( db: Database, input: { provider: ProviderId; accountId: string; connectionId: string; expectedRefreshGeneration: number; credentialEncrypted: string; expiresAt: Date | null; lastRefreshAt: Date; planType: string | null; }, ): Promise { const kind = subscriptionCoreConnectionKind(subscriptionCoreProvider(input.provider)); assertPositiveGeneration(input.expectedRefreshGeneration); const [row] = await rawRows<{ persisted: boolean }>( db, sql`select opengeni_private.write_subscription_connection_refresh(${input.provider}, ${kind}, ${input.accountId}::uuid, ${input.connectionId}::uuid, ${input.expectedRefreshGeneration}::bigint, ${input.credentialEncrypted}, ${input.expiresAt?.toISOString() ?? null}::timestamptz, ${input.lastRefreshAt.toISOString()}::timestamptz, ${subscriptionRefreshPlanValue(input.planType)} ) as persisted`, ); return row?.persisted === true; } /** A plan the refresh writer accepts, or null (keep the recorded plan). */ function subscriptionRefreshPlanValue(planType: string | null | undefined): string | null { const trimmed = planType?.trim() ?? ""; return /^[A-Za-z0-9_.-]{1,64}$/.test(trimmed) ? trimmed : null; } /** Renew only the exact, still-live chat-turn lease generation. */ export async function renewSubscriptionTurnLease( db: Database, input: SubscriptionTurnLeaseIdentity & { ttlMs: number }, ): Promise { assertPositiveLeaseTtl(input.ttlMs); const [row] = await rawRows<{ leased_until: Date | string }>( db, sql`update subscription_leases set leased_until = clock_timestamp() + (${input.ttlMs} * interval '1 millisecond') where ${turnLeaseWhere(input)} and leased_until > clock_timestamp() returning leased_until`, ); return row ? new Date(row.leased_until) : null; } /** Pre-dispatch fence; placement and current eligibility are separate checks. */ export async function assertSubscriptionTurnLeaseCurrent( db: Database, input: SubscriptionTurnLeaseIdentity, ): Promise { const [row] = await rawRows<{ current: boolean }>( db, sql`select exists ( select 1 from subscription_leases where ${turnLeaseWhere(input)} and leased_until > clock_timestamp() ) as current`, ); return row?.current ?? false; } /** Release is fenced by turn, connection, holder and generation. */ export async function releaseSubscriptionTurnLease( db: Database, input: SubscriptionTurnLeaseIdentity, ): Promise { const rows = await rawRows<{ turn_id: string }>( db, sql`delete from subscription_leases where ${turnLeaseWhere(input)} returning turn_id::text as turn_id`, ); return rows.length === 1; } function turnLeaseIdentity(input: SubscriptionTurnLeaseIdentity): SubscriptionTurnLeaseIdentity { return { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, provider: input.provider, connectionId: input.connectionId, holderId: input.holderId, generation: input.generation, }; } function turnLeaseWhere(input: SubscriptionTurnLeaseIdentity) { return sql`account_id = ${input.accountId}::uuid and workspace_id = ${input.workspaceId}::uuid and session_id = ${input.sessionId}::uuid and turn_id = ${input.turnId}::uuid and provider = ${input.provider} and connection_id = ${input.connectionId}::uuid and holder_id = ${input.holderId} and generation = ${input.generation}`; } export type SubscriptionOperationKind = | "session_title" | "image" | "video" | "realtime" | "transcription" | "completion"; export type SubscriptionOperationLeaseIdentity = { accountId: string; workspaceId: string; operationId: string; attemptId: string; operationKind: SubscriptionOperationKind; sessionId?: string | null; turnId?: string | null; provider: ProviderId; connectionId: string; holderId: string; generation: number; }; export type SubscriptionOperationLease = SubscriptionOperationLeaseIdentity & { leasedUntil: Date; }; /** * Acquire a lease for one durable operation. Replays of the same exact * generation are idempotent; a later generation can replace only an expired * lease. A caller must first own the corresponding operation-ledger claim. */ export async function acquireSubscriptionOperationLease( db: Database, input: SubscriptionOperationLeaseIdentity & { ttlMs: number }, ): Promise { assertPositiveLeaseTtl(input.ttlMs); assertPositiveGeneration(input.generation); const [row] = await rawRows<{ leased_until: Date | string; }>( db, sql`insert into subscription_operation_leases ( account_id, workspace_id, operation_id, attempt_id, operation_kind, session_id, turn_id, provider, connection_id, holder_id, generation, leased_until, updated_at ) values ( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.operationId}::uuid, ${input.attemptId}::uuid, ${input.operationKind}, ${input.sessionId ?? null}::uuid, ${input.turnId ?? null}::uuid, ${input.provider}, ${input.connectionId}::uuid, ${input.holderId}, ${input.generation}, clock_timestamp() + (${input.ttlMs} * interval '1 millisecond'), clock_timestamp() ) on conflict (account_id, operation_id) do update set attempt_id = excluded.attempt_id, operation_kind = excluded.operation_kind, session_id = excluded.session_id, turn_id = excluded.turn_id, provider = excluded.provider, connection_id = excluded.connection_id, holder_id = excluded.holder_id, generation = excluded.generation, leased_until = clock_timestamp() + (${input.ttlMs} * interval '1 millisecond'), updated_at = clock_timestamp() where ( subscription_operation_leases.generation = excluded.generation and subscription_operation_leases.attempt_id = excluded.attempt_id and subscription_operation_leases.operation_kind = excluded.operation_kind and subscription_operation_leases.session_id is not distinct from excluded.session_id and subscription_operation_leases.turn_id is not distinct from excluded.turn_id and subscription_operation_leases.provider = excluded.provider and subscription_operation_leases.holder_id = excluded.holder_id and subscription_operation_leases.connection_id = excluded.connection_id and subscription_operation_leases.leased_until > clock_timestamp() ) or ( subscription_operation_leases.generation < excluded.generation and subscription_operation_leases.leased_until <= clock_timestamp() and subscription_operation_leases.operation_kind = excluded.operation_kind and subscription_operation_leases.session_id is not distinct from excluded.session_id and subscription_operation_leases.turn_id is not distinct from excluded.turn_id and subscription_operation_leases.provider = excluded.provider and subscription_operation_leases.connection_id = excluded.connection_id ) returning leased_until`, ); return row ? { ...operationLeaseIdentity(input), leasedUntil: new Date(row.leased_until) } : null; } /** Renew only the exact, still-live operation lease generation. */ export async function renewSubscriptionOperationLease( db: Database, input: SubscriptionOperationLeaseIdentity & { ttlMs: number }, ): Promise { assertPositiveLeaseTtl(input.ttlMs); const identity = operationLeaseWhere(input); const [locked] = await rawRows<{ operation_id: string }>( db, sql`select operation_id::text as operation_id from subscription_operation_leases where ${identity} for update`, ); if (!locked) return null; const [row] = await rawRows<{ leased_until: Date | string }>( db, sql`update subscription_operation_leases set leased_until = clock_timestamp() + (${input.ttlMs} * interval '1 millisecond'), updated_at = clock_timestamp() where ${identity} and leased_until > clock_timestamp() returning leased_until`, ); return row ? new Date(row.leased_until) : null; } /** Pre-dispatch fence; the caller must separately recheck current eligibility. */ export async function assertSubscriptionOperationLeaseCurrent( db: Database, input: SubscriptionOperationLeaseIdentity, ): Promise { const [row] = await rawRows<{ current: boolean }>( db, sql`select exists ( select 1 from subscription_operation_leases where ${operationLeaseWhere(input)} and leased_until > clock_timestamp() ) as current`, ); return row?.current ?? false; } /** Release is fenced by operation, attempt, holder and generation. */ export async function releaseSubscriptionOperationLease( db: Database, input: SubscriptionOperationLeaseIdentity, ): Promise { const rows = await rawRows<{ operation_id: string }>( db, sql`delete from subscription_operation_leases where ${operationLeaseWhere(input)} returning operation_id::text as operation_id`, ); return rows.length === 1; } export type SubscriptionCapacityWaiter = { accountId: string; workspaceId: string; sessionId: string; turnId: string; waiterId: string; provider: ProviderId; waitReason: string; policyHash?: string | null; resetKind?: string | null; refreshAttempt?: number; resumedUpdateId?: string | null; earliestResetAt?: Date | null; generation: number; wakeRevision: number; observedWakeRevision: number; nextCheckAt?: Date | null; blockedTurnGeneration?: number | null; }; /** Upsert is monotonic: stale generations cannot replace the current waiter. */ export async function upsertSubscriptionCapacityWaiter( db: Database, input: SubscriptionCapacityWaiter, ): Promise { assertPositiveGeneration(input.generation); if (!Number.isSafeInteger(input.wakeRevision) || input.wakeRevision < 1) throw new Error("Subscription waiter wake revision must be a positive safe integer"); if ( !Number.isSafeInteger(input.observedWakeRevision) || input.observedWakeRevision < 0 || input.observedWakeRevision > input.wakeRevision ) { throw new Error("Subscription waiter observed revision must be between zero and wake revision"); } const [row] = await rawRows<{ waiter_id: string; provider: ProviderId; wait_reason: string; policy_hash: string | null; reset_kind: string | null; refresh_attempt: number | string; resumed_update_id: string | null; earliest_reset_at: Date | string | null; generation: number | string; wake_revision: number | string; observed_wake_revision: number | string; next_check_at: Date | string | null; blocked_turn_generation: number | string | null; }>( db, sql`insert into subscription_capacity_waiters ( account_id, workspace_id, session_id, turn_id, waiter_id, provider, wait_reason, policy_hash, reset_kind, refresh_attempt, resumed_update_id, earliest_reset_at, generation, wake_revision, observed_wake_revision, next_check_at, blocked_turn_generation, updated_at ) values ( ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.sessionId}::uuid, ${input.turnId}::uuid, ${input.waiterId}::uuid, ${input.provider}, ${input.waitReason}, ${input.policyHash ?? null}, ${input.resetKind ?? null}, ${input.refreshAttempt ?? 0}, ${input.resumedUpdateId ?? null}::uuid, ${input.earliestResetAt?.toISOString() ?? null}::timestamptz, ${input.generation}, ${input.wakeRevision}, ${input.observedWakeRevision}, ${input.nextCheckAt?.toISOString() ?? null}::timestamptz, ${input.blockedTurnGeneration ?? null}, clock_timestamp() ) on conflict (workspace_id, session_id) do update set turn_id = excluded.turn_id, provider = CASE WHEN excluded.generation > subscription_capacity_waiters.generation OR excluded.wake_revision > subscription_capacity_waiters.wake_revision THEN excluded.provider ELSE subscription_capacity_waiters.provider END, wait_reason = CASE WHEN excluded.generation > subscription_capacity_waiters.generation OR excluded.wake_revision > subscription_capacity_waiters.wake_revision THEN excluded.wait_reason ELSE subscription_capacity_waiters.wait_reason END, policy_hash = CASE WHEN excluded.generation > subscription_capacity_waiters.generation OR excluded.wake_revision > subscription_capacity_waiters.wake_revision THEN excluded.policy_hash ELSE subscription_capacity_waiters.policy_hash END, reset_kind = CASE WHEN excluded.generation > subscription_capacity_waiters.generation OR excluded.wake_revision > subscription_capacity_waiters.wake_revision THEN excluded.reset_kind ELSE subscription_capacity_waiters.reset_kind END, refresh_attempt = CASE WHEN excluded.generation > subscription_capacity_waiters.generation OR excluded.wake_revision > subscription_capacity_waiters.wake_revision THEN excluded.refresh_attempt ELSE subscription_capacity_waiters.refresh_attempt END, resumed_update_id = CASE WHEN excluded.generation > subscription_capacity_waiters.generation OR excluded.wake_revision > subscription_capacity_waiters.wake_revision THEN excluded.resumed_update_id ELSE subscription_capacity_waiters.resumed_update_id END, earliest_reset_at = CASE WHEN excluded.generation > subscription_capacity_waiters.generation OR excluded.wake_revision > subscription_capacity_waiters.wake_revision THEN excluded.earliest_reset_at ELSE subscription_capacity_waiters.earliest_reset_at END, generation = greatest(subscription_capacity_waiters.generation, excluded.generation), wake_revision = CASE WHEN excluded.generation > subscription_capacity_waiters.generation THEN excluded.wake_revision ELSE greatest(subscription_capacity_waiters.wake_revision, excluded.wake_revision) END, observed_wake_revision = CASE WHEN excluded.generation > subscription_capacity_waiters.generation THEN excluded.observed_wake_revision ELSE greatest(subscription_capacity_waiters.observed_wake_revision, excluded.observed_wake_revision) END, next_check_at = CASE WHEN excluded.generation > subscription_capacity_waiters.generation OR excluded.wake_revision > subscription_capacity_waiters.wake_revision THEN excluded.next_check_at ELSE subscription_capacity_waiters.next_check_at END, blocked_turn_generation = CASE WHEN excluded.generation > subscription_capacity_waiters.generation OR excluded.wake_revision > subscription_capacity_waiters.wake_revision THEN excluded.blocked_turn_generation ELSE subscription_capacity_waiters.blocked_turn_generation END, updated_at = CASE WHEN excluded.generation > subscription_capacity_waiters.generation OR excluded.wake_revision > subscription_capacity_waiters.wake_revision THEN clock_timestamp() ELSE subscription_capacity_waiters.updated_at END where subscription_capacity_waiters.account_id = excluded.account_id and (subscription_capacity_waiters.generation < excluded.generation or (subscription_capacity_waiters.generation = excluded.generation and subscription_capacity_waiters.turn_id = excluded.turn_id)) returning waiter_id::text as waiter_id, provider, wait_reason, policy_hash, reset_kind, refresh_attempt, resumed_update_id::text as resumed_update_id, earliest_reset_at, generation, wake_revision, observed_wake_revision, next_check_at, blocked_turn_generation`, ); if (!row) return null; return { ...input, waiterId: row.waiter_id, provider: row.provider, waitReason: row.wait_reason, policyHash: row.policy_hash, resetKind: row.reset_kind, refreshAttempt: Number(row.refresh_attempt), resumedUpdateId: row.resumed_update_id, earliestResetAt: row.earliest_reset_at === null ? null : new Date(row.earliest_reset_at), generation: Number(row.generation), wakeRevision: Number(row.wake_revision), observedWakeRevision: Number(row.observed_wake_revision), nextCheckAt: row.next_check_at === null ? null : new Date(row.next_check_at), blockedTurnGeneration: row.blocked_turn_generation === null ? null : Number(row.blocked_turn_generation), }; } /** Bump one exact waiter's revision; workflow signalling remains outbox-owned. */ export async function wakeSubscriptionCapacityWaiter( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; waiterId: string; generation: number; nextCheckAt?: Date | null; }, ): Promise { const [row] = await rawRows<{ wake_revision: number | string }>( db, sql`with bumped as ( update subscription_capacity_waiters set wake_revision = wake_revision + 1, next_check_at = ${input.nextCheckAt?.toISOString() ?? null}::timestamptz, updated_at = clock_timestamp() where account_id = ${input.accountId}::uuid and workspace_id = ${input.workspaceId}::uuid and session_id = ${input.sessionId}::uuid and waiter_id = ${input.waiterId}::uuid and generation = ${input.generation} returning account_id, workspace_id, session_id, waiter_id, generation, wake_revision ) insert into subscription_capacity_wake_outbox ( account_id, workspace_id, session_id, waiter_id, generation, wake_revision ) select account_id, workspace_id, session_id, waiter_id, generation, wake_revision from bumped on conflict (account_id, waiter_id, generation, wake_revision) do nothing returning wake_revision`, ); return row ? Number(row.wake_revision) : null; } export type SubscriptionCapacityWakeDelivery = { id: string; accountId: string; workspaceId: string; sessionId: string; waiterId: string; generation: number; wakeRevision: number; claimGeneration: number; /** Delivery attempts including this claim. */ attemptCount: number; }; /** * Claims due wake obligations under the trusted empty-subject worker scope. * Claim generations fence a delayed Temporal signaler from a later retry. */ export async function claimSubscriptionCapacityWakeDeliveries( db: Database, input: { limit: number; claimTtlMs: number }, ): Promise { if (!Number.isSafeInteger(input.limit) || input.limit < 1 || input.limit > 500) throw new Error("Subscription wake claim limit must be between 1 and 500"); assertPositiveLeaseTtl(input.claimTtlMs); return await rawRows<{ id: string; account_id: string; workspace_id: string; session_id: string; waiter_id: string; generation: number | string; wake_revision: number | string; claim_generation: number | string; attempt_count: number | string; }>( db, sql`with due as ( select id from subscription_capacity_wake_outbox where delivered_at is null and next_attempt_at <= clock_timestamp() order by next_attempt_at, created_at, id for update skip locked limit ${input.limit} ) update subscription_capacity_wake_outbox outbox set attempt_count = attempt_count + 1, claim_generation = claim_generation + 1, next_attempt_at = clock_timestamp() + (${input.claimTtlMs} * interval '1 millisecond') from due where outbox.id = due.id and outbox.delivered_at is null returning outbox.id::text as id, outbox.account_id::text as account_id, outbox.workspace_id::text as workspace_id, outbox.session_id::text as session_id, outbox.waiter_id::text as waiter_id, outbox.generation, outbox.wake_revision, outbox.claim_generation, outbox.attempt_count`, ).then((rows) => rows.map((row) => ({ id: row.id, accountId: row.account_id, workspaceId: row.workspace_id, sessionId: row.session_id, waiterId: row.waiter_id, generation: Number(row.generation), wakeRevision: Number(row.wake_revision), claimGeneration: Number(row.claim_generation), attemptCount: Number(row.attempt_count), })), ); } export async function markSubscriptionCapacityWakeDelivered( db: Database, input: { id: string; claimGeneration: number }, ): Promise { const rows = await rawRows<{ id: string }>( db, sql`update subscription_capacity_wake_outbox set delivered_at = clock_timestamp(), last_error = null where id = ${input.id}::uuid and claim_generation = ${input.claimGeneration} and delivered_at is null returning id::text as id`, ); return rows.length === 1; } /** Failure codes are deliberately bounded identifiers, never exception text. */ export async function retrySubscriptionCapacityWakeDelivery( db: Database, input: { id: string; claimGeneration: number; retryInMs: number; failureCode: string; }, ): Promise { assertPositiveLeaseTtl(input.retryInMs); if (!/^[a-z][a-z0-9_]{0,63}$/.test(input.failureCode)) throw new Error("Subscription wake failure code must be a bounded identifier"); const rows = await rawRows<{ id: string }>( db, sql`update subscription_capacity_wake_outbox set next_attempt_at = clock_timestamp() + (${input.retryInMs} * interval '1 millisecond'), last_error = ${input.failureCode} where id = ${input.id}::uuid and claim_generation = ${input.claimGeneration} and delivered_at is null returning id::text as id`, ); return rows.length === 1; } /** * Stop retrying one typed wake signal after its bounded attempts. The waiter's * wake revision stays unobserved, and the same commit also queued the generic * session workflow wake, so the workflow still re-evaluates the waiter; only * the typed fast path is given up. */ export async function abandonSubscriptionCapacityWakeDelivery( db: Database, input: { id: string; claimGeneration: number; failureCode: string }, ): Promise { if (!/^[a-z][a-z0-9_]{0,63}$/.test(input.failureCode)) throw new Error("Subscription wake failure code must be a bounded identifier"); const rows = await rawRows<{ id: string }>( db, sql`update subscription_capacity_wake_outbox set delivered_at = clock_timestamp(), last_error = ${input.failureCode} where id = ${input.id}::uuid and claim_generation = ${input.claimGeneration} and delivered_at is null returning id::text as id`, ); return rows.length === 1; } export type DueSubscriptionCapacityWaiter = { accountId: string; workspaceId: string; sessionId: string; turnId: string; waiterId: string; provider: ProviderId; generation: number; wakeRevision: number; observedWakeRevision: number; nextCheckAt: Date | null; }; /** Lists due or newly-woken waiters inside the caller's authorized workspace scope. */ export async function listDueSubscriptionCapacityWaiters( db: Database, input: { provider?: ProviderId; limit: number }, ): Promise { if (!Number.isSafeInteger(input.limit) || input.limit < 1 || input.limit > 500) throw new Error("Subscription waiter list limit must be between 1 and 500"); const rows = await rawRows<{ account_id: string; workspace_id: string; session_id: string; turn_id: string; waiter_id: string; provider: ProviderId; generation: number | string; wake_revision: number | string; observed_wake_revision: number | string; next_check_at: Date | string | null; }>( db, sql`select account_id::text as account_id, workspace_id::text as workspace_id, session_id::text as session_id, turn_id::text as turn_id, waiter_id::text as waiter_id, provider, generation, wake_revision, observed_wake_revision, next_check_at from subscription_capacity_waiters where (${input.provider ?? null}::text is null or provider = ${input.provider ?? null}) and (wake_revision > observed_wake_revision or (next_check_at is not null and next_check_at <= clock_timestamp())) order by coalesce(next_check_at, updated_at), account_id, waiter_id limit ${input.limit}`, ); return rows.map((row) => ({ accountId: row.account_id, workspaceId: row.workspace_id, sessionId: row.session_id, turnId: row.turn_id, waiterId: row.waiter_id, provider: row.provider, generation: Number(row.generation), wakeRevision: Number(row.wake_revision), observedWakeRevision: Number(row.observed_wake_revision), nextCheckAt: row.next_check_at === null ? null : new Date(row.next_check_at), })); } /** Acknowledges only the revision actually observed by the workflow. */ export async function observeSubscriptionCapacityWaiterWake( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; waiterId: string; generation: number; wakeRevision: number; }, ): Promise { const rows = await rawRows<{ waiter_id: string }>( db, sql`update subscription_capacity_waiters set observed_wake_revision = ${input.wakeRevision}, updated_at = clock_timestamp() where account_id = ${input.accountId}::uuid and workspace_id = ${input.workspaceId}::uuid and session_id = ${input.sessionId}::uuid and waiter_id = ${input.waiterId}::uuid and generation = ${input.generation} and wake_revision = ${input.wakeRevision} and observed_wake_revision <= ${input.wakeRevision} returning waiter_id::text as waiter_id`, ); return rows.length === 1; } function assertPositiveLeaseTtl(ttlMs: number): void { if (!Number.isSafeInteger(ttlMs) || ttlMs <= 0) throw new Error("Subscription operation lease TTL must be a positive safe integer"); } function assertPositiveGeneration(generation: number): void { if (!Number.isSafeInteger(generation) || generation <= 0) throw new Error("Subscription generation must be a positive safe integer"); } function operationLeaseIdentity( input: SubscriptionOperationLeaseIdentity, ): SubscriptionOperationLeaseIdentity { return { ...input, sessionId: input.sessionId ?? null, turnId: input.turnId ?? null, }; } function operationLeaseWhere(input: SubscriptionOperationLeaseIdentity) { return sql`account_id = ${input.accountId}::uuid and workspace_id = ${input.workspaceId}::uuid and operation_id = ${input.operationId}::uuid and attempt_id = ${input.attemptId}::uuid and operation_kind = ${input.operationKind} and session_id is not distinct from ${input.sessionId ?? null}::uuid and turn_id is not distinct from ${input.turnId ?? null}::uuid and provider = ${input.provider} and connection_id = ${input.connectionId}::uuid and holder_id = ${input.holderId} and generation = ${input.generation}`; }