Files
member-console/internal/entitlements/querier.go
T
cgalo5758 f8a3478f2a Rebuild the entitlement set Rules surface as a staged batch
The Rules section is one record table grouped by kind, Limit then
Boolean, on fixed columns, edited in place: Edit opens a row's controls
in their columns, Add rule opens a dense row above the table, and every
change is staged into a tray that lists the deltas with Undo and applies
them as one rule-change act. The reduction policy is a column of the
rule beside its limit. History shows counts only. Group rows are a quiet
heading rather than a divider, the maintainer's pick from four rounds of
outside-model ideation.

Dense rows align to the top and render each error under its control in
every form family (design D16), replacing the below-row error block; the
forms library gains the batch form (rows plus one tray) and the RowField
dense and label-hidden options. Migration 00019 records the governing
reduction policy on effect rows.

Archive staged-rule-changes with its spec updates (entitlement-set-
management, entitlement-set-history, entitlements, form-library,
form-conventions, ui-quality-gate). Screens accepted 2026-09-19.
2026-09-19 19:46:09 -05:00

411 lines
30 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
package entitlements
import (
"context"
"database/sql"
"github.com/google/uuid"
)
type Querier interface {
// Setup-checklist existence probe: the whole-table answer, not a lookup.
AnyActiveEntitlementSet(ctx context.Context) (bool, error)
// Empty-validation-domain probe: the topology health strip claims health
// only when at least one active attachment existed for the checks to cover.
AnyActiveLadderAttachment(ctx context.Context) (bool, error)
AtomicDecrementUsage(ctx context.Context, arg AtomicDecrementUsageParams) (sql.Result, error)
AtomicIncrementUsage(ctx context.Context, arg AtomicIncrementUsageParams) (sql.Result, error)
// The act rows (core.entitlement_set_changes) and the effect rows
// (core.entitlement_set_change_effects) are append-only: nothing in this file
// updates or deletes one. Both are written by core.commit_rule_change and
// core.settle_obligation, so no Create query exists for any of the three
// tables. The obligations are the one mutable table, a work list rather than
// history, and only its status columns move.
// The only write path to core.entitlement_set_rules. The calling transaction
// must hold the exclusive materialization rendezvous, which the function
// asserts: open it with BeginRuleChange.
CommitRuleChange(ctx context.Context, arg CommitRuleChangeParams) (CommitRuleChangeRow, error)
CountActiveAttachmentsByLadder(ctx context.Context, planLadderID string) (int64, error)
CountActiveAttachmentsByTier(ctx context.Context, arg CountActiveAttachmentsByTierParams) (int64, error)
// Carrying pools whose recorded usage of one key has reached or passed the
// pool's materialized limit: the aggregate-mode preview's one exact fact.
CountCarryingPoolsAtOrOverLimit(ctx context.Context, arg CountCarryingPoolsAtOrOverLimitParams) (int64, error)
// The delivering-grants caption: how many signup defaults are delivering,
// excluded from the headline above. Same provision join as
// CountDeliveringOperatorGrants so the two can never disagree about what
// "delivering" means.
CountDeliveringDefaultGrants(ctx context.Context) (int64, error)
// Operator overview headline: grants someone deliberately issued that are
// delivering right now. Signup defaults are excluded — conferral mints one
// per org, so they drown the number an operator can act on; their count
// rides the tile's caption (CountDeliveringDefaultGrants). Non-default is
// exactly the operator-authored set per chk_grants_default_iff_system_authored.
//
// grants.status is an issuance LEDGER — it records what was written and
// whether it was later revoked, not whether service is flowing today. The
// current-delivery fact lives on core.pool_provisions.status, so this counts
// distinct grants that own at least one active provision rather than
// filtering grants.status alone.
CountDeliveringOperatorGrants(ctx context.Context) (int64, error)
CountEntitlementSetChangeEffectsByOrg(ctx context.Context, orgID string) (int64, error)
CountEntitlementSetChanges(ctx context.Context, setID string) (int64, error)
// The same count for a page of sets in one query rather than one per row.
CountFailedObligationsBySets(ctx context.Context, setIds []string) ([]CountFailedObligationsBySetsRow, error)
// Maintenance check, unexposed since acceptance-fixes round 2: the database's exclusion constraint makes a violation impossible.
CountMultiActiveLadderAttachments(ctx context.Context) ([]CountMultiActiveLadderAttachmentsRow, error)
// The drain's own reads, beside the ledger queries in
// entitlement_set_changes.sql. Neither writes: one counts what a change still
// owes, the other names the pools whose last attempt left an error so the
// drain activity can log each one.
// What the drain's activity returns to its workflow: the pools this change
// still owes. failed rows are the dead letter and are not counted, so a
// change whose remainder is all failed owes nothing until Retry requeues it.
CountPendingObligationsByChange(ctx context.Context, changeID string) (int64, error)
CountPoolsCarryingSet(ctx context.Context, entitlementSetID string) (CountPoolsCarryingSetRow, error)
// Pools holding the set only through suspended provisions: they carry nothing
// today, so a change does not reach them until the provision resumes.
CountSuspendedOnlyPoolsCarryingSet(ctx context.Context, entitlementSetID string) (int64, error)
// What the set's Rules section reads: still draining and failed, separately.
CountUnsettledObligationsBySet(ctx context.Context, setID string) (CountUnsettledObligationsBySetRow, error)
// `key` is the optional declarative address (entity-keys §3), root-scoped.
// The operator create form does not collect one, so a UI-created set leaves
// it NULL; a seed or a configuration loader supplies it.
CreateEntitlementSet(ctx context.Context, arg CreateEntitlementSetParams) (EntitlementSet, error)
CreateGrant(ctx context.Context, arg CreateGrantParams) (Grant, error)
CreateNumericEntitlement(ctx context.Context, arg CreateNumericEntitlementParams) (NumericEntitlement, error)
CreateNumericEntitlementContribution(ctx context.Context, arg CreateNumericEntitlementContributionParams) (NumericEntitlementContribution, error)
CreateNumericEntitlementUsage(ctx context.Context, arg CreateNumericEntitlementUsageParams) (NumericEntitlementUsage, error)
CreatePoolAssignment(ctx context.Context, arg CreatePoolAssignmentParams) (PoolAssignment, error)
// `key` is the optional declarative address (entity-keys §3), unique within
// the organization because a pool is a child of one. The console writes it
// for exactly one row it creates by design: every organization's default
// pool, keyed `default` (§4). Any other pool leaves it NULL unless a seed or
// an API client names one.
CreateResourcePool(ctx context.Context, arg CreateResourcePoolParams) (ResourcePool, error)
// Scoped to one entitlement: a provision that funds several resource keys
// keeps its rows on the keys the caller is not rebuilding.
DeleteContributionsByProvisionID(ctx context.Context, arg DeleteContributionsByProvisionIDParams) error
// Marks a grant expired at its valid_until bound. Enacting the position end is
// end_conferral's job; this is the decree half (design D5).
ExpireGrant(ctx context.Context, grantID string) (Grant, error)
GetActiveAttachmentsByPool(ctx context.Context, poolID string) ([]PoolProvisionLadder, error)
// Writes to core.pool_provision_ladders go through the conferral functions
// (queries/conferral.sql) alone; core_writer holds no direct DML on this
// table (migration 00005 enclosure). Only read paths live here.
GetActiveLadderAttachmentByPoolLadder(ctx context.Context, arg GetActiveLadderAttachmentByPoolLadderParams) (PoolProvisionLadder, error)
GetActivePoolProvisionsByPoolID(ctx context.Context, poolID string) ([]PoolProvision, error)
GetActiveRulesBySetID(ctx context.Context, setID string) ([]EntitlementSetRule, error)
GetBooleanEntitlementByPoolAndResource(ctx context.Context, arg GetBooleanEntitlementByPoolAndResourceParams) (BooleanEntitlement, error)
GetDefaultPoolByOrgID(ctx context.Context, orgID string) (ResourcePool, error)
GetEntitlementSetByID(ctx context.Context, setID string) (EntitlementSet, error)
// Root key resolver (entity-keys §5). uq_entitlement_sets_key guarantees at
// most one row matches.
GetEntitlementSetByKey(ctx context.Context, key sql.NullString) (EntitlementSet, error)
// One rule in any state, so a preview and a commit can tell a rule that was
// deactivated a moment ago from a rule id that is not on this set. Writes go
// through core.commit_rule_change alone (migration 00018 revokes the DML).
GetEntitlementSetRule(ctx context.Context, ruleID string) (EntitlementSetRule, error)
// The reduction policy governing one pool and one resource key: the strongest
// among the active limit rules that fund the pool through its active
// provisions, in the order force_reduce, clamp, block, defer. The order is
// stated here as an explicit CASE and once more as a list in the Go fold
// (entitlements, "The reduction policy governing a pool and key is the
// strongest across the rules funding it"); neither compares the values as
// text, which is what MIN() did until this query was rewritten.
GetGoverningReductionPolicy(ctx context.Context, arg GetGoverningReductionPolicyParams) (string, error)
GetGrantByID(ctx context.Context, grantID string) (Grant, error)
// Walks the ancestry chain of the focal grant via extends_grant_id, returning
// the focal grant first followed by each ancestor (parent, grandparent, ...)
// in chain-walk order. Revoked or expired ancestors are included; lineage is
// about who-came-before, not current validity.
GetGrantLineage(ctx context.Context, grantID string) ([]GetGrantLineageRow, error)
GetLadderAttachmentsByPool(ctx context.Context, poolID string) ([]PoolProvisionLadder, error)
GetLadderAttachmentsByProvision(ctx context.Context, provisionID string) ([]PoolProvisionLadder, error)
// Live (active|suspended) plan-ladder attachments for a pool together with
// their source provenance, for the org-type default-change classification:
// a grant-sourced row with grant_reason = 'default' marks the pool as holding
// the outgoing default (bucket 2); any other live row is another source's
// plan (bucket 3); no rows at all is a plan-less pool (bucket 1).
GetLivePlanAttachmentsWithSourceByPool(ctx context.Context, poolID string) ([]GetLivePlanAttachmentsWithSourceByPoolRow, error)
// Live (non-ended) provisions delivering a product. Tier add/remove aligns
// each of these to the product's new conferral shape.
GetLivePoolProvisionsByProductID(ctx context.Context, productID string) ([]PoolProvision, error)
// Live (non-ended) provisions of a subscription, one per product. Reconcile
// diffs these against the subscription's desired-by-product line items.
GetLivePoolProvisionsBySubscriptionID(ctx context.Context, subscriptionID uuid.NullUUID) ([]PoolProvision, error)
GetNumericEntitlementByPoolAndResource(ctx context.Context, arg GetNumericEntitlementByPoolAndResourceParams) (NumericEntitlement, error)
// One obligation's state, which the drain reads before it does any work: an
// obligation already settled is returned to a redispatched drain untouched.
GetObligationStatus(ctx context.Context, arg GetObligationStatusParams) (GetObligationStatusRow, error)
GetPoolProvisionByGrantID(ctx context.Context, grantID uuid.NullUUID) (PoolProvision, error)
GetPoolProvisionByProvisionID(ctx context.Context, provisionID string) (PoolProvision, error)
GetPoolProvisionBySubscriptionID(ctx context.Context, subscriptionID uuid.NullUUID) (PoolProvision, error)
// Writes to core.pool_provisions go through the conferral functions
// (queries/conferral.sql) alone; core_writer holds no direct DML on this
// table (migration 00005 enclosure). Only read paths live here.
GetPoolProvisionsByPoolID(ctx context.Context, poolID string) ([]PoolProvision, error)
GetPrimaryPoolAssignmentByWorkspace(ctx context.Context, workspaceID string) (PoolAssignment, error)
// Single-key lookup for the rule-authoring handler: rule_type is derived
// server-side from the key's kind, never taken from client input.
GetResourceKey(ctx context.Context, resourceKey string) (ResourceKey, error)
GetResourcePoolByID(ctx context.Context, poolID string) (ResourcePool, error)
// Child key resolver (entity-keys §5). uq_resource_pools_org_id_key
// guarantees at most one row matches; `default` resolves the pool the
// console creates for every organization.
GetResourcePoolByOrgAndKey(ctx context.Context, arg GetResourcePoolByOrgAndKeyParams) (ResourcePool, error)
GetResourcePoolsByOrgID(ctx context.Context, orgID string) ([]ResourcePool, error)
// The changed rule's resource key and reduction policy. The policy is
// stamped on that key's effect row alone (doc-47 §5.2: the reduction policy
// is the changed rule's, where the key is the rule's), so the key comes back
// with it. The drain reads the pair once per change.
GetRuleChangeStamp(ctx context.Context, changeID string) (GetRuleChangeStampRow, error)
GetUsageByPoolAndResource(ctx context.Context, arg GetUsageByPoolAndResourceParams) (NumericEntitlementUsage, error)
// Update-only by design: a lapse never creates a row. Absence of a row means
// the key was never conferred; granted = FALSE means conferred, then lapsed.
LapseBooleanEntitlement(ctx context.Context, arg LapseBooleanEntitlementParams) (int64, error)
ListActiveEntitlementSets(ctx context.Context) ([]EntitlementSet, error)
ListAllGrants(ctx context.Context) ([]Grant, error)
// Read-only per-pool boolean state for a batch of pools, the boolean half of
// what the preview folds.
ListBooleanEntitlementStateForPools(ctx context.Context, poolIds []string) ([]ListBooleanEntitlementStateForPoolsRow, error)
ListBooleanEntitlementsByPoolID(ctx context.Context, poolID string) ([]BooleanEntitlement, error)
// The acts of one applied batch: the change named and every other act on the
// same set carrying the same request identifier, which is what relates them
// (entitlement-set-history, "Every committed act writes one change row and
// one effect row per pool and key that moved"). Each comes back with its
// rule's key and reduction policy, so the drain stamps and routes from one
// read. The order is the commit's own, resource key ascending under the C
// collation, which is the byte order Go sorted the deltas by, so the drain
// re-derives the order the acts were filed in whatever the database's own
// collation is; the first row is then the batch's first act, the one a
// movement on a key no act names hangs off. A change with no request
// identifier returns itself alone.
ListChangesSharingRequest(ctx context.Context, changeID string) ([]ListChangesSharingRequestRow, error)
// The poller's entry point, oldest act first: changes that still owe a
// pending pool. A change whose remaining rows are all failed owes the drain
// nothing until an operator's Retry requeues them.
ListChangesWithUnsettledObligations(ctx context.Context, limit int32) ([]ListChangesWithUnsettledObligationsRow, error)
ListContributionsByEntitlementID(ctx context.Context, entitlementID string) ([]NumericEntitlementContribution, error)
// Returns only grants currently delivering entitlements to a pool in the
// given org — i.e. grants with at least one provision in status='active'.
// Used by the member-facing Sources panel where audit history would be
// noise (members only need to see what they actually have right now).
// DISTINCT collapses multi-provision grants to one row.
ListDeliveringGrantsByOrgID(ctx context.Context, grantedToOrgID uuid.NullUUID) ([]Grant, error)
// The History row's expander: what one change did, per organization and key.
ListEntitlementSetChangeEffects(ctx context.Context, arg ListEntitlementSetChangeEffectsParams) ([]EntitlementSetChangeEffect, error)
// The organization's trail: every rule change that moved one of its pools.
// This is the effect row's audit projection (entitlement-set-history, "The
// change row and every effect row project onto the audit view shape"): the
// pool as the resource, the act's actor triple and occurrence reached through
// the foreign key, and the payload's fields, which carry both policies, the
// rule's own and the one that governed the pool and key.
ListEntitlementSetChangeEffectsByOrg(ctx context.Context, arg ListEntitlementSetChangeEffectsByOrgParams) ([]ListEntitlementSetChangeEffectsByOrgRow, error)
// The paged History of one set. The per-change counts are correlated
// subqueries over the obligations and the effects, not stored columns.
ListEntitlementSetChanges(ctx context.Context, arg ListEntitlementSetChangesParams) ([]ListEntitlementSetChangesRow, error)
// Batch reader for the products list's per-page verdict (product-management
// "The verdict per page, from batches, never cached", design D4): active
// rules across every entitlement set the page's products reference, one
// query instead of one per product (mirrors GetActiveRulesBySetID).
ListEntitlementSetRulesBySetIDs(ctx context.Context, setIds []string) ([]EntitlementSetRule, error)
ListEntitlementSets(ctx context.Context) ([]EntitlementSet, error)
// The products list's set names for one page in one read (purchasability-
// status "The verdict per page, from batches, never cached", design D4,
// folded in on the maintainer's word 2026-09-06): the sets the page's
// products reference, instead of GetEntitlementSetByID once per row.
ListEntitlementSetsByIDs(ctx context.Context, setIds []string) ([]EntitlementSet, error)
ListFailedObligations(ctx context.Context, arg ListFailedObligationsParams) ([]ListFailedObligationsRow, error)
ListGrantsByOrgID(ctx context.Context, grantedToOrgID uuid.NullUUID) ([]Grant, error)
// The one shared delivery-state derivation (ux-honest-surfaces design
// decision 1): every operator surface that lists grants renders from this
// query so the grants index and the org-detail composite can never
// disagree about what "live" / "superseded" / "inactive" mean.
//
// live -> at least one linked pool_provision is status='active'
// superseded -> not live, AND a later grant actually names this one as
// its extends_grant_id ancestor (a replacement was issued
// -- see replaced_by_grant_id below)
// inactive -> not live and not superseded: revoked/expired with no
// recorded successor, or a grant that never delivered
//
// This is deliberately narrower than "not live" alone: a grant whose
// provision simply ended (revoked, expired) with no replacement grant on
// record is "inactive", not "superseded" -- "superseded" is reserved for
// the case the UI can point at a specific replacing grant (the lineage
// requirement: a superseded row must be able to name what replaced it).
//
// replaced_by_grant_id is the most recently created grant (if any) whose
// extends_grant_id points at this row; NULL when nothing replaced it.
// extends_grant_id (this grant's own ancestor pointer) is passed through
// unchanged so the UI can walk lineage in either direction.
//
// Off-ladder grants (add-ons / usage / one-time) have no ladder attachment,
// so activated_at / ended_at may be NULL even when delivery_state='live'.
// Ordered by created_at DESC alone (tier-changes-ledger design D5): the
// Live facet and the Active tab already select the delivering rows, so
// ordering states creation time only and does not also pretend to filter.
// The lineage sub-ordering (the replaced_by_grant_id subquery below) stays
// child.created_at DESC.
//
// sqlc.narg(org_id): NULL returns every grant system-wide (the grants
// index, /operator/grants); set, scopes to one organization (org-detail).
ListGrantsWithDelivery(ctx context.Context, orgID uuid.NullUUID) ([]ListGrantsWithDeliveryRow, error)
// Paginated, searchable, filterable system-wide variant of
// ListGrantsWithDelivery for /operator/grants (operator-list-scale,
// design D4). Same derivation, join shape, and ordering as
// ListGrantsWithDelivery above -- do not let the two drift, and never
// scope this one to an org_id; the org-detail composite keeps calling
// ListGrantsWithDelivery unpaged. Ordered by created_at DESC alone
// (tier-changes-ledger design D5): the Live facet and the Active tab
// already select the delivering rows, so ordering does not also pretend
// to filter.
//
// sqlc.narg(q): NULL means search is inactive and every row matches.
// Non-NULL matches a grant when the granted-to organization's name
// ILIKE's the term, OR the grant's product_id is present in
// sqlc.narg(product_ids) -- the grants module cannot query the billing
// schema directly, so the caller (Go) pre-resolves product IDs whose name
// matches the search term and passes them here; a NULL or empty array
// with a non-NULL q simply means the q criterion rides on org name alone.
//
// sqlc.narg(delivery_state): NULL returns every delivery state; otherwise
// only rows whose derived state equals the value. The HAVING clause below
// repeats the exact CASE expression from the SELECT list (HAVING cannot
// reference a SELECT-list alias) so the filter can never disagree with
// what the SELECT list -- and therefore the Go derivation reading it --
// renders as that row's state (a mixed-fixture test pins this agreement).
//
// count(*) OVER() is evaluated after GROUP BY/HAVING, so with the GROUP
// BY below it counts grouped (one-per-grant) rows that passed WHERE and
// HAVING -- the true total of matching grants, not a join-multiplied
// count of the underlying pool_provisions/pool_provision_ladders rows.
ListGrantsWithDeliveryPage(ctx context.Context, arg ListGrantsWithDeliveryPageParams) ([]ListGrantsWithDeliveryPageRow, error)
// The whole population for the org-type default-change classification in one
// round trip: one row per (org, live plan attachment), plus a row with NULL
// pool for orgs lacking a default pool and a row with NULL attachment for
// plan-less pools (LEFT JOINs). Replaces a per-org query pair, which does not
// scale past a few hundred organizations of one type.
ListLivePlanPositionsByOrgType(ctx context.Context, orgType string) ([]ListLivePlanPositionsByOrgTypeRow, error)
// The tier-removal preview/commit population in one round trip: every live
// (active|suspended) junction on this ladder whose provision delivers this
// product, with the org name and grant provenance so holders classify
// per position source (default-sourced needs a disposition; any other source
// is align-shrunk and never force-ended).
ListLiveTierHoldersByLadderProduct(ctx context.Context, arg ListLiveTierHoldersByLadderProductParams) ([]ListLiveTierHoldersByLadderProductRow, error)
// Read-only per-pool numeric state for a batch of pools, each row carrying the
// usage the limit is read against. The preview folds these without locking.
ListNumericEntitlementStateForPools(ctx context.Context, poolIds []string) ([]ListNumericEntitlementStateForPoolsRow, error)
ListNumericEntitlementUsageByPoolID(ctx context.Context, poolID string) ([]NumericEntitlementUsage, error)
ListNumericEntitlementsByPoolID(ctx context.Context, poolID string) ([]NumericEntitlement, error)
// The pools of one change whose last attempt recorded an error at or after a
// moment, for the drain activity's per-pool error log.
ListObligationFailuresSince(ctx context.Context, arg ListObligationFailuresSinceParams) ([]ListObligationFailuresSinceRow, error)
// The drain's work list for one change. failed is the dead letter: the drain
// never picks one up again, and only RequeueFailedObligations, which the
// operator's Retry calls, returns it to pending.
ListPendingObligations(ctx context.Context, arg ListPendingObligationsParams) ([]EntitlementSetChangeObligation, error)
// Per-resource usage counters for a pool joined to their materialized
// limit (used vs limit per resource key), for the org-detail pools panel
// (ux-honest-surfaces: "pool status and usage are visible on the
// organization view"). A counter row exists only under a materialized
// numeric entitlement (invariant 9, resource-pools card), so the JOIN
// never orphans.
ListPoolUsageWithLimitsByPoolID(ctx context.Context, poolID string) ([]ListPoolUsageWithLimitsByPoolIDRow, error)
// The carrying population of a set: pools with an active provision of it, one
// row per pool, ascending by pool_id, which is both the predicate and the lock
// order a commit takes them in (Decision 143).
ListPoolsCarryingSet(ctx context.Context, entitlementSetID string) ([]ListPoolsCarryingSetRow, error)
ListPoolsGrantedBooleanKey(ctx context.Context, resourceKey string) ([]ListPoolsGrantedBooleanKeyRow, error)
// Recent grants for the operator landing activity timeline. Returns the
// raw row data with org_id + granted_by_person_id; Go-side merger resolves
// those UUIDs to display names via batch lookups (avoids cross-schema
// joins that don't fit per-module sqlc scope). Only org-targeted grants —
// person-targeted and billing-account-targeted grants don't show up on
// the org-centric operator timeline.
ListRecentGrants(ctx context.Context, limit int32) ([]ListRecentGrantsRow, error)
// Recent transitions for the operator landing activity timeline. Joins to
// core.resource_pools to resolve the org_id (same schema, safe for
// sqlc). Operator-actor transitions carry actor_id; system/webhook actors
// don't, so person_id is nullable in the result.
ListRecentTransitions(ctx context.Context, limit int32) ([]ListRecentTransitionsRow, error)
// Display metadata for entitlement rendering: each key's human-friendly
// label plus its owning integration's display name. LEFT JOIN because
// provider NULL = platform-owned/pooled (see the resource_keys DDL
// comment); such keys render un-attributed.
ListResourceKeyLabels(ctx context.Context) ([]ListResourceKeyLabelsRow, error)
ListResourceKeys(ctx context.Context) ([]ResourceKey, error)
// Every pool row for the organization regardless of status -- unlike
// GetResourcePoolsByOrgID's active-only filter, this does not hide a
// suspended or archived pool from view. The org-detail composite uses
// this for its pools panel so an operator sees a pool's actual status
// (ux-honest-surfaces requirement: "pool status and usage are visible on
// the organization view") instead of the pool silently vanishing from the
// list, and so "this org has zero pool rows" (the pool-less breakage
// case) is distinguishable from "this org's only pool exists but is not
// active".
ListResourcePoolsByOrgIDAnyStatus(ctx context.Context, orgID string) ([]ResourcePool, error)
// Writes to core.pool_provision_transitions go through the conferral functions
// (queries/conferral.sql) alone; core_writer holds no direct DML on this
// table (migration 00005 enclosure). Only read paths live here.
// Joins to core.pool_provisions (on provision_id) and core.grants (on
// grant_id) so the Tier changes view can tell a grant-backed row from any
// other: a row whose provision came from a grant renders that grant's
// reason and description (tier-changes-ledger design D4) instead of the
// transition's own reason string, which Issue grant and Extend fill with
// the operator's free-text note. Both joins are LEFT JOINs -- a
// subscription- or purchase-sourced provision has no grant, and an
// expiry/revocation/cancellation's restorative row has no provision_id at
// all in some paths -- so a row with neither join match still renders via
// its own reason. The transition id (uuidv7, rising with insertion) ends the
// ORDER BY so the order is total: the two rows one act writes share
// effective_at and created_at (one transaction), and the snapshot's clock
// pin keeps such ties tied; the later-written row (a restoration after an
// end) lists first.
ListTransitionsByPool(ctx context.Context, poolID string) ([]ListTransitionsByPoolRow, error)
ListTransitionsByProvision(ctx context.Context, provisionID uuid.NullUUID) ([]PoolProvisionTransition, error)
// The set row taken FOR UPDATE: the guard a rule change holds beside the
// exclusive materialization rendezvous against a writer that changes the set
// row without that lock. A batch takes it once for every act it files
// (entitlement-set-management, "A rule change commit reaches every carrying
// pool").
LockEntitlementSet(ctx context.Context, setID string) (string, error)
// The pool row taken FOR UPDATE: the lock a rule commit below the cap and
// each drained pool above it hold while they materialize, taken in ascending
// pool_id order (Decision 144).
LockResourcePool(ctx context.Context, poolID string) (string, error)
// The failure half of the same function: no effect rows, the attempt and its
// error recorded, and the row failed once attempts reach max_attempts.
MarkObligationFailed(ctx context.Context, arg MarkObligationFailedParams) error
// Raise-only reconcile against the count of rows the owning integration holds.
// Never lowers: a create workflow holds a reservation between its gated
// increment and its row insert, and lowering here would erase it. Lowering on
// a real deletion stays with the decrement and drift paths.
// Creates no usage row; a missing counter remains the materializer's to create.
RaiseNumericUsageTo(ctx context.Context, arg RaiseNumericUsageToParams) (sql.Result, error)
// The Retry control: failed rows go back on the work list with their attempt
// count reset, so the drain gives each a fresh run of recomputeMaxAttempts.
RequeueFailedObligations(ctx context.Context, setID string) error
RevokeGrant(ctx context.Context, arg RevokeGrantParams) (Grant, error)
// Exact set, for boot reconciliation only: at boot no create workflow holds an
// unmaterialized reservation, so the owned rows are the whole truth and an
// overstated counter (which refuses creates) can be brought down.
// Creates no usage row.
SetNumericUsage(ctx context.Context, arg SetNumericUsageParams) (sql.Result, error)
// Records what one pool's recomputation did and marks the obligation. The
// calling transaction must hold the rendezvous in either mode.
SettleObligation(ctx context.Context, arg SettleObligationParams) (int32, error)
UpdateEntitlementSet(ctx context.Context, arg UpdateEntitlementSetParams) (EntitlementSet, error)
UpdateNumericEntitlementLimit(ctx context.Context, arg UpdateNumericEntitlementLimitParams) (NumericEntitlement, error)
UpsertBooleanEntitlementGranted(ctx context.Context, arg UpsertBooleanEntitlementGrantedParams) (BooleanEntitlement, error)
}
var _ Querier = (*Queries)(nil)