rfgen.quota_enforcement and rfgen.quota_runtime¶
These modules form the sealed, fail-closed quota-enforcement boundary for a
single admission request. rfgen.quota_enforcement decides whether a complete
offline cost estimate may proceed under a canonical budget. rfgen.quota_runtime
contains separate operational guards for rate limiting, bounded concurrency,
and a hard-breach pause request. Neither module obtains cloud prices or quotas,
creates a cloud resource, or supplies a production run-control adapter.
All public V1 records are frozen, strict Pydantic models: unknown fields are
rejected and instances are immutable. Timestamps are timezone-aware UTC
datetime values. A digest is a lowercase 64-character SHA-256 hexadecimal
string. Self-hashes use RFC 8785 canonical JSON and omit only the model’s own
hash field.
Budget and approval records¶
CanonicalAmount and CurrencyCode¶
CanonicalAmount is a nonnegative decimal string with no leading zeroes,
scientific notation, or trailing fractional zeroes. CurrencyCode is exactly
three uppercase ASCII letters. Approval predicates use these strings rather
than JSON floating-point values, so an approval can reproduce an estimate
without a serialization-dependent numeric change.
UnitCeilingV1 and BudgetV1¶
UnitCeilingV1(unit, soft, hard) defines finite Decimal ceilings for one
PriceUnit; it requires 0 <= soft <= hard.
BudgetV1 has the following fields:
Field |
Contract |
|---|---|
|
Literal |
|
UUID identifying this budget policy |
|
|
|
Finite Decimal aggregate limits with |
|
Nonempty, uniquely sorted |
|
Nonempty, uniquely sorted nonblank signer identities |
|
UTC interval with |
|
RFC 8785 self-hash excluding |
The decision compares only aggregate UnitCostTotalV1.high values and the
estimate’s aggregate high_total; it never compares individual price lines to
budget ceilings.
ApprovedUnitTotalV1 and BudgetApprovalPredicateV1¶
ApprovedUnitTotalV1 is a signed canonical echo of one estimate total. Its
low, expected, and high fields are CanonicalAmount values,
line_item_count is positive, and total_sha256 equals SHA-256 of the RFC
8785 unit_total_projection(unit, low, expected, high, line_item_count).
BudgetApprovalPredicateV1 is the exact DSSE predicate accepted for an
approval. It binds budget_sha256, estimate_sha256,
admission_resource_spec_sha256, unit_totals_sha256, ordered approved
totals, run_id, approver_subject, currency, approved aggregate high,
budget hard limit, issue/expiry times, a UUID replay_id, and its
approval_sha256 self-hash. The signed rows must match the estimate rows
field-for-field after canonical Decimal serialization, including
line_item_count and total_sha256. Its UTC validity interval satisfies
issued_at < expires_at <= issued_at + 24 hours.
decide_admission¶
decide_admission(
budget: BudgetV1,
estimate: CostEstimateV1,
spec: AdmissionResourceSpecV1,
*,
approval_bundle: Bundle | None,
approval_policy: AttestationPolicyV1 | None,
adapter: SigstoreDSSEAdapter,
replay_store: ApprovalReplayStore,
as_of: datetime,
) -> AdmissionDecisionResultV1
This is the only admission decision entry point. It first revalidates all
self- and cross-hashes, the estimate/spec binding, currency, and UTC
as_of. It then checks the budget validity window and the one-to-one matrix
between estimate units and budget ceilings. These input-integrity checks take
precedence over budget comparison and approval inspection.
AdmissionDecisionResultV1 is a frozen, self-hashing audit result with
decision, enum-ordered nonempty reasons, budget/estimate/spec/total
digests, optional approval_sha256, and evaluated_at. Its closed decision
and reason enums are:
Decision |
Reason |
Condition |
|---|---|---|
|
|
The estimate status is not |
|
|
An estimated |
|
|
A budget ceiling has no estimated |
|
|
The aggregate high or any unit high exceeds its hard limit. |
|
|
The aggregate and every unit high are within soft limits and no approval artifact is supplied. |
|
|
The request is above a soft limit but not above a hard limit, and both approval inputs are absent. |
|
|
The request requires approval, the DSSE artifact and bindings verify, and the first replay claim succeeds. |
The procedure raises AuthorizationError and returns no result for a
non-UTC evaluation time; invalid input hashes or currency/spec/run bindings;
an expired budget; an unexpected approval on the within-soft path; only one of
bundle/policy being supplied; malformed or untrusted DSSE; signer, predicate,
time, total, or policy binding mismatch; and rejected or unavailable replay
storage. The stable error context["code"] is one of INPUT_INTEGRITY,
EXPIRED, UNEXPECTED_APPROVAL, APPROVAL_REQUIRED, ATTESTATION,
BINDING, REPLAY, or REPLAY_STORE.
Approval verification and replay boundary¶
SigstoreDSSEAdapter is injected from rfgen.attestation; quota enforcement
calls its verify method with BudgetApprovalPredicateV1. A verified predicate
must reproduce the exact budget, estimate, resource-spec, ordered total hash,
run, currency, aggregate high, hard limit, authorized signer, and policy
identity before it can be admitted. The adapter is not a plug-in extension
point for the decision procedure: tests may use a compatible fake, while a
production caller supplies the Layer 14 adapter and its attestation policy.
ApprovalReplayStore and RedisApprovalReplayStore¶
class ApprovalReplayStore(Protocol):
def claim(self, key: str, value: str, ttl_s: int) -> bool: ...
The shipped Redis implementation accepts only a key of the form
rfgen:budget-approval:{<64 lowercase hex approval hash>}, a nonblank value,
and a positive integer TTL. It makes exactly this redis-py call:
client.set(name=key, value=value, nx=True, ex=ttl_s)
Only a literal True result is a successful first claim. False, None, any
other result, timeout, connection failure, cluster error, replica-only state,
or exhausted redirect handling raises AuthorizationError with
REPLAY_STORE. The braces are a Redis Cluster hash tag: each approval’s claim
is routed to one slot and therefore one primary. Redis owns expiry; rfgen
does not pass a wall-clock value or attempt a second claim.
Operational guards¶
Operational guards do not alter decide_admission’s durable result. They are
caller-composed actions around a running workload and fail closed when their
authoritative external system cannot confirm an outcome.
RedisFixedWindowRateLimiter¶
RedisFixedWindowRateLimiter(storage_uri: str, *, key_prefix: str = "rfgen:admission-rate")
allow(decision_key: str, limit: RateLimitItem, *, cost: int = 1) -> bool
This guard delegates to limits.RedisStorage and
limits.strategies.FixedWindowRateLimiter. It normalizes each nonblank decision
key to rfgen:admission-rate:{<sha256(decision_key)>} so all counters for that
decision use one Redis Cluster primary. Redis performs the atomic increment
and TTL handling; rfgen supplies no timestamp and makes no Redis TIME claim.
An exhausted, otherwise reachable fixed window returns False. Initialization
or primary-confirmation failure raises AuthorizationError with
RATE_LIMIT_STORE; it is not treated as permission to run.
PostgresAdvisorySemaphore¶
PostgresAdvisorySemaphore(connection, *, namespace: str, capacity: int)
try_acquire() -> AdvisorySemaphoreLease | None
release(lease: AdvisorySemaphoreLease) -> None
acquire() -> contextmanager[AdvisorySemaphoreLease | None]
This is a bounded-concurrency adapter, not a distributed queue. It derives
exactly capacity namespace-specific PostgreSQL session advisory-lock keys,
returns a lease for one acquired slot, and returns None when all slots are
held. The supplied DB-API connection remains open for a lease lifetime;
PostgreSQL releases its session locks if that connection is lost. Query,
response, and release uncertainty raises ControlPlaneUnavailableError.
Foreign leases are rejected.
request_hard_breach_pause¶
request_hard_breach_pause(
adapter: HardBreachPauseAdapter,
run_handle: RunHandleV1,
*,
detected_at: datetime,
deadline: datetime,
) -> RunStatusV1
The caller provides an injected run-control adapter. detected_at and
deadline must be UTC and satisfy detected_at < deadline <= detected_at + 30 seconds. The adapter receives a compare-and-swap request from RUNNING to
PAUSING. Success requires a typed RunStatusV1 whose state is PAUSING and
whose UTC observed_at lies in the closed interval
detected_at <= observed_at <= deadline. A late or stale observation raises
DeadlineExceededError; an exception, malformed status, non-UTC observation,
or different state raises ControlPlaneUnavailableError. This establishes an
observed-time contract only; it does not claim that an in-process controller
is durable.
Verification routes¶
The acceptance tests in tests/unit/test_layer41_quota_enforcement_schemas.py,
tests/unit/test_layer41_admission_decision.py, and
tests/unit/test_layer41_quota_runtime.py cover canonical-hash validation,
the decision truth table and precedence, exact Redis replay invocation,
rate-limit failure behavior, semaphore capacity, and the 30-second pause
observation boundary.
See also¶
Admission Estimation defines the signed pricing, quota snapshot, resource-spec, and
CostEstimateV1inputs.Attestation defines the sealed DSSE verification adapter and policy model used for a budget approval.
Cloud Backends gives the operational placement and non-deployment boundaries.