# Company quotas Company quota reservations are implemented in the domain, `companyquota` usecase, and PostgreSQL adapter. They provide a transaction-bound storage port for invitation and candidate-card usage. An invitation spends one place of the weekly quota when it is sent (`SendOrganizationInvitation`): a draft spends nothing, and a repeat of the send of the same invitation does not spend a second place. An invitation that leaves the waiting state (a decline, an expiry, an acceptance) frees its place in the per-need pending limit, but never returns the weekly quota; see [Pending limit, cooldown, and expiry](ARCHITECTURE.md#pending-limit-cooldown-and-expiry). ## Policy and trusted organization level Each operation takes one UTC application-clock snapshot and reads the effective version of `ProductPolicyKey`. Limits come from that versioned policy. The bundled demo policy currently enables E0 at 10 invitations per rolling 7 days and 50 distinct candidate-card views per rolling 24 hours. E1 is 40 invitations per 7 days and 150 distinct views per 24 hours. E2 has configured limits of 100 invitations and 400 distinct views, but its tier is inactive in the bundled demo policy. E2 can be used only when an effective policy activates it and the organization loaded from storage has the corresponding verified level and basis. E3 has no quota tier and is denied. The caller cannot choose or raise a tier. The quota snapshot captures the policy version and the stored organization verification level, basis, and change time. Before writing, the PostgreSQL adapter locks the organization and checks those values and the effective policy version again. If either changed, it returns `outbound.ErrCompanyQuotaSnapshotChanged` without writing usage. The caller must reload policy and organization state, then retry the whole transaction. ## Reservation and transaction order Call `companyquota.Service.ReserveInvitation` or `ReserveCardView` with repositories from the current `outbound.UnitOfWork`. The repository returned by `UnitOfWork.CompanyQuotas()` is transaction-scoped and must not be retained. Make the quota reservation and its eventual business change in the same transaction so rollback removes both. The service is constructed with the application clock and reads the effective policy once per operation. Tenant authorization remains the caller's responsibility. Recheck active membership and owner permission inside the same transaction. Writers follow this order: organization, then for an E0 organization its holding (see [Holding pool](#holding-pool)), active membership, invitation or visibility record, then quota usage. The quota adapter locks the organization row first and, for an E0 organization, the holding row right after it; a caller that already holds those rows may lock them again in the same transaction. Do not reverse this order. The organization lock serializes concurrent reservations of one organization, and the holding lock serializes the shared E0 pool. The adapter checks existing usage, counts the active window, and inserts or refreshes usage while those locks are held. A decision is either allowed or denied; reuse implies allowed. A denied reservation writes no usage and includes `RetryAt`, the earliest active usage expiry that can free capacity. ## Windows and retries An invitation is keyed by `(organization_id, invitation_id)`. Repeating the same invitation ID is allowed as reused, even with a different request idempotency key and after the rolling window. Its usage evidence remains for the organization's lifetime, so removing an invitation in a future workflow will not refund quota. A card view is keyed by `(organization_id, candidate_id)`, so viewing the same candidate again during the active window does not consume another distinct-view slot. The repeat refreshes `last_seen_at` monotonically: a backdated application clock cannot move the stored time backward. The active-window query uses a strict comparison with the cutoff. A row exactly at `now - window` has expired. Invitation usage is counted over seven rolling days; card views are counted over 24 rolling hours. The limits apply across requests and users of the organization, except that an E0 organization shares its limits with the other E0 organizations of its holding (see [Holding pool](#holding-pool)). Expired card-view rows are deleted in batches of at most 100 after a successful allowed reservation. Window expiry is logical; this cleanup does not promise deletion at an exact time. Deleting a candidate account cascades its card-view usage row. Deleting an organization cascades both quota tables. Invitation usage has no invitation foreign key, so future invitation withdrawal cannot erase its idempotency evidence. ## Holding pool A holding groups the organizations that one founder account created; the `holdings` table and the migration `00041_create_holdings.sql` store it. `CreateWithOwner` stores each new organization in the holding of its owner account in the same transaction. The holding of an account is created with its first organization, and concurrent creations of one account end in one holding, because the insert ignores an existing founder key and the transaction then reads the stored holding. A holding carries no profile and no right; its only effect is the shared E0 pool. The E0 limits (10 invitations per 7 days and 50 distinct card views per 24 hours in the bundled demo policy) are shared by the E0 organizations of a holding. An E0 reservation counts the usage rows of every organization of its holding whose trust level is E0 when the count runs. Each usage row stays attributed to the organization that consumed it, and usage of an organization that is no longer E0 leaves the shared pool. An organization at E1 or above counts only its own usage and keeps its own pool, so its usage does not count toward the E0 pool. Idempotency stays per organization. The same invitation ID, or a repeated view of one candidate by the same organization inside the window, is not charged twice. The same candidate viewed by two organizations of one holding is two charges of the shared pool. Locks: for an E0 organization, `CompanyQuotaRepository.LockOrganization` and each reservation take the holding row with `FOR NO KEY UPDATE` right after the organization row. Reservations of one pool therefore run one after another, and the second one counts the usage that the first one committed, because it counts only after the holding lock. Every writer takes the organization lock before the holding lock, and no code takes an organization lock while it holds a holding lock, so the holding lock adds no cycle to the documented order. The cost is that E0 searches, card reads, and invitation drafts or sends of one holding wait for one another while their transactions are open; a search holds the lock for its whole ranking transaction. The migration gives each founder one holding: the founder of an organization is the account of its earliest membership, which is the creator's owner membership, and the holding is dated by its first organization. The rollback refuses while a holding groups several organizations, because the schema without holdings could not keep their E0 pool together. Merging holdings of different owners is out of scope. ## Verification `TestHoldings` in `backend/integration_test/holding_test.go` covers the shared E0 pool of two organizations of one account with a verified organization apart, a second account's own holding, usage leaving the pool when its organization is raised, concurrent reservations from two organizations that never exceed the shared limits, concurrent creations ending in one holding, and a refused creation of an unknown founder. `TestHoldingsMigrationBackfillsFoundersAndGuardsRollback` in `backend/integration_test/holding_migration_test.go` covers the backfill and the guarded rollback. `TestCompanyQuota` in `backend/integration_test/company_quota_test.go` exercises the real PostgreSQL adapter in an isolated database. It checks concurrent E0 reservations, E0/E1 boundaries, exact window cutoffs and `RetryAt`, same-ID invitation reuse, cross-request card-view reuse, monotonic refresh, rollback, policy or organization snapshot changes, an allowed reservation with an active E2 policy and stored E2 verification, rejection of a forged E2 snapshot for a stored E0 company, inactive E2 and E3 denial, and candidate-deletion cleanup. It does not test a delivered invitation because that workflow is not implemented.