economics

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 5, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Overview

Package economics defines provider-neutral public contracts for money, independent customer/operator rating, conservative exposure assumptions, immutable version snapshot references, and versioned snapshot sources.

Import DAG: authority → economics → metering (no cycles).

Boundary rules:

  • Must not import internal/*, database/sql, net/http, or provider SDKs.
  • May import pkg/lipsdk/metering for EconomicPerspective and related enums.

Compatibility (requirement 12.8): follows metering.CompatibilityPolicy — Validate/IsKnown reject or detect unknown enums for local enforcement; additive wire decode preserves unrecognized values and ignores unknown keys.

Index

Constants

View Source
const (
	MaxAllocationTargets = 4096
	MaxAllocationRefs    = 1024
)
View Source
const (
	AllocationOperationAllocate    AllocationOperation = "allocate"
	AllocationOperationRefund      AllocationOperation = "refund"
	AllocationOperationCorrection  AllocationOperation = "correction"
	AllocationOperationReplacement AllocationOperation = "replacement"
	AllocationOperationZero        AllocationOperation = "zero"
	AllocationAllocate                                 = AllocationOperationAllocate
	AllocationRefund                                   = AllocationOperationRefund
	AllocationCorrection                               = AllocationOperationCorrection
	AllocationReplacement                              = AllocationOperationReplacement
	AllocationOperationReplace                         = AllocationOperationReplacement
	AllocationZero                                     = AllocationOperationZero
)
View Source
const (
	// MaxRatingRules bounds the immutable rule material accepted from a source
	// or a host configuration. The bound keeps publication and replay work
	// deterministic without imposing a provider-specific catalog.
	MaxRatingRules             = 1024
	MaxRatingTiers             = 128
	MaxRatingConditions        = 32
	LegacyScalarSemanticsV1    = "legacy_scalar_per_million_tokens_v1"
	TariffSnapshotContentRefV1 = "tariff-snapshot:v1"
)
View Source
const (
	MaxRatingObservations   = 1024
	MaxQuoteObservationRefs = 1024
	MaxQuoteLimits          = 128
	MaxQuoteAssumptions     = 128
	MaxStatementLines       = 4096
	MaxImportResultIDs      = 4096
	MaxReconciliationPage   = 1024
)
View Source
const (
	// OperatorPageDefaultLimit bounds one operator page when the caller
	// omits a limit.
	OperatorPageDefaultLimit = 100
	// OperatorPageMaxLimit is the hard bounded page maximum.
	OperatorPageMaxLimit = 500
	// MaxOperatorCursorBytes bounds one operator continuation cursor. It is
	// larger than MaxValuationTextBytes because a journal-backed operator
	// cursor authenticates and wraps an opaque inner source position; it stays
	// bounded so a caller cannot submit unbounded continuation state.
	MaxOperatorCursorBytes = 8192
	// MaxDiscrepancyAggregateIDs bounds one aggregate plane's retained
	// missing/incomparable/conflict evidence identity lists. It matches the
	// canonical aggregate finding bound so a durable aggregate can always be
	// projected without truncation, while a caller cannot submit unbounded
	// identity state.
	MaxDiscrepancyAggregateIDs = 4096
)
View Source
const (
	// MaxSnapshotContentRefBytes bounds the durable resolver key carried by a
	// V2 contract. Resolution itself remains the responsibility of the
	// snapshot catalog; this package never performs I/O.
	MaxSnapshotContentRefBytes = 512
	// SnapshotContentHashBytes is the hexadecimal SHA-256 digest length used for
	// immutable snapshot and input-set content identity.
	SnapshotContentHashBytes = 64
)
View Source
const (
	MaxSupportAdvisoryPairs                 = 128
	MaxSupportAdvisoryContexts              = MaxValuationRefs + 3
	MaxSupportAdvisoryCandidateExaminations = 4096
	MaxSupportAdvisoryGraphVisits           = 65536
	MaxSupportAdvisoryIncompleteContexts    = MaxSupportAdvisoryContexts * supportAdvisoryReasonsPerContext
	// Scope keys embed subject JSON: nineteen bounded identity strings can
	// expand sixfold under JSON escaping, plus outer fields and framing.
	MaxSupportAdvisoryScopeKeyBytes = 64 * 1024
)

Public v1 bounds limit visibility without changing monetary rating.

View Source
const (
	// ValuationVersionV2 is the first version of the immutable valuation
	// envelope. A valuation is a derived record and never replaces an input
	// observation.
	//nolint:staticcheck // ValuationVersionV2 intentionally carries the explicit uint32 wire width used across 100+ call sites; the Max* limits stay untyped for direct use in int cardinality contexts
	ValuationVersionV2         uint32 = 2
	MaxValuationLines                 = 128
	MaxValuationTotals                = 32
	MaxValuationRefs                  = 1024
	MaxValuationTextBytes             = 512
	MaxValuationRationalDigits        = 128
)
View Source
const (
	BasisLocalExpected         ValuationBasis = "local_expected"          // E
	BasisProviderQuantityLocal ValuationBasis = "provider_quantity_local" // Q
	// BasisProviderUnitDebit is a provider-reported nonmonetary request debit
	// (for example credits consumed). It is not provider money P and cannot be
	// rated or converted without an explicit later rule.
	BasisProviderUnitDebit ValuationBasis = "provider_unit_debit"
	BasisProviderReported  ValuationBasis = "provider_reported"  // P
	BasisStatementReported ValuationBasis = "statement_reported" // S
	BasisCustomerPolicy    ValuationBasis = "customer_policy"    // R
	BasisAllocatedCost     ValuationBasis = "allocated_cost"
	// Short aliases are useful at adapter boundaries while preserving the
	// descriptive wire values above.
	BasisE          = BasisLocalExpected
	BasisQ          = BasisProviderQuantityLocal
	BasisD          = BasisProviderUnitDebit
	BasisP          = BasisProviderReported
	BasisS          = BasisStatementReported
	BasisR          = BasisCustomerPolicy
	ValuationBasisE = BasisLocalExpected
	ValuationBasisQ = BasisProviderQuantityLocal
	ValuationBasisD = BasisProviderUnitDebit
	ValuationBasisP = BasisProviderReported
	ValuationBasisS = BasisStatementReported
	ValuationBasisR = BasisCustomerPolicy
)
View Source
const (
	RoundingScopeLine   RoundingScope = "line"
	RoundingScopeCall   RoundingScope = "call"
	RoundingScopePeriod RoundingScope = "period"
	RoundingLine                      = RoundingScopeLine
	RoundingCall                      = RoundingScopeCall
	RoundingPeriod                    = RoundingScopePeriod
)
View Source
const (
	CoverageComplete    = CompletenessComplete
	CoveragePartial     = CompletenessPartial
	CoverageUnknown     = CompletenessUnknown
	CoverageConflict    = CompletenessConflict
	CoverageUnavailable = CompletenessUnavailable
)
View Source
const AllocationVersionV1 uint64 = 1

AllocationVersionV1 is the first immutable explicit allocation envelope.

View Source
const LegacyValuationContextHash = ""

LegacyValuationContextHash is the explicit marker used by historical durable valuation rows that predate the context-hash column. It is kept empty so those rows remain readable without being mistaken for a computed context.

View Source
const SupportAdvisoryVersionV1 = "component-support-advisory-v1"

SupportAdvisoryVersionV1 identifies the first frozen support-advisory contract.

Variables

View Source
var (
	ErrInvalidAllocation              = errors.New("economics: invalid allocation")
	ErrAllocationNotConserved         = errors.New("economics: allocation weights are not conserved")
	ErrAllocationTargetConflict       = errors.New("economics: allocation target conflict")
	ErrAllocationScopeMismatch        = errors.New("economics: allocation scope mismatch")
	ErrAllocationInvalidSource        = errors.New("economics: invalid allocation source")
	ErrAllocationSignMismatch         = errors.New("economics: allocation sign does not match operation")
	ErrAllocationRevisionRequired     = errors.New("economics: allocation revision required")
	ErrAllocationResidualUnassigned   = errors.New("economics: allocation rounding residual is unassigned")
	ErrAllocationSupersessionConflict = errors.New("economics: allocation supersession conflict")
	ErrAllocationSupersessionCycle    = errors.New("economics: allocation supersession cycle")
	ErrAllocationSupersessionFork     = errors.New("economics: allocation supersession fork")
	// HeadConflict is an alias of Fork so callers can classify either wording
	// without creating a second incompatible error taxonomy.
	ErrAllocationSupersessionHeadConflict = ErrAllocationSupersessionFork
)
View Source
var (
	ErrInvalidRatingRule       = errors.New("economics: invalid rating rule")
	ErrInvalidTariffSnapshot   = errors.New("economics: invalid tariff snapshot")
	ErrTariffSnapshotConflict  = errors.New("economics: tariff snapshot content conflict")
	ErrRatingRuleOverlap       = errors.New("economics: overlapping rating rules")
	ErrRatingRuleNonConserving = errors.New("economics: non-conserving rating allocation")
)
View Source
var (
	// ErrOperatorQueryInvalid identifies a malformed operator query: missing
	// scope, unbounded filters, unknown vocabulary or over-bound pages.
	ErrOperatorQueryInvalid = errors.New("economics: invalid operator query")
	// ErrOperatorScopeMismatch identifies evidence outside the trusted query
	// scope. Reads fail closed rather than mixing scopes.
	ErrOperatorScopeMismatch = errors.New("economics: operator scope mismatch")
	// ErrOperatorNotFound identifies an unknown scoped subject. Absent data
	// is not an error; unknown scope roots are.
	ErrOperatorNotFound = errors.New("economics: operator subject not found")
	// ErrOperatorBoundExceeded identifies a scope whose retained rows exceed
	// the bounded read contract.
	ErrOperatorBoundExceeded = errors.New("economics: operator page bound exceeded")
	// ErrOperatorCursorInvalid identifies a malformed, tampered or
	// cross-scope replayed page cursor.
	ErrOperatorCursorInvalid = errors.New("economics: invalid operator cursor")
	// ErrOperatorCursorStale identifies a continuation whose frozen full-scope
	// snapshot changed since the cursor was issued. The token is not a valid
	// position in the current snapshot; reusing it cannot produce a consistent
	// traversal, so the caller must restart pagination.
	ErrOperatorCursorStale = errors.New("economics: operator cursor snapshot changed")
)
View Source
var (
	ErrInvalidValuation = errors.New("economics: invalid valuation")
	ErrInvalidRating    = errors.New("economics: invalid rating input")
	ErrInvalidQuote     = errors.New("economics: invalid quote")
)
View Source
var ErrInputSetHashMismatch = errors.New("economics: input set hash mismatch")

ErrInputSetHashMismatch identifies a caller-supplied input identity that does not describe the canonical observation reference set. It is kept as a typed sentinel so direct raters and durable stores classify the same trust-boundary violation deterministically.

View Source
var ErrInvalidStatementIdentity = errors.New("economics: invalid statement identity")

ErrInvalidStatementIdentity identifies an incomplete or unsafe statement or statement-line identity. Statement revisions are immutable, so accepting an identity that cannot be reconstructed would make replay/conflict decisions ambiguous.

Functions

func CanonicalInputSetHash

func CanonicalInputSetHash(basis ValuationBasis, refs []metering.ObservationRef) (string, error)

CanonicalInputSetHash returns the SHA-256 identity of one valuation basis and its canonical observation-reference set. Exact duplicate references are collapsed, while two payload hashes for one observation revision are rejected because they cannot describe one immutable input set.

Callers must verify a supplied non-empty hash against this result before using it as an in-memory or durable identity. An empty caller hash is not an error; the trusted boundary may fill it with this result.

func CanonicalValuationInputSetHash

func CanonicalValuationInputSetHash(basis ValuationBasis, refs []metering.ObservationRef, allocationRefs []AllocationRef) (string, error)

CanonicalValuationInputSetHash returns the SHA-256 identity of one valuation basis, its canonical observation-reference set and its canonical allocation coverage-reference set. Allocation coverage references are economically significant valuation inputs: the same observations, rater, policy and tariff can be re-priced by re-proving a different immutable allocation revision, so a durable revision identity that omitted them could not persist a valid correction.

The allocation set is canonicalized by sorting and collapsing exact duplicates, mirroring observation handling. When no allocation coverage is present the preimage is byte-for-byte identical to the historical CanonicalInputSetHash, so legacy durable identity, replay and fingerprints are unchanged.

func NormalizeCurrency

func NormalizeCurrency(currency string) (string, error)

NormalizeCurrency trims and requires a nonempty uppercase A–Z currency code. Lowercase or mixed-case codes are rejected (requirement 4.6).

func NormalizeCurrencyRequired

func NormalizeCurrencyRequired(currency string) error

func ParseDecimalToNano

func ParseDecimalToNano(raw string) (int64, error)

ParseDecimalToNano converts a non-negative decimal major-unit amount into nano-units using exact integer arithmetic (requirements 4.6, 4.10).

Strict grammar (ASCII only):

  • one or more digits, optionally followed by '.' and one to nine digits
  • digits are required before the decimal point; trailing '.' is rejected
  • leading zeros are allowed ("01.5", "0.5")
  • rejected: '+'/'-', exponent, fraction slash, hex, underscores, any whitespace (including outer), more than nine fractional digits, overflow

Floats and silent Int64 truncation are never used.

func RoundQuotient

func RoundQuotient(numer, denom int64, policy RoundingPolicy) (int64, error)

RoundQuotient rounds numer/denom to int64 using a declared RoundingPolicy. Zero denominators are rejected before constructing a rational.

func RoundToInt64

func RoundToInt64(r *big.Rat, policy RoundingPolicy) (int64, error)

RoundToInt64 rounds a rational value to int64 using a declared RoundingPolicy. RoundingUnspecified follows existing toward-zero catalog multiply behavior. Ceil is not implemented. Nil rats, unknown policies, and overflow are rejected (requirements 4.6, 4.10).

func TokensFromMoneyPer1M

func TokensFromMoneyPer1M(moneyNano, pricePer1MNano int64, policy RoundingPolicy) (int64, error)

TokensFromMoneyPer1M converts a money amount in nano-units into a token count given a per-1M nano rate, using checked rational rounding (output-limit inversion helper; requirements 4.6, 4.10). Unrepresentable int64 results are rejected; values never saturate at MaxInt64.

func ValidateAllocationSupersessionGraph

func ValidateAllocationSupersessionGraph(records []AllocationRecord) error

ValidateAllocationSupersessionGraph validates immutable links while allowing absent predecessors to remain pending. Callers that need the effective/payable view should use ResolveAllocationSupersession.

func ValidateOperatorCursorSize

func ValidateOperatorCursorSize(field, value string) error

ValidateOperatorCursorSize rejects a raw operator continuation cursor whose transport bytes exceed MaxOperatorCursorBytes. It inspects only the raw byte count, so it is safe to call before any delimiter split, Base64 decode, MAC verification or inner parse, and it never echoes caller content. Operator cursor transport is ASCII, so raw bytes are the allocation boundary and Unicode codepoints are deliberately not counted here. An empty cursor is not rejected: the caller decides whether a continuation is required.

func ValidatePresentMoney

func ValidatePresentMoney(m Money) error

ValidatePresentMoney checks present money for nonnegative nano-units and normalized currency (requirements 4.6, 4.8, 4.9). Absent money is valid and distinct from authoritative zero.

func ValidateSafeRef

func ValidateSafeRef(field, value string) error

ValidateSafeRef rejects empty or control-bearing opaque references used on durable/operator surfaces (design D14).

Types

type AdjustmentComparison

type AdjustmentComparison string

AdjustmentComparison is the monetary comparability plane, separate from the transition outcome.

const (
	AdjustmentComparisonNotEvaluated AdjustmentComparison = "not_evaluated"
	AdjustmentComparisonComparable   AdjustmentComparison = "comparable"
	AdjustmentComparisonPending      AdjustmentComparison = "pending"
	AdjustmentComparisonIncomparable AdjustmentComparison = "incomparable"
)

func (AdjustmentComparison) IsKnown

func (s AdjustmentComparison) IsKnown() bool

IsKnown reports whether s is a documented comparison state.

type AdjustmentPage

type AdjustmentPage struct {
	Adjustments []AdjustmentView `json:"adjustments,omitempty"`
	NextCursor  string           `json:"next_cursor,omitempty"`
}

AdjustmentPage is one deterministic page of immutable corrections in (call, head, revision) order.

func (AdjustmentPage) Validate

func (p AdjustmentPage) Validate() error

Validate checks page bounds without mutating the page.

type AdjustmentPosting

type AdjustmentPosting string

AdjustmentPosting is the financial posting plane, separate from selection and comparison.

const (
	AdjustmentPostingUnposted AdjustmentPosting = "unposted"
	AdjustmentPostingPending  AdjustmentPosting = "pending"
	AdjustmentPostingApplied  AdjustmentPosting = "applied"
	AdjustmentPostingReplayed AdjustmentPosting = "replayed"
)

func (AdjustmentPosting) IsKnown

func (s AdjustmentPosting) IsKnown() bool

IsKnown reports whether s is a documented posting state.

type AdjustmentQuery

type AdjustmentQuery struct {
	Scope   OperatorScope `json:"scope"`
	CallID  string        `json:"call_id,omitempty"`
	HeadKey string        `json:"head_key,omitempty"`
	Limit   int           `json:"limit,omitempty"`
	Cursor  string        `json:"cursor,omitempty"`
}

AdjustmentQuery identifies a bounded selected-cost correction window for one customer account. Call and head narrow the window; all three must agree with the retained rows.

func (AdjustmentQuery) Normalize

func (q AdjustmentQuery) Normalize() (AdjustmentQuery, error)

Normalize trims scope, applies the default limit and rejects unbounded or ambiguously authorized queries.

type AdjustmentReader

type AdjustmentReader interface {
	QueryAdjustments(ctx context.Context, query AdjustmentQuery) (AdjustmentPage, error)
}

AdjustmentReader reads immutable selected-cost corrections and never performs selection, posting or provider calls.

type AdjustmentRef

type AdjustmentRef struct {
	StoreID     string `json:"store_id"`
	ValuationID string `json:"valuation_id"`
	Revision    uint64 `json:"revision"`
	OperationID string `json:"operation_id"`
}

AdjustmentRef links a line to an immutable later correction or selection operation. It carries no journal command or provider payload.

func (*AdjustmentRef) UnmarshalJSON

func (r *AdjustmentRef) UnmarshalJSON(data []byte) error

func (AdjustmentRef) Validate

func (r AdjustmentRef) Validate() error

type AdjustmentSelection

type AdjustmentSelection string

AdjustmentSelection is the selection outcome plane carried by the adjustment. Source selection alone is never labelled reconciliation.

const (
	AdjustmentSelectionFinal              AdjustmentSelection = "final"
	AdjustmentSelectionProvisional        AdjustmentSelection = "provisional"
	AdjustmentSelectionKnownZero          AdjustmentSelection = "known_zero"
	AdjustmentSelectionUnknown            AdjustmentSelection = "unknown"
	AdjustmentSelectionIncomparable       AdjustmentSelection = "incomparable"
	AdjustmentSelectionConflict           AdjustmentSelection = "conflict"
	AdjustmentSelectionNotOperatorPayable AdjustmentSelection = "not_operator_payable"
)

func (AdjustmentSelection) IsKnown

func (s AdjustmentSelection) IsKnown() bool

IsKnown reports whether s is a documented selection outcome.

type AdjustmentTransitionStatus

type AdjustmentTransitionStatus string

AdjustmentTransitionStatus is the correction outcome plane. Only applied, no-op and replay carry effects; pending, stale and conflict never do.

const (
	AdjustmentApplied  AdjustmentTransitionStatus = "applied"
	AdjustmentNoOp     AdjustmentTransitionStatus = "no_op"
	AdjustmentReplay   AdjustmentTransitionStatus = "replay"
	AdjustmentPending  AdjustmentTransitionStatus = "pending"
	AdjustmentStale    AdjustmentTransitionStatus = "stale"
	AdjustmentConflict AdjustmentTransitionStatus = "conflict"
)

func (AdjustmentTransitionStatus) IsKnown

func (s AdjustmentTransitionStatus) IsKnown() bool

IsKnown reports whether s is a documented transition status.

type AdjustmentValuationRef

type AdjustmentValuationRef struct {
	ValuationID  string `json:"valuation_id"`
	Revision     uint64 `json:"revision"`
	InputSetHash string `json:"input_set_hash"`
}

AdjustmentValuationRef is the immutable identity of one frozen selected valuation revision in the correction chain.

func (AdjustmentValuationRef) Validate

func (r AdjustmentValuationRef) Validate() error

Validate checks the immutable valuation identity.

type AdjustmentView

type AdjustmentView struct {
	OperationKey         string                     `json:"operation_key"`
	LinkKey              string                     `json:"link_key"`
	Fingerprint          string                     `json:"fingerprint"`
	AccountID            string                     `json:"account_id"`
	CallID               string                     `json:"call_id"`
	HeadKey              string                     `json:"head_key"`
	Status               AdjustmentTransitionStatus `json:"status"`
	Comparison           AdjustmentComparison       `json:"comparison"`
	Posting              AdjustmentPosting          `json:"posting"`
	SelectionStatus      AdjustmentSelection        `json:"selection_status"`
	SelectionReason      string                     `json:"selection_reason,omitempty"`
	Previous             *AdjustmentValuationRef    `json:"previous,omitempty"`
	Current              AdjustmentValuationRef     `json:"current"`
	Currency             string                     `json:"currency"`
	Delta                *ExactAmount               `json:"delta,omitempty"`
	JournalTransactionID string                     `json:"journal_transaction_id,omitempty"`
	CreatedAt            time.Time                  `json:"created_at"`
}

AdjustmentView is one immutable selected-cost correction with its comparison, selection and posting planes carried as independent fields.

func (AdjustmentView) Clone

func (v AdjustmentView) Clone() AdjustmentView

Clone deep-copies the view.

func (AdjustmentView) Validate

func (v AdjustmentView) Validate() error

Validate checks the view without mutating it.

type AllocationFraction

type AllocationFraction struct {
	Numerator   string `json:"numerator"`
	Denominator string `json:"denominator"`
}

AllocationFraction is an exact non-negative rational. Numerator and Denominator are strings to avoid floating-point loss in durable identities.

func (AllocationFraction) Normalize

func (f AllocationFraction) Normalize() (AllocationFraction, error)

func (AllocationFraction) Rat

func (f AllocationFraction) Rat() (*big.Rat, error)

func (AllocationFraction) Validate

func (f AllocationFraction) Validate() error

Validate checks an exact fraction without changing it.

type AllocationOperation

type AllocationOperation string

AllocationOperation describes the typed sign semantics of an allocation. Corrections are additive immutable records and refer to the superseded allocation; they never rewrite an earlier record.

func (AllocationOperation) IsKnown

func (o AllocationOperation) IsKnown() bool

type AllocationPage

type AllocationPage struct {
	Allocations []AllocationRecord
	NextCursor  string
}

type AllocationPolicyRef

type AllocationPolicyRef struct {
	Method  string `json:"method"`
	Version string `json:"version"`
	Hash    string `json:"hash"`
}

AllocationPolicyRef identifies the frozen policy that produced the weights. Hash is normally a lower-case SHA-256 content hash of the policy definition.

func (AllocationPolicyRef) Validate

func (p AllocationPolicyRef) Validate() error

Validate checks the policy reference without changing it.

type AllocationQuery

type AllocationQuery struct {
	StoreID       string
	SourceSubject *metering.SubjectRef
	TargetSubject *metering.SubjectRef
	PolicyMethod  string
	Operation     AllocationOperation
	Limit         int
	Cursor        string
}

AllocationQuery is a bounded durable listing filter.

type AllocationRecord

type AllocationRecord struct {
	ID       string `json:"id"`
	Version  uint64 `json:"version"`
	Revision uint64 `json:"revision,omitempty"`

	SourceSubject  metering.SubjectRef `json:"source_subject"`
	SourceBasis    ValuationBasis      `json:"source_basis"`
	SourceAmount   *metering.Decimal   `json:"source_amount,omitempty"`
	SourceQuantity *metering.Decimal   `json:"source_quantity,omitempty"`
	Currency       string              `json:"currency,omitempty"`
	Unit           string              `json:"unit,omitempty"`

	Policy                 AllocationPolicyRef      `json:"policy"`
	Operation              AllocationOperation      `json:"operation"`
	RoundingScope          RoundingScope            `json:"rounding_scope"`
	RoundingPolicy         RoundingPolicy           `json:"rounding_policy"`
	RoundingResidualPolicy AllocationResidualPolicy `json:"rounding_residual_policy"`
	RoundedSourceAmount    *AllocationRoundedAmount `json:"rounded_source_amount,omitempty"`
	RoundingResidualNano   int64                    `json:"rounding_residual_nano,omitempty"`

	SourceObservationRefs []metering.ObservationRef `json:"source_observation_refs,omitempty"`
	SourceValuationRefs   []AllocationValuationRef  `json:"source_valuation_refs,omitempty"`
	Supersedes            []AllocationRef           `json:"supersedes,omitempty"`
	Targets               []AllocationTarget        `json:"targets"`
	CreatedAt             time.Time                 `json:"created_at"`
}

AllocationRecord is an immutable, source-preserving allocation event. It is intentionally separate from provider money, account-window gauges, retail customer charges and B-leg inference quantities.

func ConserveAllocation

func ConserveAllocation(r AllocationRecord) (AllocationRecord, error)

ConserveAllocation is the named constructor used by adapters and stores. It returns a canonical copy; the caller's slices and pointers are untouched.

func (AllocationRecord) Canonical

func (r AllocationRecord) Canonical() (AllocationRecord, error)

Canonical normalizes and validates the record, computes exact shares and applies the declared integer residual policy.

func (AllocationRecord) CanonicalJSON

func (r AllocationRecord) CanonicalJSON() ([]byte, error)

func (AllocationRecord) Clone

Clone returns an independent value copy suitable for constructing an additive correction or replay probe without mutating the original record.

func (AllocationRecord) Fingerprint

func (r AllocationRecord) Fingerprint() string

func (AllocationRecord) IdentityKey

func (r AllocationRecord) IdentityKey() string

func (AllocationRecord) MarshalJSON

func (r AllocationRecord) MarshalJSON() ([]byte, error)

func (AllocationRecord) Validate

func (r AllocationRecord) Validate() error

Validate checks the immutable allocation envelope.

type AllocationRef

type AllocationRef struct {
	StoreID      string `json:"store_id"`
	AllocationID string `json:"allocation_id"`
	Version      uint64 `json:"version"`
	PayloadHash  string `json:"payload_hash"`
}

AllocationRef points to one immutable allocation revision.

func CanonicalAllocationCoverageRefs

func CanonicalAllocationCoverageRefs(refs []AllocationRef) ([]AllocationRef, error)

CanonicalAllocationCoverageRefs validates, sorts and collapses exact duplicate allocation coverage references into their canonical set. Two payload hashes for one store/allocation/version identity are rejected because they cannot describe one immutable input set.

func (AllocationRef) Validate

func (r AllocationRef) Validate() error

Validate checks an immutable allocation reference.

type AllocationResidualPolicy

type AllocationResidualPolicy string

AllocationResidualPolicy makes the treatment of a rounded residual an explicit part of replay identity. ToLastTarget means the final economic target (an explicit unallocated remainder is not preferred); ToUnallocated requires a target marked Unallocated.

const (
	AllocationResidualReject        AllocationResidualPolicy = "reject"
	AllocationResidualToLastTarget  AllocationResidualPolicy = "to_last_target"
	AllocationResidualToUnallocated AllocationResidualPolicy = "to_unallocated"
	AllocationResidualToLast                                 = AllocationResidualToLastTarget
	AllocationResidualToRemainder                            = AllocationResidualToUnallocated
)

func (AllocationResidualPolicy) IsKnown

func (p AllocationResidualPolicy) IsKnown() bool

type AllocationRoundedAmount

type AllocationRoundedAmount struct {
	NanoUnits int64          `json:"nano_units"`
	Currency  string         `json:"currency"`
	Present   bool           `json:"present"`
	Policy    RoundingPolicy `json:"policy"`
}

AllocationRoundedAmount is the integer ledger projection of an exact amount. The exact SourceAmount and target Share remain authoritative.

func (AllocationRoundedAmount) Validate

func (a AllocationRoundedAmount) Validate() error

type AllocationSupersessionResult

type AllocationSupersessionResult struct {
	Status            AllocationSupersessionStatus
	Records           []AllocationRecord
	Effective         []AllocationRecord
	Pending           []AllocationRef
	PendingSupersedes []AllocationRef
	Superseded        []AllocationRef
	Complete          bool
	Payable           bool
}

AllocationSupersessionResult is the deterministic view of an immutable allocation history. Records are canonical and identity-deduplicated; Effective contains only records at resolved active heads. Pending contains unresolved predecessor references from active records. A pending result is incomplete and not payable, while the original records remain unchanged.

func ResolveAllocationSupersession

func ResolveAllocationSupersession(records []AllocationRecord) (AllocationSupersessionResult, error)

ResolveAllocationSupersession validates and resolves an immutable allocation history. References to records outside the supplied history are retained as typed pending references. A pending record is excluded from the effective result until a later batch supplies its predecessor; no record is rewritten or inferred in the meantime.

type AllocationSupersessionStatus

type AllocationSupersessionStatus string

AllocationSupersessionStatus describes whether every supersession edge in the resolved allocation history names a predecessor that is present and verifiable. Pending is an explicit, fail-closed state; it is never treated as an effective or payable allocation.

const (
	AllocationSupersessionResolved AllocationSupersessionStatus = "resolved"
	AllocationSupersessionPending  AllocationSupersessionStatus = "pending"
)

func (AllocationSupersessionStatus) IsKnown

func (s AllocationSupersessionStatus) IsKnown() bool

type AllocationTarget

type AllocationTarget struct {
	TargetID             string                   `json:"target_id"`
	Target               metering.SubjectRef      `json:"target,omitzero"`
	Unallocated          bool                     `json:"unallocated,omitempty"`
	Informational        bool                     `json:"informational,omitempty"`
	AccountID            string                   `json:"account_id,omitempty"`
	PeriodID             string                   `json:"period_id,omitempty"`
	Currency             string                   `json:"currency,omitempty"`
	Unit                 string                   `json:"unit,omitempty"`
	Weight               AllocationFraction       `json:"weight"`
	Share                AllocationFraction       `json:"share"`
	RoundedAmount        *AllocationRoundedAmount `json:"rounded_amount,omitempty"`
	RoundingResidualNano int64                    `json:"rounding_residual_nano,omitempty"`
}

AllocationTarget is one immutable target and exact share. Unallocated is a first-class target with no subject, making a remainder auditable rather than silently losing source cost.

type AllocationValuationRef

type AllocationValuationRef struct {
	StoreID     string `json:"store_id"`
	ValuationID string `json:"valuation_id"`
	Version     uint64 `json:"version"`
	PayloadHash string `json:"payload_hash"`
}

AllocationValuationRef retains the immutable valuation basis used as input without making the allocation a provider charge or a request debit.

func (AllocationValuationRef) Validate

func (r AllocationValuationRef) Validate() error

Validate checks an immutable valuation reference.

type AllowancePage

type AllowancePage struct {
	Observations []metering.Observation `json:"observations,omitempty"`
	NextCursor   string                 `json:"next_cursor,omitempty"`
}

AllowancePage is one deterministic page of immutable allowance gauge history in effective observed-at order. Gauges are never summed: each observation stands alone and no per-request debit is inferred.

func (AllowancePage) Validate

func (p AllowancePage) Validate() error

Validate checks page bounds and observation validity without mutating it.

type AllowanceQuery

type AllowanceQuery struct {
	Scope              OperatorScope `json:"scope"`
	ProviderAccountKey string        `json:"provider_account_key"`
	PoolID             string        `json:"pool_id,omitempty"`
	WindowID           string        `json:"window_id,omitempty"`
	Limit              int           `json:"limit,omitempty"`
	Cursor             string        `json:"cursor,omitempty"`
}

AllowanceQuery identifies a bounded provider allowance-window history window. The provider account is mandatory: history without that bound would scan unrelated supplier accounts.

func (AllowanceQuery) Normalize

func (q AllowanceQuery) Normalize() (AllowanceQuery, error)

Normalize trims scope, applies the default limit and rejects unbounded or ambiguously authorized queries. Allowance history is provider-side gauge evidence under tenant authority; a customer account scope must not authorize it.

type AllowanceReader

type AllowanceReader interface {
	QueryAllowances(ctx context.Context, query AllowanceQuery) (AllowancePage, error)
}

AllowanceReader reads immutable provider allowance history and never performs rating, posting or provider calls.

type Completeness

type Completeness string

Completeness is independent of whether the economic value is estimated or reported. An estimated complete quantity and an incomplete provider claim must not collapse into one status.

const (
	CompletenessComplete    Completeness = "complete"
	CompletenessPartial     Completeness = "partial"
	CompletenessUnknown     Completeness = "unknown"
	CompletenessConflict    Completeness = "conflict"
	CompletenessUnavailable Completeness = "unavailable"
)

func (Completeness) IsKnown

func (c Completeness) IsKnown() bool

type ComponentRatingRule

type ComponentRatingRule = RatingRule

ComponentRatingRule and Rule are descriptive aliases used by adapters that prefer the domain vocabulary. They preserve one canonical representation.

type ConservativeOutputAssumption

type ConservativeOutputAssumption struct {
	BoundKind  OutputBoundKind `json:"bound_kind"`
	TokenCount int64           `json:"token_count"`
	PolicyID   string          `json:"policy_id,omitempty"`
	Present    bool            `json:"present"`
}

ConservativeOutputAssumption is the output token bound used for admission exposure when actual output is unknown.

func (ConservativeOutputAssumption) Validate

func (c ConservativeOutputAssumption) Validate() error

Validate checks bound kind when Present.

type CoverageStatus

type CoverageStatus = Completeness

CoverageStatus is a domain vocabulary alias used by reconciliation clients.

type CurrencyConversionRef

type CurrencyConversionRef struct {
	ID           string            `json:"id"`
	Version      string            `json:"version"`
	FromCurrency string            `json:"from_currency"`
	ToCurrency   string            `json:"to_currency"`
	Rate         *metering.Decimal `json:"rate"`
}

CurrencyConversionRef identifies an explicit frozen reporting conversion. Native and reporting amounts remain separate; a missing conversion is never interpreted as rate one.

func (CurrencyConversionRef) Clone

func (*CurrencyConversionRef) UnmarshalJSON

func (r *CurrencyConversionRef) UnmarshalJSON(data []byte) error

func (CurrencyConversionRef) Validate

func (r CurrencyConversionRef) Validate() error

type CurrencyTotal

type CurrencyTotal struct {
	Currency          string                 `json:"currency"`
	Amount            *metering.Decimal      `json:"amount,omitempty"`
	AmountNumerator   string                 `json:"amount_numerator,omitempty"`
	AmountDenominator string                 `json:"amount_denominator,omitempty"`
	RoundedAmount     Money                  `json:"rounded_amount,omitzero"`
	ReportingAmount   Money                  `json:"reporting_amount,omitzero"`
	Conversion        *CurrencyConversionRef `json:"conversion,omitempty"`
}

CurrencyTotal keeps exact native-currency value and checked rounded money together. ReportingAmount is optional and requires Conversion.

func (CurrencyTotal) Clone

func (t CurrencyTotal) Clone() CurrencyTotal

func (CurrencyTotal) ConvertReporting

func (t CurrencyTotal) ConvertReporting(policy RoundingPolicy) (Money, error)

ConvertReporting consumes the exact native total and applies the explicit frozen conversion rate once at reporting nano-unit precision. A rational native amount is preserved through multiplication; it is never converted through a terminating decimal approximation first.

func (*CurrencyTotal) UnmarshalJSON

func (t *CurrencyTotal) UnmarshalJSON(data []byte) error

func (CurrencyTotal) Validate

func (t CurrencyTotal) Validate() error

type DiscrepancyAggregate

type DiscrepancyAggregate struct {
	Status          DiscrepancyStatus `json:"status,omitempty"`
	Complete        bool              `json:"complete"`
	AffectedCount   int               `json:"affected_count,omitempty"`
	MissingIDs      []string          `json:"missing_ids,omitempty"`
	IncomparableIDs []string          `json:"incomparable_ids,omitempty"`
	ConflictIDs     []string          `json:"conflict_ids,omitempty"`
}

DiscrepancyAggregate is the public typed projection of one retained aggregate reconciliation plane. It preserves the bounded classification outcome and the identity of the evidence that could not be reconciled; it is an independent plane that never substitutes for, and never carries or implies, a quantity or monetary amount. Status is the most severe retained classification (conflict, incomparable, missing_provider, missing_local, partial, discrepant, within_tolerance, matched) or empty when the aggregate carries no finding at all. Complete is true exactly when no retained classification is missing, incomparable, conflicting or partial.

func (DiscrepancyAggregate) Clone

Clone deep-copies the aggregate projection.

func (DiscrepancyAggregate) Validate

func (a DiscrepancyAggregate) Validate() error

Validate checks the aggregate projection without mutating it.

type DiscrepancyDiagnostic

type DiscrepancyDiagnostic struct {
	Code   string            `json:"code"`
	Reason DiscrepancyReason `json:"reason,omitempty"`
	Detail string            `json:"detail,omitempty"`
}

DiscrepancyDiagnostic is one safe bounded operational signal. It never contains prompts, media, credentials or raw provider payloads.

func (DiscrepancyDiagnostic) Validate

func (d DiscrepancyDiagnostic) Validate() error

Validate checks the diagnostic without mutating it.

type DiscrepancyPage

type DiscrepancyPage struct {
	Items      []DiscrepancyView `json:"items,omitempty"`
	NextCursor string            `json:"next_cursor,omitempty"`
}

DiscrepancyPage is one deterministic page of retained reconciliation summaries in durable order.

func (DiscrepancyPage) Validate

func (p DiscrepancyPage) Validate() error

Validate checks page bounds without mutating the page.

type DiscrepancyQuery

type DiscrepancyQuery struct {
	Scope       OperatorScope        `json:"scope"`
	SubjectKind metering.SubjectKind `json:"subject_kind,omitempty"`
	SubjectID   string               `json:"subject_id,omitempty"`
	Limit       int                  `json:"limit,omitempty"`
	Cursor      string               `json:"cursor,omitempty"`
}

DiscrepancyQuery identifies a bounded retained-reconciliation window. Subject kind and ID narrow the window; both must be supplied together.

func (DiscrepancyQuery) Normalize

func (q DiscrepancyQuery) Normalize() (DiscrepancyQuery, error)

Normalize trims scope, applies the default limit and rejects unbounded or ambiguous queries.

type DiscrepancyReader

type DiscrepancyReader interface {
	QueryDiscrepancies(ctx context.Context, query DiscrepancyQuery) (DiscrepancyPage, error)
}

DiscrepancyReader reads immutable retained reconciliation summaries and never performs rating, posting or provider calls.

type DiscrepancyReason

type DiscrepancyReason string

DiscrepancyReason is the public typed explanation for a non-complete comparison term. Spellings match the durable reason vocabulary exactly.

const (
	DiscrepancyReasonNone                         DiscrepancyReason = ""
	DiscrepancyReasonSubjectMismatch              DiscrepancyReason = "subject_mismatch"
	DiscrepancyReasonPeriodMismatch               DiscrepancyReason = "period_mismatch"
	DiscrepancyReasonPayerMismatch                DiscrepancyReason = "payer_mismatch"
	DiscrepancyReasonCurrencyMismatch             DiscrepancyReason = "currency_mismatch"
	DiscrepancyReasonScopeMismatch                DiscrepancyReason = "scope_mismatch"
	DiscrepancyReasonChargeMismatch               DiscrepancyReason = "charge_mismatch"
	DiscrepancyReasonCoverageMismatch             DiscrepancyReason = "coverage_mismatch"
	DiscrepancyReasonContextMismatch              DiscrepancyReason = "measurement_context_mismatch"
	DiscrepancyReasonSchemaMismatch               DiscrepancyReason = "schema_mismatch"
	DiscrepancyReasonQualifierMismatch            DiscrepancyReason = "qualifier_mismatch"
	DiscrepancyReasonTokenizerMismatch            DiscrepancyReason = "tokenizer_mismatch"
	DiscrepancyReasonTokenizerMissing             DiscrepancyReason = "tokenizer_missing"
	DiscrepancyReasonTokenizerRequired            DiscrepancyReason = "tokenizer_required"
	DiscrepancyReasonSemanticsMismatch            DiscrepancyReason = "semantics_mismatch"
	DiscrepancyReasonValueUnavailableLocal        DiscrepancyReason = "value_unavailable_local"
	DiscrepancyReasonValueUnavailableProvider     DiscrepancyReason = "value_unavailable_provider"
	DiscrepancyReasonValueUnavailableBoth         DiscrepancyReason = "value_unavailable_both"
	DiscrepancyReasonDuplicateLocal               DiscrepancyReason = "duplicate_local"
	DiscrepancyReasonDuplicateProvider            DiscrepancyReason = "duplicate_provider"
	DiscrepancyReasonConflictingLocal             DiscrepancyReason = "conflicting_local"
	DiscrepancyReasonConflictingProvider          DiscrepancyReason = "conflicting_provider"
	DiscrepancyReasonZeroDenominator              DiscrepancyReason = "zero_denominator"
	DiscrepancyReasonUnitMismatch                 DiscrepancyReason = "unit_mismatch"
	DiscrepancyReasonTolerancePolicyMissing       DiscrepancyReason = "tolerance_policy_missing"
	DiscrepancyReasonEstimatedNotExact            DiscrepancyReason = "estimated_not_exact"
	DiscrepancyReasonMissingE                     DiscrepancyReason = "missing_e"
	DiscrepancyReasonMissingQ                     DiscrepancyReason = "missing_q"
	DiscrepancyReasonMissingP                     DiscrepancyReason = "missing_p"
	DiscrepancyReasonAmountUnavailable            DiscrepancyReason = "amount_unavailable"
	DiscrepancyReasonCurrencyMissing              DiscrepancyReason = "currency_missing"
	DiscrepancyReasonTariffMismatch               DiscrepancyReason = "tariff_mismatch"
	DiscrepancyReasonValuationIncomplete          DiscrepancyReason = "valuation_incomplete"
	DiscrepancyReasonValuationConflict            DiscrepancyReason = "valuation_conflict"
	DiscrepancyReasonQuantityEvidencePartial      DiscrepancyReason = "quantity_evidence_partial"
	DiscrepancyReasonQuantityEvidenceIncomparable DiscrepancyReason = "quantity_evidence_incomparable"
	DiscrepancyReasonQuantityEvidenceConflict     DiscrepancyReason = "quantity_evidence_conflict"
)

func (DiscrepancyReason) IsKnown

func (r DiscrepancyReason) IsKnown() bool

IsKnown reports whether r is a documented discrepancy reason.

type DiscrepancyStatus

type DiscrepancyStatus string

DiscrepancyStatus is the public comparison outcome vocabulary. Spellings match the durable reconciliation vocabulary exactly; readers pass them through without reinterpretation.

const (
	DiscrepancyMatched          DiscrepancyStatus = "matched"
	DiscrepancyWithinTolerance  DiscrepancyStatus = "within_tolerance"
	DiscrepancyDiscrepant       DiscrepancyStatus = "discrepant"
	DiscrepancyPartial          DiscrepancyStatus = "partial"
	DiscrepancyIncomparable     DiscrepancyStatus = "incomparable"
	DiscrepancyMissingLocal     DiscrepancyStatus = "missing_local"
	DiscrepancyMissingProvider  DiscrepancyStatus = "missing_provider"
	DiscrepancyPendingStatement DiscrepancyStatus = "pending_statement"
	DiscrepancyConflict         DiscrepancyStatus = "conflict"
)

func (DiscrepancyStatus) IsKnown

func (s DiscrepancyStatus) IsKnown() bool

IsKnown reports whether s is a documented discrepancy status.

type DiscrepancyView

type DiscrepancyView struct {
	ID               string                    `json:"id"`
	Revision         uint64                    `json:"revision"`
	Subject          metering.SubjectRef       `json:"subject"`
	Scope            string                    `json:"scope,omitempty"`
	Payer            metering.PaymentParty     `json:"payer,omitzero"`
	PolicyID         string                    `json:"policy_id"`
	PolicyVersion    string                    `json:"policy_version"`
	InputSetHash     string                    `json:"input_set_hash,omitempty"`
	ValuationIDs     []string                  `json:"valuation_ids,omitempty"`
	ObservationRefs  []metering.ObservationRef `json:"observation_refs,omitempty"`
	QuantityStatus   DiscrepancyStatus         `json:"quantity_status,omitempty"`
	QuantityComplete bool                      `json:"quantity_complete"`
	MonetaryState    MonetaryState             `json:"monetary_state,omitempty"`
	MonetaryReason   DiscrepancyReason         `json:"monetary_reason,omitempty"`
	Aggregate        *DiscrepancyAggregate     `json:"aggregate,omitempty"`
	Diagnostics      []DiscrepancyDiagnostic   `json:"diagnostics,omitempty"`
	CreatedAt        time.Time                 `json:"created_at"`
}

DiscrepancyView is one retained reconciliation summary. Quantity, monetary and aggregate planes are independent fields; an absent plane is nil-like (empty status) and never reads as reconciled.

func SortDiscrepancies

func SortDiscrepancies(in []DiscrepancyView) []DiscrepancyView

SortDiscrepancies returns a copy sorted by stable identity. It is a helper for operator consumers and does not mutate caller-owned slices.

func (DiscrepancyView) Clone

func (v DiscrepancyView) Clone() DiscrepancyView

Clone deep-copies the view for consumers that need local sorting.

func (DiscrepancyView) Validate

func (v DiscrepancyView) Validate() error

Validate checks the view without mutating it.

type EvidenceCapability

type EvidenceCapability struct {
	Name     string `json:"name"`
	Required bool   `json:"required"`
}

EvidenceCapability states an evidence requirement for a quote without embedding provider-specific request data.

func (*EvidenceCapability) UnmarshalJSON

func (c *EvidenceCapability) UnmarshalJSON(data []byte) error

func (EvidenceCapability) Validate

func (c EvidenceCapability) Validate() error

type ExactAmount

type ExactAmount struct {
	Currency    string            `json:"currency"`
	Decimal     *metering.Decimal `json:"decimal,omitempty"`
	Numerator   string            `json:"numerator,omitempty"`
	Denominator string            `json:"denominator,omitempty"`
}

ExactAmount is one signed exact native-currency amount for adjustment deltas. Exactly one representation is present: a canonical bounded decimal, or reduced rational parts. Downward corrections carry negative deltas; the balanced journal reverses debit/credit sides instead of recording a negative gross amount.

func (ExactAmount) Clone

func (a ExactAmount) Clone() ExactAmount

Clone deep-copies the amount.

func (ExactAmount) Validate

func (a ExactAmount) Validate() error

Validate enforces the canonical exact-amount contract.

type ExposureBasis

type ExposureBasis struct {
	Perspective metering.EconomicPerspective `json:"perspective"`
	Boundary    metering.Boundary            `json:"boundary"`
	Lifecycle   metering.LifecycleScope      `json:"lifecycle"`
	Quantities  []metering.Quantity          `json:"quantities,omitempty"`
	Money       Money                        `json:"money,omitzero"`
	Output      ConservativeOutputAssumption `json:"output,omitzero"`
	FactRefs    []metering.FactRef           `json:"fact_refs,omitempty"`
}

ExposureBasis describes quantities and assumptions used for authority admission.

func (ExposureBasis) Validate

func (e ExposureBasis) Validate() error

Validate checks perspective/boundary/lifecycle and optional output assumption.

type ExposureQuote

type ExposureQuote struct {
	ID                   string                       `json:"id,omitempty"`
	Version              uint32                       `json:"version"`
	Perspective          metering.EconomicPerspective `json:"perspective,omitempty"`
	Basis                ValuationBasis               `json:"basis,omitempty"`
	Subject              metering.SubjectRef          `json:"subject"`
	Minimum              Money                        `json:"minimum,omitzero"`
	Maximum              Money                        `json:"maximum,omitzero"`
	CreditBound          Money                        `json:"credit_bound,omitzero"`
	CreditUnits          []UnitBound                  `json:"credit_units,omitempty"`
	AllowanceUnits       []UnitBound                  `json:"allowance_units,omitempty"`
	Assumptions          []QuoteAssumption            `json:"assumptions,omitempty"`
	RequiredCapabilities []EvidenceCapability         `json:"required_capabilities,omitempty"`
	Policy               PolicySnapshotRef            `json:"policy"`
	PolicyContent        *SnapshotContentRef          `json:"policy_content,omitempty"`
	Tariff               RatingSnapshotRef            `json:"tariff"`
	TariffContent        *SnapshotContentRef          `json:"tariff_content,omitempty"`
	InputSetHash         string                       `json:"input_set_hash,omitempty"`
	QualifierSnapshotRef *SnapshotContentRef          `json:"qualifier_snapshot_ref,omitempty"`
	Completeness         Completeness                 `json:"completeness"`
	CreatedAt            time.Time                    `json:"created_at,omitzero"`
}

ExposureQuote is a bounded quote result. Money remains absent/present-aware; no quote silently turns unavailable exposure into zero.

func (ExposureQuote) Clone

func (q ExposureQuote) Clone() ExposureQuote

func (*ExposureQuote) UnmarshalJSON

func (q *ExposureQuote) UnmarshalJSON(data []byte) error

func (ExposureQuote) Validate

func (q ExposureQuote) Validate() error

type FixedFeeIdentity

type FixedFeeIdentity struct {
	ID      string        `json:"id"`
	Scope   FixedFeeScope `json:"scope"`
	Version string        `json:"version,omitempty"`
}

FixedFeeIdentity is the stable identity of a non-quantity charge line. Scope is part of identity and must be frozen by the commercial policy.

func (*FixedFeeIdentity) UnmarshalJSON

func (f *FixedFeeIdentity) UnmarshalJSON(data []byte) error

func (FixedFeeIdentity) Validate

func (f FixedFeeIdentity) Validate() error

type FixedFeeScope

type FixedFeeScope string

FixedFeeScope identifies the trusted commercial scope of a fixed fee. It is deliberately separate from B-leg inference quantities so a call fee is not repeated once for every retry.

const (
	FixedFeeScopeSubmission FixedFeeScope = "submission"
	FixedFeeScopeCall       FixedFeeScope = "call"
	FixedFeeScopePeriod     FixedFeeScope = "period"
)

func (FixedFeeScope) IsKnown

func (s FixedFeeScope) IsKnown() bool

type ImportResult

type ImportResult struct {
	Accepted  []string `json:"accepted,omitempty"`
	Replayed  []string `json:"replayed,omitempty"`
	Unmatched []string `json:"unmatched,omitempty"`
	Rejected  []string `json:"rejected,omitempty"`
}

ImportResult reports identity-level outcomes without executing model calls.

func (ImportResult) Validate

func (r ImportResult) Validate() error

type Limit

type Limit struct {
	Name  string `json:"name"`
	Value int64  `json:"value"`
	Unit  string `json:"unit"`
}

Limit is one finite candidate/work quantity for exposure admission. Value is an exact integer bound; it is not a provider utilization gauge.

func SortLimits

func SortLimits(in []Limit) []Limit

SortLimits returns a copy sorted by stable name/unit identity. It is a helper for quote implementations and does not mutate caller-owned slices.

func (*Limit) UnmarshalJSON

func (l *Limit) UnmarshalJSON(data []byte) error

func (Limit) Validate

func (l Limit) Validate() error

type LineItem

type LineItem struct {
	ID              string                 `json:"id"`
	RuleID          string                 `json:"rule_id"`
	ItemID          string                 `json:"item_id"`
	Component       *metering.ComponentKey `json:"component,omitempty"`
	FixedFee        *FixedFeeIdentity      `json:"fixed_fee,omitempty"`
	Quantity        *metering.Decimal      `json:"quantity,omitempty"`
	Unit            string                 `json:"unit"`
	UnitPrice       *metering.Decimal      `json:"unit_price,omitempty"`
	RateNumerator   *metering.Decimal      `json:"rate_numerator,omitempty"`
	RateDenominator *metering.Decimal      `json:"rate_denominator,omitempty"`
	Amount          *metering.Decimal      `json:"amount,omitempty"`
	// AmountNumerator and AmountDenominator preserve an exact bounded rational
	// when Amount cannot be represented as a terminating Decimal. They are
	// mutually required and never contain a rounded approximation.
	AmountNumerator       string                    `json:"amount_numerator,omitempty"`
	AmountDenominator     string                    `json:"amount_denominator,omitempty"`
	RoundedAmount         *Money                    `json:"rounded_amount,omitempty"`
	RoundingScope         RoundingScope             `json:"rounding_scope,omitempty"`
	RoundingPolicy        RoundingPolicy            `json:"rounding_policy,omitempty"`
	IncludedUnit          bool                      `json:"included_unit,omitempty"`
	Status                RatingLineStatus          `json:"status,omitempty"`
	ReportedAggregate     bool                      `json:"reported_aggregate,omitempty"`
	ChargeKind            string                    `json:"charge_kind,omitempty"`
	SourceObservationRefs []metering.ObservationRef `json:"source_observation_refs,omitempty"`
	AdjustmentRefs        []AdjustmentRef           `json:"adjustment_refs,omitempty"`
}

LineItem is one exact economic line. Component and FixedFee are mutually exclusive identities; no provider aggregate is decomposed by this DTO.

func (LineItem) Clone

func (l LineItem) Clone() LineItem

func (*LineItem) UnmarshalJSON

func (l *LineItem) UnmarshalJSON(data []byte) error

func (LineItem) Validate

func (l LineItem) Validate() error

type MonetaryState

type MonetaryState string

MonetaryState is the public monetary decomposition outcome. It is a separate field from the quantity comparison status by design.

const (
	MonetaryComplete     MonetaryState = "complete"
	MonetaryPartial      MonetaryState = "partial"
	MonetaryIncomparable MonetaryState = "incomparable"
	MonetaryConflict     MonetaryState = "conflict"
)

func (MonetaryState) IsKnown

func (s MonetaryState) IsKnown() bool

IsKnown reports whether s is a documented monetary state.

type Money

type Money struct {
	NanoUnits int64  `json:"nano_units"`
	Currency  string `json:"currency,omitempty"`
	Present   bool   `json:"present"`
}

Money is a currency-tagged amount in nano-units of the major currency unit. Present distinguishes authoritative zero from an absent amount (requirement 6.2).

func AggregateMoney

func AggregateMoney(parts ...Money) (Money, error)

AggregateMoney sums present same-currency amounts with checked arithmetic.

func MulTokensByRatePer1M

func MulTokensByRatePer1M(tokens, pricePer1MNano int64) (Money, error)

MulTokensByRatePer1M multiplies token count by a per-1M nano rate with overflow detection. A successful result is always Present, including authoritative zero when tokens or rate are non-positive (mirrors Phase 2 checked multiply semantics). Fractional nanos truncate toward zero (RoundingUnspecified default).

func (Money) Add

func (m Money) Add(other Money) (Money, error)

Add returns the checked sum of two present amounts in the same currency.

func (Money) Sub

func (m Money) Sub(other Money) (Money, error)

Sub returns the checked difference m - other for non-negative present amounts.

func (Money) Validate

func (m Money) Validate() error

Validate accepts absent money; present money must be nonnegative with a normalized currency code (requirements 4.6, 4.8).

type NanoRate

type NanoRate struct {
	NanoUnits int64
	Present   bool
}

NanoRate is a monetary rate in nano-units of the major currency unit per pricing basis (for example per 1M tokens). Present distinguishes an authoritative zero rate from an absent/unspecified rate (requirements 2.9, 4.8).

func ParseOptionalNanoRate

func ParseOptionalNanoRate(raw string) (NanoRate, error)

ParseOptionalNanoRate treats empty/whitespace-only as absent; otherwise parses an explicit rate including authoritative zero. Non-empty values must satisfy ParseDecimalToNano (no surrounding whitespace on a present rate).

func ParseRequiredNanoRate

func ParseRequiredNanoRate(raw string) (NanoRate, error)

ParseRequiredNanoRate rejects absent rates; explicit zero remains valid.

type OperatorReader

OperatorReader is the combined protected operator surface. Adapters may implement readers individually; the combination exists so composition roots can require the full 16.2A surface with one bound.

type OperatorScope

type OperatorScope struct {
	StoreID   string `json:"store_id"`
	TenantID  string `json:"tenant_id,omitempty"`
	AccountID string `json:"account_id,omitempty"`
}

OperatorScope is the explicit trusted scope of one operator read. StoreID is always required; at least one of TenantID or AccountID is required so no query runs under a store-only scope. Per-reader rules narrow further.

func (OperatorScope) Validate

func (s OperatorScope) Validate() error

Validate checks the trusted scope without normalizing caller memory.

type OutputBoundKind

type OutputBoundKind string

OutputBoundKind classifies how a conservative max-output assumption was chosen at admission (requirement 7.6; aligns with Phase 2 unknown-output policies).

const (
	OutputBoundRequireClientLimit  OutputBoundKind = "require_client_limit"
	OutputBoundConfiguredDefault   OutputBoundKind = "configured_default"
	OutputBoundModelBackendMaximum OutputBoundKind = "model_backend_maximum"
	OutputBoundClamp               OutputBoundKind = "clamp"
	OutputBoundDeny                OutputBoundKind = "deny"
	OutputBoundClientProvided      OutputBoundKind = "client_provided"
)

func (OutputBoundKind) IsKnown

func (k OutputBoundKind) IsKnown() bool

IsKnown reports whether k is a documented output bound kind.

type PolicyKind

type PolicyKind string

PolicyKind identifies which rule plane a policy snapshot represents.

const (
	PolicyKindUsageAuthority PolicyKind = "usage_authority"
	PolicyKindConcurrency    PolicyKind = "concurrency"
)

func (PolicyKind) IsKnown

func (k PolicyKind) IsKnown() bool

IsKnown reports whether k is a documented policy kind.

type PolicyRulesView

type PolicyRulesView struct {
	Kind    PolicyKind `json:"kind"`
	Payload []byte     `json:"payload,omitempty"`
}

PolicyRulesView is the public, opaque policy payload for injectable sources. Concrete rule decoding stays internal; enterprise modules may supply opaque bytes.

type PolicySnapshotRef

type PolicySnapshotRef struct {
	VersionRef
	PolicyID string `json:"policy_id,omitempty"`
}

PolicySnapshotRef binds an authority/policy snapshot used for an admission or settlement.

type PostUsageRatingInput

type PostUsageRatingInput = RatingInput

PostUsageRatingInput is the billing-owned spelling of the existing provider-neutral rating input. Keeping this alias distinct at integration boundaries prevents internal post-usage code from being mistaken for the deleted stream-time customer-rating bridge while preserving wire and type compatibility for callers that already construct RatingInput values.

type QualifierCondition

type QualifierCondition struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

QualifierCondition is an exact match against one effective qualifier. A missing qualifier never matches the condition, so the rule carrying it is not a candidate; the miss is recorded as a diagnostic and becomes the reported fail-closed ErrQualifierMissing only when NO rule for the component remains a candidate. A less specific rule whose own conditions ARE satisfied is a legitimate candidate, so a miss falls back to it rather than failing closed over a rate that was actually declared for this case.

The fallback is specificity resolution, not a silent default: the general rule is published, applicable and its rate is known, so no quantity is invented. A tariff that needs "this conditional rate or nothing" has no way to say so yet; that would need a separate versioned field rather than a reinterpretation of the miss.

func (QualifierCondition) Validate

func (c QualifierCondition) Validate() error

type QuoteAssumption

type QuoteAssumption struct {
	Name   string `json:"name"`
	Value  string `json:"value"`
	Reason string `json:"reason,omitempty"`
}

QuoteAssumption is a safe, human-readable assumption label. It is not raw prompt text and has no effect on account state.

func (*QuoteAssumption) UnmarshalJSON

func (a *QuoteAssumption) UnmarshalJSON(data []byte) error

func (QuoteAssumption) Validate

func (a QuoteAssumption) Validate() error

type QuoteInput

type QuoteInput struct {
	Version              uint32                       `json:"version"`
	Perspective          metering.EconomicPerspective `json:"perspective,omitempty"`
	Basis                ValuationBasis               `json:"basis,omitempty"`
	Subject              metering.SubjectRef          `json:"subject"`
	Scope                string                       `json:"scope,omitempty"`
	ObservationRefs      []metering.ObservationRef    `json:"observation_refs,omitempty"`
	EffectiveQualifiers  []metering.Dimension         `json:"effective_qualifiers,omitempty"`
	InputSetHash         string                       `json:"input_set_hash,omitempty"`
	QualifierSnapshotRef *SnapshotContentRef          `json:"qualifier_snapshot_ref,omitempty"`
	CandidateLimits      []Limit                      `json:"candidate_limits"`
	WorkLimits           []Limit                      `json:"work_limits,omitempty"`
	Tariff               RatingSnapshotRef            `json:"tariff"`
	TariffContent        *SnapshotContentRef          `json:"tariff_content,omitempty"`
	Policy               PolicySnapshotRef            `json:"policy"`
	PolicyContent        *SnapshotContentRef          `json:"policy_content,omitempty"`
	AsOf                 time.Time                    `json:"as_of,omitzero"`
}

QuoteInput carries finite execution candidates and an explicit commercial policy version. It cannot accept an opaque provider request or mutate an account balance.

func (QuoteInput) Clone

func (in QuoteInput) Clone() QuoteInput

func (*QuoteInput) UnmarshalJSON

func (in *QuoteInput) UnmarshalJSON(data []byte) error

func (QuoteInput) Validate

func (in QuoteInput) Validate() error

type Quoter

type Quoter interface {
	Quote(ctx context.Context, in QuoteInput) (ExposureQuote, error)
}

Quoter computes a bounded pre-execution exposure quote for one commercial policy. It does not reserve or mutate money.

type Rater

type Rater interface {
	Rate(ctx context.Context, in RatingInput) (Valuation, error)
}

Rater evaluates one explicit economic plane against an immutable input set. Implementations may be supplied by an application or enterprise module; the contract contains no provider SDK or persistence dependency. Runtime stream handlers do not invoke this post-usage seam.

type RatingCatalogView

type RatingCatalogView struct {
	Currency               string               `json:"currency,omitempty"`
	CatalogVersion         string               `json:"catalog_version,omitempty"`
	Rules                  []RatingRule         `json:"rules,omitempty"`
	EffectiveQualifiers    []metering.Dimension `json:"effective_qualifiers,omitempty"`
	LegacySemantics        string               `json:"legacy_semantics,omitempty"`
	SupportAdvisoryVersion string               `json:"support_advisory_version,omitempty"`
	// Schemas carries optional frozen component-relationship material published
	// by a rating source. It is the view-plane counterpart of
	// TariffSnapshot.Schemas: a view that omits or drops schemas reconstructs a
	// different content identity than the published tariff. Nil/empty schemas
	// reproduce the exact legacy contract.
	Schemas []metering.ComponentSchema `json:"schemas,omitempty"`
}

RatingCatalogView is the public rating/catalog snapshot payload.

func (RatingCatalogView) Clone

func (RatingCatalogView) Tariff

Tariff materializes a catalog view under an immutable rating identity.

func (RatingCatalogView) Validate

func (v RatingCatalogView) Validate() error

Validate validates supplied generic catalog material without requiring a snapshot identity; the source envelope supplies ID/version separately.

type RatingInput

type RatingInput struct {
	Version         uint32                       `json:"version"`
	Perspective     metering.EconomicPerspective `json:"perspective"`
	Basis           ValuationBasis               `json:"basis"`
	Subject         metering.SubjectRef          `json:"subject"`
	Scope           string                       `json:"scope,omitempty"`
	Payer           metering.PaymentParty        `json:"payer,omitzero"`
	Observations    []metering.Observation       `json:"observations,omitempty"`
	ObservationRefs []metering.ObservationRef    `json:"observation_refs,omitempty"`
	// AllocationCoverageRefs declares the exact immutable allocation
	// revisions whose conserved distribution is an economic input to this
	// valuation. They are separate from the observation plane: the input-set
	// hash authenticates observations only, while the full allocation-aware
	// valuation identity additionally authenticates this set. An allocation-only
	// correction therefore produces a distinct immutable revision without
	// fabricating observation revisions. Empty preserves legacy behavior.
	AllocationCoverageRefs []AllocationRef      `json:"allocation_coverage_refs,omitempty"`
	EffectiveQualifiers    []metering.Dimension `json:"effective_qualifiers,omitempty"`
	Rater                  RatingSnapshotRef    `json:"rater"`
	RaterContent           *SnapshotContentRef  `json:"rater_content,omitempty"`
	Tariff                 RatingSnapshotRef    `json:"tariff"`
	TariffContent          *SnapshotContentRef  `json:"tariff_content,omitempty"`
	Policy                 PolicySnapshotRef    `json:"policy"`
	PolicyContent          *SnapshotContentRef  `json:"policy_content,omitempty"`
	InputSetHash           string               `json:"input_set_hash,omitempty"`
	QualifierSnapshotRef   *SnapshotContentRef  `json:"qualifier_snapshot_ref,omitempty"`
	AsOf                   time.Time            `json:"as_of,omitzero"`
}

RatingInput explicitly selects one valuation basis. Observations are copied by Clone before an implementation mutates local working state.

func (RatingInput) Clone

func (in RatingInput) Clone() RatingInput

Clone protects custom raters from mutating caller-owned observations and slices. It does not claim persistence immutability by itself.

func (*RatingInput) UnmarshalJSON

func (in *RatingInput) UnmarshalJSON(data []byte) error

func (RatingInput) Validate

func (in RatingInput) Validate() error

type RatingLineStatus

type RatingLineStatus string

RatingLineStatus records why a line is or is not economically usable. An explicit free rule is intentionally distinct from missing/unsupported rate evidence; neither missing state is represented as a zero amount.

const (
	RatingLineRated              RatingLineStatus = "rated"
	RatingLineExplicitFree       RatingLineStatus = "explicit_free"
	RatingLineProviderReported   RatingLineStatus = "provider_reported"
	RatingLineRateMissing        RatingLineStatus = "rate_missing"
	RatingLineRateUnsupported    RatingLineStatus = "rate_unsupported"
	RatingLineCurrencyMismatch   RatingLineStatus = "currency_mismatch"
	RatingLineQuantityIncomplete RatingLineStatus = "quantity_incomplete"
	RatingLineCoverageIncomplete RatingLineStatus = "coverage_incomplete"
)

func (RatingLineStatus) IsKnown

func (s RatingLineStatus) IsKnown() bool

type RatingRule

type RatingRule struct {
	ID               string                 `json:"id"`
	Kind             RatingRuleKind         `json:"kind,omitempty"`
	Component        *metering.ComponentKey `json:"component,omitempty"`
	Currency         string                 `json:"currency"`
	UnitPrice        *metering.Decimal      `json:"unit_price,omitempty"`
	PricePer         *metering.Decimal      `json:"price_per,omitempty"`
	RateNumerator    *metering.Decimal      `json:"rate_numerator,omitempty"`
	RateDenominator  *metering.Decimal      `json:"rate_denominator,omitempty"`
	FixedAmount      *metering.Decimal      `json:"fixed_amount,omitempty"`
	FixedScope       FixedFeeScope          `json:"fixed_scope,omitempty"`
	BlockSize        *metering.Decimal      `json:"block_size,omitempty"`
	MinimumAmount    *metering.Decimal      `json:"minimum_amount,omitempty"`
	RoundingScope    RoundingScope          `json:"rounding_scope,omitempty"`
	RoundingPolicy   RoundingPolicy         `json:"rounding_policy,omitempty"`
	SelectionScope   RatingSelectionScope   `json:"selection_scope,omitempty"`
	TierMode         TierMode               `json:"tier_mode,omitempty"`
	Conditions       []QualifierCondition   `json:"conditions,omitempty"`
	Tiers            []RatingTier           `json:"tiers,omitempty"`
	ConversionSchema string                 `json:"conversion_schema,omitempty"`
	IncludedUnit     bool                   `json:"included_unit,omitempty"`
}

RatingRule is provider-neutral immutable tariff material. Component rules require Component; fixed rules require FixedAmount and FixedScope. A rule's Currency is explicit even when it matches the containing tariff so currency mismatch cannot silently become a zero charge.

func (RatingRule) Clone

func (r RatingRule) Clone() RatingRule

func (RatingRule) Validate

func (r RatingRule) Validate(tariffCurrency string) error

type RatingRuleKind

type RatingRuleKind string

RatingRuleKind describes the bounded operations supported by the reference post-usage evaluator. A rule may combine a linear price with block and minimum modifiers; fixed rules use FixedAmount and FixedScope instead.

const (
	RatingRuleLinear     RatingRuleKind = "linear"
	RatingRuleFixed      RatingRuleKind = "fixed"
	RatingRuleBlock      RatingRuleKind = "block"
	RatingRuleMinimum    RatingRuleKind = "minimum"
	RatingRuleAllUnits   RatingRuleKind = "all_units"
	RatingRuleGraduated  RatingRuleKind = "graduated"
	RatingRuleConversion RatingRuleKind = "conversion"
)

func (RatingRuleKind) IsKnown

func (k RatingRuleKind) IsKnown() bool

type RatingSelectionScope

type RatingSelectionScope string

RatingSelectionScope controls which quantity drives threshold/tier selection. It is intentionally separate from the quantity that is charged: whole-context rules can select a rate from aggregate context while pricing only a declared billable component.

const (
	SelectionBillableQuantity RatingSelectionScope = "billable_quantity"
	SelectionWholeContext     RatingSelectionScope = "whole_context"
	SelectionPeriod           RatingSelectionScope = "period"
)

func (RatingSelectionScope) IsKnown

func (s RatingSelectionScope) IsKnown() bool

type RatingSnapshotRef

type RatingSnapshotRef struct {
	VersionRef
	RaterID string `json:"rater_id,omitempty"`
}

RatingSnapshotRef binds a rating/pricebook snapshot used for an admission or settlement.

type RatingSnapshotSource

type RatingSnapshotSource interface {
	Snapshot(ctx context.Context) (Snapshot[RatingCatalogView], error)
}

RatingSnapshotSource provides immutable rating/pricebook snapshots.

type RatingTier

type RatingTier struct {
	UpTo            *metering.Decimal `json:"up_to,omitempty"`
	UnitPrice       *metering.Decimal `json:"unit_price,omitempty"`
	PricePer        *metering.Decimal `json:"price_per,omitempty"`
	RateNumerator   *metering.Decimal `json:"rate_numerator,omitempty"`
	RateDenominator *metering.Decimal `json:"rate_denominator,omitempty"`
}

RatingTier is one threshold/price pair. A nil UpTo is the final unbounded tier. UnitPrice is the amount for PricePer units; a nil PricePer means one unit. RateNumerator/RateDenominator provide an exact rational alternative when a terminating decimal is not available.

func (RatingTier) Validate

func (t RatingTier) Validate() error

type ReconciliationPage

type ReconciliationPage struct {
	Valuations []Valuation `json:"valuations,omitempty"`
	Next       string      `json:"next,omitempty"`
	Complete   bool        `json:"complete"`
}

ReconciliationPage is a typed result page; implementations may add details in later versions without exposing persistence handles.

func (ReconciliationPage) Clone

Clone deep-copies page valuations for a consumer that needs local sorting.

func (ReconciliationPage) Validate

func (p ReconciliationPage) Validate() error

type ReconciliationQuery

type ReconciliationQuery struct {
	StoreID          string               `json:"store_id"`
	Subject          *metering.SubjectRef `json:"subject,omitempty"`
	Basis            ValuationBasis       `json:"basis,omitempty"`
	Currency         string               `json:"currency,omitempty"`
	AfterValuationID string               `json:"after_valuation_id,omitempty"`
	Limit            uint32               `json:"limit"`
}

ReconciliationQuery identifies a bounded immutable read window.

func (ReconciliationQuery) Validate

func (q ReconciliationQuery) Validate() error

type ReconciliationReader

type ReconciliationReader interface {
	Query(ctx context.Context, in ReconciliationQuery) (ReconciliationPage, error)
}

ReconciliationReader reads immutable reconciliation results and never performs rating, posting or provider calls.

type RoundingPolicy

type RoundingPolicy string

RoundingPolicy identifies how fractional nano-units are resolved by exact money/token arithmetic. Monetary rating itself is owned by internal/core/billing.

const (
	RoundingUnspecified      RoundingPolicy = ""
	RoundingHalfAwayFromZero RoundingPolicy = "half_away_from_zero"
	RoundingHalfEven         RoundingPolicy = "half_even"
	RoundingTowardZero       RoundingPolicy = "toward_zero"
	RoundingFloor            RoundingPolicy = "floor"
)

func (RoundingPolicy) IsKnown

func (p RoundingPolicy) IsKnown() bool

IsKnown reports whether p is a documented rounding policy.

type RoundingScope

type RoundingScope string

RoundingScope records the boundary at which exact rating output entered the integer nano-money ledger. Sum-of-rounded-lines and round-of-total therefore remain distinguishable during replay.

func (RoundingScope) IsKnown

func (s RoundingScope) IsKnown() bool

type Rule

type Rule = RatingRule

ComponentRatingRule and Rule are descriptive aliases used by adapters that prefer the domain vocabulary. They preserve one canonical representation.

type RuleSnapshotSource

type RuleSnapshotSource interface {
	Snapshot(ctx context.Context) (Snapshot[PolicyRulesView], error)
}

RuleSnapshotSource provides immutable authority or concurrency rule snapshots (design: Dynamic Sources; requirements 11.1, 11.5, 11.6).

type Snapshot

type Snapshot[T any] struct {
	ID          string        `json:"id"`
	Version     string        `json:"version"`
	EffectiveAt time.Time     `json:"effective_at,omitzero"`
	FetchedAt   time.Time     `json:"fetched_at,omitzero"`
	State       SnapshotState `json:"state"`
	Value       T             `json:"value"`
}

Snapshot is an immutable versioned envelope for policy or rating material (design: Versioned Snapshots / Dynamic Sources).

func (Snapshot[T]) PolicyRef

func (s Snapshot[T]) PolicyRef(policyID string) PolicySnapshotRef

Ref returns a PolicySnapshotRef for authority/concurrency binding.

func (Snapshot[T]) RatingRef

func (s Snapshot[T]) RatingRef(raterID string) RatingSnapshotRef

RatingRef returns a RatingSnapshotRef for rating binding.

type SnapshotContentRef

type SnapshotContentRef struct {
	ContentRef  string `json:"content_ref"`
	ContentHash string `json:"content_hash"`
}

SnapshotContentRef identifies immutable material that a resolver can load and verify. A snapshot ID/version without this pair is only a label and is not sufficient for replayable V2 valuation.

func (*SnapshotContentRef) UnmarshalJSON

func (r *SnapshotContentRef) UnmarshalJSON(data []byte) error

func (SnapshotContentRef) Validate

func (r SnapshotContentRef) Validate() error

Validate checks the bounded resolver key and canonical lowercase SHA-256 content digest. It deliberately does not fetch or trust the referenced material; that belongs to the catalog at the validation boundary that has access to it.

type SnapshotState

type SnapshotState string

SnapshotState classifies versioned snapshot readiness (requirement 11.7).

const (
	SnapshotReady       SnapshotState = "ready"
	SnapshotStale       SnapshotState = "stale"
	SnapshotDegraded    SnapshotState = "degraded"
	SnapshotUnavailable SnapshotState = "unavailable"
	SnapshotDisabled    SnapshotState = "disabled"
)

func (SnapshotState) IsKnown

func (s SnapshotState) IsKnown() bool

IsKnown reports whether s is a documented snapshot state.

type StatementBatch

type StatementBatch struct {
	Version            uint32                 `json:"version"`
	ProviderAccountKey string                 `json:"provider_account_key"`
	StatementID        string                 `json:"statement_id"`
	Revision           uint64                 `json:"revision"`
	PeriodID           string                 `json:"period_id"`
	Subject            metering.SubjectRef    `json:"subject"`
	Observations       []metering.Observation `json:"observations,omitempty"`
	Lines              []StatementLine        `json:"lines"`
}

StatementBatch is a normalized statement import envelope. Raw statement bytes and provider-shaped fields deliberately have no public representation.

func (StatementBatch) Canonical

func (b StatementBatch) Canonical() (StatementBatch, error)

Canonical returns a normalized deep copy with observations and lines in deterministic order. The receiver is not mutated; semantically unordered sets are the only members reordered.

func (StatementBatch) Identity

func (b StatementBatch) Identity() (StatementIdentity, error)

Identity returns the canonical statement revision identity of this batch.

func (StatementBatch) ReplayFingerprints

func (b StatementBatch) ReplayFingerprints() (StatementFingerprints, error)

ReplayFingerprints returns the canonical statement and per-line replay fingerprints for this batch. An exact replay of the same claim content produces the same fingerprints; any economically significant change produces a different one.

func (*StatementBatch) UnmarshalJSON

func (b *StatementBatch) UnmarshalJSON(data []byte) error

func (StatementBatch) Validate

func (b StatementBatch) Validate() error

type StatementFingerprints

type StatementFingerprints struct {
	Identity  StatementIdentity
	Statement string
	Lines     map[string]string
}

StatementFingerprints is the deterministic replay identity of one statement revision. Statement and line fingerprints cover only economic claim content: transport receipt timestamps and the input order of observations and lines do not change them. Lines maps each StatementLineIdentity.Key to its line fingerprint.

type StatementIdentity

type StatementIdentity struct {
	StoreID            string `json:"store_id"`
	ProviderAccountKey string `json:"provider_account_key"`
	StatementID        string `json:"statement_id"`
	PeriodID           string `json:"period_id"`
	Revision           uint64 `json:"revision"`
}

StatementIdentity is the immutable identity of one normalized statement revision: trusted store, provider account, statement identifier, billing period and revision. It intentionally contains no raw statement payload and no request/B-leg lineage.

func (StatementIdentity) Equal

func (i StatementIdentity) Equal(other StatementIdentity) bool

Equal reports whether two identities describe the same statement revision.

func (StatementIdentity) Key

func (i StatementIdentity) Key() string

Key returns a bounded opaque identity suitable for durable statement keys. Every identity member participates in the SHA-256 preimage.

func (StatementIdentity) Validate

func (i StatementIdentity) Validate() error

Validate checks the complete bounded identity without mutating the value.

type StatementImporter

type StatementImporter interface {
	Import(ctx context.Context, in StatementBatch) (ImportResult, error)
}

StatementImporter accepts normalized statement evidence. Provider parsing, authentication and raw-payload handling belong to the supplying adapter.

type StatementLine

type StatementLine struct {
	ID              string                  `json:"id"`
	Revision        uint64                  `json:"revision"`
	Subject         metering.SubjectRef     `json:"subject"`
	Observation     metering.ObservationRef `json:"observation"`
	ChargeItemID    string                  `json:"charge_item_id"`
	Outcome         StatementLineOutcome    `json:"outcome,omitempty"`
	UnmatchedReason string                  `json:"unmatched_reason,omitempty"`
}

StatementLine is one already-normalized provider statement line. Its charge identity is retained as a safe ID and references are store-scoped.

func (StatementLine) Identity

Identity returns this line's canonical identity inside the supplied statement. The line subject must belong to that statement; the statement envelope revision is intentionally not part of the line identity.

func (*StatementLine) UnmarshalJSON

func (l *StatementLine) UnmarshalJSON(data []byte) error

func (StatementLine) Validate

func (l StatementLine) Validate(store string) error

type StatementLineIdentity

type StatementLineIdentity struct {
	StoreID            string `json:"store_id"`
	ProviderAccountKey string `json:"provider_account_key"`
	StatementID        string `json:"statement_id"`
	PeriodID           string `json:"period_id"`
	LineID             string `json:"line_id"`
	Revision           uint64 `json:"revision"`
}

StatementLineIdentity is the immutable identity of one statement-line revision. It is deliberately scoped to the statement fields without the statement envelope revision: a line claim is versioned by its own revision, so a later statement revision that restates the same line revision with changed content is a conflict rather than a new identity.

func (StatementLineIdentity) Equal

Equal reports whether two identities describe the same line revision.

func (StatementLineIdentity) Key

func (i StatementLineIdentity) Key() string

Key returns a bounded opaque identity suitable for durable line keys.

func (StatementLineIdentity) Validate

func (i StatementLineIdentity) Validate() error

Validate checks the complete bounded line identity without mutating the value.

type StatementLineOutcome

type StatementLineOutcome string

StatementLineOutcome records whether a normalized line was linked to an included observation charge. Unmatched is an explicit, reviewable outcome; it does not imply a missing B-leg attribution.

const (
	StatementLineMatched   StatementLineOutcome = "matched"
	StatementLineUnmatched StatementLineOutcome = "unmatched"
)

func (StatementLineOutcome) IsKnown

func (o StatementLineOutcome) IsKnown() bool

type StatementLinePage

type StatementLinePage struct {
	Lines      []StatementLineView `json:"lines,omitempty"`
	NextCursor string              `json:"next_cursor,omitempty"`
}

StatementLinePage is one deterministic page of retained statement lines in line-key order.

func (StatementLinePage) Validate

func (p StatementLinePage) Validate() error

Validate checks page bounds without mutating the page.

type StatementLineQuery

type StatementLineQuery struct {
	Scope              OperatorScope        `json:"scope"`
	ProviderAccountKey string               `json:"provider_account_key,omitempty"`
	StatementID        string               `json:"statement_id,omitempty"`
	PeriodID           string               `json:"period_id,omitempty"`
	LineID             string               `json:"line_id,omitempty"`
	Outcome            StatementLineOutcome `json:"outcome,omitempty"`
	Limit              int                  `json:"limit,omitempty"`
	Cursor             string               `json:"cursor,omitempty"`
}

StatementLineQuery identifies a bounded retained statement-line window. At least one narrow filter (provider account, statement, period or line) is required so the read stays index-backed instead of scanning a tenant.

func (StatementLineQuery) Normalize

func (q StatementLineQuery) Normalize() (StatementLineQuery, error)

Normalize trims scope, applies the default limit and rejects unbounded or ambiguously authorized queries. Customer account scope must not authorize provider statement history.

type StatementLineReader

type StatementLineReader interface {
	QueryStatementLines(ctx context.Context, query StatementLineQuery) (StatementLinePage, error)
}

StatementLineReader reads immutable retained statement lines and never performs matching, rating, posting or provider calls. Import stays on StatementImporter; this reader cannot authorize imports.

type StatementLineView

type StatementLineView struct {
	StatementID        string                  `json:"statement_id"`
	LineID             string                  `json:"line_id"`
	Revision           uint64                  `json:"revision"`
	PeriodID           string                  `json:"period_id"`
	ProviderAccountKey string                  `json:"provider_account_key"`
	Outcome            StatementLineOutcome    `json:"outcome,omitempty"`
	UnmatchedReason    string                  `json:"unmatched_reason,omitempty"`
	ChargeItemID       string                  `json:"charge_item_id,omitempty"`
	Observation        metering.ObservationRef `json:"observation,omitzero"`
}

StatementLineView is one retained normalized statement line. The statement/period/provider scope is the aggregate identity: unmatched lines keep it and never gain a request linkage. Matched lines carry their explicit charge linkage; nothing is guessed.

func (StatementLineView) Validate

func (v StatementLineView) Validate() error

Validate checks the view without mutating it.

type SupportAdvisoryContext

type SupportAdvisoryContext struct {
	Version       string             `json:"version"`
	Tariff        RatingSnapshotRef  `json:"tariff"`
	TariffContent SnapshotContentRef `json:"tariff_content"`
}

SupportAdvisoryContext identifies the immutable source of an assessment.

func (SupportAdvisoryContext) Key

Key identifies reporting semantics independently of retrieval timestamps.

func (SupportAdvisoryContext) Validate

func (c SupportAdvisoryContext) Validate() error

Validate checks frozen advisory identity without resolving its content.

type SupportAdvisoryIncomplete

type SupportAdvisoryIncomplete struct {
	ContextKey string                `json:"context_key"`
	Reason     SupportAdvisoryReason `json:"reason"`
}

SupportAdvisoryIncomplete records a context-wide reporting limitation.

type SupportAdvisoryPair

type SupportAdvisoryPair struct {
	ContextKey string                `json:"context_key"`
	ScopeKey   string                `json:"scope_key"`
	Left       metering.ComponentKey `json:"left"`
	Right      metering.ComponentKey `json:"right"`
}

SupportAdvisoryPair names unordered uncertain supports within one scope.

type SupportAdvisoryReason

type SupportAdvisoryReason string

SupportAdvisoryReason explains why an assessment could not finish.

const (
	SupportAdvisoryCandidateBudget     SupportAdvisoryReason = "candidate_budget"
	SupportAdvisoryGraphBudget         SupportAdvisoryReason = "graph_budget"
	SupportAdvisoryPairLimit           SupportAdvisoryReason = "pair_limit"
	SupportAdvisoryEvidenceUnavailable SupportAdvisoryReason = "evidence_unavailable"
)

type SupportAdvisoryReport

type SupportAdvisoryReport struct {
	Pairs              []SupportAdvisoryPair       `json:"pairs,omitempty"`
	IncompleteContexts []SupportAdvisoryIncomplete `json:"incomplete_contexts,omitempty"`
}

SupportAdvisoryReport carries visibility only, never amounts or quantities.

func (*SupportAdvisoryReport) Clone

Clone copies all component dimensions and report slices independently.

type TariffSnapshot

type TariffSnapshot struct {
	Ref                    RatingSnapshotRef    `json:"ref"`
	Currency               string               `json:"currency"`
	CatalogVersion         string               `json:"catalog_version,omitempty"`
	Rules                  []RatingRule         `json:"rules"`
	EffectiveQualifiers    []metering.Dimension `json:"effective_qualifiers,omitempty"`
	LegacySemantics        string               `json:"legacy_semantics,omitempty"`
	SupportAdvisoryVersion string               `json:"support_advisory_version,omitempty"`
	// Schemas carries optional frozen component-relationship material that a
	// later post-usage evaluator may consult without re-querying a provider or
	// re-deriving inclusion semantics. It is additive: nil/empty schemas
	// reproduce the exact pre-schema canonical bytes, content hash and resolver
	// identity, so historical snapshots are never rewritten.
	Schemas []metering.ComponentSchema `json:"schemas,omitempty"`
	Content SnapshotContentRef         `json:"content"`
}

TariffSnapshot is immutable rule material bound to one rating identity. The content hash is over canonical tariff fields, excluding ContentRef itself. ContentRef is a durable resolver key and can be supplied by a catalog.

func BuildTariffSnapshot

func BuildTariffSnapshot(ref RatingSnapshotRef, currency string, rules []RatingRule) (TariffSnapshot, error)

BuildTariffSnapshot validates and content-addresses one tariff snapshot.

func BuildTariffSnapshotWithSchemas

func BuildTariffSnapshotWithSchemas(ref RatingSnapshotRef, currency string, rules []RatingRule, schemas []metering.ComponentSchema) (TariffSnapshot, error)

BuildTariffSnapshotWithSchemas validates and content-addresses one tariff snapshot carrying optional frozen component-relationship material. Passing nil or empty schemas is exactly equivalent to BuildTariffSnapshot: the canonical bytes and content hash are unchanged for existing snapshots.

func NewTariffSnapshot

func NewTariffSnapshot(ref RatingSnapshotRef, currency string, rules []RatingRule) TariffSnapshot

NewTariffSnapshot creates canonical tariff material. It is convenient for tests and adapters that already validated their source; callers needing a publication error should use BuildTariffSnapshot.

func (TariffSnapshot) Canonical

func (s TariffSnapshot) Canonical() (TariffSnapshot, error)

Canonical returns a validated deep copy with deterministic rule/qualifier ordering and a content-addressed resolver reference.

func (TariffSnapshot) Clone

func (s TariffSnapshot) Clone() TariffSnapshot

func (TariffSnapshot) ContentHash

func (s TariffSnapshot) ContentHash() string

func (TariffSnapshot) Validate

func (s TariffSnapshot) Validate() error

type TierMode

type TierMode string

TierMode controls whether the selected tier price is applied to all units or each graduated slice independently.

const (
	TierAllUnits  TierMode = "all_units"
	TierGraduated TierMode = "graduated"
)

func (TierMode) IsKnown

func (m TierMode) IsKnown() bool

type UnitBound

type UnitBound struct {
	Unit    string            `json:"unit"`
	Amount  *metering.Decimal `json:"amount,omitempty"`
	Present bool              `json:"present"`
}

UnitBound keeps non-monetary credits or allowances separate from Money. A present zero is distinct from an unavailable bound.

func (UnitBound) Clone

func (b UnitBound) Clone() UnitBound

func (*UnitBound) UnmarshalJSON

func (b *UnitBound) UnmarshalJSON(data []byte) error

func (UnitBound) Validate

func (b UnitBound) Validate() error

type Valuation

type Valuation struct {
	ID                   string                       `json:"id"`
	Version              uint32                       `json:"version"`
	Perspective          metering.EconomicPerspective `json:"perspective"`
	Basis                ValuationBasis               `json:"basis"`
	Subject              metering.SubjectRef          `json:"subject"`
	Scope                string                       `json:"scope,omitempty"`
	InputObservations    []metering.ObservationRef    `json:"input_observations"`
	InputSetHash         string                       `json:"input_set_hash,omitempty"`
	Rater                RatingSnapshotRef            `json:"rater"`
	RaterContent         *SnapshotContentRef          `json:"rater_content,omitempty"`
	Tariff               RatingSnapshotRef            `json:"tariff"`
	TariffContent        *SnapshotContentRef          `json:"tariff_content,omitempty"`
	Policy               PolicySnapshotRef            `json:"policy"`
	PolicyContent        *SnapshotContentRef          `json:"policy_content,omitempty"`
	QualifierSnapshot    string                       `json:"qualifier_snapshot,omitempty"`
	QualifierSnapshotRef *SnapshotContentRef          `json:"qualifier_snapshot_ref,omitempty"`
	// EffectiveQualifiers are the canonical values actually used for rule
	// selection. They are immutable valuation identity, not merely retrieval
	// metadata, because changing one can select a different rate.
	EffectiveQualifiers []metering.Dimension         `json:"effective_qualifiers,omitempty"`
	Payer               metering.PaymentParty        `json:"payer,omitzero"`
	Lines               []LineItem                   `json:"lines"`
	Totals              []CurrencyTotal              `json:"totals"`
	Completeness        Completeness                 `json:"completeness"`
	MissingObservations []metering.ObservationRef    `json:"missing_observations,omitempty"`
	CoverageRefs        []metering.ChargeCoverageRef `json:"coverage_refs,omitempty"`
	// AllocationCoverageRefs names the exact immutable non-request allocation
	// revisions this valuation's monetary amount proves included. It is the
	// allocation counterpart of CoverageRefs: a conserved resource/statement
	// allocation is only proven contained in this valuation when it is named
	// here by exact allocation identity (store, allocation, version and payload
	// hash). It carries identity only, never money, and never turns an
	// allocation into provider-charge evidence or a request debit.
	AllocationCoverageRefs  []AllocationRef          `json:"allocation_coverage_refs,omitempty"`
	SupportAdvisoryContexts []SupportAdvisoryContext `json:"support_advisory_contexts,omitempty"`
	SupportAdvisory         *SupportAdvisoryReport   `json:"support_advisory,omitempty"`
	CreatedAt               time.Time                `json:"created_at"`
}

Valuation is an immutable, derived E/Q/P/S/R record. It contains safe economic metadata and references, never raw prompts, responses or provider payloads.

func (Valuation) Canonical

func (v Valuation) Canonical() (Valuation, error)

Canonical returns a validated deep copy with unordered refs, lines and totals sorted by their stable identities.

func (Valuation) CanonicalContextJSON

func (v Valuation) CanonicalContextJSON() ([]byte, error)

CanonicalContextJSON returns the deterministic economic-context preimage for a valuation. It includes trusted subject/scope/perspective/payer identity, all snapshot VersionRef IDs and versions, provider/policy IDs, and every content resolver reference/hash, plus optional support-advisory source contexts. The report itself is excluded because it is result content rather than interpretation identity. Absent content uses an explicit empty object so legacy and current callers share one unambiguous representation. Publication timestamps are excluded because they describe retrieval metadata rather than the economic interpretation.

func (Valuation) CanonicalJSON

func (v Valuation) CanonicalJSON() ([]byte, error)

CanonicalJSON is the deterministic wire form used for durable identity.

func (Valuation) CanonicalKey

func (v Valuation) CanonicalKey() string

func (Valuation) Clone

func (v Valuation) Clone() Valuation

Clone makes all nested valuation data independent of the source.

func (Valuation) ContextHash

func (v Valuation) ContextHash() string

ContextHash returns the lowercase SHA-256 digest of CanonicalContextJSON. An invalid or out-of-bounds context leaves the digest unavailable rather than letting callers treat it as a valid hash.

func (Valuation) Fingerprint

func (v Valuation) Fingerprint() string

func (Valuation) MarshalJSON

func (v Valuation) MarshalJSON() ([]byte, error)

func (*Valuation) UnmarshalJSON

func (v *Valuation) UnmarshalJSON(data []byte) error

func (Valuation) Validate

func (v Valuation) Validate() error

type ValuationBasis

type ValuationBasis string

ValuationBasis identifies the economic plane represented by a valuation. The values intentionally distinguish locally derived Q from provider P and statement S; equal amounts do not make those claims interchangeable.

func (ValuationBasis) IsKnown

func (b ValuationBasis) IsKnown() bool

func (ValuationBasis) Validate

func (b ValuationBasis) Validate() error

type VersionRef

type VersionRef struct {
	ID          string    `json:"id"`
	Version     string    `json:"version"`
	EffectiveAt time.Time `json:"effective_at,omitzero"`
	FetchedAt   time.Time `json:"fetched_at,omitzero"`
}

VersionRef is an immutable snapshot identity with optional timestamps (requirements 6.2, 7.6, 11.x deferred binding).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL