# Persistence responsibilities and adapter contracts

**Last updated:** 2026-11-19T06:03:29-03:00 (UTC-3)

PostgreSQL is the gateway's only implemented persistence engine. It currently serves identity and configuration authority, protected quota accounting, and request history. These responsibilities have different consistency and failure requirements even when they share one database. A future adapter must satisfy the contract of each responsibility it implements; accepting a connection URL is not adapter support.

Standalone and externally hosted PostgreSQL use the same engine contract. Their connection, TLS, proxy, authentication, backup and failover profiles need separate operational validation. Changing an endpoint neither provisions a database nor transfers identities, revocations or financial history. ClickHouse is an optional analytics and log store, not a primary engine; MySQL, Cassandra and DuckDB were cancelled by the owner. See [PostgreSQL operation](/docs/operate/managed-postgres/) and [deployment modes](/docs/operate/deployment-modes/).

## Identity and configuration authority

Managed credentials, users, memberships, team policy and configuration overrides are authoritative data. Successful managed-key lookups are checked against current committed credential, key, owner and team state. Named administrative sessions read their current role and memberships together. A lookup failure cannot widen permissions or substitute an analytics record for an identity.

Revocation prevents subsequent authorization. An operation already authorized and dispatched keeps its captured identity; revoking that identity does not erase its usage or financial history. The bounded negative-key cache may briefly retain a prior denial after reactivation; it does not cache successful authorization or database errors.

A configuration snapshot reads its version and override bodies in one repeatable-read transaction. A failed refresh preserves the last valid published snapshot. Configuration mutations commit their body, applicable version and request-correlated audit together. Identity mutations use their own operation-specific versions and locks: not every identity change increments the global configuration version. A team deletion retains the team tombstone and atomically revokes its keys.

Database failure denies applicable managed authorization, team policy and shared admission checks. Administrative reads and writes that query the database report unavailability. A safe configuration view can still return the last valid published snapshot; that is not a fresh database read or a health claim. A declarative YAML key remains independent only when the requested operation has no separately applicable database-backed policy.

## Quotas and financial state

Protected admission commits a reservation before dispatch. The reservation captures an internal ID, its subjects and windows, approved rate inputs and exact units. All applicable counters and the reservation change together; a later subject's refusal must not leave a partial charge. Policy edits do not erase consumption, and advisory price feeds are not an authorization or budget ledger.

Settlement uses the captured reservation and its approved rate. Missing or unproven terminal usage keeps the reservation unknown; it is not a zero charge or permission to replay the request. Known above-reservation usage is handled by the existing accounting contract. Recovery never guesses a provider result or releases unknown spend merely because an owner disappeared. See [budgets and token quotas](/docs/features/budgets-and-tpm/) and [protected usage profiles](/docs/features/quota-protocols/).

Receipt acceptance, quota measurement, quota settlement and receipt finalization are separate operations. Measurement can commit before settlement. The handler attempts quota completion and then records usage separately. A settlement failure can leave a reservation held while a receipt records an observation; a completed receipt is not proof of a settled financial charge. Sharing PostgreSQL does not create one transaction across these steps, nor automatic compensation after a partial failure.

## Receipts, events and analytics

With durable usage enabled, an accepted receipt precedes provider dispatch. Finalization commits that receipt's state, usage event and optional historical valuation/rate snapshot in one transaction. A failure at the last receipt write must also roll back the event and valuation writes. An identical final observation can be retried; a divergent one conflicts. The internal event ID identifies the operation; a client request ID can be reused and is not an idempotency key.

Protected receipt and quota writes require PostgreSQL `fsync=on` and force transaction-local synchronous commit. This does not certify the operator's storage hardware, replication or regional recovery guarantees. Other writes retain their configured PostgreSQL durability policy. An ambiguous acknowledgement is not a general instruction to retry any mutation.

Expired pending receipts become indeterminate through bounded recovery. The original owner may later provide its final observation according to the existing conditional transition rules. Recovery does not reconstruct or replay a provider call. See [durable usage and recovery](/docs/features/durable-usage/#recovery).

Ordinary event recording is best effort after the provider response. The client can receive HTTP 200 before that write attempt finishes; the response is not proof that an event was persisted. A recording failure is logged without replacing that response. Ordinary append does not promise universal deduplication or complete traffic coverage. Historical valuation is distinct from the protected budget ledger; a known estimate is not an invoice.

Event queries apply team scope before lookup, aggregation and pagination. Missing usage stays unknown, and rollup coverage and truncation remain explicit. The current multi-query analytics report does not promise one globally serializable database snapshot. A future analytics sink cannot become authorization or budget authority merely because it contains request records. See [usage valuation](/docs/features/usage-valuation/) and [access control](/docs/features/access-control/).

## Existing typed operation boundaries

The implementation still uses the concrete PostgreSQL `store.Store`. The gateway consumes the existing narrow `KeyReader` and `UsageReader` interfaces for managed-key lookup and log listing. This contract does not introduce a replacement repository framework.

| Existing operation | Typed boundary | Required outcome |
| --- | --- | --- |
| `LookupManagedKey` | `context.Context`, digest bytes → optional `config.Key`, error | Current applicable authority; no authorization on a storage error |
| `ControlSnapshot` | context → `ControlSnapshot`, error | Coherent version and bodies; no partial publication |
| Versioned control mutations | typed policy/body, expected version, request ID → new version, error | Operation-specific comparison, mutation and correlated audit commit together |
| `ReserveQuota` | context, `config.QuotaConfig`, `QuotaAdmission` → optional `QuotaReservation`, error | All applicable counters and reservation commit before protected dispatch |
| `SettleQuotaTokens` and unit-specific variants | reservation ID, typed measurement and proof state → error | Conditional completion under captured rates; unknown work remains held |
| `BeginDurableUsage` | internal ID, `UsageEvent` → error | Durable acceptance or refusal before dispatch |
| `FinalizeDurableUsage` | internal ID, `UsageEvent`, optional `UsageValuation`, uncertainty → error | Receipt, event and optional valuation/rate commit together; identical/divergent retry rules |
| `Record` / `RecordValuedUsage` | typed event, or internal ID plus typed valuation → error | Ordinary best-effort append versus fingerprinted event/valuation transaction; neither replaces quota authority |
| `ListUsage`, scoped request lookup and analytics | typed bounded filters → typed page/report, error | Scope before selection/aggregation; explicit unknown and coverage semantics |
| `OpenConfigured` / `Close` | context and existing storage configuration → store/error; owned close | Bounded lifecycle, coordinated migrations and cleanup of owned connections |

These are operation contracts, not a claim that the current store exposes three independently selectable backends. An adapter implementation may use different database primitives, but it must demonstrate the same required outcomes for its supported role. It must reject an unsupported responsibility rather than silently degrade to eventual authority, floating-point charges or an unprotected event append.

## Conformance and extension requirements

An adapter's accepted profile must identify its engine/version, served responsibilities, transaction boundaries, durability assumptions, cancellation, conflict and unknown-outcome behavior, migration compatibility, and failure/recovery limits. PostgreSQL currently uses explicit row locks and stable lock order for shared counters, repeatable-read snapshots where required, exact integer/decimal accounting, and coordinated per-migration transactions. This is not a claim that every transaction or report is serializable.

The contract regressions cover a late receipt-write failure after observation inserts and an already accepted operation completing after its team is logically deleted. The latter must deny the next authorization while preserving independently completed quota and receipt history. Existing tests separately cover concurrent reservations, version conflicts, audit rollback, snapshot ownership, divergent completion, uncertainty recovery and migration history. No single case certifies every persistence operation or hosting profile.

A physical outage test must own its database, processes, credentials and network. It must distinguish fail-closed authority and protected admission from ordinary best-effort recording, preserve the last valid configuration, then verify recovery. It must never stop a database shared by another test or infer managed-cloud support from a local container. Standalone and external-profile certification remain separate from this contract.

No runtime parameter, endpoint, adapter or product capability is added by documenting and testing these existing boundaries. Future engine selection, transfer procedures or split-store delivery need their own validated configuration, flags, authorization, API/console parity and real-service evidence. Physical separation would additionally need an explicit delivery and consistency protocol; this document does not supply one.

## Reference basis

PostgreSQL's versioned documentation explains [statement versus transaction snapshots](https://www.postgresql.org/docs/17/transaction-iso.html) and the durability tradeoff of [asynchronous commit](https://www.postgresql.org/docs/17/wal-async-commit.html). The gateway's actual typed consumers and transaction code define this product's contract; each advertised storage profile requires its own conformance evidence.

## MySQL

MySQL is not an engine of this gateway: T017 was cancelled on 2026-11-14 and its internal components were removed in T048 ([status](/docs/operate/mysql/)).

## Planned optional JDBC bridge

T073 records an optional JDBC extension after native adapters are consolidated. The standard gateway remains a Go executable without a Java runtime or JDBC drivers; an operator-selected isolated bridge/container would own those components. This is queued architecture, not an implemented connector, configuration field or supported storage profile.

Each approved driver, engine version and served responsibility must satisfy the same authority/financial/history contracts above. JDBC does not normalize SQL dialects, migrations, types, transaction isolation or durable acknowledgement. Selecting the future bridge will neither provision a database nor transfer existing data. Native profiles must remain independent when the bridge is unselected; credentials, driver code and transport trust require their own bounded configuration and real-service evidence. See the architecture direction.


## Regression and adapter certification

PostgreSQL is the only general regression engine. Optional engine support is qualified once at its support-delivery boundary; accepted evidence is retained. A routine schema, shared-helper or general feature change does not reopen that qualification. Only a registered concrete adapter defect or incompatible adapter change needs its affected check, without replaying unchanged product or adapter suites. The quality profiles record selection, required fixtures and evidence boundaries.
