billing

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: 28 Imported by: 0

Documentation

Index

Constants

View Source
const (
	AccountingCutoverGenerationV1 = 1
	AccountingCutoverGenerationV2 = 2
)
View Source
const (
	AccountingPostingOwnerV1 = HistoricalV1WriterVersion
	AccountingPostingOwnerV2 = V2WriterVersion
)

Posting owners reuse the durable writer lineage so later claim fencing can compare against the same ownership vocabulary used by historical readers.

View Source
const (
	AccountingCompatFloorV1 = HistoricalV1WriterVersion
	AccountingCompatFloorV2 = V2WriterVersion
)

Compatibility floors record the minimum reader/binary generation that may operate against the store. v1_active/v2_shadow/v1_draining remain readable by V1-aware binaries; v2_active requires V2-aware readers. Rollback policy (17.4) consumes this field but is not implemented here.

View Source
const (
	// ALegSettlementKind is the canonical customer settlement operation kind.
	ALegSettlementKind = "customer_call_settlement"
	// ALegRepairKind is the canonical no-charge repair operation kind.
	ALegRepairKind = "customer_no_charge_repair"
)
View Source
const (
	ALegIssueMarkerMissing        = "customer_marker_missing"
	ALegIssueMarkersConflicting   = "customer_markers_conflicting"
	ALegIssueMarkerKey            = "customer_marker_key"
	ALegIssueMarkerIntegrity      = "customer_marker_integrity"
	ALegIssueMarkerCurrency       = "customer_marker_currency"
	ALegIssueMarkerFingerprint    = "customer_marker_fingerprint"
	ALegIssueJournalMissing       = "customer_journal_missing"
	ALegIssueJournalMismatch      = "customer_journal_mismatch"
	ALegIssueJournalInvalid       = "customer_journal_invalid"
	ALegIssueStrayJournal         = "customer_stray_journal"
	ALegIssueCorrectionUnresolved = "customer_correction_unresolved"
	ALegIssueAdjustmentPending    = "customer_adjustment_pending"
	ALegIssueMarkerInvalid        = "customer_marker_invalid"
	ALegIssueBookConflict         = "customer_book_conflict"
)

Cycle 1 customer-authority issue codes owned by the core evaluator. Retention/fanout bounds (leg/journal/entry fanout, truncation) stay with the report shell; they are not financial proof.

View Source
const (
	ALegProviderIssuePending    = "provider_cost_pending"
	ALegProviderIssueUnresolved = "provider_cost_unresolved"
)

Cycle 2B provider-authority issue codes owned by the core evaluator.

View Source
const (
	ALegProviderZeroNeverStarted = "never_started_not_billable"
	ALegProviderZeroRejected     = "rejected_not_payable"
	ALegProviderZeroRecorded     = "provider_recorded_zero"
	ALegProviderZeroExcluded     = "provider_excluded_non_payable"
	// ALegProviderZeroAllChildrenZero is the deterministic aggregate
	// basis when every evaluated payable child is proven zero: no
	// single child basis is preferred over another.
	ALegProviderZeroAllChildrenZero = "all_children_zero"
)

Explicit known-zero bases. The basis names the exact lineage that proves nothing is payable; consumers must not treat a zero basis as a missing measurement.

View Source
const (
	// ALegReportDefaultLimit bounds one snapshot page when the caller omits a limit.
	ALegReportDefaultLimit = 100
	// ALegReportMaxLimit is the hard bounded page maximum.
	ALegReportMaxLimit = 500
)
View Source
const (
	CutoverCoordinatorMinBatchSize             = 1
	CutoverCoordinatorMaxBatchSize             = 1000
	CutoverCoordinatorDefaultBatchSize         = 100
	CutoverCoordinatorDefaultMaxBatches        = 100
	CutoverCoordinatorMaxUnclassifiableSamples = 32
)
View Source
const (
	// EconomicDetailDefaultLimit bounds one detail page when the caller omits a limit.
	EconomicDetailDefaultLimit = 100
	// EconomicDetailMaxLimit is the hard bounded page maximum.
	EconomicDetailMaxLimit = 500
	// MaxEconomicDetailObservations bounds one assembly input set.
	MaxEconomicDetailObservations = 1024
	// MaxEconomicDetailValuations bounds retained valuation contributions per
	// scope. A scope may legitimately gather one latest revision per logical
	// subject/perspective/basis stream across many calls and B-legs, so this
	// matches the observation bound instead of a single-plane count; exceeding
	// it still fails closed.
	MaxEconomicDetailValuations = 1024
	// MaxEconomicDetailMissingRefs bounds retained missing evidence refs.
	MaxEconomicDetailMissingRefs = 1024
	// MaxEconomicDetailCoverageRefs bounds retained coverage edges.
	MaxEconomicDetailCoverageRefs = 1024
	// MaxEconomicDetailHeads bounds retained selected-cost heads.
	MaxEconomicDetailHeads = 128
	// MaxEconomicDetailAllocations bounds retained allocation lines.
	MaxEconomicDetailAllocations = 256
	// MaxEconomicDetailReconciliations bounds the independent reconciliation
	// comparisons one detail page may carry: one per authoritative in-scope
	// subject (primary call/A-leg plus its calls and B-legs). Exceeding it fails
	// closed rather than silently dropping later child subjects, so a
	// reconciliation present only on a later subject is never lost without an
	// explicit error.
	MaxEconomicDetailReconciliations = 128
	// MaxEconomicDetailExecutionLegs bounds the authoritative executed B-leg
	// execution facts one detail page may carry into assembly. It reuses the
	// same finite leg-record budget the durable reader already enforces, so a
	// scope above it fails closed before any Go growth instead of materializing
	// the excess.
	MaxEconomicDetailExecutionLegs = MaxEconomicDetailReconciliations
	// MaxEconomicDetailJournalTransactions bounds the financial journal rows
	// one call summary may materialize. A call's correction history is an
	// operator-query result set, so it shares the public economic-detail page
	// ceiling instead of being unbounded; exceeding it fails closed before any
	// secondary journal-entry load.
	MaxEconomicDetailJournalTransactions = EconomicDetailMaxLimit
	// MaxEconomicDetailOperationSnapshots bounds the settlement operation
	// snapshots one call summary may materialize. It mirrors the journal bound
	// so both independent correction histories are finite before Go growth.
	MaxEconomicDetailOperationSnapshots = EconomicDetailMaxLimit
	// EconomicDetailObservationOrder names the limit-independent canonical
	// observation ordering of an economic-detail page. It is part of the
	// continuation contract: a durable cursor binds this exact definition, so
	// changing the ordering invalidates previously issued cursors instead of
	// silently skipping or repeating observations.
	EconomicDetailObservationOrder = "economic-detail-observation-v1"
	// EconomicDetailSnapshotVersion names the exact deterministic
	// full-scope-snapshot fingerprint definition. It is prefixed onto every
	// fingerprint, so a future fingerprint-shape change invalidates outstanding
	// continuations by mismatch instead of silently accepting a token issued
	// against a different snapshot definition. v2 folds each reconciliation's
	// aggregate plane into the repeated full-scope fact set.
	EconomicDetailSnapshotVersion = "economic-detail-snapshot-v2"
)
View Source
const (
	// MaxEconomicDetailStatementLines bounds one statement-evidence line set.
	MaxEconomicDetailStatementLines = 256
	// MaxEconomicDetailStatementRefs bounds the referenced observation set that
	// may be resolved for one detail page.
	MaxEconomicDetailStatementRefs = 1024
	// MaxEconomicDetailStatementLineRevisions bounds the persisted
	// statement-line revisions resolved for one referenced observation before Go
	// growth.
	MaxEconomicDetailStatementLineRevisions = 64
	// EconomicDetailStatementReaderUnavailableReason is the stable reason
	// recorded when no statement observation source was composed.
	EconomicDetailStatementReaderUnavailableReason = "statement_observation_reader_unavailable"
)
View Source
const (
	EconomicEvidenceCoverageComplete    = "complete"
	EconomicEvidenceCoveragePartial     = "partial"
	EconomicEvidenceCoverageUnsupported = "unsupported"
)
View Source
const (
	EconomicHealthQueueOther          = "other"
	EconomicHealthQueueProviderLegacy = "provider_legacy"
	EconomicHealthReasonOther         = "other"
	EconomicHealthReasonUnclassified  = "unclassified"
	EconomicHealthStatementOther      = "other"
	EconomicHealthStatusOther         = "other"
	EconomicHealthMaxWindowRows       = 256
	EconomicHealthMaxReasonBuckets    = 16
)

Economic health queue vocabulary. Worker queues, legacy provider costing and the three documented economic work kinds are the only values that survive summarization; anything else becomes "other".

View Source
const (
	// MaxEconomicWorkReasonLength bounds any durable free-form failure text.
	MaxEconomicWorkReasonLength = 256
	// MaxEconomicJobDependencies bounds the dependency set of one job.
	MaxEconomicJobDependencies = 8
	// MaxEconomicRevisionClaimBatchSize bounds one claim batch.
	MaxEconomicRevisionClaimBatchSize = 256
	// DefaultEconomicRevisionClaimBatchSize is used when no batch bound is
	// supplied.
	DefaultEconomicRevisionClaimBatchSize = 32
)
View Source
const (
	// OperatorCostSelectionPolicyV1 is the first supported policy format.
	OperatorCostSelectionPolicyV1 uint32 = 1
	// MaxOperatorCostSelectionRules bounds the ordered policy.
	MaxOperatorCostSelectionRules = 16
	// MaxOperatorCostCandidates bounds the candidate set (one per basis).
	MaxOperatorCostCandidates = 4
	// MaxOperatorCostSelectionRefs bounds retained source refs per candidate.
	MaxOperatorCostSelectionRefs = 1024
)
View Source
const (
	PostingOwnerV1 = HistoricalV1WriterVersion
	PostingOwnerV2 = V2WriterVersion
)

Posting owners reuse the durable writer lineage so later claim fencing compares against the same ownership vocabulary used by historical readers.

View Source
const (
	// MaxReconciliationAggregateFindings bounds one aggregate projection.
	MaxReconciliationAggregateFindings = 4096
	// MaxReconciliationAggregateRows bounds distinct scope/currency/unit rows.
	MaxReconciliationAggregateRows = 256
)
View Source
const (
	// MaxReconciliationObservations bounds one side's frozen observation set.
	MaxReconciliationObservations = 1024
	// MaxReconciliationMeasures bounds one side's total component measures.
	MaxReconciliationMeasures = 8192
	// MaxReconciliationItems bounds the comparison result cardinality.
	MaxReconciliationItems = 4096
)
View Source
const (
	// MaxMonetaryDiscrepancyValuations bounds the input to the three E/Q/P
	// roles; a larger slice always contains a duplicate or unsupported role.
	MaxMonetaryDiscrepancyValuations = 3
	// MaxMonetaryDiscrepancyRows bounds the output currency rows by the union
	// of three bounded valuation total sets.
	MaxMonetaryDiscrepancyRows = 3 * economics.MaxValuationTotals
)
View Source
const (
	// ReconciliationRetentionSchemaVersionV1 is the first durable result
	// schema version.
	ReconciliationRetentionSchemaVersionV1 uint32 = 1
	// MaxReconciliationRetentionBytes bounds the canonical durable payload.
	MaxReconciliationRetentionBytes = 1 << 20
	// MaxReconciliationRetentionObservationRefs bounds retained source refs.
	MaxReconciliationRetentionObservationRefs = 4096
	// MaxReconciliationRetentionValuations bounds retained valuation ids.
	MaxReconciliationRetentionValuations = 128
	// MaxReconciliationRetentionDiagnostics bounds retained diagnostics.
	MaxReconciliationRetentionDiagnostics = 64
	// MaxReconciliationRetentionDiagnosticBytes bounds one diagnostic detail.
	MaxReconciliationRetentionDiagnosticBytes = 512
)
View Source
const (
	// ReconciliationTolerancePolicyV1 is the first supported policy format.
	ReconciliationTolerancePolicyV1 uint32 = 1
	// MaxReconciliationToleranceRules bounds one policy's disjoint rule set.
	MaxReconciliationToleranceRules = 64
)
View Source
const (
	// ReconciliationStatusWithinTolerance is distinct from an exact match.
	ReconciliationStatusWithinTolerance ReconciliationComparisonStatus = "within_tolerance"

	ReconciliationReasonZeroDenominator        ReconciliationComparisonReason = "zero_denominator"
	ReconciliationReasonUnitMismatch           ReconciliationComparisonReason = "unit_mismatch"
	ReconciliationReasonTolerancePolicyMissing ReconciliationComparisonReason = "tolerance_policy_missing"
	ReconciliationReasonEstimatedNotExact      ReconciliationComparisonReason = "estimated_not_exact"
)

Additive reconciliation vocabulary shared with Tasks 12.1/12.2. Declaring these here keeps the earlier comparator files untouched.

View Source
const (
	// MaxCallLegEvidenceObservations bounds terminal evidence retained for one
	// B-leg. A provider may emit many frames, but terminal accounting must stay
	// bounded and retain a deterministic incomplete/conflict signal when the
	// bound is reached.
	MaxCallLegEvidenceObservations = 1024
	MaxCallLegEvidenceRefs         = 1024
	MaxCallLegEvidenceConflicts    = 128
)
View Source
const (
	// RetailChargeKindInferenceUsage identifies lines priced from the frozen
	// policy-selected B-leg quantity set.
	RetailChargeKindInferenceUsage = "inference_usage"
	// RetailChargeKindCommercialFee identifies fixed customer charges whose
	// trusted scope is call or submission rather than a B-leg quantity.
	RetailChargeKindCommercialFee = "commercial_fee"
	// RetailChargeKindProxyService identifies an explicit customer-boundary
	// service meter. It is never a substitute for inference usage.
	RetailChargeKindProxyService = "proxy_service"
)
View Source
const (
	// MaxStatementMatchStatements bounds one matching batch.
	MaxStatementMatchStatements = 128
	// MaxStatementMatchEvidence bounds the eligible retained evidence set.
	MaxStatementMatchEvidence = 4096
	// MaxStatementMatchCoverageRefs bounds coverage references on one claim.
	MaxStatementMatchCoverageRefs = 4096
)
View Source
const (
	// HistoricalV1WriterVersion owns old in-flight V1 calls. EvidenceVersion
	// zero with no V2 observations/refs/conflicts/dispositions and no
	// auxiliary economic provenance selects it.
	HistoricalV1WriterVersion = "v1"
	// V2WriterVersion owns new source-separated evidence (EvidenceVersion 2
	// with the V1 compatibility projection label).
	V2WriterVersion = "v2"
)

Historical migration compatibility for Task 17.1 (Migration Strategy steps 1-3). This is a read-only compatibility preflight: baseline V1 records keep their exact byte/hash/identity semantics, legacy pricing semantics stay versioned, and old in-flight V1 work is reported under explicit V1 writer ownership. No V2-native E/Q/P/S/R breakdown or local/provider source separation is synthesized for V1; unavailable detail stays explicitly legacy/opaque. Durable cutover/posting enforcement belongs to Phase 17.3.

View Source
const (
	WorkloadRoleCompactionContinuityExtractor   = "compaction_continuity_extractor"
	WorkloadRoleReasoningPreservationCompressor = "reasoning_preservation_compressor"
)
View Source
const ALegIssueAdjustmentUnresolved = "customer_adjustment_unresolved"

ALegIssueAdjustmentUnresolved marks conflicting pass-through evidence: the call keeps pending/unknown status and validated lineage is withheld.

View Source
const CostPassThroughAdjustmentOperationKind = "customer_cost_pass_through_adjustment"
View Source
const CurrentRecordSchemaVersion = 1
View Source
const (
	// CustomerUnitOperationVersionV1 is the first persisted operation contract.
	CustomerUnitOperationVersionV1 uint32 = 1
)
View Source
const EconomicEvidenceDispositionVersionV1 = 1

EconomicEvidenceDispositionVersionV1 is the additive durable carrier version for transport coverage metadata. It is intentionally separate from the provider observation payload and therefore cannot be interpreted as a billable measure.

View Source
const EvidenceFormatVersionV2 = 2

EvidenceFormatVersionV2 identifies the additive observation envelope carried by a call-leg record. The durable record schema remains at v1: old rows keep their exact payload shape and continue to use FinalBillingEvidence as a compatibility projection.

View Source
const EvidenceProjectionV1 = "v1_compatibility_projection"

EvidenceProjectionV1 labels the legacy scalar fields retained on a record while the source-separated V2 observations remain the economic evidence.

View Source
const JournalFingerprintPrefix = "journal-fp:v2:"
View Source
const LegacyScalarRaterID = "legacy_scalar_v1"

LegacyScalarRaterID identifies the compatibility adapter for the historic per-million-token PricingSnapshot. It is deliberately named in the material so replay cannot confuse a scalar card with a generic tariff.

View Source
const LegacyScalarSemantics = economics.LegacyScalarSemanticsV1

LegacyScalarSemantics is the published meaning of the old integer fields: each token dimension is multiplied by its per-million nano rate and rounded toward zero at the line boundary, matching the pre-V2 rating path.

Variables

View Source
var (
	ErrAccountInvalid        = errors.New("billing: invalid account")
	ErrAccountNotReady       = errors.New("billing: account is not ready")
	ErrInsufficientSpendable = errors.New("billing: insufficient spendable balance")
)
View Source
var (
	ErrAccountingCutoverInvalid  = errors.New("billing: invalid accounting cutover")
	ErrAccountingCutoverFence    = errors.New("billing: accounting cutover fence conflict")
	ErrAccountingCutoverConflict = errors.New("billing: accounting cutover replay conflict")
	ErrAccountingCutoverNotFound = errors.New("billing: accounting cutover not found")
)
View Source
var (
	// ErrAccountingRollbackBlocked identifies a capture-rollback request
	// against a store that already carries durable V2 financial state.
	ErrAccountingRollbackBlocked = errors.New("billing: accounting capture rollback blocked after V2 monetary posting")
	// ErrAccountingStaleBinary identifies a serving binary whose accounting
	// reader/epoch capability cannot operate the durable financial state.
	ErrAccountingStaleBinary = errors.New("billing: accounting binary is not compatible with durable financial state")
	// ErrAccountingStrictQuiesced identifies a denied strict monetary
	// admission while the process runs quiesced pending compatible recovery.
	ErrAccountingStrictQuiesced = errors.New("billing: strict monetary admissions quiesced pending compatible recovery")
)
View Source
var (
	ErrTrustedCommandInvalid      = errors.New("billing: invalid trusted command")
	ErrUnsafeCreditLimitReduction = errors.New("billing: unsafe credit-limit reduction")
)
View Source
var (
	ErrCallIncomplete    = errors.New("billing: call is not complete")
	ErrCallClaimConflict = errors.New("billing: complete-call claim conflict")
)
View Source
var (
	ErrSchemaSubsetContradiction = errors.New("billing: frozen schema subset quantity exceeds its parent quantity")

	// ErrSchemaQuantityContradiction reports an effective reduced ordinary-usage
	// component quantity strictly below zero. Every nonzero deviation from the
	// evidence is a structural contradiction: pkg/lipsdk/metering exposes no
	// component-level correction or credit marker on Measure values (only
	// metering.Fact carries FactKindCorrection, which never reaches the reduced
	// component aggregates the rater sees), so the rater cannot distinguish a
	// legitimate credit from corrupt arithmetic. It fails the valuation closed and
	// never silently clamps the quantity to zero. This is the narrow rule named by
	// review decision 7; a future SDK credit marker would be honoured here.
	ErrSchemaQuantityContradiction = errors.New("billing: frozen schema effective quantity is negative")
)

ErrSchemaSubsetContradiction reports a frozen subset containment relationship whose child quantity strictly exceeds its parent quantity in the exact same reduction scope, economic direction and unit, with both quantities present, complete and comparable. A subset is contained in its parent, so subset > parent is unambiguously inconsistent evidence, and it is inconsistent regardless of what either side costs. The rater therefore keeps the independent lines payable but classifies the enclosing valuation partial rather than certifying a complete money figure from contradictory quantities.

The check is a quantity fact, so it runs on the same reduced evidence as the partition conservation proof and never on effective charge positivity. A missing, unavailable or otherwise unquantified operand is NOT this condition: the arithmetic is simply not comparable and the existing quantity/missing-rate diagnostics carry it. It is raised by the compiled constraint solver for any containment violation over the transitive union of subset and complete-coverage edges, so a chain that changes edge class partway (A subset B, B partition C) is bounded exactly like a pure subset chain.

View Source
var (
	// These errors classify post-usage rating failures. They are deliberately
	// separate from stream/transport errors so callers can retain an
	// incomplete valuation without mistaking it for a zero-cost result.
	ErrRateMissing     = errors.New("billing: rating rate is missing")
	ErrRateUnsupported = errors.New("billing: rating rate is unsupported")
	ErrRatePrecision   = errors.New("billing: rating precision is unsupported")
	// Reuse the established scalar-rating sentinels so callers can classify
	// legacy and component rating failures uniformly.
	ErrRateCurrencyMismatch  = ErrRatingCurrencyMismatch
	ErrQuantityIncomplete    = errors.New("billing: rating quantity is incomplete")
	ErrQualifierMissing      = errors.New("billing: required rating qualifier is missing")
	ErrQualifierConflict     = errors.New("billing: rating qualifiers conflict")
	ErrCoverageInvalid       = errors.New("billing: charge coverage is invalid")
	ErrPeriodScopeRequired   = errors.New("billing: period-scoped rule requires period valuation")
	ErrFixedFeeScopeMismatch = errors.New("billing: fixed fee scope does not match valuation scope")
	ErrTariffInvalid         = errors.New("billing: invalid tariff snapshot")
	ErrTariffImmutable       = errors.New("billing: tariff snapshot is immutable")
	// Input-set identity is a public economics trust-boundary contract. Keep a
	// billing alias so internal callers can classify direct-rater failures
	// without importing a second sentinel.
	ErrInputSetHashMismatch = economics.ErrInputSetHashMismatch
)
View Source
var (
	ErrMissingRate          = ErrRateMissing
	ErrUnsupportedRate      = ErrRateUnsupported
	ErrUnsupportedPrecision = ErrRatePrecision
	ErrCurrencyMismatch     = ErrRateCurrencyMismatch
	ErrIncompleteQuantity   = ErrQuantityIncomplete
	ErrRatingPrecision      = ErrRatePrecision
	ErrRateInvalid          = ErrRatingInvalid
)

Compatibility aliases make the classification explicit at call sites while retaining one sentinel for errors.Is checks.

View Source
var (
	ErrCostPassThroughPolicyInvalid      = errors.New("billing: invalid cost pass-through policy")
	ErrCostPassThroughProviderIncomplete = errors.New("billing: cost pass-through provider cost is incomplete")
	ErrCostPassThroughProviderUntrusted  = errors.New("billing: cost pass-through provider cost is untrusted")
	ErrCostPassThroughCurrencyMismatch   = errors.New("billing: cost pass-through currency is incomparable")
	ErrCostPassThroughBoundExceeded      = errors.New("billing: cost pass-through amount exceeds approved bound")
	ErrCostPassThroughSettlementInvalid  = errors.New("billing: invalid cost pass-through settlement")
	ErrCostPassThroughRevisionConflict   = errors.New("billing: cost pass-through revision conflicts")
	ErrCostPassThroughLateAdjustment     = errors.New("billing: late cost pass-through adjustment is not permitted")
	ErrCostPassThroughHeadNotFound       = errors.New("billing: cost pass-through settlement head not found")
)
View Source
var (
	// ErrAllocationTargetNotAttributable means an allocation names a target
	// that is not represented by one of the concrete B-legs/calls supplied to
	// the COGS attribution. Failing closed prevents a synthetic B-leg from
	// being introduced solely to carry a shared-resource amount.
	ErrAllocationTargetNotAttributable = errors.New("billing: allocation target is not an attributable executed call or B-leg")
	// ErrAllocationRequestScoped prevents an already request-scoped provider
	// charge from being added a second time through the non-request allocation
	// seam. Provider-charge costs belong to the B-leg charge selector.
	ErrAllocationRequestScoped = errors.New("billing: request-scoped provider charge cannot be allocated into B-leg COGS")
	// ErrAllocationAmountUnavailable keeps a non-payable allocation from being
	// presented as a payable monetary subtotal when its integer ledger amount
	// is absent.
	ErrAllocationAmountUnavailable = errors.New("billing: allocated monetary amount is unavailable")
)
View Source
var (
	ErrCreditScreenDenied      = errors.New("billing: cheap credit screen denied")
	ErrCreditScreenUnavailable = errors.New("billing: cheap credit screen unavailable")
	ErrCreditScreenInvalid     = errors.New("billing: invalid cheap credit screen")
)
View Source
var (
	ErrCustomerUnitInvalid = errors.New("billing: invalid customer unit")
	// The more specific names are aliases so callers can classify a failure at
	// either the domain or operation boundary without introducing duplicate
	// error identities.
	ErrCustomerUnitKeyInvalid       = ErrCustomerUnitInvalid
	ErrCustomerUnitBalanceInvalid   = ErrCustomerUnitInvalid
	ErrCustomerUnitOperationInvalid = ErrCustomerUnitInvalid
	ErrCustomerUnitResultInvalid    = ErrCustomerUnitInvalid

	ErrCustomerUnitAuthority           = errors.New("billing: customer unit authority rejected")
	ErrCustomerUnitEntitlementMissing  = errors.New("billing: customer unit entitlement is missing")
	ErrCustomerUnitEntitlementPartial  = errors.New("billing: customer unit entitlement is partial")
	ErrCustomerUnitEntitlementConflict = errors.New("billing: customer unit entitlement is conflicting")
	ErrCustomerUnitInsufficient        = errors.New("billing: insufficient customer units")
	ErrCustomerUnitStaleVersion        = errors.New("billing: stale customer unit version")
	ErrCustomerUnitStaleFence          = errors.New("billing: stale customer unit fence")
	ErrCustomerUnitOperationConflict   = errors.New("billing: customer unit operation replay conflict")
	ErrCustomerUnitReservationInvalid  = errors.New("billing: invalid customer unit reservation")
	ErrCustomerUnitUnavailable         = errors.New("billing: customer unit ledger unavailable")
)

Customer-unit errors are intentionally separate from monetary-account and supplier-gauge errors. A customer unit balance is a customer-owned non-monetary authority; provider account/window observations must never be accepted as a source for one of these operations.

View Source
var (
	ErrCutoverCoordinatorInvalid = errors.New("billing: invalid cutover coordinator")
	ErrCutoverDrainBlocked       = errors.New("billing: cutover drain blocked")
	ErrCutoverV1Fenced           = errors.New("billing: V1 financial work fenced by cutover")
	ErrCutoverV2NotAuthorized    = errors.New("billing: V2 new work not authorized")
)
View Source
var (
	// ErrEconomicDetailInvalid identifies a malformed query or input set.
	ErrEconomicDetailInvalid = errors.New("billing: invalid economic detail query")
	// ErrEconomicDetailScopeMismatch identifies evidence outside the trusted
	// query scope. Assembly fails closed rather than mixing scopes.
	ErrEconomicDetailScopeMismatch = errors.New("billing: economic detail scope mismatch")
	// ErrEconomicDetailBoundExceeded identifies an input or result that exceeds
	// the bounded detail cardinality. Exceeding a bound fails closed and never
	// truncates silently except for the explicit Limit page.
	ErrEconomicDetailBoundExceeded = errors.New("billing: economic detail bound exceeded")
)
View Source
var (
	// ErrEconomicDetailStatementObservationMissing identifies a referenced
	// statement observation that the composed source authoritatively reports as
	// not retained. It is deliberately distinct from a failing or unavailable
	// reader so a missing fact is never confused with an unimplemented seam.
	ErrEconomicDetailStatementObservationMissing = errors.New("billing: referenced statement observation is not retained")
	// ErrEconomicDetailStatementSourceUnavailable identifies a composed
	// statement observation reader that failed for a non-missing reason. The
	// caller must not treat this as an absent fact.
	ErrEconomicDetailStatementSourceUnavailable = errors.New("billing: statement observation reader unavailable")
)
View Source
var (
	// ErrInvalidEconomicRevision identifies malformed durable revision work.
	ErrInvalidEconomicRevision = errors.New("billing: invalid economic revision")
	// ErrEconomicRevisionSubjectMismatch prevents a rater/reconciler from
	// writing a result for a different trusted B-leg or economic subject.
	ErrEconomicRevisionSubjectMismatch = errors.New("billing: economic revision subject mismatch")
	// ErrEconomicRevisionBasisMismatch prevents a derived result from silently
	// changing the explicit plane selected by durable work.
	ErrEconomicRevisionBasisMismatch = errors.New("billing: economic revision basis mismatch")
	// ErrEconomicRevisionInputMismatch identifies a result whose immutable input
	// references no longer describe the revision that caused the work.
	ErrEconomicRevisionInputMismatch = errors.New("billing: economic revision input mismatch")
	// ErrEconomicRevisionConflict identifies a same-identity result with changed
	// derived output. Durable stores must retain the first result and reject the
	// conflicting replay rather than overwrite it.
	ErrEconomicRevisionConflict = errors.New("billing: economic revision conflict")
	// ErrEconomicRevisionClaimLost identifies a stale worker lease attempting
	// to retire or retry work after another worker fenced it out.
	ErrEconomicRevisionClaimLost = errors.New("billing: economic revision claim lost")
	// ErrEconomicRevisionFence identifies an unsafe current-head transition,
	// including a same-revision evidence branch that cannot be proven to contain
	// or be contained by the durable head evidence.
	ErrEconomicRevisionFence = errors.New("billing: economic revision head fence conflict")
)
View Source
var (
	ErrEstimateInvalid   = errors.New("billing: invalid max-charge estimate input")
	ErrEstimateUnbounded = errors.New("billing: charge exposure is unknown or unbounded")
	ErrEstimateCurrency  = errors.New("billing: max-charge currency mismatch")
	ErrEstimateOverflow  = errors.New("billing: max-charge arithmetic overflow")
	ErrEstimateSnapshot  = errors.New("billing: max-charge snapshot mismatch")
)
View Source
var (
	ErrExposureInvalid          = errors.New("billing: invalid call exposure")
	ErrExposureInsufficient     = errors.New("billing: insufficient safety margin")
	ErrExposureConflict         = errors.New("billing: call exposure replay conflict")
	ErrExposureNotFound         = errors.New("billing: call exposure not found")
	ErrExposureClosed           = errors.New("billing: call exposure is closed")
	ErrExposureActualExceedsMax = errors.New("billing: actual charge exceeds admitted maximum")
)
View Source
var (
	ErrJournalInvalid     = errors.New("billing: invalid journal transaction")
	ErrJournalUnbalanced  = errors.New("billing: unbalanced journal transaction")
	ErrJournalFingerprint = errors.New("billing: journal fingerprint mismatch")
)
View Source
var (
	ErrMoneyCurrencyMismatch = errors.New("billing: money currency mismatch")
	ErrMoneyOverflow         = errors.New("billing: money arithmetic overflow")
	ErrMoneyInvalid          = errors.New("billing: invalid money")
)
View Source
var (
	// ErrOperatorCostSelectionInput identifies a malformed policy, input or
	// out-of-bounds candidate set.
	ErrOperatorCostSelectionInput = errors.New("billing: invalid operator cost selection input")
	// ErrOperatorCostSelectionConflict identifies duplicate candidate roles;
	// the selection fails closed instead of choosing one silently.
	ErrOperatorCostSelectionConflict = errors.New("billing: conflicting operator cost selection candidates")
)
View Source
var (
	ErrPostingOwnershipInvalid  = errors.New("billing: invalid posting ownership")
	ErrPostingOwnershipFence    = errors.New("billing: posting ownership fence conflict")
	ErrPostingOwnershipConflict = errors.New("billing: posting ownership conflict")
	ErrPostingOwnershipNotFound = errors.New("billing: posting ownership not found")
)
View Source
var (
	// ErrProviderCostRevisionInvalid identifies malformed revision posting
	// input. Provider work is immutable and must be rejected before a journal
	// transaction is opened when its identity is not complete.
	ErrProviderCostRevisionInvalid = errors.New("billing: invalid provider cost revision")
	// ErrProviderCostRevisionConflict identifies a same immutable revision
	// identity whose valuation, subject, or selected amount differs from the
	// durable first result.
	ErrProviderCostRevisionConflict = errors.New("billing: provider cost revision conflict")
	// ErrProviderCostRevisionFence identifies a stale head transition. Stores
	// may retry the enclosing transaction, but must never overwrite a newer
	// selected-cost head.
	ErrProviderCostRevisionFence = errors.New("billing: provider cost revision fence conflict")
	// ErrProviderCostHeadNotFound identifies a requested current provider-cost
	// head that has not yet been created.
	ErrProviderCostHeadNotFound = errors.New("billing: provider cost head not found")
	// ErrProviderCostRevisionAuthority identifies a provider-cost revision that
	// claims payable authority without the matching typed provider evidence.
	ErrProviderCostRevisionAuthority = errors.New("billing: provider cost revision authority rejected")
)
View Source
var (
	ErrAccountConflict = errors.New("billing: account identity conflict")
	ErrAccountNotFound = errors.New("billing: account not found")
)
View Source
var (
	ErrRatingInvalid          = errors.New("billing: invalid rating input")
	ErrRatingSnapshotMismatch = errors.New("billing: rating snapshot identity mismatch")
	ErrRatingCurrencyMismatch = errors.New("billing: rating currency mismatch")
	ErrRatingEvidenceMissing  = errors.New("billing: required rating evidence is missing")
	ErrUnreconciledCost       = errors.New("billing: provider cost is unreconciled")
	// ErrBillingAttemptSequenceUnknown fails closed when customer leg
	// selection requires the persisted B2BUA attempt sequence but a legacy
	// pre-fix leg row carries none. The call must be retried/reconciled rather
	// than guessing order from IDs or timestamps.
	ErrBillingAttemptSequenceUnknown = errors.New("billing: customer leg selection requires unknown attempt sequence")
)
View Source
var (
	// ErrReconciliationAggregateInvalid identifies malformed findings or an
	// invalid tolerance policy.
	ErrReconciliationAggregateInvalid = errors.New("billing: invalid reconciliation aggregate input")
	// ErrReconciliationAggregateBoundExceeded identifies input or row
	// cardinality beyond the bounded aggregate contract.
	ErrReconciliationAggregateBoundExceeded = errors.New("billing: reconciliation aggregate bound exceeded")
	// ErrReconciliationAggregateOverflow identifies an exact aggregate total
	// outside the bounded decimal/rational contract.
	ErrReconciliationAggregateOverflow = errors.New("billing: reconciliation aggregate arithmetic overflow")
)
View Source
var (
	// ErrReconciliationInput identifies malformed, cross-store or empty
	// comparison input. It is never returned for a legitimately incompatible
	// evidence pair, which is reported as an incomparable result instead.
	ErrReconciliationInput = errors.New("billing: invalid reconciliation comparison input")
	// ErrReconciliationBoundExceeded identifies an input or result that exceeds
	// the bounded comparison cardinality. Exceeding a bound fails closed and
	// never truncates silently.
	ErrReconciliationBoundExceeded = errors.New("billing: reconciliation comparison bound exceeded")
	// ErrReconciliationArithmetic identifies an exact delta that cannot be
	// represented by the bounded decimal contract. No float fallback exists.
	ErrReconciliationArithmetic = errors.New("billing: reconciliation arithmetic exceeds bounded decimal")
)
View Source
var (
	// ErrMonetaryDiscrepancyInput identifies malformed, empty or out-of-bounds
	// decomposition input.
	ErrMonetaryDiscrepancyInput = errors.New("billing: invalid monetary discrepancy input")
	// ErrMonetaryDiscrepancyConflict identifies two valuations claiming one
	// E/Q/P role. The comparison fails closed instead of selecting one.
	ErrMonetaryDiscrepancyConflict = errors.New("billing: conflicting monetary valuation roles")
	// ErrMonetaryDiscrepancyRole identifies a valuation basis outside the E/Q/P
	// decomposition contract.
	ErrMonetaryDiscrepancyRole = errors.New("billing: unsupported monetary valuation role")
	// ErrMonetaryDiscrepancyOverflow identifies an exact difference outside the
	// bounded decimal/rational contract. No inexact fallback exists.
	ErrMonetaryDiscrepancyOverflow = errors.New("billing: monetary discrepancy arithmetic overflow")
)
View Source
var (
	// ErrReconciliationToleranceInvalid identifies a malformed or ambiguous
	// policy, or an evaluation input that cannot be compared at all.
	ErrReconciliationToleranceInvalid = errors.New("billing: invalid reconciliation tolerance policy or input")
	// ErrReconciliationToleranceOverflow identifies an exact tolerance
	// intermediate outside the bounded decimal/rational contract.
	ErrReconciliationToleranceOverflow = errors.New("billing: reconciliation tolerance arithmetic overflow")
)
View Source
var (
	ErrInvalidRecord     = errors.New("billing: invalid usage record")
	ErrReplayConflict    = errors.New("billing: replay fingerprint conflict")
	ErrReplayKeyMismatch = errors.New("billing: durable key mismatch")
)
View Source
var (
	ErrReportInvalid  = errors.New("billing: invalid report query")
	ErrReportNotFound = errors.New("billing: report subject not found")
)
View Source
var (
	ErrRetailRatingInvalid             = errors.New("billing: invalid retail rating input")
	ErrRetailRateIncomplete            = errors.New("billing: retail rating is incomplete")
	ErrRetailSubmissionIdentityMissing = errors.New("billing: trusted submission identity is required")
	ErrRetailFixedScopeUnsupported     = errors.New("billing: retail fixed-fee scope is unsupported")
	ErrRetailProxyScopeMismatch        = errors.New("billing: proxy-service observation is outside customer boundary scope")
)
View Source
var (
	ErrRetailSelectionInvalid        = errors.New("billing: invalid retail selection")
	ErrRetailSelectionIncomplete     = errors.New("billing: retail selection evidence is incomplete")
	ErrRetailSelectionEmpty          = errors.New("billing: retail selection is empty")
	ErrRetailSelectionAmbiguous      = errors.New("billing: retail selection is ambiguous")
	ErrRetailSelectionOutcomeUnknown = errors.New("billing: retail selection outcome is unknown")
	ErrRetailSelectionDuplicate      = errors.New("billing: retail selection contains a duplicate reference")
	ErrRetailSelectionScopeMismatch  = errors.New("billing: retail selection evidence is outside the call scope")
	ErrRetailSelectionUntrusted      = errors.New("billing: retail selection evidence is not trusted")
)
View Source
var (
	// ErrSelectedCostAdjustmentInvalid identifies malformed selected-cost
	// adjustment input. Invalid input fails closed before a transaction opens.
	ErrSelectedCostAdjustmentInvalid = errors.New("billing: invalid selected cost adjustment")
	// ErrSelectedCostAdjustmentConflict identifies a replay that is not backed
	// by the durable adjustment operation, or a durable head whose identity
	// does not match the caller's CAS read.
	ErrSelectedCostAdjustmentConflict = errors.New("billing: selected cost adjustment conflict")
)
View Source
var (
	// ErrSelectedCostHeadInvalid identifies malformed or inconsistent selected
	// cost head transition input. Invalid input fails closed and produces no
	// plan.
	ErrSelectedCostHeadInvalid = errors.New("billing: invalid selected cost head transition")
	// ErrSelectedCostHeadLedgerPrecision identifies an exact monetary delta that
	// cannot be represented as checked integer ledger nanos. The planner never
	// rounds; callers need an explicit rounding policy before posting.
	ErrSelectedCostHeadLedgerPrecision = errors.New("billing: selected cost delta is not ledger-exact")
)
View Source
var (
	ErrSettlementInvalid           = errors.New("billing: invalid settlement")
	ErrSettlementConflict          = errors.New("billing: settlement replay conflict")
	ErrSettlementReconcileRequired = errors.New("billing: settlement requires reconciliation")
)
View Source
var (
	// ErrStatementImportInvalid identifies a malformed, overbound or
	// unsupported normalized statement claim.
	ErrStatementImportInvalid = errors.New("billing: invalid statement import")
	// ErrStatementImportScopeMismatch identifies evidence outside the trusted
	// caller scope. Imports fail closed rather than trusting statement-claimed
	// tenant/account identity.
	ErrStatementImportScopeMismatch = errors.New("billing: statement import scope mismatch")
	// ErrStatementImportConflict identifies a retained immutable identity whose
	// content differs from the submitted revision. No durable change is made.
	ErrStatementImportConflict = errors.New("billing: statement import revision conflict")
	// ErrStatementImportLedgerUnavailable identifies a missing or failing
	// durable statement ledger.
	ErrStatementImportLedgerUnavailable = errors.New("billing: statement import ledger unavailable")
)
View Source
var (
	// ErrStatementMatchInvalid identifies malformed, duplicated or overbound
	// matching input. Invalid input fails closed and produces no match result.
	ErrStatementMatchInvalid = errors.New("billing: invalid statement match input")
	// ErrStatementMatchAmbiguous identifies input that contains more than one
	// revision of one statement identity. Choosing a current revision is not
	// this component's policy, so no guessed coverage is produced.
	ErrStatementMatchAmbiguous = errors.New("billing: ambiguous statement match input")
)
View Source
var (
	// ErrSubmissionFeeInvalid means a customer valuation carries a submission
	// fee that is not safe to admit to the durable settlement boundary.
	ErrSubmissionFeeInvalid = errors.New("billing: invalid submission fee")
	// ErrSubmissionFeeIdentityMissing means a submission-scoped fee cannot be
	// keyed because the trusted call identity did not carry SubmissionID.
	ErrSubmissionFeeIdentityMissing = errors.New("billing: submission fee identity missing")
)
View Source
var (
	// ErrHistoricalV1Ambiguous identifies malformed or ambiguous
	// version/identity data that must fail closed.
	ErrHistoricalV1Ambiguous = errors.New("billing: ambiguous historical version")
	// ErrHistoricalV1WriterConflict identifies a writer mismatch against the
	// resolved owner. This read-only preflight reports ownership; durable
	// epoch/posting enforcement belongs to Phase 17.3.
	ErrHistoricalV1WriterConflict = errors.New("billing: historical writer ownership conflict")
)
View Source
var ErrAllocationRollupIncomplete = errors.New("billing: allocation rollup is incomplete")

ErrAllocationRollupIncomplete classifies the legacy rollup's fail-closed compatibility error. Callers that need known lines from a partial result must use RollupAllocatedCostsDetailed instead.

View Source
var ErrBillingCallIDInvalid = errors.New("billing: invalid billing call id")
View Source
var ErrBillingStoreUnavailable = errors.New("billing: store unavailable")
View Source
var ErrEconomicHealthInput = errors.New("billing: invalid economic health input")

ErrEconomicHealthInput identifies malformed snapshot input: negative counts, unknown clocks or inexact arithmetic outside the bounded exact contract.

View Source
var ErrEconomicRevisionDependencyOutputMissing = errors.New("billing: economic revision dependency output missing")

ErrEconomicRevisionDependencyOutputMissing identifies dependency-anchored work whose immutable rating output is not durable yet. It is retryable with the bounded dependency_pending reason rather than a terminal failure.

View Source
var ErrInvalidEconomicJobRunner = errors.New("billing: invalid economic job runner")

ErrInvalidEconomicJobRunner identifies an incomplete or malformed application runner configuration.

View Source
var ErrInvalidMonetaryExactAmount = errors.New("billing: invalid exact monetary amount")

ErrInvalidMonetaryExactAmount identifies a noncanonical or unbounded exact monetary amount.

View Source
var ErrInvalidReconciliationRetention = errors.New("billing: invalid reconciliation retention result")

ErrInvalidReconciliationRetention identifies a malformed, non-canonical or oversized durable reconciliation result.

View Source
var ErrInvalidWorkloadIdentity = errors.New("billing: invalid workload identity")
View Source
var ErrProviderCostAuthority = ErrProviderCostRevisionAuthority

ErrProviderCostAuthority is the legacy provider-cost monetary-boundary classification. It aliases the revision-era sentinel so adapters can share one authority vocabulary while older callers retain their existing errors.Is behavior.

View Source
var ErrProviderCostCallUnavailable = errors.New("billing: provider-cost call closure unavailable")
View Source
var ErrProviderCostUntrusted = ErrProviderCostAuthority

ErrProviderCostUntrusted is a descriptive compatibility alias used by provider-cost callers that do not distinguish legacy and revision writers.

View Source
var ErrSchemaOverlapConflict = errors.New("billing: frozen schema component overlap is not payable")

ErrSchemaOverlapConflict reports a frozen component-schema inclusion or partition relationship whose parent aggregate and declared child are both priced within the same source/B-leg/work scope and economic direction. The rater refuses to emit those overlapping payable lines rather than double-charge the same underlying work, while unrelated scopes, unrelated components, and independent fixed fees stay payable. Cross-direction, transform, and separate-scope edges are not overlaps and remain additive.

View Source
var ErrSchemaPartitionContradiction = errors.New("billing: frozen schema complete partition contradicts observed quantities")

ErrSchemaPartitionContradiction reports a frozen complete child partition whose present, complete and rateable declared children do not arithmetically account for the present parent's comparable effective reduced quantity in the exact same reduction scope. The partition evidence is inconsistent, so the rater keeps the independent lines payable but classifies the enclosing valuation partial/incomparable instead of suppressing the parent (which would make the children-only money look complete) or inventing the residual (Requirement 3.5). This classification is independent of the parent's own missing-rate diagnostic: a complete zero parent and an informational parent are skipped from line emission by the rating loop, yet their contradicted partition must still fail the valuation closed.

View Source
var ErrSchemaPartitionIncomparable = errors.New("billing: frozen schema complete partition has ambiguously shared children")

ErrSchemaPartitionIncomparable reports an observed aggregate parent whose declared complete child partition cannot be proven because at least one declared child is also declared under another complete parent (ambiguous ownership). The children sum is not comparable in that case, so this is deliberately distinct from ErrSchemaPartitionContradiction: the rater exposes partial/incomparable evidence (Requirement 3.5) rather than asserting an arithmetic contradiction, and never lets the child-only money look complete. It is independent of the parent's own rating: a zero or informational parent is skipped from line emission, yet its ambiguously shared partition still classifies the enclosing valuation partial.

View Source
var ErrSchemaPartitionIncomplete = errors.New("billing: frozen schema complete partition is missing required members")

ErrSchemaPartitionIncomplete reports an observed parent whose declared complete child partition cannot be evaluated because a REQUIRED declared member is absent from the evidence, unavailable, or has no complete comparable quantity. A declared complete partition is usable only when its required members are known: missing operands stay missing, so the children-only money must never be certified complete from an incomplete partition.

The sentinel is raised for the parents where that incompleteness governs the money, which is decided against the parent's own effective charge and never against rule existence. An absent OPTIONAL member is not this condition; the frozen schema declares its own optional zero for it.

Functions

func AccountingCutoverExpectations

func AccountingCutoverExpectations(state AccountingCutoverState) (generation int, owner string, floor string, ok bool)

AccountingCutoverExpectations returns the generation, active posting owner, and compatibility floor pinned to one approved state.

func AccountingRequiresStrictQuiesce

func AccountingRequiresStrictQuiesce(snapshot AccountingRecoverySnapshot, capability AccountingBinaryCapability) bool

AccountingRequiresStrictQuiesce is the single deterministic predicate behind both startup rejection and explicit quiesce: it is true exactly when the binary cannot safely serve the durable financial state. Invalid snapshots or capabilities quiesce (fail closed).

func AddReportAmount

func AddReportAmount(total int64, amount Money, currency string) (int64, error)

func AuthoritativeIsMonetary

func AuthoritativeIsMonetary(work EconomicRevisionWork, providerPosting bool) bool

AuthoritativeIsMonetary reports the single authoritative delivery intent for one immutable payload plus its mutable queue delivery state: monetary iff the payload has monetary shape AND state says provider_posting. Payload EvidenceOnly/PostingOwner alone never decides.

func BoundedEconomicWorkReasonText

func BoundedEconomicWorkReasonText(text string) string

BoundedEconomicWorkReasonText trims and truncates free-form error text so a durable delivery row cannot grow without bound.

func BuildCustomerPolicyObservationInput

func BuildCustomerPolicyObservationInput(subject metering.SubjectRef, observations []metering.Observation, policy ChargePolicy, tariff economics.TariffSnapshot) (economics.PostUsageRatingInput, error)

BuildCustomerPolicyObservationInput creates the snapshot-bound R input used by stock composition. Snapshot content hashes are derived from the immutable policy/tariff bodies, so replay does not depend on a live mutable catalog.

func CallLegUsageKey

func CallLegUsageKey(callID BillingCallID, bLegID string) (string, error)

func CallUsageKey

func CallUsageKey(callID BillingCallID) (string, error)

func CheckAccountingStartup

func CheckAccountingStartup(snapshot AccountingRecoverySnapshot, capability AccountingBinaryCapability) error

CheckAccountingStartup proves the binary may serve the store before it admits or posts anything. Compatible binaries pass; anything requiring quiesce fails with ErrAccountingStaleBinary so the process never serves (and never silently downgrades) unsupported financial state.

func CheckCallLegUsageReplay

func CheckCallLegUsageReplay(existing, incoming CallLegUsageRecord) error

func CheckCallUsageReplay

func CheckCallUsageReplay(existing, incoming CallUsageRecord) error

func CheckCaptureRollbackAllowed

func CheckCaptureRollbackAllowed(snapshot AccountingRecoverySnapshot) error

CheckCaptureRollbackAllowed permits capture-only rollback (serving the store with a pre-cutover binary again) only while no V2 monetary posting is durable and the compatibility floor remains V1. Any V2 posting, a V2 floor, or an unknown floor blocks rollback: an old writer must never reopen against unsupported new-format financial state.

func CheckCustomerUnitOperationReplay

func CheckCustomerUnitOperationReplay(existing, incoming CustomerUnitOperation) error

CheckCustomerUnitOperationReplay accepts an exact payload replay and rejects reuse of an operation identity with a different economic meaning. ExpectedVersion and Fence are intentionally not part of the replay payload.

func CheckCustomerUnitPrecondition

func CheckCustomerUnitPrecondition(op CustomerUnitOperation, balance CustomerUnitBalance) error

CheckCustomerUnitPrecondition enforces the optimistic version and monotonic fencing contract against the exact balance locked by a ledger adapter.

func CheckExposureReplay

func CheckExposureReplay(existing CallExposure, incoming AdmitExposureInput) error

func CheckHistoricalV1WriterClaim

func CheckHistoricalV1WriterClaim(legs []CallLegUsageRecord, claimant string) error

CheckHistoricalV1WriterClaim is a read-only ownership preflight for old in-flight work. Every leg must carry valid sealed identity matching its sealed recomputation, resolve to one unambiguous writer version, and belong to a single call; a claimant other than that owner fails with ErrHistoricalV1WriterConflict. Empty, mixed-version, mixed-call, or unknown-claimant inputs fail closed. Durable epoch/posting enforcement belongs to Phase 17.3; this helper performs no writes.

func CheckSettledRouteTariffs

func CheckSettledRouteTariffs(admitted, used []RouteTariffBinding, actual Money) error

CheckSettledRouteTariffs compares the route tariff material actually used for the rated routes against the admitted frozen binding. Every used route must resolve to an identical admitted entry (route, tariff version, and content). Only admitted-empty + used-empty passes without proof: the legacy scalar path, which uses no tariff material on either side. A used binding against a legacy-empty exposure, or an omitted binding list against a rich exposure at any charge including zero, fails closed.

func CostPassThroughAdjustmentSourceKey

func CostPassThroughAdjustmentSourceKey(accountID string, callID BillingCallID, provider CostPassThroughProviderCost) (string, error)

func CostPassThroughFinancialAdjustmentPostingOperationKey

func CostPassThroughFinancialAdjustmentPostingOperationKey(storeID, accountID string, callID BillingCallID) (string, error)

CostPassThroughFinancialAdjustmentPostingOperationKey derives the deterministic per-head pin for synchronous cost pass-through revisions. Preimage is exactly the canonical head lineage (store/account/call/head) with explicit version "cost-pass-through-adjustment-pin:v1". One head pin remains authoritative for the replacement chain: each revision keeps its own canonical source/journal identity while pin completion advances to the latest outcome under the same owner. No B-leg/subject is required.

func CostPassThroughHeadKey

func CostPassThroughHeadKey(accountID string, callID BillingCallID) string

CostPassThroughHeadKey derives the canonical customer pass-through head identity for one account/call. The store persists the same key; the pin reuses it so head lineage never requires fake B-leg data.

func CustomerPostingOperationKey

func CustomerPostingOperationKey(accountID string, callID BillingCallID) (string, error)

CustomerPostingOperationKey derives the canonical customer settlement pin key. It reuses CustomerSettlementSourceKey so the pin and the settlement posting share one identity.

func CustomerSettlementSourceKey

func CustomerSettlementSourceKey(accountID string, callID BillingCallID) (string, error)

func DecodeALegReportCursor

func DecodeALegReportCursor(raw, storeID, accountID, aLegID string) (legCall, legBLeg, call string, err error)

DecodeALegReportCursor strictly validates an opaque cursor against the query scope and returns the two durable stream positions. An empty cursor is page 1. The raw token is never normalized: every structurally partial or inconsistent state — leading/trailing/interior whitespace, one-sided leg positions, legs without a call position, unsupported versions, mismatched scope, oversize raw input, malformed encoding, and non-canonical forms — is rejected with ErrReportInvalid.

func DedupeKeyForBLeg

func DedupeKeyForBLeg(callID BillingCallID, bLegID string) (string, error)

DedupeKeyForBLeg returns the bounded fallback identity used when a provider did not report one. Provider-reported keys must remain unchanged; this helper only supplies a proxy-owned key that is scoped to BillingCallID and B-leg.

func DirectFinancialAdjustmentPostingOperationKey

func DirectFinancialAdjustmentPostingOperationKey(storeID, accountID, sourceKey string) (string, error)

DirectFinancialAdjustmentPostingOperationKey derives the deterministic per-source pin for synchronous direct adjustments (PostAdjustment). Preimage is exactly the existing canonical idempotency identity: the scoped adjustment operation key ScopedOperationKey("adjustment", account, source) plus store/account, with explicit version "direct-adjustment-pin:v1". No call/head/B-leg lineage is required; the pin row carries the caller source in head_key so durability remains recomputable without fake lineage.

func EconomicValuationStreamKey

func EconomicValuationStreamKey(valuation economics.Valuation) string

EconomicValuationStreamKey returns the stable identity of the logical valuation stream that a valuation revision belongs to.

The ownership root of an economic valuation is its authoritative subject (Requirement 6.2: B-leg/attempt, call, A-leg or another declared subject), the economic party is its reporting perspective and the source plane is its basis. Two valuations are revisions of one stream only when all three agree; distinct subjects, economic parties or bases are independent contributions even when their basis label matches. This mirrors the durable head identity (queue + subject-derived head key) with the basis plane made explicit.

The key deliberately excludes mutable derived values (amounts, native currency totals, payer, completeness and snapshot revisions). Those are preserved verbatim per revision, and advancing evidence changes the revision while the stream identity stays the same. Callers select the latest revision within one key and must never collapse across keys, so totals and payers of independent subjects are never merged or mixed. Every field the canonical subject validator accepts, including the ResetAt/StartAt/EndAt interval identity, is folded in through writeEconomicSubjectIdentity.

func EffectiveEconomicPostingOwner

func EffectiveEconomicPostingOwner(work EconomicRevisionWork) string

EffectiveEconomicPostingOwner returns the stable posting owner for one monetary work envelope: explicit V1/V2 when set, otherwise the legacy V1 default. Evidence-only work has no posting owner. Retained for payload-only callers; production list/claim/worker must use the authoritative overlay above so state and payload cannot disagree.

func EncodeALegReportCursor

func EncodeALegReportCursor(storeID, accountID, aLegID, legCall, legBLeg, call string) string

EncodeALegReportCursor builds an opaque, scope-bound page cursor over durable BillingCallID (call stream) and (BillingCallID, B-leg) (B-leg stream) identities. Ordering never uses timestamps. Structurally partial positions encode to the empty page-1 token only when fully empty; anything else partial encodes to "" and must be treated as invalid.

func EvaluateALegCallAuthority

func EvaluateALegCallAuthority(scope ALegAuthorityScope, markers []ALegMarker, journals []JournalTransaction) (ALegCallVerdict, []ReconciliationIssue, error)

EvaluateALegCallAuthority proves one call's customer authority inside the snapshot. It returns the verdict plus any issues; only infrastructure failures and unrepresentable money fail the query.

func EvaluateALegPassThroughAuthority

func EvaluateALegPassThroughAuthority(scope ALegAuthorityScope, facts ALegPassThroughFacts) (ALegPassThroughVerdict, []ReconciliationIssue, error)

EvaluateALegPassThroughAuthority proves one call's pass-through plane inside the snapshot. It returns the verdict plus any issues; only infrastructure failures and unrepresentable money fail the query.

func EvaluateALegProviderLeg

EvaluateALegProviderLeg proves one B-leg's provider authority inside the snapshot. It returns the verdict plus any issues; only infrastructure failures and unrepresentable money fail the query.

func FinancialAdjustmentPostingOperationKey

func FinancialAdjustmentPostingOperationKey(storeID, accountID string, callID BillingCallID, headKey string, subject metering.SubjectRef) (string, error)

FinancialAdjustmentPostingOperationKey derives the deterministic head pin key from the canonical adjustment identity (account/call/head/subject). The sha256 preimage carries an explicit version so head pins never collide with settlement or provider keys. B2b4 keeps this selected-cost head identity unchanged; cost pass-through and direct adjustments use their own versioned preimages below.

func IsAccountingCutoverReplay

func IsAccountingCutoverReplay(current AccountingCutoverMarker, req AccountingCutoverTransition) bool

IsAccountingCutoverReplay reports whether current is the exact durable result of req: same expected version/epoch advanced by one, same target state, same transition identity. Callers use it to return idempotent success on retry; any same-version advance with a different payload is a conflict, not a replay.

func IsCostPassThroughAdjustmentPinKey

func IsCostPassThroughAdjustmentPinKey(key string) bool

IsCostPassThroughAdjustmentPinKey reports whether key is a B2b4 cost-pass-through per-head pin.

func IsCutoverTokenCurrentForMarker

func IsCutoverTokenCurrentForMarker(tok CutoverClaimMetadata, marker AccountingCutoverMarker) bool

IsCutoverTokenCurrentForMarker reports whether tok exactly matches the current marker authority (version/epoch/state). Owner/identity checks belong to the posting fence; this helper isolates the staleness comparison so workers and stores share one definition of "stale".

func IsDirectAdjustmentPinKey

func IsDirectAdjustmentPinKey(key string) bool

IsDirectAdjustmentPinKey reports whether key is a B2b4 direct-adjustment per-source pin.

func IsMonetaryEconomicRevisionWork

func IsMonetaryEconomicRevisionWork(work EconomicRevisionWork) bool

Phase 17.3 F2B: monetary economic revision intent.

Only provider-queue provider-rating work can create provider payable/cost/ exclusion through the production EconomicRevisionWorker with a provider-cost adapter. Customer rating, reconciliation jobs (any queue), shadow observations/valuations (no-post path), and queues without a posting adapter are evidence-only and must never be classified, pinned, or fenced as monetary work.

Intent is inferred from the immutable work envelope (queue + kind + B-leg/provider-charge subject lineage), never from queue name alone:

  • queue must be provider,
  • kind must be provider_rating (legacy empty normalizes to provider_rating),
  • subject must be B-leg or provider-charge with a valid store/account/call lineage capable of deriving a canonical ProviderPostingOperationKey.

Adapter presence is explicit at composition (process_billing wires provider-cost only for the provider queue); the durable classifier counts only this narrow set. Explicit evidence-only overrides (e.g. shadow) are recorded in queue delivery state (provider_posting=0), not in the immutable work identity, so legacy payloads remain byte-compatible.

func IsMonetaryEconomicShape

func IsMonetaryEconomicShape(work EconomicRevisionWork) bool

IsMonetaryEconomicShape reports whether one work envelope has monetary provider-rating shape (queue/kind/subject lineage) ignoring delivery intent (EvidenceOnly/PostingOwner). Delivery state (provider_posting) decides whether that shape is actually monetary; the immutable payload alone is never authoritative after R2.

func IsNilPort

func IsNilPort(port any) bool

IsNilPort reports whether an explicit interface port holds no usable implementation. It rejects both untyped nil and typed-nil values (nil pointers, maps, slices, functions, channels, or interfaces boxed in a non-nil interface) before any shadow or billing composition trusts them. Non-nil-capable concrete values (structs, arrays, scalars) are accepted. The helper holds no global or registry state.

func IsPostingOwnerAllowedForNew

func IsPostingOwnerAllowedForNew(state AccountingCutoverState, owner string) bool

IsPostingOwnerAllowedForNew reports whether a fresh (unpinned) operation may be pinned to owner under state. Draining forbids all new; v2_active permits only V2 new.

func IsPostingPinAcquireReplayAllowed

func IsPostingPinAcquireReplayAllowed(currentState AccountingCutoverState, pin PostingPin) bool

IsPostingPinAcquireReplayAllowed reports whether an already pinned operation with the same owner may be re-acquired (idempotent replay) under the current marker. Draining replays pinned V1; v2_active replays V2 and exact V1 completed history only.

func IsPostingPinCompleteAllowed

func IsPostingPinCompleteAllowed(currentState AccountingCutoverState, pin PostingPin) bool

IsPostingPinCompleteAllowed reports whether a pinned (uncompleted) operation may transition to completed under the current marker. Completed-history replay bypasses this check; callers handle that before consulting it.

func IsPostingPinReplay

func IsPostingPinReplay(pin PostingPin, req AcquirePostingPinRequest, operationKey string) bool

IsPostingPinReplay reports whether req is the exact durable replay of pin: same kind, same canonical operation key, same owner. Marker snapshots are intentionally excluded so draining replays succeed after the marker advances; staleness is fenced separately via ExpectedMarkerVersion/Epoch.

func IsProviderRevisionPinKey

func IsProviderRevisionPinKey(key string) bool

IsProviderRevisionPinKey reports whether key is a revision-specific provider pin (scoped provider_call_cogs operation derived from ProviderCostRevisionSourceKey).

func IsSelectedCostAdjustmentPinKey

func IsSelectedCostAdjustmentPinKey(key string) bool

IsSelectedCostAdjustmentPinKey reports whether key is a B2b3 selected-cost head pin (unchanged identity).

func IsV1ClaimEligible

func IsV1ClaimEligible(state AccountingCutoverState, pin PostingPin) bool

IsV1ClaimEligible reports whether a V1 worker claim may proceed under state for pin. Pre-drain states preserve ordinary V1 claims without pin gating. Draining returns only correctly V1-pinned work. v2_active permits no V1 claim (V1 completed-history replay flows through B1 pin replay, not worker claims).

func IsV1FinancialWorkAllowed

func IsV1FinancialWorkAllowed(state AccountingCutoverState) bool

IsV1FinancialWorkAllowed reports whether ordinary (unpinned) V1 append/admission/queue creation is allowed. v1_active/v2_shadow allow new V1 with legacy defaults preserved; v1_draining/v2_active fence new V1. Historical replay of already pinned/completed V1 is handled separately via B1 replay paths, not this gate.

func IsV2NewWorkAuthorized

func IsV2NewWorkAuthorized(state AccountingCutoverState) bool

IsV2NewWorkAuthorized reports whether explicit V2-new-work authorization holds. Only v2_active authorizes V2 posting admissions/new pins. Shadow capture remains no-post and unaffected (it does not consult this gate).

func LegacyTariffFromPricing

func LegacyTariffFromPricing(snapshot PricingSnapshot) (economics.TariffSnapshot, error)

LegacyTariffFromPricing is a descriptive compatibility alias.

func NormalizeRevisionValuationForWork

func NormalizeRevisionValuationForWork(work EconomicRevisionWork, identity EconomicRevisionIdentity, valuation economics.Valuation) (economics.Valuation, error)

NormalizeRevisionValuationForWork is the single shared shadow/worker valuation contract. It preserves the full valid rater clone (allocation coverage, snapshot identities and content, qualifiers, payer, missing observations, charge coverage and other provenance) while rejecting foreign subject/basis/perspective/scope/observation/allocation identity. CreatedAt anchors to immutable work metadata so retries stay byte-stable.

func ObservationEvidenceHash

func ObservationEvidenceHash(observation metering.Observation) string

ObservationEvidenceHash returns the replay-stable source hash used by the durable economic disposition carrier. It does not alter the observation or its provider-owned fingerprint.

func ParseCostPassThroughAdjustmentSourceKey

func ParseCostPassThroughAdjustmentSourceKey(source string) (accountID, callID, lurKey string, revision uint64, valuationID string, err error)

ParseCostPassThroughAdjustmentSourceKey strictly parses a canonical adjustment source key. Any non-canonical shape — wrong prefix or version, wrong field count, empty coordinates, unparseable call identity, or zero revision — fails closed.

func PricingSnapshotToTariff

func PricingSnapshotToTariff(snapshot PricingSnapshot) (economics.TariffSnapshot, error)

PricingSnapshotToTariff adapts an existing scalar customer pricing card into immutable component rules. No provider lookup or external pricing source is involved; the input card remains the sole source of truth.

func ProviderCostRevisionSourceKey

func ProviderCostRevisionSourceKey(in ProviderCostRevisionInput) (string, error)

ProviderCostRevisionSourceKey returns a bounded revision-specific source identity. The stable head key remains in the preimage, while the durable operation/index value is a fixed-size digest.

func ProviderCostSourceKey

func ProviderCostSourceKey(lurKey string) (string, error)

func ProviderPostingOperationKey

func ProviderPostingOperationKey(storeID, accountID string, callID BillingCallID, subject metering.SubjectRef) (string, error)

ProviderPostingOperationKey derives the canonical provider charge pin key from the request-scoped subject. B-leg subjects pin the leg lineage; provider-charge subjects pin the charge lineage beneath that leg.

func ProviderRevisionPostingOperationKey

func ProviderRevisionPostingOperationKey(in ProviderCostRevisionInput) (string, error)

ProviderRevisionPostingOperationKey derives the immutable revision-specific posting pin/operation identity for one provider monetary revision/outcome. It is ScopedOperationKey("provider_call_cogs", account, sourceKey) where sourceKey is ProviderCostRevisionSourceKey. Base legacy charges keep their own ProviderCostSourceKey lineage operation; each higher/replacement revision is a distinct pin while heads/fences still order lineage. Completed pins/outcomes are immutable: exact same operation+fingerprint+tx replay only.

func ProviderRevisionPostingOperationKeyForWork

func ProviderRevisionPostingOperationKeyForWork(accountID string, callID BillingCallID, headKey string, revision uint64, fullHash string) (string, error)

ProviderRevisionPostingOperationKeyForWork derives the same revision-specific pin for one monetary economic work item before valuation exists. fullHash must be the allocation-aware full input hash (DerivationHash when present, else InputSetHash) so work-based classification matches the later revision input whose InputSetHash prefers the persisted valuation full hash.

func RateCustomerPolicyObservation

func RateCustomerPolicyObservation(ctx context.Context, input economics.PostUsageRatingInput, snapshot economics.TariffSnapshot) (economics.Valuation, error)

RateCustomerPolicyObservation rates the incremental B-leg inference plane from a frozen customer tariff. Call/submission fixed fees are commercial lines owned by terminal call settlement, so they are intentionally omitted from this B-leg valuation; evaluating them once per observation head would multiply a call-scoped fee across retries or selected legs.

func RateProviderReported

func RateProviderReported(ctx context.Context, input economics.PostUsageRatingInput) (economics.Valuation, error)

RateProviderReported preserves provider monetary claims without requiring a local tariff catalog. P is an evidence plane, not a locally priced estimate; a missing or refreshing customer/provider tariff must not block its durable representation.

func RateWithTariff

RateWithTariff is a one-shot convenience for post-turn workers that resolve a snapshot from a catalog immediately before rating.

func ResolveCostPassThroughAdjustmentOwner

func ResolveCostPassThroughAdjustmentOwner(input CostPassThroughRevisionInput) (string, error)

ResolveCostPassThroughAdjustmentOwner returns the effective pin owner for one synchronous cost pass-through revision. Empty preserves legacy V1.

func ResolveCustomerSettlementOwner

func ResolveCustomerSettlementOwner(input ApplyCallBillingInput) (string, error)

ResolveCustomerSettlementOwner returns the effective pin owner for one customer settlement. Empty preserves the legacy V1 default.

func ResolveDirectAdjustmentOwner

func ResolveDirectAdjustmentOwner(input AdjustmentInput) (string, error)

ResolveDirectAdjustmentOwner returns the effective pin owner for one synchronous direct adjustment. Empty preserves legacy V1.

func ResolveFinancialAdjustmentOwner

func ResolveFinancialAdjustmentOwner(input SelectedCostAdjustmentInput) (string, error)

ResolveFinancialAdjustmentOwner returns the effective pin owner for one selected-cost adjustment. Empty preserves the legacy V1 default.

func ResolveProviderCostOwner

func ResolveProviderCostOwner(input ApplyProviderCostInput) (string, error)

ResolveProviderCostOwner returns the effective pin owner for one legacy provider posting. Empty preserves the legacy V1 default.

func ResolveProviderRevisionOwner

func ResolveProviderRevisionOwner(input ProviderCostRevisionInput) (string, error)

ResolveProviderRevisionOwner returns the effective pin owner for one provider revision posting. Empty preserves the legacy V1 default.

func RouteTariffKey

func RouteTariffKey(backendID, modelID string) string

RouteTariffKey returns the canonical binding key for a backend/model route. Quote and settlement must derive it identically; it deliberately excludes routing display params, which never change tariff resolution.

func ScopedOperationKey

func ScopedOperationKey(kind, accountID, sourceKey string) string

func ValidateCallRatingResultForOwner

func ValidateCallRatingResultForOwner(result CallRatingResult, owner string) error

ValidateCallRatingResultForOwner is the posting-boundary companion to owner-aware selection: V2-owned money must carry a complete, structurally valid customer component valuation (or an explicit cost-pass-through settlement under its own complete contract). An ID-only valuation, a scalar result (empty valuation, no pass-through), or a malformed component/basis valuation is rejected for V2 before any journal, balance, or exposure effect. V1 drain and legacy empty owners preserve historical scalar replay.

This is the structural gate: it reuses the approved economics.Valuation contract (Validate plus V2 customer R-plane completeness) but cannot bind account/call/currency/amount without settlement context. Production worker/store/resolver boundaries must use ValidateCallRatingResultForSettlement with the settled call and exposure so wrong subject/account/call, wrong currency/amount, or mismatched result identity also fails closed before money.

func ValidateCallRatingResultForSettlement

func ValidateCallRatingResultForSettlement(result CallRatingResult, call CallUsageRecord, exposure CallExposure, owner string) error

ValidateCallRatingResultForSettlement is the generic V2 settlement boundary: it enforces the complete customer valuation contract bound to the exact settlement subject/scope, currency, and rated amount/result identity, reusing the approved domain validators. It must be called at the generic worker before Apply and at the billingstore transactional boundary (including direct Apply) so ID-only, wrong account/call/subject, wrong currency/amount, malformed component/basis, or mismatched result fails closed with zero balance/journal/exposure/pin effects. V1 drain and legacy empty owners preserve historical scalar replay. Explicit cost-pass-through remains a separate valid path only under its existing complete contract (policy/amount/currency bound to the settled call); it never serves as a generic bypass.

func ValidateCostPassThroughAdjustmentClaim

func ValidateCostPassThroughAdjustmentClaim(claim CutoverClaimMetadata, storeID, accountID string, callID BillingCallID) error

ValidateCostPassThroughAdjustmentClaim checks narrow B2a claim metadata for one cost pass-through revision against its canonical per-head pin identity (store/account/call/head). It does not consult the current marker; the store compares claim epoch to the durable marker to fence stale workers.

func ValidateCustomerMonetaryFallback

func ValidateCustomerMonetaryFallback(amount, bound Money) error

ValidateCustomerMonetaryFallback proves a concrete monetary charge is a non-negative same-currency amount within a previously admitted bound. It is intended for the settlement adapter after exact uncovered units are rated.

func ValidateCustomerSettlementClaim

func ValidateCustomerSettlementClaim(claim CutoverClaimMetadata, accountID string, callID BillingCallID) error

ValidateCustomerSettlementClaim checks narrow B2a claim metadata for one customer settlement against its canonical identity. It does not consult the current marker; the store compares claim epoch to the durable marker to fence stale workers.

func ValidateCustomerSettlementOperationKind

func ValidateCustomerSettlementOperationKind(operationKind string) error

ValidateCustomerSettlementOperationKind fails closed when the settlement operation kind is not the customer settlement namespace. Provider and adjustment posting are later phases and must not flow through this fence. The zero-charge repair kind (ALegRepairKind, "customer_no_charge_repair") shares the same customer settlement pin identity (same sourceKey/call) and is therefore allowed: it closes exposure and marks processed with zero money, never a second monetary authority.

func ValidateDirectAdjustmentClaim

func ValidateDirectAdjustmentClaim(claim CutoverClaimMetadata, storeID, accountID, sourceKey string) error

ValidateDirectAdjustmentClaim checks narrow B2a claim metadata for one direct adjustment against its canonical per-source pin identity (store/account/source). It does not consult the current marker; the store compares claim epoch to the durable marker to fence stale workers.

func ValidateFinancialAdjustmentClaim

func ValidateFinancialAdjustmentClaim(claim CutoverClaimMetadata, input SelectedCostAdjustmentInput) error

ValidateFinancialAdjustmentClaim checks narrow B2a claim metadata for one selected-cost adjustment against its canonical head identity derived from the normalized input. It does not consult the current marker; the store compares claim epoch to the durable marker to fence stale workers.

func ValidateFinancialAdjustmentOperationKind

func ValidateFinancialAdjustmentOperationKind(operationKind string) error

ValidateFinancialAdjustmentOperationKind fails closed when an adjustment operation kind is not the financial adjustment namespace. Customer and provider posting must not flow through this fence.

func ValidateIndependentLeg

func ValidateIndependentLeg(leg CallLegUsageRecord) error

ValidateIndependentLeg is the terminal-accounting contract for a leg that is persisted independently (including auxiliary and failover B-legs). Legacy CallLegUsageRecord rows remain readable through Seal, while new independent delivery fails closed when sequence or evidence identity is absent.

func ValidateProviderChargeOperationKind

func ValidateProviderChargeOperationKind(operationKind string) error

ValidateProviderChargeOperationKind fails closed when a provider operation kind is not the provider charge namespace. Customer and adjustment posting must not flow through this fence.

func ValidateProviderCostAuthority

func ValidateProviderCostAuthority(leg CallLegUsageRecord, result OperatorCostResult) error

ValidateProviderCostAuthority validates the result together with the source-qualified V1 leg that it claims to represent. The result flag is not enough to turn local or estimated evidence into provider-reported money.

func ValidateProviderCostClaim

func ValidateProviderCostClaim(claim CutoverClaimMetadata, accountID string, callID BillingCallID, legKey string) error

ValidateProviderCostClaim checks narrow B2a claim metadata for one legacy provider posting against its canonical identity (ProviderCostSourceKey of the sealed leg key). It does not consult the current marker; the store compares claim epoch to the durable marker to fence stale workers.

func ValidateProviderRevisionClaim

func ValidateProviderRevisionClaim(claim CutoverClaimMetadata, input ProviderCostRevisionInput) error

ValidateProviderRevisionClaim checks narrow B2a claim metadata for one provider revision posting against its canonical revision-specific identity derived from the immutable revision (ProviderRevisionPostingOperationKey). It does not consult the current marker; the store compares claim epoch to the durable marker to fence stale workers. F6: token operation key must bind the revision-specific pin, not merely B-leg lineage.

func WriterVersionForLeg

func WriterVersionForLeg(leg CallLegUsageRecord) (string, error)

WriterVersionForLeg resolves the explicit writer version for one durable call-leg record. Only the existing supported evidence conventions are accepted: EvidenceVersion 0 with no V2 envelope and no auxiliary economic provenance selects the V1 writer; EvidenceVersion 2 with the V1 compatibility projection label selects the V2 writer. Unknown versions (including 1, 3, 999), contradictory projections, and incompatible auxiliary provenance fail closed as ambiguous, aligned with CallLegUsageRecord validation rather than future-format guessing.

Types

type ALegAdjustmentRef

type ALegAdjustmentRef struct {
	TransactionID string
	Amount        Money
	Validated     bool
}

ALegAdjustmentRef is one pass-through journal in the distinct customer adjustment plane. Amounts here never enter retail totals. Validated is true only when head-anchored pass-through authority admitted this lineage; otherwise the ref is lineage-only evidence that keeps the call pending/unknown.

type ALegAuthorityScope

type ALegAuthorityScope struct {
	AccountID string
	ALegID    string
	CallID    string
	Currency  string
	// StoreID scopes provider-leg facts to the serving store. Customer
	// authority ignores it; provider authority requires exact agreement.
	StoreID string
}

ALegAuthorityScope is the explicit queried scope threaded through every customer-authority decision. Authority never consults evidence outside these four coordinates plus the operation kind under proof.

type ALegCallStatus

type ALegCallStatus string

ALegCallStatus is the explicit per-call customer authority state. Pending means no settlement proof yet (the call may settle or resume later); unknown means conflicting or stray evidence with an attached issue. Unknown is never a zero amount.

const (
	ALegCallKnown   ALegCallStatus = "known"
	ALegCallPending ALegCallStatus = "pending"
	ALegCallUnknown ALegCallStatus = "unknown"
)

type ALegCallVerdict

type ALegCallVerdict struct {
	Status      ALegCallStatus
	Charge      Money
	Known       bool
	OpKey       string
	Adjustments []ALegAdjustmentRef
}

ALegCallVerdict is the per-call customer authority verdict for one snapshot.

type ALegLegProviderStatus

type ALegLegProviderStatus string

ALegLegProviderStatus is the explicit per-B-leg provider completeness state. Pending means no proof yet; known means proven nonzero operator COGS; known_zero means a proven zero with an explicit basis; unknown means conflicting evidence with an attached issue. Unknown is never zero, and provider economics never enters retail totals.

const (
	ALegProviderPending   ALegLegProviderStatus = "pending"
	ALegProviderKnown     ALegLegProviderStatus = "known"
	ALegProviderKnownZero ALegLegProviderStatus = "known_zero"
	ALegProviderUnknown   ALegLegProviderStatus = "unknown"
)

type ALegMarker

type ALegMarker struct {
	OperationKey         string
	AccountID            string
	OperationKind        string
	SourceKey            string
	Fingerprint          string
	IntegrityFingerprint string
	Currency             string
	Mode                 string
	Before               AccountSnapshot
	After                AccountSnapshot
	SequenceStart        uint64
	SequenceEnd          uint64
}

ALegMarker is one durable operation snapshot fact for the call under proof, already loaded inside the report snapshot transaction.

type ALegPassThroughFacts

type ALegPassThroughFacts struct {
	Head      *ALegPassThroughHead
	Policy    VersionRef
	Marker    ALegMarker
	HasMarker bool
	Snapshots []ALegPassThroughSnapshot
	Journals  []JournalTransaction
}

ALegPassThroughFacts bundles every pass-through fact the shell loads for one retail-known call: the trusted head (nil when absent), the expected charge policy from the call exposure, the selected settlement marker carrying the telescoping base snapshots, the canonical adjustment operation snapshots, and the candidate adjustment journals. Journals for other calls are ignored; the shell partitions by call.

type ALegPassThroughHead

type ALegPassThroughHead struct {
	AccountID              string
	CallID                 string
	ALegID                 string
	SettlementOperationKey string
	OriginalTransactionID  string
	PolicyRef              VersionRef
	MissingCost            CostPassThroughMissingCostPolicy
	SafeBound              Money
	AllowLateAdjustment    bool
	Status                 CostPassThroughSettlementStatus
	PostedAmount           Money
	ProviderLURKey         string
	ProviderValuationID    string
	ProviderRevision       uint64
	ProviderInputHash      string
	HeadVersion            uint64
	Fence                  uint64
	SettlementFingerprint  string
}

ALegPassThroughHead is one trusted durable head fact for the call under proof, already loaded inside the report snapshot transaction.

type ALegPassThroughSnapshot

type ALegPassThroughSnapshot struct {
	OperationKey         string
	SourceKey            string
	Fingerprint          string
	IntegrityFingerprint string
	Currency             string
	Mode                 string
	Before               AccountSnapshot
	After                AccountSnapshot
	SequenceStart        uint64
	SequenceEnd          uint64
}

ALegPassThroughSnapshot is one canonical adjustment operation snapshot fact for the call under proof, already loaded inside the report snapshot transaction.

type ALegPassThroughStatus

type ALegPassThroughStatus string

ALegPassThroughStatus is the per-call pass-through plane state. None means no pass-through involvement; pending means no proof yet; known means complete validated authority; unknown means conflicting evidence with an attached issue.

const (
	ALegPassThroughNone    ALegPassThroughStatus = "none"
	ALegPassThroughPending ALegPassThroughStatus = "pending"
	ALegPassThroughKnown   ALegPassThroughStatus = "known"
	ALegPassThroughUnknown ALegPassThroughStatus = "unknown"
)

type ALegPassThroughVerdict

type ALegPassThroughVerdict struct {
	Status       ALegPassThroughStatus
	PostedAmount Money
	Revision     uint64
	Adjustments  []ALegAdjustmentRef
}

ALegPassThroughVerdict is the per-call pass-through authority verdict for one snapshot. Adjustments carry validated lineage only when Status is known; otherwise they are lineage-only evidence with Validated false or withheld entirely.

type ALegProviderChild

type ALegProviderChild struct {
	ChargeID         string
	HeadKey          string
	Status           ALegLegProviderStatus
	ZeroBasis        string
	Amount           Money
	OperationKey     string
	TransactionID    string
	EvidenceRevision uint64
	ValuationID      string
	InputSetHash     string
}

ALegProviderChild is one independently evaluated provider-charge child: exact charge lineage with its own status, amount, current operation, and revision identity. Only known children contribute to leg and scope totals; entries for other statuses never appear on a known leg (unknown legs carry no child entries at all).

type ALegProviderExecutionFence

type ALegProviderExecutionFence struct {
	StoreID           string
	LineageKey        string
	Authority         string
	OwnerSubjectKind  string
	OwnerHeadKey      string
	OwnerRevision     uint64
	OwnerInputSetHash string
	OwnerFingerprint  string
	Fence             uint64
	LastOperationKey  string
	LastTransactionID string
}

ALegProviderExecutionFence is one durable execution-fence fact for the B-leg lineage under proof. It carries the full persisted owner envelope; the evaluator compares every field against the current head, posting fence, and leg scope.

type ALegProviderFence

type ALegProviderFence struct {
	StoreID               string
	LineageKey            string
	Authority             string
	HeadKey               string
	EvidenceRevision      uint64
	InputSetHash          string
	Fingerprint           string
	Amount                Money
	Fence                 uint64
	LastOperationKey      string
	OriginalTransactionID string
	LastTransactionID     string
}

ALegProviderFence is one durable posting-fence fact: the per-head monetary gate. The execution fence below is the amount-free writer gate shared across the B-leg lineage.

type ALegProviderHead

type ALegProviderHead struct {
	StoreID               string
	AccountID             string
	CallID                string
	HeadKey               string
	SubjectKind           string
	SubjectID             string
	Subject               metering.SubjectRef
	EvidenceRevision      uint64
	InputSetHash          string
	ValuationID           string
	CurrentAmount         Money
	HeadVersion           uint64
	Fence                 uint64
	LastOperationKey      string
	OriginalTransactionID string
	LastTransactionID     string
}

ALegProviderHead is one trusted durable provider-cost head fact for the leg under proof, already loaded inside the report snapshot transaction. SubjectKind/SubjectID carry the durable head columns; Subject carries the decoded subject JSON. The evaluator requires all three to agree.

type ALegProviderLegFacts

type ALegProviderLegFacts struct {
	BLegID          string
	Outcome         LegOutcome
	WorkPending     bool
	RevisionPending bool
	Heads           []ALegProviderHead
	PostingFences   []ALegProviderFence
	ExecutionFences []ALegProviderExecutionFence
	Snapshots       []ALegProviderSnapshot
	Journals        []JournalTransaction
}

ALegProviderLegFacts bundles every provider fact the shell loads for one B-leg: outcome, pending signals, candidate heads, fences, snapshots, and journals. The evaluator filters each class to this leg; facts for other legs are ignored.

type ALegProviderLegVerdict

type ALegProviderLegVerdict struct {
	Status        ALegLegProviderStatus
	Cost          Money
	OperationKey  string
	TransactionID string
	ZeroBasis     string
	Children      []ALegProviderChild
}

ALegProviderLegVerdict is the per-leg provider authority verdict for one snapshot. Cost with its operation lineage is set only when Status is known; ZeroBasis only when it is known_zero.

type ALegProviderSnapshot

type ALegProviderSnapshot struct {
	AccountID            string
	OperationKind        string
	OperationKey         string
	SourceKey            string
	Fingerprint          string
	IntegrityFingerprint string
	Currency             string
	Mode                 string
	Before               AccountSnapshot
	After                AccountSnapshot
	SequenceStart        uint64
	SequenceEnd          uint64
}

ALegProviderSnapshot is one canonical provider operation snapshot fact, already loaded inside the report snapshot transaction. Account and operation kind ride the fact so the evaluator binds snapshots to the queried scope instead of trusting SQL scoping alone.

type ALegProviderTotals

type ALegProviderTotals struct {
	Currency      string
	KnownSubtotal Money
	KnownLegs     int
	PendingLegs   int
	ZeroLegs      int
	UnknownLegs   int
}

ALegProviderTotals is the native-currency operator plane: proven per-leg COGS plus explicit completeness counts over every attributable B-leg in scope, including failed, retry, and loser attempts. Only known legs contribute to KnownSubtotal; pending, zero, and unknown legs never do. Provider totals never affect retail subtotals.

type ALegReport

type ALegReport struct {
	StoreID       string
	AccountID     string
	ALegID        string
	Currency      string
	AsOf          time.Time
	Contributions []ALegReportContribution
	Calls         []ALegReportCall
	// CallCount is the distinct BillingCallID count in scope, which may
	// exceed len(Calls) when calls span pages.
	CallCount  int
	Retail     ALegRetailTotals
	Provider   ALegProviderTotals
	Issues     []ReconciliationIssue
	NextCursor string
}

ALegReport is one page of a rolling A-leg snapshot. Totals and counts cover the whole scope; Contributions carries at most Limit B-leg rows and Calls carries at most Limit call summaries, each paged independently under the one opaque cursor. Closure-only calls and expected-but-missing B-legs stay discoverable through bounded traversal of the call stream. There is intentionally no finality marker: a resumed BillingCallID appears in a later snapshot.

type ALegReportCall

type ALegReportCall struct {
	ALegReportCallSummary
	BLegs []ALegReportLeg
}

ALegReportCall is one call stream row: the summary plus the B-legs of that call present on the current leg page. A call with legs split across leg pages repeats across pages with disjoint leg subsets; union by CallID.

type ALegReportCallSummary

type ALegReportCallSummary struct {
	CallID               BillingCallID
	SessionID            string
	Outcome              TurnOutcome
	ExpectedBLegIDs      []string
	MissingBLegIDs       []string
	Status               ALegCallStatus
	CustomerCharge       Money
	CustomerChargeKnown  bool
	CustomerOperationKey string
	Adjustments          []ALegAdjustmentRef
}

ALegReportCallSummary is the durable parent-call context for one call stream row. CustomerChargeKnown distinguishes a proven zero from an unproven call; MissingBLegIDs names expected B-leg identities with no durable leg row (explicit unresolved lineage, never a synthetic B-leg).

type ALegReportContribution

type ALegReportContribution struct {
	Call                  ALegReportCallSummary
	LegKey                string
	BLegID                string
	Outcome               LegOutcome
	Surfaced              SurfacedState
	BackendID             string
	ProviderID            string
	ModelID               string
	Fingerprint           string
	ProviderStatus        ALegLegProviderStatus
	ZeroBasis             string
	ProviderCost          Money
	ProviderOperationKey  string
	ProviderTransactionID string
	ProviderChildren      []ALegProviderChild
}

ALegReportContribution is one B-leg row on the leg stream with its parent call summary attached. Leg and call streams page independently under the one opaque cursor; consumers union pages by LegKey and CallID. Provider lineage mirrors the leg DTO: cost and operation identity only when the leg status is known, zero basis only when it is known_zero.

type ALegReportLeg

type ALegReportLeg struct {
	BLegID         string
	Outcome        LegOutcome
	Surfaced       SurfacedState
	BackendID      string
	ProviderID     string
	ModelID        string
	Fingerprint    string
	ProviderStatus ALegLegProviderStatus
	ZeroBasis      string
	// ProviderCost is the proven nonzero operator COGS for this leg.
	ProviderCost Money
	// ProviderOperationKey is the canonical operation key of the current
	// head lineage proving ProviderCost.
	ProviderOperationKey string
	// ProviderTransactionID is the latest immutable provider journal of
	// that lineage; empty when the current head posted no journal.
	ProviderTransactionID string
	// ProviderChildren is the deterministic per-provider-charge
	// breakdown, charge-ID ordered. Only known legs carry entries, and
	// only known children contribute to totals.
	ProviderChildren []ALegProviderChild
}

ALegReportLeg is one durable B-leg row with its lineage. ProviderCost with its operation lineage is set only when ProviderStatus is known; ZeroBasis is set only when ProviderStatus is known_zero and names the explicit lineage basis (for example "never_started_not_billable"). ProviderOperationKey is the current operation: journal-backed when the latest revision moved money, snapshot-proved for journal-less zero-delta revisions. ProviderTransactionID is the last monetary journal, which may be older than the current operation; it is empty only when no monetary journal was ever posted, and never fabricated. Recorded-zero verdicts carry the proved current operation with an empty transaction; other zero bases carry lineage only through ZeroBasis. ProviderChildren carries the deterministic per-charge breakdown for multi-charge legs (charge order); it is empty for aggregate legs and for any non-known leg.

type ALegReportQuery

type ALegReportQuery struct {
	AccountID string
	ALegID    string
	Limit     int
	Cursor    string
}

ALegReportQuery scopes one rolling snapshot page to StoreID (implicit in the serving store handle) + AccountID + ALegID. Cursor is opaque; callers must not construct or interpret it.

func (ALegReportQuery) Normalize

func (q ALegReportQuery) Normalize() (ALegReportQuery, error)

Normalize trims scope, applies the default limit, and rejects unbounded or unscoped queries. The opaque cursor is preserved byte-for-byte: callers must supply the exact token from a prior page, and the decoder at the store boundary rejects any non-canonical form, including whitespace.

type ALegReportReader

type ALegReportReader interface {
	QueryALegReport(context.Context, ALegReportQuery) (ALegReport, error)
}

ALegReportReader is the consumer-owned billing query seam for rolling A-leg snapshots. Implementations must serve the current snapshot inside one read-only transaction with a dialect-compatible repeatable snapshot, and must not mutate accounting state.

type ALegRetailTotals

type ALegRetailTotals struct {
	Currency      string
	KnownSubtotal Money
	SettledCalls  int
	PendingCalls  int
	UnknownCalls  int
}

ALegRetailTotals is the native-currency customer plane: proven per-call charges only, never multiplied by B-leg count.

type Account

type Account struct {
	ID          string
	Currency    string
	Mode        AccountMode
	CreditLimit int64
	BalanceNano int64
	Version     uint64
	State       AccountState
}

func (Account) ApplyBalanceDelta

func (a Account) ApplyBalanceDelta(delta Money) (Account, error)

func (Account) CreditFloorNano

func (a Account) CreditFloorNano() int64

func (Account) Spendable

func (a Account) Spendable() (Money, error)

func (Account) SpendableNano

func (a Account) SpendableNano() (int64, error)

func (Account) Validate

func (a Account) Validate() error

type AccountMode

type AccountMode string
const (
	AccountPrepaid  AccountMode = "prepaid"
	AccountPostpaid AccountMode = "postpaid"
)

type AccountProvisioner

type AccountProvisioner interface {
	CreateAccount(context.Context, Account) error
	PostFunding(context.Context, FundingInput) (Posting, error)
	ChangeCreditPolicy(context.Context, CreditPolicyInput) (PolicyChange, error)
}

type AccountReport

type AccountReport struct {
	Account         Account
	SpendableNano   int64
	CreditFloorNano int64
	OpenExposure    Money
	Transactions    []JournalTransaction
	NextCursor      uint64
}

type AccountSnapshot

type AccountSnapshot struct {
	BalanceNano     int64
	SpendableNano   int64
	CreditFloorNano int64
	CreditLimitNano int64
	Mode            AccountMode
	Currency        string
	Version         uint64
}

type AccountState

type AccountState string
const (
	AccountReady             AccountState = "ready"
	AccountReconcileRequired AccountState = "reconcile_required"
)

type AccountStatePage

type AccountStatePage struct {
	Items      []Account
	NextCursor string
}

type AccountStore

type AccountStore interface {
	CreditScreenStore
	AccountProvisioner
}

AccountStore combines account lookup and provisioner capabilities.

type AccountingBinaryCapability

type AccountingBinaryCapability struct {
	SupportsV1Reader bool
	SupportsV2Reader bool
	EpochAware       bool
}

AccountingBinaryCapability declares the accounting format/epoch-reader capability one serving binary proves at startup. SupportsV1Reader covers the historical V1 writer lineage; SupportsV2Reader covers V2 source- separated formats; EpochAware covers marker version/epoch claim fencing (a V2 reader without epoch fencing could double-post across an epoch change, so it is not a compatible V2 binary).

func CurrentAccountingBinaryCapability

func CurrentAccountingBinaryCapability() AccountingBinaryCapability

CurrentAccountingBinaryCapability returns the capability of this binary: both reader lineages plus epoch fencing.

func (AccountingBinaryCapability) SupportsFloor

func (c AccountingBinaryCapability) SupportsFloor(floor string) bool

SupportsFloor reports whether the capability may operate a store whose durable compatibility floor is floor. Unknown future floors are never supported: a binary must not silently serve financial state it cannot parse.

func (AccountingBinaryCapability) Validate

func (c AccountingBinaryCapability) Validate() error

Validate fails closed unless the capability can serve at least one accounting lineage.

type AccountingCutoverMarker

type AccountingCutoverMarker struct {
	StoreID            string
	Generation         int
	State              AccountingCutoverState
	ActivePostingOwner string
	CompatibilityFloor string
	Version            uint64
	Epoch              uint64
	TransitionID       string
	CreatedAtUnix      int64
	UpdatedAtUnix      int64
}

AccountingCutoverMarker is the durable per-store cutover row.

func DefaultAccountingCutoverMarker

func DefaultAccountingCutoverMarker(storeID string, nowUnix int64) (AccountingCutoverMarker, error)

DefaultAccountingCutoverMarker returns the safe legacy default for stores with no marker: V1 remains the sole posting authority (generation 1, version/epoch 1). nowUnix carries the auditable creation timestamp and must be positive.

func ValidateAccountingCutoverTransition

func ValidateAccountingCutoverTransition(current AccountingCutoverMarker, req AccountingCutoverTransition, nowUnix int64) (AccountingCutoverMarker, error)

ValidateAccountingCutoverTransition checks one monotonic forward step and builds the next marker. Stale expected version/epoch fails with ErrAccountingCutoverFence; skipped/backward/same-state/unknown targets fail with ErrAccountingCutoverInvalid. nowUnix becomes the next UpdatedAt and must be positive.

func (AccountingCutoverMarker) Validate

func (m AccountingCutoverMarker) Validate() error

Validate fails closed on any malformed or inconsistent marker.

type AccountingCutoverState

type AccountingCutoverState string
const (
	AccountingCutoverV1Active   AccountingCutoverState = "v1_active"
	AccountingCutoverV2Shadow   AccountingCutoverState = "v2_shadow"
	AccountingCutoverV1Draining AccountingCutoverState = "v1_draining"
	AccountingCutoverV2Active   AccountingCutoverState = "v2_active"
)

func (AccountingCutoverState) Valid

func (s AccountingCutoverState) Valid() bool

Valid reports whether the state is one of the four approved cutover states.

type AccountingCutoverTransition

type AccountingCutoverTransition struct {
	ExpectedVersion uint64
	ExpectedEpoch   uint64
	NextState       AccountingCutoverState
	TransitionID    string
}

AccountingCutoverTransition is the narrow CAS request later 17.3B consumes.

func (AccountingCutoverTransition) Validate

func (t AccountingCutoverTransition) Validate() error

Validate fails closed on malformed CAS requests.

type AccountingRecoverySnapshot

type AccountingRecoverySnapshot struct {
	StoreID              string
	MarkerFound          bool
	Marker               AccountingCutoverMarker
	HasV2MonetaryPosting bool
}

AccountingRecoverySnapshot is the durable per-store recovery input for one deployment/store boundary. MarkerFound is false for legacy stores that predate the cutover marker; those stores converge on the explicit V1 floor. HasV2MonetaryPosting reports durable V2 financial authority (V2-owned posting pins or V2-owned monetary work), never shadow capture or pending evidence-only work.

func (AccountingRecoverySnapshot) EffectiveFloor

func (s AccountingRecoverySnapshot) EffectiveFloor() string

EffectiveFloor returns the compatibility floor governing the store: the durable marker floor when present, otherwise the legacy V1 default.

func (AccountingRecoverySnapshot) Validate

func (s AccountingRecoverySnapshot) Validate() error

Validate fails closed on malformed snapshots. A present marker must be internally consistent; the store scope is always required.

type AcquirePostingPinRequest

type AcquirePostingPinRequest struct {
	Kind                  PostingOperationKind
	AccountID             string
	CallID                BillingCallID
	Subject               metering.SubjectRef
	HeadKey               string
	Owner                 string
	ExpectedMarkerVersion uint64
	ExpectedMarkerEpoch   uint64
}

AcquirePostingPinRequest pins one logical operation to one owner under the caller's observed marker epoch. The store derives the canonical operation key; callers never supply weak IDs.

func (AcquirePostingPinRequest) Validate

func (r AcquirePostingPinRequest) Validate() error

Validate fails closed on malformed pin acquisition requests.

type AdjustmentDirection

type AdjustmentDirection string
const (
	AdjustmentCredit AdjustmentDirection = "credit"
	AdjustmentDebit  AdjustmentDirection = "debit"
)

func (AdjustmentDirection) Valid

func (d AdjustmentDirection) Valid() bool

type AdjustmentInput

type AdjustmentInput struct {
	AccountID string
	Amount    Money
	Direction AdjustmentDirection
	SourceKey string
	Reason    string
	// PostingOwner selects the B1 pin owner for the B2b4 financial adjustment
	// fence. Empty preserves the legacy V1 default for backward compatibility.
	// Draining forbids new adjustments; v2_active permits only V2.
	PostingOwner string
	// Claim carries the B2a worker-claim metadata (owner/epoch) captured at
	// claim time. When present, posting validates it against the current
	// marker and pin to close TOCTOU between claim and posting. Nil preserves
	// legacy direct calls in v1_active/shadow.
	Claim *CutoverClaimMetadata
}

func (AdjustmentInput) Fingerprint

func (in AdjustmentInput) Fingerprint() (string, error)

func (AdjustmentInput) Validate

func (in AdjustmentInput) Validate() error

type AdmitExposureInput

type AdmitExposureInput struct {
	AccountID       string
	CallID          string
	Max             Money
	PricingRef      VersionRef
	ChargePolicyRef VersionRef
	// RouteTariffs carries the frozen per-route customer tariff bindings
	// quoted for this call. Empty on the legacy scalar path.
	RouteTariffs []RouteTariffBinding
	Now          time.Time
}

func (AdmitExposureInput) SemanticFingerprint

func (in AdmitExposureInput) SemanticFingerprint() (string, error)

type AllocatedCostLine

type AllocatedCostLine struct {
	AllocationID       string
	AllocationVersion  uint64
	AllocationRevision uint64
	Operation          economics.AllocationOperation
	// PayloadHash is the exact canonical fingerprint of the immutable source
	// allocation record (identity plus content). It is retained so a selected
	// valuation's explicit allocation-coverage reference can be verified
	// against the exact allocation revision instead of matching on a reusable
	// id and version alone.
	PayloadHash string
	// Policy is the immutable allocation policy that produced Weight/Share.
	// Keeping it on every expanded line prevents a payable rollup from losing
	// the policy/version that explains its conserved distribution.
	Policy         economics.AllocationPolicyRef
	TargetID       string
	SourceSubject  metering.SubjectRef
	SourceBasis    economics.ValuationBasis
	SourceAmount   *metering.Decimal
	SourceQuantity *metering.Decimal
	Currency       string
	Unit           string
	Target         metering.SubjectRef
	Unallocated    bool
	Informational  bool
	Weight         economics.AllocationFraction
	Share          economics.AllocationFraction
	RoundedAmount  *economics.AllocationRoundedAmount
	// InferenceEligible is deliberately always false. A target B-leg is useful
	// for an explicit allocation's informational linkage only when a real
	// request exists; allocation alone never creates request evidence.
	InferenceEligible bool
	// Redacted is true when the source aggregate economics could not be proven
	// to belong to the requesting scope and were withheld. The line keeps its
	// authoritative membership identity, policy reference and exact shares, so
	// conservation remains auditable without exposing a foreign or unattributed
	// source total or remainder by subtraction.
	Redacted bool
}

AllocatedCostLine is a source-preserving rollup view. SourceAmount or SourceQuantity remains the original exact value and Share remains the exact rational; consumers must not treat this view as provider money or request inference evidence.

func RollupAllocatedCosts

func RollupAllocatedCosts(records []economics.AllocationRecord) ([]AllocatedCostLine, error)

RollupAllocatedCosts expands canonical records into deterministic target lines while retaining each source's basis and ownership. Duplicate exact replay rows are collapsed; a conflicting immutable identity is rejected.

type AllocationRollupIncompleteError

type AllocationRollupIncompleteError struct {
	Status            economics.AllocationSupersessionStatus
	Pending           []economics.AllocationRef
	PendingSupersedes []economics.AllocationRef
	Complete          bool
	Payable           bool
}

AllocationRollupIncompleteError reports the detailed state that prevented the legacy lines-only API from returning a result. Pending ancestry and non-payable or incomplete flags are retained for callers that classify the compatibility failure with errors.As.

func (*AllocationRollupIncompleteError) Error

func (*AllocationRollupIncompleteError) Unwrap

type AllocationRollupResult

type AllocationRollupResult struct {
	Lines             []AllocatedCostLine
	Status            economics.AllocationSupersessionStatus
	Pending           []economics.AllocationRef
	PendingSupersedes []economics.AllocationRef
	// Superseded is the bounded audit set of predecessor references that were
	// authoritatively retired by a resolved successor. It is retained so a
	// scope that loses a contribution to a target-moving replacement can still
	// explain why the contribution is no longer live.
	Superseded []economics.AllocationRef
	Complete   bool
	Payable    bool
}

AllocationRollupResult is the fail-closed rollup view. Pending supersession references are retained for audit and make the view incomplete and non-payable; only resolved active records contribute Lines.

func RollupAllocatedCostsDetailed

func RollupAllocatedCostsDetailed(records []economics.AllocationRecord) (AllocationRollupResult, error)

RollupAllocatedCostsDetailed resolves immutable supersession links and expands only effective active heads. A missing predecessor is not silently treated as resolved: it is returned in Pending and excluded from Lines.

func RollupAllocatedCostsWithStatus

func RollupAllocatedCostsWithStatus(records []economics.AllocationRecord) (AllocationRollupResult, error)

RollupAllocatedCostsWithStatus is an explicit alias for callers that want the pending/completeness state together with the target lines.

type AllocationStore

type AllocationStore interface {
	AppendAllocation(context.Context, economics.AllocationRecord) error
	GetAllocation(context.Context, string, uint64) (economics.AllocationRecord, error)
	ListAllocations(context.Context, economics.AllocationQuery) (economics.AllocationPage, error)
}

AllocationStore is the billing boundary for immutable explicit allocation records. Implementations own persistence; this interface carries no account balance mutation and no provider request debit.

type ApplyCallBillingInput

type ApplyCallBillingInput struct {
	Call          CallUsageRecord
	Exposure      CallExposure
	Result        CallRatingResult
	OperationKind string
	// PostingOwner selects the B1 pin owner for the customer settlement fence.
	// Empty preserves the legacy V1 default for backward compatibility.
	// Draining forbids new pins; v2_active permits only V2.
	PostingOwner string
	// Claim carries the B2a worker-claim metadata (owner/epoch) captured at
	// claim time. When present, settlement validates it against the current
	// marker and pin to close TOCTOU between claim and posting. Nil preserves
	// legacy direct calls in v1_active/shadow; draining/active still fence
	// unpinned/stale work even without a claim.
	Claim *CutoverClaimMetadata
}

type ApplyCostPassThroughRevisionInput

type ApplyCostPassThroughRevisionInput = CostPassThroughRevisionInput

type ApplyCostPassThroughRevisionResult

type ApplyCostPassThroughRevisionResult = CostPassThroughRevisionResult

type ApplyProviderCostInput

type ApplyProviderCostInput struct {
	AccountID string
	CallID    BillingCallID
	Leg       CallLegUsageRecord
	Result    OperatorCostResult
	// PostingOwner selects the B1 pin owner for the provider charge fence.
	// Empty preserves the legacy V1 default for backward compatibility.
	// Draining requires a classified V1 pin plus matching claim metadata;
	// v2_active permits only V2.
	PostingOwner string
	// Claim carries the B2a worker-claim metadata (owner/epoch) captured at
	// claim time. When present, posting validates it against the current
	// marker and pin to close TOCTOU between claim and posting. Nil preserves
	// legacy direct calls in v1_active/shadow; draining fences unpinned/stale
	// work even without a claim, and B2b2 draining requires a matching claim
	// for new postings.
	Claim *CutoverClaimMetadata
}

type AuthoritativeBilling

type AuthoritativeBilling interface {
	CallSettlementStore
	ReportingStore
}

type BalancedJournalIntent

type BalancedJournalIntent struct {
	OperationKey          string
	AccountID             string
	TurnID                string
	ALegID                string
	BLegID                string
	HeadKey               string
	OperationKind         string
	Currency              string
	CorrectionGroupID     string
	ReversalOf            string
	CorrectsTransactionID string
	Entries               []JournalEntry
	Replayed              bool
}

BalancedJournalIntent is one pure two-sided journal posting plan. It uses the existing debit/credit and ledger-account contracts with strictly positive exact amounts; a downward correction reverses the applicable accounts instead of recording a negative gross amount. Entry amounts and transaction IDs are assigned by the durable journal writer.

func (BalancedJournalIntent) IsNoOp

func (i BalancedJournalIntent) IsNoOp() bool

IsNoOp reports a comparable head transition with no monetary delta; such an intent carries no journal entries and writes no journal row.

func (BalancedJournalIntent) Validate

func (i BalancedJournalIntent) Validate() error

Validate checks the two-sided balanced contract with positive gross amounts.

type BillingCallID

type BillingCallID string

func MonetaryEconomicPostingKey

func MonetaryEconomicPostingKey(storeID string, work EconomicRevisionWork) (accountID string, callID BillingCallID, operationKey string, err error)

MonetaryEconomicPostingKey derives the canonical revision-specific provider operation identity for one monetary economic revision (F5+F7). It fails closed for evidence-only work so classifiers never invent pins from customer/reconciliation envelopes. The key is the immutable revision pin (ProviderRevisionPostingOperationKeyForWork using the allocation-aware full hash), not merely B-leg lineage: base legacy charges keep lineage pins, each revision outcome is a distinct pin while heads/fences order lineage.

func NewBillingCallID

func NewBillingCallID() (BillingCallID, error)

func ParseBillingCallID

func ParseBillingCallID(raw string) (BillingCallID, error)

func (BillingCallID) String

func (id BillingCallID) String() string

func (BillingCallID) Validate

func (id BillingCallID) Validate() error

type BillingReconciliationReport

type BillingReconciliationReport struct {
	Financial ReconciliationReport
	Exposure  ExposureReconciliationReport
	OK        bool
}

type BoundComponent

type BoundComponent struct {
	RouteID string
	Kind    string
	Name    string
	Amount  Money
}

type BoundStatementImporter

type BoundStatementImporter struct {
	// contains filtered or unexported fields
}

BoundStatementImporter adapts one authenticated trusted scope to the frozen public economics.StatementImporter seam. The host constructs it from the authenticated import context; the public signature cannot choose or widen the scope, and no SQL, provider or persistence type crosses this boundary.

func NewBoundStatementImporter

func NewBoundStatementImporter(service *StatementImportService, scope TrustedStatementScope) (*BoundStatementImporter, error)

NewBoundStatementImporter constructs a scope-bound adapter. It rejects a missing service or an incomplete scope before any statement is trusted.

func (*BoundStatementImporter) Import

Import implements economics.StatementImporter with the constructor-bound authenticated scope.

type CallExplanation

type CallExplanation struct {
	CallID                 string
	Exposure               ExposureReport
	Closure                CallUsageRecord
	Legs                   []CallLegUsageRecord
	CustomerOperations     []OperationSnapshot
	ProviderCostOperations []OperationSnapshot
	Transactions           []JournalTransaction
	Result                 TurnResultSummary
	Reconciliation         *ReconciliationReport
}

type CallExposure

type CallExposure struct {
	AccountID       string
	CallID          string
	Max             Money
	PricingRef      VersionRef
	ChargePolicyRef VersionRef
	// RouteTariffs carries the frozen per-route customer tariff bindings
	// admitted with this exposure. Empty on the legacy scalar path, which
	// stays bound through the base pricing/policy references alone.
	RouteTariffs []RouteTariffBinding
	Fingerprint  string
	CreatedAt    time.Time
	ClosedAt     time.Time
	Status       ExposureStatus
	Basis        ExposureBasis
}

func EvaluateAdmit

func EvaluateAdmit(account Account, exposures []CallExposure, in AdmitExposureInput) (CallExposure, error)

func (CallExposure) IsOpen

func (e CallExposure) IsOpen() bool

type CallLegUsageReader

type CallLegUsageReader interface {
	ListCallLegUsage(context.Context, BillingCallID) ([]CallLegUsageRecord, error)
}

type CallLegUsageRecord

type CallLegUsageRecord struct {
	Key         string
	Fingerprint string
	CallID      BillingCallID
	// SubmissionID is optional trusted customer scope and is never a provider
	// usage meter. B-leg observations retain the same lineage separately.
	SubmissionID string `json:"SubmissionID,omitempty"`
	ALegID       string
	BLegID       string
	AttemptSeq   int
	BackendID    string
	ProviderID   string
	ModelID      string
	StartedAt    time.Time
	FinishedAt   time.Time
	Outcome      LegOutcome
	Surfaced     SurfacedState
	Evidence     FinalBillingEvidence
	// EvidenceVersion is zero for legacy V1 rows. Version 2 carries the
	// source-separated immutable observations captured for this concrete
	// B-leg; Evidence remains the explicitly labelled V1 projection.
	EvidenceVersion    int                       `json:"evidence_version,omitempty"`
	EvidenceProjection string                    `json:"evidence_projection,omitempty"`
	Observations       []metering.Observation    `json:"observations,omitempty"`
	ObservationRefs    []metering.ObservationRef `json:"observation_refs,omitempty"`
	EvidenceConflicts  []EvidenceConflict        `json:"evidence_conflicts,omitempty"`
	// EconomicEvidenceVersion and EconomicDispositions are an additive,
	// source-separated carrier for connector coverage. The observation payload
	// remains unchanged and is still the only input to meter/charge semantics.
	EconomicEvidenceVersion int                           `json:"economic_evidence_version,omitempty"`
	EconomicDispositions    []EconomicEvidenceDisposition `json:"economic_dispositions,omitempty"`
	OperatorRateRef         VersionRef
	Workload                WorkloadIdentity
}

func SelectRetailBLegs

func SelectRetailBLegs(legs []CallLegUsageRecord, outcome TurnOutcome) ([]CallLegUsageRecord, error)

SelectRetailBLegs exposes the narrow default retail selector without coupling it to supplier COGS attribution. The default surfaced-turn policy selects the surfaced B-leg for a completed call; interrupted calls retain the existing one-logical-accepted-leg ordering rule.

func (CallLegUsageRecord) Clone

Clone returns a deep, caller-owned copy suitable for a terminal snapshot or a durable handoff. It is intentionally additive to the existing immutable record contract and does not expose request payloads.

func (CallLegUsageRecord) HasV2Evidence

func (l CallLegUsageRecord) HasV2Evidence() bool

HasV2Evidence reports whether the record carries an additive V2 envelope.

func (CallLegUsageRecord) Seal

func (CallLegUsageRecord) SemanticFingerprint

func (l CallLegUsageRecord) SemanticFingerprint() (string, error)

SemanticFingerprint computes the immutable evidence hash for a call-leg record.

Fingerprint versions:

  • v1 (legacy): AttemptSeq == 0. The sequence is unknown (pre-fix durable rows have attempt_seq NULL). The byte stream is byte-for-byte identical to the pre-sequence contract so historical fingerprints stay valid.
  • v2 (sequence-aware): AttemptSeq > 0. The exact b2bua.BLegRecord.Seq is a financial fact and participates in replay identity, so a same-key replay with a different sequence fingerprints differently and conflicts.

A zero AttemptSeq never represents a known sequence; the runtime append seam requires a positive sequence for every new record.

func (CallLegUsageRecord) V2ObservationRefs

func (l CallLegUsageRecord) V2ObservationRefs() []metering.ObservationRef

V2ObservationRefs returns a deep slice snapshot of immutable references.

func (CallLegUsageRecord) V2Observations

func (l CallLegUsageRecord) V2Observations() []metering.Observation

V2Observations returns a bounded deep snapshot. V1 callers should continue using Evidence, which is a compatibility projection and not an independent authority.

type CallPostUsageWorker

type CallPostUsageWorker struct {
	// contains filtered or unexported fields
}

func NewCallPostUsageWorker

func NewCallPostUsageWorker(usage CallUsageStore, settlement CallSettlementStore, resolver CallRatingResolver, batch int) (*CallPostUsageWorker, error)

NewCallPostUsageWorker constructs the legacy test-only complete-call worker without a required claim port. It preserves pure test doubles that do not implement GetCutoverClaimMetadata. Production compositions must use NewCallPostUsageWorkerWithClaim.

func NewCallPostUsageWorkerWithClaim

func NewCallPostUsageWorkerWithClaim(usage CallUsageStore, settlement CallSettlementStore, resolver CallRatingResolver, claimProvider CutoverClaimMetadataProvider, batch int) (*CallPostUsageWorker, error)

NewCallPostUsageWorkerWithClaim constructs the production complete-call worker with a required B2a claim port. A nil claim provider is rejected so durable/posting compositions cannot silently bypass claim metadata via a decorator hiding the optional interface. Lookup failures other than authorized first acquisition (NotFound) fail closed without posting; they are never swallowed into nil/default owner.

func NewCallPostUsageWorkerWithCutover

func NewCallPostUsageWorkerWithCutover(usage CallUsageStore, settlement CallSettlementStore, resolver CallRatingResolver, claimer ClaimedCompleteCallClaimer, batch int) (*CallPostUsageWorker, error)

NewCallPostUsageWorkerWithCutover constructs the F6+F8 production complete-call worker with a required token-carrying claim port. The claimed item already carries its current-marker token; no optional post-claim lookup occurs. A nil claimer is rejected. Legacy test-only construction remains NewCallPostUsageWorker.

func (*CallPostUsageWorker) ProcessOnce

func (w *CallPostUsageWorker) ProcessOnce(ctx context.Context) error

func (*CallPostUsageWorker) Start

func (w *CallPostUsageWorker) Start(ctx context.Context) error

func (*CallPostUsageWorker) Stop

type CallProviderCostWorker

type CallProviderCostWorker struct {
	// contains filtered or unexported fields
}

func NewCallProviderCostWorker

func NewCallProviderCostWorker(work ProviderCostWorkReader, store ProviderCostStore, resolver ProviderCostResolver, batch int) (*CallProviderCostWorker, error)

func NewCallProviderCostWorkerWithClaim

func NewCallProviderCostWorkerWithClaim(work ProviderCostWorkReader, store ProviderCostStore, resolver ProviderCostResolver, claimProvider ProviderCostWorkClaimStore, batch int) (*CallProviderCostWorker, error)

NewCallProviderCostWorkerWithClaim constructs the production provider-cost worker with a required B2a claim port. A nil claim provider is rejected. Lookup failures other than authorized first acquisition (NotFound) fail closed without posting; they are never swallowed into nil/default owner.

func NewCallProviderCostWorkerWithCutover

func NewCallProviderCostWorkerWithCutover(work ProviderCostWorkReader, store ProviderCostStore, resolver ProviderCostResolver, claimer ClaimedProviderCostWorkClaimer, batch int) (*CallProviderCostWorker, error)

NewCallProviderCostWorkerWithCutover constructs the F6+F8 production provider-cost worker with a required token-carrying claim port. Each claimed item already carries its current-marker token; no optional post-claim lookup occurs. Legacy test-only construction remains NewCallProviderCostWorker.

func (*CallProviderCostWorker) ProcessOnce

func (w *CallProviderCostWorker) ProcessOnce(ctx context.Context) error

func (*CallProviderCostWorker) Start

func (*CallProviderCostWorker) Stop

type CallRatingInput

type CallRatingInput struct {
	Call              CallUsageRecord
	Legs              []CallLegUsageRecord
	MaxCustomerCharge Money
	CustomerPricing   PricingSnapshot
	CustomerPolicy    ChargePolicy
	// ModelPricing carries the effective per backend/model customer pricing
	// cards resolved for the call legs. An empty set means no route/model
	// override exists and the configured default pricing applies to every
	// selected leg. When overrides exist, each selected leg must resolve its
	// own card; a missing applicable card fails rating explicitly rather than
	// silently substituting an unrelated model or the default price.
	//
	// Operator-rate data is deliberately absent from this customer type: it
	// belongs to provider COGS processing only, so provider-cost readiness can
	// never couple into customer settlement.
	ModelPricing []ModelCustomerPricing
	// CustomerTariff and ModelTariffs carry the immutable generic customer
	// tariff material for V2 B-leg retail rating. A legacy-tagged tariff
	// materialized from a scalar pricing card is explicitly mapped component
	// material: V2-owned work rates it through the component path from
	// canonical V2 quantities wherever those semantics are supported, and
	// fails closed where they are not. It never selects the scalar live
	// engine for V2-owned work.
	CustomerTariff economics.TariffSnapshot
	ModelTariffs   []ModelCustomerTariff
	// ProviderCost is used only by an explicit cost-pass-through customer
	// policy. It is never consulted by independent retail rating.
	ProviderCost *CostPassThroughProviderCost
	// PostingOwner selects the durable B1 pin owner this rating is produced
	// for (PostingOwnerV1/PostingOwnerV2). Empty preserves the legacy
	// historical-replay default: V1 scalar for V1-classified legs, V2
	// component (or fail-closed) when V2 quantity evidence is present.
	// Production workers/resolvers must supply the explicit claim owner so
	// V2-owned work can never silently select the scalar live engine and V1
	// drain work stays isolated behind durable V1 ownership.
	PostingOwner string
}

type CallRatingResolver

type CallRatingResolver interface {
	ResolveCallRating(context.Context, CompleteCall, CallExposure) (CallRatingResult, error)
}

type CallRatingResult

type CallRatingResult struct {
	CallID            BillingCallID
	CustomerCharge    Money
	Fingerprint       string
	CustomerValuation economics.Valuation
	// CustomerUnitOperation is an optional customer-owned allowance debit or
	// reservation plan. When supplied, the durable settlement adapter applies it
	// in the same transaction as the monetary customer posting.
	CustomerUnitOperation *CustomerUnitOperation
	// CustomerUnitFallbackCharge is the concrete charge for uncovered units. It
	// is required when the atomic unit result reports a bounded fallback and is
	// checked against that operation's bound before settlement commits.
	CustomerUnitFallbackCharge *Money
	CostPassThrough            *CostPassThroughSettlement
	// RouteTariffs carries the route tariff bindings actually used to rate
	// this call (one entry per rated route). The terminal settlement compares
	// them against the admitted frozen binding before posting. Empty on the
	// scalar legacy and cost-pass-through paths, which use no tariff material.
	RouteTariffs []RouteTariffBinding
}

func RateCall

func RateCall(in CallRatingInput) (CallRatingResult, error)

type CallSettlement

type CallSettlement struct {
	CallID             BillingCallID
	Customer           Posting
	CustomerUnitResult *CustomerUnitOperationResult
	CostPassThrough    *CostPassThroughSettlement
	Replayed           bool
	// Breached reports that the posted customer charge exceeded the admitted
	// exposure maximum. The actual incurred amount is retained in the posting;
	// it is never truncated to the quote. OverrunNano carries the exact
	// excess and is zero when not breached.
	Breached    bool
	OverrunNano int64
}

type CallSettlementStore

type CallSettlementStore interface {
	// ApplyCallBillingResult settles one durably closed BillingCallID. An
	// implementation must reject a constructed-but-not-appended call closure;
	// independent retail has no provisional customer-debit contract.
	ApplyCallBillingResult(context.Context, ApplyCallBillingInput) (CallSettlement, error)
}

type CallUsageReader

type CallUsageReader interface {
	ListCallUsage(context.Context, string) ([]CallUsageRecord, error)
}

type CallUsageRecord

type CallUsageRecord struct {
	SchemaVersion int
	Key           string
	Fingerprint   string
	CallID        BillingCallID
	// SubmissionID is optional trusted customer scope. It is independent from
	// BillingCallID: one A-leg may resume with a new call/submission identity.
	SubmissionID       string `json:"SubmissionID,omitempty"`
	AccountID          string
	ALegID             string
	SessionID          string
	StartedAt          time.Time
	FinishedAt         time.Time
	Outcome            TurnOutcome
	CustomerPricingRef VersionRef
	ChargePolicyRef    VersionRef
	ExpectedBLegIDs    []string
	Workload           WorkloadIdentity
}

func (CallUsageRecord) Seal

func (CallUsageRecord) SemanticFingerprint

func (r CallUsageRecord) SemanticFingerprint() (string, error)

type CallUsageStore

type CallUsageStore interface {
	CompleteCallClaimer
	ClaimCompleteCalls(context.Context, int) ([]CompleteCall, error)
	GetCallExposure(context.Context, BillingCallID) (CallExposure, error)
	RetryCompleteCall(context.Context, BillingCallID, string) error
}

type ChargeComponent

type ChargeComponent struct {
	Name   string
	Amount Money
}

type ChargePolicy

type ChargePolicy struct {
	Ref                    VersionRef
	PricingRef             VersionRef
	Scope                  ChargePolicyScope
	IncludeInputTokens     bool
	IncludeOutputTokens    bool
	IncludeFixedCharges    bool
	IncludeResourceCharges bool
	// Retail freezes the request-scoped B-leg selection used for customer
	// inference quantities. A zero value migrates from Scope for compatibility.
	Retail *RetailSelectionPolicy
}

func (ChargePolicy) Clone

func (p ChargePolicy) Clone() ChargePolicy

Clone returns a detached ChargePolicy snapshot, including its explicit retail selection subset.

func (ChargePolicy) Validate

func (p ChargePolicy) Validate() error

type ChargePolicyScope

type ChargePolicyScope string
const (
	ChargeSurfacedTurn     ChargePolicyScope = "surfaced_turn"
	ChargeAllPotentialLegs ChargePolicyScope = "all_potential_legs"
)

type ChargeRoute

type ChargeRoute struct {
	ID                          string
	Pricing                     PricingSnapshot
	ModelMaxOutputTokens        int64
	ModelMaxOutputTokensPresent bool
	ClientMaxOutputTokens       *int64
	FixedCharges                []ChargeComponent
	ResourceCharges             []ChargeComponent
}

type CheapCreditScreen

type CheapCreditScreen struct {
	Store                   CreditScreenStore
	Currency                string
	MinPreRouteHeadroomNano int64
}

func (CheapCreditScreen) Check

func (s CheapCreditScreen) Check(ctx context.Context, accountID string) error

type ClaimedCompleteCall

type ClaimedCompleteCall struct {
	Call  CompleteCall
	Claim CutoverClaimMetadata
}

ClaimedCompleteCall pairs one durably claimed complete call with its current-marker cutover token. The token is issued atomically with the claim-status transition; it is not an optional post-claim lookup.

func (ClaimedCompleteCall) Validate

func (c ClaimedCompleteCall) Validate() error

Validate fails closed when the claimed call or its token is malformed or cross-wired.

type ClaimedCompleteCallClaimer

type ClaimedCompleteCallClaimer interface {
	ClaimCompleteCallsWithCutover(ctx context.Context, limit int) ([]ClaimedCompleteCall, error)
}

ClaimedCompleteCallClaimer is the production token-carrying claim port for customer settlement. Implementations must atomically claim the call and issue a current-marker token; they must fail closed on operational, cancellation, malformed or ineligible-renewal errors, never returning a nil/default token for draining/active pinned work.

type ClaimedEconomicRevisionWork

type ClaimedEconomicRevisionWork struct {
	Work      EconomicRevisionWork
	WorkClaim EconomicRevisionWorkClaim
	Cutover   *CutoverClaimMetadata
}

ClaimedEconomicRevisionWork pairs one leased economic revision with its cutover token for monetary provider posting. Evidence-only work carries a nil Cutover (no monetary authority); monetary provider work carries a non-nil current-marker token issued atomically with the work lease.

type ClaimedProviderCostWork

type ClaimedProviderCostWork struct {
	Work  ProviderCostWork
	Claim CutoverClaimMetadata
}

ClaimedProviderCostWork pairs one pending B-leg with its current-marker cutover token. The token is issued atomically with the pending-work claim; it is not an optional post-list lookup.

func (ClaimedProviderCostWork) Validate

func (c ClaimedProviderCostWork) Validate() error

Validate fails closed when the work/token pair is malformed or cross-wired.

type ClaimedProviderCostWorkClaimer

type ClaimedProviderCostWorkClaimer interface {
	ClaimProviderCostWorkWithCutover(ctx context.Context, limit int) ([]ClaimedProviderCostWork, error)
}

ClaimedProviderCostWorkClaimer is the production token-carrying claim port for legacy provider work. Implementations must atomically list eligible pending work and issue current-marker tokens; they must fail closed on operational/cancellation/malformed errors and withhold ineligible work (unpinned in draining, V1 in active) without inventing tokens.

type CompleteCall

type CompleteCall struct {
	Closure CallUsageRecord
	Legs    []CallLegUsageRecord
}

func JoinCompleteCall

func JoinCompleteCall(closure CallUsageRecord, legs []CallLegUsageRecord) (CompleteCall, error)

type CompleteCallClaimer

type CompleteCallClaimer interface {
	ClaimCompleteCall(context.Context, BillingCallID) (CompleteCall, error)
}

type CompletePostingPinRequest

type CompletePostingPinRequest struct {
	Kind                    PostingOperationKind
	AccountID               string
	CallID                  BillingCallID
	Subject                 metering.SubjectRef
	HeadKey                 string
	Owner                   string
	ExpectedMarkerVersion   uint64
	ExpectedMarkerEpoch     uint64
	CompletionOperationKey  string
	CompletionTransactionID string
}

CompletePostingPinRequest records the posting outcome for a pinned operation. CompletionOperationKey is the durable journal/snapshot operation identity; CompletionTransactionID is the journal transaction when one exists and may be empty for legitimate no-journal (zero-amount) postings.

func (CompletePostingPinRequest) Validate

func (r CompletePostingPinRequest) Validate() error

Validate fails closed on malformed pin completion requests.

type ComponentComparisonReconciler

type ComponentComparisonReconciler struct{}

ComponentComparisonReconciler is a pure deterministic EconomicJobReconciler over frozen revision outputs. It joins every declared dependency valuation on component identity, reports exact signed provider-minus-local quantity deltas with matched/discrepant/partial/conflict/incomparable status, and carries no balance, journal, exposure, or payable port. It performs no rating, persistence, or policy selection; those remain the surrounding job runner and store seams.

Comparability follows the approved C4/D1 grouping: only genuinely independent local measurement (BasisLocalExpected/E) compares against provider evidence (BasisProviderQuantityLocal/Q or BasisProviderReported/P). Retail/customer-policy (R) may derive from policy-selected provider data (requirement 6.4) and never masquerades as independent local evidence. Subject/payer, coverage and effective measurement context must agree across every dependency valuation; mismatches are explicit incomparable outcomes with typed reasons, never matches. Dependency Completeness/MissingObservations are preserved: equal known subtotals with missing evidence stay partial/incomplete, never complete matched. The join reuses the established canonicalReconciliationCoverageKey/canonicalReconciliationQualifierKey contracts and exact big.Rat arithmetic; it introduces no second reduced interpretation.

func (ComponentComparisonReconciler) ReconcileJob

ReconcileJob resolves every frozen dependency output into local and provider quantity planes and compares them component by component. All outputs are consumed; a result that silently dropped one dependency would be indistinguishable from agreement. Missing quantities stay partial, conflicting duplicates stay conflicts, and incompatible subjects stay incomparable instead of becoming zeros or matches.

F4 comparability gates run before any quantity join, in stable precedence: independent-basis, payer, coverage, then effective measurement context. Each returns an explicit incomparable envelope with empty items (no foreign or non-independent quantities leaked, no unsafe values echoed) when the frozen inputs are not comparable as independent local-versus-provider evidence. Completeness/missing evidence is preserved after the join: equal known subtotals with missing observations or severe incompleteness stay partial/incomplete, never complete matched.

type ComponentQuantityComparison

type ComponentQuantityComparison struct {
	Status   ReconciliationComparisonStatus    `json:"status"`
	Reason   ReconciliationComparisonReason    `json:"reason,omitempty"`
	Complete bool                              `json:"complete"`
	Items    []ComponentQuantityComparisonItem `json:"items"`
}

ComponentQuantityComparison is the bounded, deterministically ordered quantity comparison result for one economic subject context.

func CompareComponentQuantities

func CompareComponentQuantities(local, provider ReconciliationEvidenceSet) (ComponentQuantityComparison, error)

CompareComponentQuantities joins local and provider quantity evidence on the full economic subject, payer/account, charge, coverage, currency, period, effective measurement context and full component key. It computes exact signed/absolute provider-minus-local deltas only for compatible evidence. Incompatible contexts are reported as typed incomparable/partial outcomes, never as matches or zeros.

type ComponentQuantityComparisonItem

type ComponentQuantityComparisonItem struct {
	Key           metering.ComponentKey            `json:"key"`
	Status        ReconciliationComparisonStatus   `json:"status"`
	Reason        ReconciliationComparisonReason   `json:"reason,omitempty"`
	Local         []ReconciliationQuantityEvidence `json:"local,omitempty"`
	Provider      []ReconciliationQuantityEvidence `json:"provider,omitempty"`
	SignedDelta   *metering.Decimal                `json:"signed_delta,omitempty"`
	AbsoluteDelta *metering.Decimal                `json:"absolute_delta,omitempty"`
}

ComponentQuantityComparisonItem is one component outcome. Local/Provider carry every source retained for the component; conflict and duplicate outcomes keep all sources instead of selecting one silently.

type ComponentRater

type ComponentRater = ReferenceRater

ComponentRater is the descriptive name used by billing composition.

func NewComponentRater

func NewComponentRater(snapshot economics.TariffSnapshot) (*ComponentRater, error)

NewComponentRater is an explicit alias for NewReferenceRater.

type CostCompleteness

type CostCompleteness string

CostCompleteness describes whether an operator subtotal contains every attributable payable item. A partial result is useful for reporting, but it is never eligible for a complete payable posting.

const (
	CostCompletenessKnown   CostCompleteness = "known"
	CostCompletenessPartial CostCompleteness = "partial"
)

type CostPassThroughMissingCostPolicy

type CostPassThroughMissingCostPolicy string

CostPassThroughMissingCostPolicy controls the bounded customer outcome when the authoritative provider cost is not available at call settlement. The policy is part of the frozen retail offer; provider readiness never selects this basis implicitly.

const (
	CostPassThroughMissingCostPending     CostPassThroughMissingCostPolicy = "pending"
	CostPassThroughMissingCostProvisional CostPassThroughMissingCostPolicy = "provisional"
)

type CostPassThroughPolicy

type CostPassThroughPolicy struct {
	MissingCost         CostPassThroughMissingCostPolicy
	SafeBound           *Money
	AllowLateAdjustment bool
}

CostPassThroughPolicy is the explicit customer offer for provider-cost pass-through. SafeBound is mandatory for direct rating and is the maximum customer amount that admission/settlement may accept. RateCall may fill it from its already-admitted MaxCustomerCharge when the policy is supplied by a legacy catalog adapter.

func (CostPassThroughPolicy) Clone

func (CostPassThroughPolicy) Validate

func (p CostPassThroughPolicy) Validate() error

type CostPassThroughProviderCost

type CostPassThroughProviderCost struct {
	LURKey        string
	ValuationID   string
	Revision      uint64
	InputHash     string
	Amount        Money
	AmountPresent bool
	Reconciled    bool
	Authoritative bool
}

CostPassThroughProviderCost is a normalized, source-qualified provider amount. It is accepted only when the amount is present, reconciled and authoritative. InputHash is the immutable upstream valuation-input hash; it participates in replay/conflict identity but never substitutes for provider authority.

func (CostPassThroughProviderCost) Clone

func (CostPassThroughProviderCost) SemanticFingerprint

func (p CostPassThroughProviderCost) SemanticFingerprint() (string, error)

func (CostPassThroughProviderCost) Validate

func (p CostPassThroughProviderCost) Validate(expectedCurrency string) error

type CostPassThroughRevisionInput

type CostPassThroughRevisionInput struct {
	AccountID    string
	CallID       BillingCallID
	ProviderCost CostPassThroughProviderCost
	// PostingOwner selects the B1 pin owner for the B2b4 financial adjustment
	// fence. Empty preserves the legacy V1 default for backward compatibility.
	// Draining forbids new revisions; v2_active permits only V2.
	PostingOwner string
	// Claim carries the B2a worker-claim metadata (owner/epoch) captured at
	// claim time. When present, posting validates it against the current
	// marker and pin to close TOCTOU between claim and posting. Nil preserves
	// legacy direct calls in v1_active/shadow; draining fences unpinned/stale
	// work even without a claim.
	Claim *CutoverClaimMetadata
}

CostPassThroughRevisionInput is the store-facing late authoritative revision. Provider computation and trust checks happen before this atomic posting boundary, so no account lock is held while a supplier is queried.

func (CostPassThroughRevisionInput) Validate

func (in CostPassThroughRevisionInput) Validate() error

type CostPassThroughRevisionResult

type CostPassThroughRevisionResult struct {
	CallID         BillingCallID
	Status         CostPassThroughSettlementStatus
	PreviousAmount Money
	CurrentAmount  Money
	Delta          Money
	ProviderCost   CostPassThroughProviderCost
	Posting        Posting
	Applied        bool
	Replayed       bool
	Stale          bool
	Ignored        bool
}

CostPassThroughRevisionResult reports an idempotent head transition. Delta is signed: a negative value credits the customer, while a positive value is a new customer debit.

type CostPassThroughSettlement

type CostPassThroughSettlement struct {
	PolicyRef             VersionRef
	Policy                CostPassThroughPolicy
	Status                CostPassThroughSettlementStatus
	SafeBound             Money
	PostedAmount          Money
	ProviderCost          *CostPassThroughProviderCost
	OriginalTransactionID string
}

CostPassThroughSettlement is frozen customer settlement metadata. The store persists it beside the customer operation and uses PostedAmount as the current head for subsequent revision deltas.

func (CostPassThroughSettlement) Clone

func (CostPassThroughSettlement) SemanticFingerprint

func (s CostPassThroughSettlement) SemanticFingerprint() (string, error)

func (CostPassThroughSettlement) Validate

func (s CostPassThroughSettlement) Validate(expectedCurrency string) error

type CostPassThroughSettlementStatus

type CostPassThroughSettlementStatus string

CostPassThroughSettlementStatus is the customer-side state retained with a cost-pass-through settlement. Pending has no monetary posting, provisional posts the approved bound, and final posts either the authoritative cost or a bound whose policy explicitly forbids later adjustment.

const (
	CostPassThroughSettlementPending     CostPassThroughSettlementStatus = "pending"
	CostPassThroughSettlementProvisional CostPassThroughSettlementStatus = "provisional"
	CostPassThroughSettlementFinal       CostPassThroughSettlementStatus = "final"
)

type CostPassThroughSettlementStore

type CostPassThroughSettlementStore interface {
	ApplyCostPassThroughRevision(context.Context, CostPassThroughRevisionInput) (CostPassThroughRevisionResult, error)
}

CostPassThroughSettlementStore is an optional late-adjustment seam. The customer settlement store remains usable without it, preserving the independent-retail path and older adapters.

type CreditPolicyInput

type CreditPolicyInput struct {
	AccountID   string
	Mode        AccountMode
	Currency    string
	CreditLimit int64
	SourceKey   string
	Reason      string
	EffectiveAt time.Time
}

func (CreditPolicyInput) Fingerprint

func (in CreditPolicyInput) Fingerprint() (string, error)

func (CreditPolicyInput) Validate

func (in CreditPolicyInput) Validate() error

type CreditScreenStore

type CreditScreenStore interface {
	GetAccount(context.Context, string) (Account, error)
}

type CustomerEntitlementStatus

type CustomerEntitlementStatus string

CustomerEntitlementStatus describes the completeness of an authoritative customer-owned allowance row. Partial and missing are not zero balances: callers must not debit either state.

const (
	CustomerEntitlementComplete CustomerEntitlementStatus = "complete"
	CustomerEntitlementPartial  CustomerEntitlementStatus = "partial"
	CustomerEntitlementMissing  CustomerEntitlementStatus = "missing"
	CustomerEntitlementConflict CustomerEntitlementStatus = "conflict"
)

type CustomerOperationKey

type CustomerOperationKey struct {
	AccountID string
	CallID    BillingCallID
}

func NewCustomerOperationKey

func NewCustomerOperationKey(accountID string, callID BillingCallID) (CustomerOperationKey, error)

func (CustomerOperationKey) String

func (k CustomerOperationKey) String() string

type CustomerUnitBalance

type CustomerUnitBalance struct {
	Key       CustomerUnitKey           `json:"key"`
	Status    CustomerEntitlementStatus `json:"status"`
	Granted   *metering.Decimal         `json:"granted,omitempty"`
	Available *metering.Decimal         `json:"available,omitempty"`
	Reserved  *metering.Decimal         `json:"reserved,omitempty"`
	Consumed  *metering.Decimal         `json:"consumed,omitempty"`
	Version   uint64                    `json:"version"`
	Fence     uint64                    `json:"fence"`
}

CustomerUnitBalance is the authoritative customer-owned allowance state. Complete rows satisfy Granted = Available + Reserved + Consumed. Pointer quantities allow an adapter to represent a partial row without turning an unknown quantity into zero.

func (CustomerUnitBalance) Clone

Clone deep-copies decimal pointers and component dimensions.

func (CustomerUnitBalance) Validate

func (b CustomerUnitBalance) Validate() error

Validate rejects incomplete balances for operational use while preserving typed partial/missing states for diagnostics and safe fail-closed decisions.

type CustomerUnitKey

type CustomerUnitKey struct {
	AccountID string                `json:"account_id"`
	PoolID    string                `json:"pool_id"`
	PeriodID  string                `json:"period_id"`
	Component metering.ComponentKey `json:"component"`
}

CustomerUnitKey is the complete identity of one customer-owned unit pool. AccountID, PoolID and PeriodID are deliberately customer scope fields. No provider account, provider window, or utilization gauge is part of this key. Component carries the unit/component and any approved dimensions.

func (CustomerUnitKey) CanonicalKey

func (k CustomerUnitKey) CanonicalKey() (string, error)

CanonicalKey returns the complete deterministic customer-unit identity. It is suitable for an adapter's canonical-key column and must be compared in addition to (rather than replaced by) any hash index.

func (CustomerUnitKey) Equal

func (k CustomerUnitKey) Equal(other CustomerUnitKey) bool

Equal compares normalized customer-unit identities. Invalid keys never compare equal.

func (CustomerUnitKey) IdentityKey

func (k CustomerUnitKey) IdentityKey() (string, error)

IdentityKey returns a deterministic, bounded digest suitable for a balance/operation uniqueness index. The canonical key remains available via CanonicalKey and is the collision-safe comparison identity.

func (CustomerUnitKey) Validate

func (k CustomerUnitKey) Validate() error

Validate checks trusted customer scope and canonical component identity.

type CustomerUnitLedger

type CustomerUnitLedger interface {
	ApplyCustomerUnitOperation(context.Context, CustomerUnitOperation) (CustomerUnitOperationResult, error)
}

CustomerUnitLedger is the sole consumed customer-unit mutation port. An implementation must perform idempotency lookup, row locking, version/fence comparison, transition, reservation binding, and any customer posting in a single authoritative transaction. It intentionally has no GetBalance method: callers cannot accidentally assemble a stale read-then-spend sequence.

type CustomerUnitOperation

type CustomerUnitOperation struct {
	Version               uint32                      `json:"version"`
	OperationID           string                      `json:"operation_id"`
	Key                   CustomerUnitKey             `json:"key"`
	Kind                  CustomerUnitOperationKind   `json:"kind"`
	Source                CustomerUnitOperationSource `json:"source"`
	Quantity              metering.Decimal            `json:"quantity"`
	ReservationID         string                      `json:"reservation_id,omitempty"`
	ExpectedVersion       uint64                      `json:"expected_version"`
	Fence                 uint64                      `json:"fence"`
	MonetaryFallbackBound *Money                      `json:"monetary_fallback_bound,omitempty"`
}

CustomerUnitOperation is the idempotent command consumed by the unit ledger. ExpectedVersion and Fence are checked by the same atomic operation that mutates the row; they are not an invitation to perform a read-then-write sequence in an adapter.

func (CustomerUnitOperation) SemanticFingerprint

func (op CustomerUnitOperation) SemanticFingerprint() (string, error)

SemanticFingerprint identifies the operation payload. Compare-and-fence values are excluded so an identical retried operation can replay after the first transaction has advanced the balance version.

func (CustomerUnitOperation) Validate

func (op CustomerUnitOperation) Validate() error

Validate checks operation identity, source ownership, quantities and compare-and-fence preconditions.

type CustomerUnitOperationKind

type CustomerUnitOperationKind string

CustomerUnitOperationKind is one atomic mutation of a customer unit row.

const (
	CustomerUnitOperationGrant   CustomerUnitOperationKind = "grant"
	CustomerUnitOperationDebit   CustomerUnitOperationKind = "debit"
	CustomerUnitOperationReserve CustomerUnitOperationKind = "reserve"
	CustomerUnitOperationCommit  CustomerUnitOperationKind = "commit"
	CustomerUnitOperationRelease CustomerUnitOperationKind = "release"
)

type CustomerUnitOperationResult

type CustomerUnitOperationResult struct {
	OperationID       string                      `json:"operation_id"`
	Key               CustomerUnitKey             `json:"key"`
	Kind              CustomerUnitOperationKind   `json:"kind"`
	Status            CustomerUnitOperationStatus `json:"status"`
	Replayed          bool                        `json:"replayed"`
	Entitlement       CustomerEntitlementStatus   `json:"entitlement"`
	Before            CustomerUnitBalance         `json:"before"`
	After             CustomerUnitBalance         `json:"after"`
	AppliedQuantity   *metering.Decimal           `json:"applied_quantity,omitempty"`
	UncoveredQuantity *metering.Decimal           `json:"uncovered_quantity,omitempty"`
	FallbackRequired  bool                        `json:"fallback_required"`
	FallbackBound     *Money                      `json:"fallback_bound,omitempty"`
	Fingerprint       string                      `json:"fingerprint"`
	ReservationID     string                      `json:"reservation_id,omitempty"`
}

CustomerUnitOperationResult is the immutable result of one atomic ledger call. FallbackRequired means only the uncovered quantity is eligible for a separately rated monetary charge bounded by FallbackBound.

func ApplyCustomerUnitOperation

func ApplyCustomerUnitOperation(ctx context.Context, ledger CustomerUnitLedger, op CustomerUnitOperation) (CustomerUnitOperationResult, error)

ApplyCustomerUnitOperation validates and invokes exactly one atomic ledger operation. It validates the returned result before exposing it to callers.

func (CustomerUnitOperationResult) ValidateFor

ValidateFor proves that a result belongs to the operation that requested it and that no invalid/negative balance or fallback quantity crossed the port.

type CustomerUnitOperationSource

type CustomerUnitOperationSource string

CustomerUnitOperationSource identifies a customer-owned authority. The provider-account/window source is intentionally absent; unknown values are rejected rather than interpreted as customer credit.

const (
	CustomerUnitOperationSourceCustomerProvisioning CustomerUnitOperationSource = "customer_provisioning"
	CustomerUnitOperationSourceRetailSettlement     CustomerUnitOperationSource = "retail_settlement"
	// CustomerUnitOperationSourceCustomerSettlement is a descriptive alias for
	// callers that use the settlement terminology from the posting boundary.
	CustomerUnitOperationSourceCustomerSettlement CustomerUnitOperationSource = CustomerUnitOperationSourceRetailSettlement
	CustomerUnitOperationSourceCustomerPolicy     CustomerUnitOperationSource = "customer_policy"
)

type CustomerUnitOperationStatus

type CustomerUnitOperationStatus string

CustomerUnitOperationStatus tells an adapter whether it applied or replayed an idempotent command.

const (
	CustomerUnitOperationApplied  CustomerUnitOperationStatus = "applied"
	CustomerUnitOperationReplayed CustomerUnitOperationStatus = "replayed"
)

type CustomerUnitOperationStore

type CustomerUnitOperationStore = CustomerUnitLedger

CustomerUnitOperationStore is a descriptive alias used by adapters that name their durable implementation a store.

type CustomerUnitTransition

type CustomerUnitTransition struct {
	Before          CustomerUnitBalance
	After           CustomerUnitBalance
	Decision        IncludedAllowanceDecision
	AppliedQuantity metering.Decimal
}

CustomerUnitTransition is the pure state transition an atomic adapter runs while holding its balance/reservation transaction. Decision contains the included/fallback split for debit and reserve operations.

func TransitionCustomerUnitBalance

func TransitionCustomerUnitBalance(op CustomerUnitOperation, before CustomerUnitBalance) (CustomerUnitTransition, error)

TransitionCustomerUnitBalance applies one validated operation to one locked balance. It does no I/O, and on failure returns the original state in After.

type CutoverClaimMetadata

type CutoverClaimMetadata struct {
	Kind          PostingOperationKind
	OperationKey  string
	AccountID     string
	CallID        BillingCallID
	Owner         string
	MarkerVersion uint64
	MarkerEpoch   uint64
	MarkerState   AccountingCutoverState
	// WorkID is the economic revision work identity (identity.Key()) for
	// monetary economic leases; empty for customer/provider tokens.
	WorkID string
	// LeaseOwner is the economic lease owner bound to this token; empty for
	// customer/provider tokens.
	LeaseOwner string
	// LeaseFence is the economic lease fence bound to this token; zero for
	// customer/provider tokens.
	LeaseFence uint64
}

CutoverClaimMetadata is the narrow claim eligibility record B2b consumes for posting-time worker checks (including leases waking after an epoch change). It carries the expected owner/epoch/state needed to fence stale workers without re-reading the full pin.

R4 mandatory binding: for economic revision leases the token additionally carries the work identity (WorkID) and the lease fence (LeaseOwner/Fence) issued atomically with the lease. Posting validates the fence against current delivery state before any monetary effect so a reclaimed lease fences the stale token. Customer/provider tokens leave these empty; any partially populated lease binding fails closed as malformed.

func CutoverClaimMetadataForPin

func CutoverClaimMetadataForPin(pin PostingPin) CutoverClaimMetadata

CutoverClaimMetadataForPin derives the narrow B2b claim record from a durable pin.

func CutoverClaimTokenForEconomicLease

func CutoverClaimTokenForEconomicLease(pin PostingPin, marker AccountingCutoverMarker, workID string, lease EconomicRevisionWorkClaim) (CutoverClaimMetadata, error)

CutoverClaimTokenForEconomicLease builds the mandatory current-marker token for one monetary economic lease. Pin owner/identity come from the pin, version/epoch/state come from the locked current marker snapshot, and the work/lease fence come from the atomically acquired lease claim. All three authorities commit in the same transaction; the token is never issued for a different marker than the lease. It fails closed on malformed inputs.

func CutoverClaimTokenForPinAtMarker

func CutoverClaimTokenForPinAtMarker(pin PostingPin, marker AccountingCutoverMarker) (CutoverClaimMetadata, error)

CutoverClaimTokenForPinAtMarker builds the renewable current-marker token for one stable pin. Owner/identity come from the pin (historical ownership); version/epoch/state come from the current marker (lease authority). It does not rewrite the pin. It fails closed on malformed pins/markers.

func (CutoverClaimMetadata) Validate

func (m CutoverClaimMetadata) Validate() error

Validate fails closed on malformed claim metadata. Direct-adjustment pins (B2b4, "financial-adjustment-direct:v1:") carry no call lineage, so empty CallID is canonical there; all other namespaces require a valid call. Lease binding (WorkID/LeaseOwner/LeaseFence) must be all-present or all-absent; any partial binding fails closed as malformed.

type CutoverClaimMetadataProvider

type CutoverClaimMetadataProvider interface {
	GetCutoverClaimMetadata(ctx context.Context, kind PostingOperationKind, operationKey string) (CutoverClaimMetadata, error)
}

CutoverClaimMetadataProvider is the narrow B2a claim port B2b workers consume to pass claim-time owner/epoch to posting-time validation without reread-only TOCTOU. DurableStore implements it; core workers type-assert to it.

type CutoverCoordinatorConfig

type CutoverCoordinatorConfig struct {
	BatchSize  int
	MaxBatches int
}

CutoverCoordinatorConfig bounds draining readers. BatchSize bounds one deterministic page; MaxBatches bounds one Classify call so a huge backlog cannot hold a transaction open.

func NewCutoverCoordinatorConfig

func NewCutoverCoordinatorConfig(batchSize int) (CutoverCoordinatorConfig, error)

NewCutoverCoordinatorConfig validates bounded reader configuration.

type CutoverDrainCounts

type CutoverDrainCounts struct {
	CustomerPending   int
	ProviderPending   int
	AdjustmentPending int
	V1Pinned          int
	V1Completed       int
	Unclassifiable    int
	// OpenExposures counts admitted call_exposures rows with status='open'.
	// F2A: admitted/open V1 calls survive drain; activation cannot succeed
	// while an admitted exposure remains open, even when no closure/leg row
	// or pin exists yet. Closed via terminal settlement (or legitimate
	// cancellation outcome through the same settlement seam); never invented.
	OpenExposures int
	// EconomicProviderPending counts pending/leased monetary provider economic
	// revision work (F2B). Evidence-only customer rating, reconciliation jobs,
	// shadow observations/valuations, and queues without a posting adapter are
	// never counted here.
	EconomicProviderPending int
}

CutoverDrainCounts is the durable precondition snapshot for activation.

type CutoverDrainStatus

type CutoverDrainStatus struct {
	State              AccountingCutoverState
	MarkerVersion      uint64
	MarkerEpoch        uint64
	Counts             CutoverDrainCounts
	Unclassifiable     []CutoverUnclassifiableItem
	ReadyForActivation bool
}

CutoverDrainStatus is the explicit draining result. ReadyForActivation is true only when no pending/leased/uncompleted V1 pins/work remain across all three namespaces and no unclassifiable items exist.

type CutoverUnclassifiableItem

type CutoverUnclassifiableItem struct {
	Namespace string
	Key       string
	Reason    string
}

CutoverUnclassifiableItem records one operation that cannot be safely classified. The coordinator never invents completion for these; the marker remains draining with this explicit status.

type EconomicCurrencyAmount

type EconomicCurrencyAmount struct {
	Currency string `json:"currency"`
	Amount   string `json:"amount"`
}

EconomicCurrencyAmount is one exact native-currency total rendered as an exact rational string (integers without a denominator). Currencies are never converted into each other.

type EconomicDetail

type EconomicDetail struct {
	Scope        EconomicDetailQuery    `json:"scope"`
	Observations []metering.Observation `json:"observations,omitempty"`
	Valuations   []economics.Valuation  `json:"valuations,omitempty"`
	// SelectedValuations is the bounded set of exact frozen selected revisions
	// resolved by authoritative selected identity. It is separate from
	// Valuations so the latest-per-stream display projection is unchanged while
	// cost coverage can still resolve the exact revision a selected head names.
	SelectedValuations []economics.Valuation          `json:"selected_valuations,omitempty"`
	Quantity           *ComponentQuantityComparison   `json:"quantity,omitempty"`
	Monetary           *MonetaryDiscrepancyComparison `json:"monetary,omitempty"`
	// Selection is the singular selection convenience field. It is the
	// caller-supplied full selection when present, otherwise a candidate-less
	// projection of the one unambiguous persisted head. When the scope holds
	// multiple independent heads it stays nil and Totals.SelectedAmbiguous is
	// set; it never represents an invented aggregate or candidate set.
	Selection *OperatorCostSelectionResult `json:"selection,omitempty"`
	// Heads is the authoritative bounded, deterministically ordered set of
	// persisted selected/posted heads with their exact identity, version,
	// frozen selection and transaction/operation lineage. It is never collapsed
	// to one entry.
	Heads          []SelectedCostHead         `json:"heads,omitempty"`
	PerBasisTotals []EconomicDetailBasisTotal `json:"per_basis_totals,omitempty"`
	Totals         EconomicDetailTotals       `json:"totals"`
	Margin         EconomicDetailMargin       `json:"margin"`
	Coverage       EconomicDetailCoverage     `json:"coverage"`
	Payers         EconomicDetailPayers       `json:"payers"`
	Summary        EconomicDetailSummary      `json:"summary"`
	// Reconciliations is the full bounded, deterministically ordered set of
	// independent in-scope subject comparisons. Quantity and Monetary above are
	// the singular convenience projection of the deterministic-first entry that
	// carries a comparison plane; this set is authoritative and is never
	// collapsed to one result.
	Reconciliations []EconomicDetailReconciliation `json:"reconciliations,omitempty"`
	// StatementEvidence is the resolved statement-origin S evidence of the
	// scope, exposed separately from the embedded leg observations. Missing and
	// unattributed references are enumerated inside it, never implied.
	StatementEvidence EconomicDetailStatementEvidence `json:"statement_evidence,omitzero"`
	// ExecutionCoverage is the bounded, deterministically ordered set of
	// authoritative in-scope executed B-leg facts carried from the loaded leg
	// records. It is part of the repeated full-scope snapshot: a leg added,
	// removed or reclassified between pages invalidates the continuation even
	// when it contributed no observation or valuation. It is never a monetary
	// authority.
	ExecutionCoverage []EconomicDetailExecutionLeg `json:"execution_coverage,omitempty"`
	// NextCursor is the opaque continuation token for the next observation
	// page, populated by the durable adapter from NextPosition. Empty means the
	// page is final or empty.
	NextCursor string `json:"next_cursor,omitempty"`
	// NextPosition is the decoded keyset position of this page's last
	// observation. It is a durable-adapter seam, never serialized.
	NextPosition *EconomicObservationPosition `json:"-"`
	// SnapshotFingerprint is the deterministic, bounded fingerprint of the full
	// pre-pagination observation membership and every repeated full-scope fact
	// of this detail. It is a durable-adapter seam and is never serialized.
	SnapshotFingerprint string `json:"-"`
	// PreviousSnapshotFingerprint is the authenticated composed snapshot
	// fingerprint asserted by the incoming continuation, or empty on a first
	// page. The outermost composed reader verifies it before returning a next
	// cursor. It is a durable-adapter seam and is never serialized.
	PreviousSnapshotFingerprint string `json:"-"`
	Truncated                   bool   `json:"truncated"`
}

EconomicDetail is one assembled scoped page. Observations are the Limit page in canonical order; every other fact (valuations, heads, per-basis totals, margin, coverage, payers, summary, reconciliations, selection and statement evidence) is the same full-scope snapshot fact set on every page of one continuation. The continuation is only valid while that full-scope snapshot is unchanged: page one binds an authenticated deterministic fingerprint of the full observation membership and every repeated fact, and a continuation whose recomputed fingerprint differs is rejected as a stale cursor that requires restarting pagination. A caller therefore never consumes a mixed snapshot (for example a resumed call silently omitted while newer totals appear), and monetary aggregation is never duplicated per page.

NextCursor is the opaque, authenticated continuation token for the next page; it is empty exactly on a final or empty page. NextPosition is the decoded form the durable adapter converts into NextCursor; it is not part of the wire contract. Truncated is retained for compatibility and is true exactly when NextPosition is present.

func AssembleEconomicDetail

func AssembleEconomicDetail(in EconomicDetailInput) (EconomicDetail, error)

AssembleEconomicDetail validates scope, bounds and cross-scope identities, then projects the frozen input sets into a deterministic scoped detail.

func (EconomicDetail) ValuationFor

ValuationFor returns the first deterministically ordered valuation for one basis, or nil when the plane is absent. A scoped detail may legitimately retain several independent contributions that share a basis but belong to different subjects; callers that need all of them must iterate Valuations. Planes are never merged.

type EconomicDetailAllocationCoverage

type EconomicDetailAllocationCoverage struct {
	AllocationID      string                                 `json:"allocation_id"`
	AllocationVersion uint64                                 `json:"allocation_version"`
	TargetID          string                                 `json:"target_id,omitempty"`
	State             EconomicDetailCostCoverageState        `json:"state"`
	Reason            EconomicDetailAllocationCoverageReason `json:"reason"`
	Currency          string                                 `json:"currency,omitempty"`
	Redacted          bool                                   `json:"redacted,omitempty"`
}

EconomicDetailAllocationCoverage is the coverage classification of one active attributable monetary allocation line. It carries membership identity, target reference and state only: never a source amount, share or remainder.

type EconomicDetailAllocationCoverageReason

type EconomicDetailAllocationCoverageReason string

EconomicDetailAllocationCoverageReason is the bounded truthful cause of one allocation line's coverage classification. It carries no source or share amount, so an unauthorized allocation can fail closed without leaking economics.

const (
	// EconomicDetailAllocationCoverageIncluded means the exact allocation
	// revision was named by a frozen selected valuation's allocation-coverage
	// reference and is currency-compatible with the selected amount.
	EconomicDetailAllocationCoverageIncluded EconomicDetailAllocationCoverageReason = "included"
	// EconomicDetailAllocationCoverageKnownZero means the allocation carries an
	// exact canonical zero, so it cannot move the margin.
	EconomicDetailAllocationCoverageKnownZero EconomicDetailAllocationCoverageReason = "known_zero"
	// EconomicDetailAllocationCoverageNotIncluded means the allocation is
	// positive and no frozen selected result proves it included.
	EconomicDetailAllocationCoverageNotIncluded EconomicDetailAllocationCoverageReason = "not_included"
	// EconomicDetailAllocationCoverageCurrencyMismatch means the allocation's
	// native currency differs from the selected amount's currency, so no
	// selected inclusion can be asserted without a frozen conversion basis.
	EconomicDetailAllocationCoverageCurrencyMismatch EconomicDetailAllocationCoverageReason = "currency_mismatch"
	// EconomicDetailAllocationCoverageRedactedSource means the source aggregate
	// was withheld as unauthorized, so inclusion can neither be proven nor
	// exempted and the allocation fails closed without exposing an amount.
	EconomicDetailAllocationCoverageRedactedSource EconomicDetailAllocationCoverageReason = "redacted_source"
)

type EconomicDetailAllocationState

type EconomicDetailAllocationState struct {
	Status            economics.AllocationSupersessionStatus `json:"status,omitempty"`
	Complete          bool                                   `json:"complete"`
	Payable           bool                                   `json:"payable"`
	Pending           []economics.AllocationRef              `json:"pending,omitempty"`
	PendingSupersedes []economics.AllocationRef              `json:"pending_supersedes,omitempty"`
	Superseded        []economics.AllocationRef              `json:"superseded,omitempty"`
	Redacted          bool                                   `json:"redacted,omitempty"`
}

EconomicDetailAllocationState is the truthful correction state of the bounded allocation lineage backing Coverage.Allocations. It is separate from the line slice because the lines are the effective, in-scope contributions while pending ancestry, retired predecessors, completeness and payable state explain why that contribution set may be partial or missing. Every retained reference is an immutable allocation identity plus payload hash, never money, a source aggregate or a remainder. Redacted is true when at least one retained line had unauthorized (account-less) source economics withheld.

type EconomicDetailBasisPayer

type EconomicDetailBasisPayer struct {
	Basis economics.ValuationBasis `json:"basis"`
	Payer metering.PaymentParty    `json:"payer,omitzero"`
}

EconomicDetailBasisPayer binds one valuation plane to its trusted payer.

type EconomicDetailBasisTotal

type EconomicDetailBasisTotal struct {
	Basis          economics.ValuationBasis    `json:"basis"`
	ValuationID    string                      `json:"valuation_id"`
	CurrencyTotals []economics.CurrencyTotal   `json:"currency_totals"`
	Completeness   economics.Completeness      `json:"completeness"`
	Payer          metering.PaymentParty       `json:"payer,omitzero"`
	Rater          economics.RatingSnapshotRef `json:"rater"`
	Tariff         economics.RatingSnapshotRef `json:"tariff"`
	Policy         economics.PolicySnapshotRef `json:"policy"`
}

EconomicDetailBasisTotal preserves one valuation plane's native totals verbatim for audit without merging planes.

type EconomicDetailCostCoverage

type EconomicDetailCostCoverage struct {
	Subjects        []EconomicDetailCostSubject `json:"subjects,omitempty"`
	UnresolvedCount int                         `json:"unresolved_count"`
	// AllocationCoverage classifies every active attributable monetary
	// allocation line against the singular selected result. An allocation is
	// never added to the selected amount or margin; it only participates in
	// completeness.
	AllocationCoverage []EconomicDetailAllocationCoverage `json:"allocation_coverage,omitempty"`
	// AllocationUnresolvedCount counts active attributable monetary allocations
	// that are neither proven included nor a canonical explicit zero.
	AllocationUnresolvedCount int  `json:"allocation_unresolved_count,omitempty"`
	Complete                  bool `json:"complete"`
}

EconomicDetailCostCoverage is the bounded, deterministic, deduped full-scope cost-coverage projection. UnresolvedCount counts subjects with no authoritative coverage; AllocationUnresolvedCount counts active attributable monetary allocations with no explicit selected-result inclusion proof. Complete is true exactly when every attributable operator-payable cost subject is covered, explicitly known-zero, customer-BYOK or proven inclusive and every active attributable monetary allocation is either proven included or a canonical explicit zero. The projection is part of the snapshot fingerprint, so a between-page uncovered charge or allocation invalidates an outstanding continuation and the current page margin stays incomplete.

type EconomicDetailCostCoverageState

type EconomicDetailCostCoverageState string

EconomicDetailCostCoverageState classifies why one attributable in-scope cost subject is or is not covered by the singular authoritative selected result.

const (
	// EconomicDetailCostCoverageSelected names the subject of the singular
	// authoritative selected result itself.
	EconomicDetailCostCoverageSelected EconomicDetailCostCoverageState = "selected"
	// EconomicDetailCostCoverageInclusive names a subject proven contained in
	// the selected result through an explicit inclusive charge-coverage edge.
	EconomicDetailCostCoverageInclusive EconomicDetailCostCoverageState = "inclusive"
	// EconomicDetailCostCoverageHead names a subject with its own authoritative
	// frozen selected/posted head, so it is independently valued.
	EconomicDetailCostCoverageHead EconomicDetailCostCoverageState = "authoritative_head"
	// EconomicDetailCostCoverageKnownZero names a subject whose only
	// operator-attributable charges are explicitly reported as exactly zero.
	EconomicDetailCostCoverageKnownZero EconomicDetailCostCoverageState = "known_zero"
	// EconomicDetailCostCoverageBYOK names a subject whose attributable charges
	// are all customer-paid, so no operator payable exists.
	EconomicDetailCostCoverageBYOK EconomicDetailCostCoverageState = "customer_byok"
	// EconomicDetailCostCoverageUnresolved names an attributable operator-payable
	// or unpriced subject with no authoritative coverage in the selected result.
	EconomicDetailCostCoverageUnresolved EconomicDetailCostCoverageState = "unresolved"
	// EconomicDetailCostCoverageNeverStarted names an authoritative leg whose
	// canonical outcome proves it never began execution, so it carries no
	// operator exposure (parent design C4: proven never-started work may be
	// known zero with its basis).
	EconomicDetailCostCoverageNeverStarted EconomicDetailCostCoverageState = "never_started"
	// EconomicDetailCostCoverageNonbillable names an authoritative leg whose
	// canonical outcome proves the provider never accepted billable execution
	// (a rejected attempt), so it carries no operator exposure.
	EconomicDetailCostCoverageNonbillable EconomicDetailCostCoverageState = "nonbillable"
)

type EconomicDetailCostSubject

type EconomicDetailCostSubject struct {
	Subject         metering.SubjectRef             `json:"subject"`
	State           EconomicDetailCostCoverageState `json:"state"`
	OperatorPayable bool                            `json:"operator_payable"`
	ChargeItemIDs   []string                        `json:"charge_item_ids,omitempty"`
}

EconomicDetailCostSubject is one attributable executed in-scope cost subject with its bounded coverage classification. ChargeItemIDs lists the observed charge identities that made the subject attributable to the operator.

type EconomicDetailCoverage

type EconomicDetailCoverage struct {
	MissingRefs        []metering.ObservationRef    `json:"missing_refs,omitempty"`
	MissingCount       int                          `json:"missing_count"`
	AggregateCharges   []metering.ReportedCharge    `json:"aggregate_charges,omitempty"`
	AggregateOnly      bool                         `json:"aggregate_only"`
	CoverageRefs       []metering.ChargeCoverageRef `json:"coverage_refs,omitempty"`
	NonRequestSubjects []metering.SubjectRef        `json:"non_request_subjects,omitempty"`
	Allocations        []AllocatedCostLine          `json:"allocations,omitempty"`
	// AllocationState is the bounded correction/completeness state of the
	// allocation lineage that produced Allocations. It is populated whenever an
	// authoritative in-scope allocation lineage exists, even when no line is
	// effective, so a superseded, pending or redacted contribution is never
	// silently reported as an absent or complete allocation set.
	AllocationState *EconomicDetailAllocationState `json:"allocation_state,omitempty"`
	// CostCoverage is the bounded full-scope projection of attributable executed
	// in-scope cost subjects and charge identities. It is the marker that lets
	// margin completeness prove every operator-payable cost is either covered by
	// the single authoritative selected result, explicitly known-zero,
	// customer-BYOK, or proven inclusively covered. A Complete margin requires
	// CostCoverage.Complete.
	CostCoverage *EconomicDetailCostCoverage `json:"cost_coverage,omitempty"`
}

EconomicDetailCoverage surfaces missing evidence, aggregate-only charges, account-period subjects and conserved allocations without inventing per-request allocations.

type EconomicDetailExecutionLeg

type EconomicDetailExecutionLeg struct {
	Subject    metering.SubjectRef `json:"subject"`
	AttemptSeq int                 `json:"attempt_seq,omitempty"`
	Outcome    LegOutcome          `json:"outcome"`
	Surfaced   SurfacedState       `json:"surfaced,omitempty"`
	// AcceptedEvidence is a presence-only fact: the leg's canonical V1 evidence
	// carries an authoritative provider cost or at least one accepted quantity.
	AcceptedEvidence bool `json:"accepted_evidence,omitempty"`
	// AuthoritativeZeroCost is true only for an explicit authoritative provider
	// cost of exactly zero, which is a definite known-zero cost rather than a
	// missing or estimated one.
	AuthoritativeZeroCost bool `json:"authoritative_zero_cost,omitempty"`
}

EconomicDetailExecutionLeg is one bounded, provider-neutral execution fact carried from an already-loaded authoritative call-leg record into assembly. It carries only canonical lineage, outcome and evidence-presence/authority classification: never a measurement, token count or amount, and missing evidence is never turned into zero. It exists so an executed/attempted B-leg whose embedded observations are absent, empty or unusable still participates in cost completeness; parent design C4 says attempted work without accepted provider evidence is unknown, not reconciled zero.

func NewEconomicDetailExecutionLeg

func NewEconomicDetailExecutionLeg(subject metering.SubjectRef, attemptSeq int, outcome LegOutcome, surfaced SurfacedState, evidence FinalBillingEvidence) EconomicDetailExecutionLeg

NewEconomicDetailExecutionLeg classifies one already-loaded authoritative leg record into a bounded execution fact. The classification reads only canonical evidence presence and authority, never a value, so no measurement or amount is invented and absent evidence stays absent.

func (EconomicDetailExecutionLeg) Validate

func (l EconomicDetailExecutionLeg) Validate() error

Validate bounds one execution fact without requiring the source leg.

type EconomicDetailInput

type EconomicDetailInput struct {
	Query EconomicDetailQuery
	// After is the decoded continuation position of an authenticated cursor, or
	// nil for the first page. When set, assembly returns only observations
	// strictly after it in the canonical order. It is never trusted raw: the
	// durable adapter authenticates the opaque token and validates the decoded
	// position before assembly.
	After        *EconomicObservationPosition
	Observations []metering.Observation
	Valuations   []economics.Valuation
	// SelectedValuations is the bounded set of exact frozen selected
	// valuations resolved by their authoritative durable selected identity
	// (valuation id plus canonical input-set hash). It is deliberately separate
	// from Valuations so the latest-per-stream display projection is unchanged
	// while cost coverage can resolve the exact frozen revision a selected head
	// names even when a newer revision of the same stream exists. Age is
	// ordering, never identity: a submitted candidate is matched only by its
	// exact immutable id and input-set hash.
	SelectedValuations []economics.Valuation
	Quantity           *ComponentQuantityComparison
	Monetary           *MonetaryDiscrepancyComparison
	Selection          *OperatorCostSelectionResult
	Heads              []SelectedCostHead
	TurnSummary        *TurnResultSummary
	RetailTotals       *ALegRetailTotals
	ProviderTotals     *ALegProviderTotals
	Allocations        []AllocatedCostLine
	// AllocationState is the correction/completeness state of the allocation
	// lineage that produced Allocations. It is optional; when supplied it is
	// bounded, scope-validated and projected verbatim into Coverage so a
	// superseded, pending or redacted contribution is explicit rather than
	// implied by an empty or partial line slice.
	AllocationState *EconomicDetailAllocationState
	// Reconciliations is the bounded set of independently identified
	// reconciliation comparisons, one per authoritative in-scope subject. When
	// non-empty it is authoritative: the singular Quantity/Monetary inputs
	// above are ignored and the output's singular convenience fields are
	// projected from the deterministic-first entry that carries a comparison
	// plane. Supply either the set or the singular inputs, not both.
	Reconciliations []EconomicDetailReconciliation
	// ExecutionCoverage is the bounded set of authoritative in-scope executed
	// B-leg facts the durable reader already loaded. Each fact is a provider-
	// neutral execution identity/outcome/evidence-presence classification that
	// keeps an executed leg without materialized observations from disappearing
	// from cost completeness. Attempted work without accepted provider evidence
	// stays unresolved; only canonical never-started/nonbillable/known-zero
	// proof exempts it. It carries no measurement or amount.
	ExecutionCoverage []EconomicDetailExecutionLeg
	// StatementEvidence is the source-separated statement-origin S evidence
	// resolved through a consumer-owned exact observation source. It is
	// optional; nil means no statement reader was composed and is projected as
	// an explicit unavailable reader rather than as absent evidence.
	StatementEvidence *EconomicDetailStatementEvidence
}

EconomicDetailInput is the frozen assembly input. Observations and valuations carry full source separation; comparisons, selection and heads carry their own statuses for echo without recomputation. Summaries are existing projections echoed verbatim, never reinterpreted.

type EconomicDetailMargin

type EconomicDetailMargin struct {
	Currency string               `json:"currency,omitempty"`
	Amount   *MonetaryExactAmount `json:"amount,omitempty"`
	Complete bool                 `json:"complete"`
	Reason   string               `json:"reason"`
}

EconomicDetailMargin is explicit incomplete margin. Amount is present only when Complete is true; otherwise Reason names the bounded cause.

type EconomicDetailPayers

type EconomicDetailPayers struct {
	ByBasis            []EconomicDetailBasisPayer `json:"by_basis,omitempty"`
	Distinct           []metering.PaymentParty    `json:"distinct,omitempty"`
	HasOperatorPayable bool                       `json:"has_operator_payable"`
	HasCustomerBYOK    bool                       `json:"has_customer_byok"`
	HasUnallocated     bool                       `json:"has_unallocated"`
}

EconomicDetailPayers makes BYOK payment responsibility explicit. Retail customer policy payers do not count as BYOK; only provider-side customer payers on E/Q/P/S planes do.

type EconomicDetailQuery

type EconomicDetailQuery struct {
	StoreID       string `json:"store_id"`
	TenantID      string `json:"tenant_id,omitempty"`
	AccountID     string `json:"account_id"`
	BillingCallID string `json:"billing_call_id,omitempty"`
	ALegID        string `json:"a_leg_id,omitempty"`
	Limit         int    `json:"limit,omitempty"`
	Cursor        string `json:"cursor,omitempty"`
}

EconomicDetailQuery scopes one call or A-leg economic detail page to StoreID + AccountID plus exactly one primary continuity identity. A call query carries BillingCallID with an optional ALegID continuity check; an A-leg query carries ALegID only. TenantID is an optional additional trust bound. Limit bounds returned observations per page. Cursor is the opaque, durable-store-authenticated continuation position echoed from a previous page's NextCursor; assembly never interprets it, and the durable adapter rejects a tampered, cross-scope or cross-kind token before it is trusted. A continuation is valid only while the full-scope snapshot it was issued against is unchanged; a resumed call inserted ahead of the position or a late correction invalidates it with a stale-cursor classification that requires restarting pagination rather than silently mixing two snapshots.

func (EconomicDetailQuery) IsCallScope

func (q EconomicDetailQuery) IsCallScope() bool

IsCallScope reports whether the query targets one billing call.

func (EconomicDetailQuery) Normalize

Normalize trims scope, applies the default limit and rejects unbounded or ambiguous queries. BillingCallID is validated through the canonical BillingCallID contract; other identities use the bounded economic identity contract without surrounding whitespace.

type EconomicDetailReader

type EconomicDetailReader interface {
	QueryEconomicDetail(context.Context, EconomicDetailQuery) (EconomicDetail, error)
}

EconomicDetailReader is the durable query port for scoped call/A-leg economic detail. Implementations load persisted sources and assemble them through AssembleEconomicDetail; they perform no rating or posting.

func NewStatementEvidenceEconomicDetailReader

func NewStatementEvidenceEconomicDetailReader(base EconomicDetailReader, source EconomicDetailStatementSource) EconomicDetailReader

NewStatementEvidenceEconomicDetailReader wraps a scoped detail reader so each page also resolves statement-origin S evidence through the supplied exact observation source. The wrapper is opt-in: passing a nil base returns nil, and passing a nil source is supported and surfaces an explicit unavailable reader rather than silently omitting the references.

type EconomicDetailReconciliation

type EconomicDetailReconciliation struct {
	Subject  metering.SubjectRef            `json:"subject"`
	Quantity *ComponentQuantityComparison   `json:"quantity,omitempty"`
	Monetary *MonetaryDiscrepancyComparison `json:"monetary,omitempty"`
	// Aggregate is that subject's retained aggregate reconciliation plane. It is
	// an independent typed projection: it is preserved verbatim, participates in
	// full-scope completeness, and is never coerced into the quantity or
	// monetary planes or treated as a second monetary authority.
	Aggregate *ReconciliationAggregate `json:"aggregate,omitempty"`
}

EconomicDetailReconciliation is one independently identified reconciliation comparison result for one authoritative in-scope subject. Subject is the ownership root and lineage of the comparison; Quantity, Monetary and Aggregate are that subject's retained comparison planes copied verbatim. Independent subjects are never merged, summed or FX-converted, and revision selection happens only within one true subject/source identity before assembly. A subject with no retained comparison plane is still preserved so its reconciliation is never silently dropped.

type EconomicDetailSnapshotContinuationEncoder

type EconomicDetailSnapshotContinuationEncoder interface {
	EncodeEconomicDetailSnapshotContinuation(query EconomicDetailQuery, position EconomicObservationPosition, baseFingerprint, outerFingerprint string) string
}

EconomicDetailSnapshotContinuationEncoder is implemented by durable readers that authenticate and produce economic-detail continuation tokens. A reader composed above the durable adapter (for example the statement-evidence wrapper) uses it to bind facts it resolves after the durable read into the same authenticated snapshot boundary, so one continuation never crosses two different full-scope snapshots.

type EconomicDetailStatementEvidence

type EconomicDetailStatementEvidence struct {
	ReaderAvailable  bool                          `json:"reader_available"`
	ReaderReason     string                        `json:"reader_reason,omitempty"`
	Lines            []EconomicDetailStatementLine `json:"lines,omitempty"`
	MissingRefs      []metering.ObservationRef     `json:"missing_refs,omitempty"`
	UnattributedRefs []metering.ObservationRef     `json:"unattributed_refs,omitempty"`
	UnresolvedRefs   []metering.ObservationRef     `json:"unresolved_refs,omitempty"`
}

EconomicDetailStatementEvidence is the source-separated statement evidence of one detail scope. ReaderAvailable reports whether an observation source was composed; when false, ReaderReason is a stable explanation and every referenced observation is enumerated in UnresolvedRefs rather than being implied. MissingRefs enumerates referenced observations that are absent or are not verified statement-line evidence. UnattributedRefs enumerates retained verified observations that carry no authoritative in-scope call/B-leg linkage (aggregate/account-period lines) and are therefore never attributed to the call. Lines holds the resolved in-scope evidence.

func LoadEconomicDetailStatementEvidence

func LoadEconomicDetailStatementEvidence(ctx context.Context, query EconomicDetailQuery, valuations []economics.Valuation, source EconomicDetailStatementSource) (EconomicDetailStatementEvidence, error)

LoadEconomicDetailStatementEvidence resolves the statement evidence for one detail scope from the S-basis valuation refs and the composed exact observation source. It performs no rating and no sums: each retained statement line stays an independent contribution.

type EconomicDetailStatementLine

type EconomicDetailStatementLine struct {
	StatementID        string                               `json:"statement_id"`
	StatementLineID    string                               `json:"statement_line_id"`
	Revision           uint64                               `json:"revision"`
	ProviderAccountKey string                               `json:"provider_account_key"`
	PeriodID           string                               `json:"period_id"`
	Outcome            economics.StatementLineOutcome       `json:"outcome,omitempty"`
	OutcomeSource      EconomicDetailStatementOutcomeSource `json:"outcome_source,omitempty"`
	UnmatchedReason    string                               `json:"unmatched_reason,omitempty"`
	Subject            metering.SubjectRef                  `json:"subject"`
	ObservationRef     metering.ObservationRef              `json:"observation_ref"`
	Observation        metering.Observation                 `json:"observation"`
	ChargeItemIDs      []string                             `json:"charge_item_ids,omitempty"`
	ValuationIDs       []string                             `json:"valuation_ids,omitempty"`
}

EconomicDetailStatementLine is one matched in-scope statement-line fact with its exact referenced verified observation and S valuation linkage. The statement identity is the observation's persisted statement-line subject; the immutable observation ref/hash and the exact observation revision are preserved verbatim. No amount is recomputed or summed here.

type EconomicDetailStatementLineSource

type EconomicDetailStatementLineSource interface {
	GetStatementLineRevisions(context.Context, metering.Observation) ([]economics.StatementLineView, error)
}

EconomicDetailStatementLineSource is the optional consumer-owned extension of EconomicDetailStatementSource implemented by sources that can also resolve the exact persisted statement-line outcome for one referenced observation. It returns the bounded persisted statement-line revisions for the observation's statement-line identity and must never synthesize a line from an observation.

type EconomicDetailStatementOutcomeSource

type EconomicDetailStatementOutcomeSource string

EconomicDetailStatementOutcomeSource identifies how one statement line's outcome was established. Persisted means the outcome is the exact durable statement-line outcome for the referenced observation. Observation means the observation is authoritatively linked to the requested scope but no single durable statement-line outcome was resolved, so no matched outcome is claimed.

const (
	// EconomicDetailStatementOutcomePersisted marks an outcome read from the
	// durable statement-line ledger.
	EconomicDetailStatementOutcomePersisted EconomicDetailStatementOutcomeSource = "persisted"
	// EconomicDetailStatementOutcomeObservation marks an observation-only
	// linkage whose persisted statement-line outcome was not authoritatively
	// resolved.
	EconomicDetailStatementOutcomeObservation EconomicDetailStatementOutcomeSource = "observation"
)

type EconomicDetailStatementSource

type EconomicDetailStatementSource interface {
	GetStatementObservation(context.Context, metering.ObservationRef) (metering.Observation, error)
}

EconomicDetailStatementSource is the consumer-owned, exact observation reader used to resolve statement-origin observation refs referenced by in-scope S valuations. Implementations return ErrEconomicDetailStatementObservationMissing for an absent revision and must never synthesize an observation from a reference. Store scope is enforced by the implementation; the loader re-checks it.

type EconomicDetailSummary

type EconomicDetailSummary struct {
	Turn     *TurnResultSummary  `json:"turn,omitempty"`
	Retail   *ALegRetailTotals   `json:"retail,omitempty"`
	Provider *ALegProviderTotals `json:"provider,omitempty"`
}

EconomicDetailSummary echoes existing summary projections verbatim. Detail augments these totals; it never overwrites them.

type EconomicDetailTotals

type EconomicDetailTotals struct {
	SelectedAmount       *MonetaryExactAmount        `json:"selected_amount,omitempty"`
	SelectedCurrency     string                      `json:"selected_currency,omitempty"`
	SelectedBasis        OperatorCostSelectionBasis  `json:"selected_basis,omitempty"`
	SelectedStatus       OperatorCostSelectionStatus `json:"selected_status,omitempty"`
	SelectedReason       OperatorCostSelectionReason `json:"selected_reason,omitempty"`
	SelectedCompleteness economics.Completeness      `json:"selected_completeness,omitempty"`
	SelectedHeadCount    int                         `json:"selected_head_count,omitempty"`
	SelectedAmbiguous    bool                        `json:"selected_ambiguous,omitempty"`
	Currencies           []string                    `json:"currencies,omitempty"`
}

EconomicDetailTotals carries the operator selected subtotal and the distinct native currencies observed. Margin is separate.

The selected fields are populated only when the scope has one unambiguous selected fact: either a caller-supplied full selection or exactly one authoritative persisted head. SelectedHeadCount counts the persisted heads that carry a frozen selection; SelectedAmbiguous is true when the scope holds more than one independent head, so no single truthful subtotal exists and independent heads are never summed, collapsed or FX-converted.

type EconomicDiscrepancyHealth

type EconomicDiscrepancyHealth struct {
	ByQuantity   []EconomicStatusCount    `json:"by_quantity,omitempty"`
	ByMonetary   []EconomicStatusCount    `json:"by_monetary,omitempty"`
	Gross        []EconomicCurrencyAmount `json:"gross_absolute,omitempty"`
	Partial      int                      `json:"partial"`
	Incomparable int                      `json:"incomparable"`
	Conflict     int                      `json:"conflict"`
}

EconomicDiscrepancyHealth summarizes one bounded retention window: per-plane status buckets, exact per-currency gross absolute exposure and explicit partial/incomparable/conflict rollups.

type EconomicEvidenceCoverage

type EconomicEvidenceCoverage string

EconomicEvidenceCoverage is a durable transport disposition, not a meter unit or a charge. A partial/unsupported disposition must retain a bounded, safe reason so later rating/reconciliation cannot mistake it for complete provider evidence.

type EconomicEvidenceDisposition

type EconomicEvidenceDisposition struct {
	ObservationIdentity string                   `json:"observation_identity"`
	ObservationHash     string                   `json:"observation_hash"`
	Coverage            EconomicEvidenceCoverage `json:"coverage"`
	CoverageReason      string                   `json:"coverage_reason,omitempty"`
}

EconomicEvidenceDisposition binds one coverage disposition to the immutable source observation it describes. ObservationHash is replay-stable and excludes receipt time, matching durable call-leg replay semantics; the observation's own Fingerprint is never rewritten.

func NewEconomicEvidenceDisposition

func NewEconomicEvidenceDisposition(observation metering.Observation, coverage, reason string) (EconomicEvidenceDisposition, error)

NewEconomicEvidenceDisposition constructs a bounded durable disposition from a canonical observation without changing that observation.

func (EconomicEvidenceDisposition) Validate

func (d EconomicEvidenceDisposition) Validate() error

Validate checks the durable disposition without requiring the observation. CallLegUsageRecord validation additionally verifies its identity and hash against the persisted observation list.

type EconomicEvidenceSetRelation

type EconomicEvidenceSetRelation uint8

EconomicEvidenceSetRelation describes the candidate evidence set relative to the current durable head. The relation is based on canonical immutable observation references, never on the SHA-256 input-set hash ordering.

const (
	EconomicEvidenceSetEqual EconomicEvidenceSetRelation = iota
	EconomicEvidenceSetCandidateSuperset
	EconomicEvidenceSetCandidateSubset
	EconomicEvidenceSetIncomparable
)

func CompareEconomicEvidenceSets

func CompareEconomicEvidenceSets(current, candidate []metering.ObservationRef) (EconomicEvidenceSetRelation, error)

CompareEconomicEvidenceSets compares a candidate's canonical observation references with the references retained by the current durable head. Exact duplicate references are collapsed. Two payload hashes for one store/observation/revision identity are rejected because they cannot both be members of one immutable evidence set.

type EconomicHealthInput

type EconomicHealthInput struct {
	Queues     []EconomicQueueRow
	Retries    []EconomicRetryRow
	Statements []EconomicStatementRow
	Retentions []ReconciliationRetentionResult
}

EconomicHealthInput is the frozen snapshot input. Retentions arrive as parsed immutable results in durable order; at most the bounded window supplied by the caller is summarized.

type EconomicHealthReader

type EconomicHealthReader interface {
	EconomicHealthSnapshot(context.Context) (EconomicHealthSnapshot, error)
}

EconomicHealthReader is the durable query port for the economics health snapshot. Implementations perform bounded store-scoped reads without taking customer balance locks.

type EconomicHealthSnapshot

type EconomicHealthSnapshot struct {
	Queues        []EconomicQueueHealth     `json:"queues,omitempty"`
	Statements    EconomicStatementHealth   `json:"statements"`
	Discrepancies EconomicDiscrepancyHealth `json:"discrepancies"`
	WindowRows    int                       `json:"window_rows"`
	WindowCapped  bool                      `json:"window_capped"`
	TakenAt       time.Time                 `json:"taken_at"`
}

EconomicHealthSnapshot is one deterministic point-in-time rollup. Queues sort by name; every other list sorts by its stable key.

func SummarizeEconomicHealth

func SummarizeEconomicHealth(input EconomicHealthInput, now time.Time) (EconomicHealthSnapshot, error)

SummarizeEconomicHealth folds bounded store rows into a deterministic snapshot. Unknown queue, status and reason values collapse to "other"; exact discrepancy math uses big rationals with no float fallback.

type EconomicJobDependency

type EconomicJobDependency struct {
	Kind             EconomicWorkKind `json:"kind"`
	Queue            EconomicQueue    `json:"queue"`
	HeadKey          string           `json:"head_key"`
	EvidenceRevision uint64           `json:"evidence_revision"`
	InputSetHash     string           `json:"input_set_hash"`
	DerivationHash   string           `json:"derivation_hash,omitempty"`
}

EconomicJobDependency is an explicit immutable output reference that separated reconciliation work depends on. The reference is the full revision identity (queue, head, evidence revision, observation input-set hash and allocation derivation hash) of a rating output, so a corrected rating is a new dependency rather than an overwrite of the previous output. DerivationHash is the full allocation-aware valuation input identity. It is empty for legacy observation-only outputs so the historical key preimage is byte-for-byte unchanged; allocation-aware producers must carry the exact DerivationHash from their revision identity and consumers must never guess it from the observation hash.

func NewEconomicJobDependency

func NewEconomicJobDependency(kind EconomicWorkKind, identity EconomicRevisionIdentity) (EconomicJobDependency, error)

NewEconomicJobDependency builds the exact immutable output reference for one rating revision identity. The returned dependency carries the producer's full derivation identity (including DerivationHash) so durable probes and loads resolve the allocation-aware valuation rather than the observation-only key or a stale historical output.

func (EconomicJobDependency) Equal

Equal reports whether two dependencies reference the same immutable output, including the allocation derivation.

func (EconomicJobDependency) Key

func (d EconomicJobDependency) Key() string

Key returns the deterministic rating output work identity for this dependency.

func (EconomicJobDependency) OutputIdentity

OutputIdentity returns the rating output revision identity the dependency points at. The returned identity carries the full derivation identity, including DerivationHash for allocation-aware outputs, because a rating output is never dependency-anchored but may be allocation-derived.

func (EconomicJobDependency) Validate

func (d EconomicJobDependency) Validate() error

Validate checks that the dependency is a well-formed rating output reference.

type EconomicJobDependencyCheck

type EconomicJobDependencyCheck struct {
	Dependency EconomicJobDependency
	Status     EconomicJobDependencyStatus
}

EconomicJobDependencyCheck is one dependency output probe result.

type EconomicJobDependencyOutput

type EconomicJobDependencyOutput struct {
	Dependency EconomicJobDependency
	Valuation  economics.Valuation
}

EconomicJobDependencyOutput is one exact immutable rating output loaded for dependency-anchored reconciliation work.

type EconomicJobDependencyStatus

type EconomicJobDependencyStatus uint8

EconomicJobDependencyStatus reports whether one immutable dependency output is durably present.

const (
	EconomicJobDependencySatisfied EconomicJobDependencyStatus = iota
	EconomicJobDependencyMissing
)

func (EconomicJobDependencyStatus) String

func (EconomicJobDependencyStatus) Validate

func (s EconomicJobDependencyStatus) Validate() error

Validate reports whether the dependency status is part of the closed vocabulary.

type EconomicJobFailureClass

type EconomicJobFailureClass struct {
	Stage       EconomicJobFailureStage
	Reason      EconomicWorkReason
	Disposition EconomicJobFailureDisposition
}

EconomicJobFailureClass is one classified attempt failure.

func ClassifyEconomicJobFailure

func ClassifyEconomicJobFailure(stage EconomicJobFailureStage, err error) EconomicJobFailureClass

ClassifyEconomicJobFailure maps one stage failure to the bounded reason and retry/terminal policy: deterministic invalid, mismatched or incomparable inputs are terminal; missing dependency outputs and transient failures retry with a bounded next attempt; cancellation releases through the lease-expiry retry path.

func (EconomicJobFailureClass) Terminal

func (c EconomicJobFailureClass) Terminal() bool

Terminal reports whether the failure retires the work instead of retrying.

type EconomicJobFailureDisposition

type EconomicJobFailureDisposition uint8

EconomicJobFailureDisposition is the closed retry/terminal classification.

const (
	EconomicJobFailureRetry EconomicJobFailureDisposition = iota
	EconomicJobFailureTerminal
)

func (EconomicJobFailureDisposition) String

func (EconomicJobFailureDisposition) Validate

func (d EconomicJobFailureDisposition) Validate() error

Validate reports whether the disposition is part of the closed vocabulary.

type EconomicJobFailureStage

type EconomicJobFailureStage uint8

EconomicJobFailureStage identifies the orchestration stage that failed so a failure can be classified against the approved retry/terminal policy.

const (
	EconomicJobFailureStageClaim EconomicJobFailureStage = iota
	EconomicJobFailureStageProbe
	EconomicJobFailureStageDependencyLoad
	EconomicJobFailureStageRate
	EconomicJobFailureStageReconcile
	EconomicJobFailureStageNormalize
	EconomicJobFailureStagePersist
	EconomicJobFailureStageFinalize
)

func AllEconomicJobFailureStages

func AllEconomicJobFailureStages() []EconomicJobFailureStage

AllEconomicJobFailureStages returns every documented failure stage in stable order.

func (EconomicJobFailureStage) String

func (s EconomicJobFailureStage) String() string

func (EconomicJobFailureStage) Validate

func (s EconomicJobFailureStage) Validate() error

Validate reports whether the stage is part of the closed vocabulary.

type EconomicJobQueueStore

type EconomicJobQueueStore interface {
	ClaimEconomicRevisionWorkBatch(context.Context, EconomicQueue, string, time.Duration, int) ([]EconomicRevisionClaimedWork, error)
	CompleteEconomicRevisionWork(context.Context, EconomicRevisionWork, EconomicRevisionWorkClaim) error
	RetryEconomicRevisionWorkWithReason(context.Context, EconomicRevisionWork, EconomicRevisionWorkClaim, EconomicWorkReason, time.Time) error
	FailEconomicRevisionWork(context.Context, EconomicRevisionWork, EconomicRevisionWorkClaim, EconomicWorkReason) error
}

EconomicJobQueueStore is the consumer-owned queue port for one bounded worker run: claim a batch, then complete, retry or fail each claim with its exact fence.

type EconomicJobReconciler

type EconomicJobReconciler interface {
	ReconcileJob(context.Context, EconomicRevisionWork, []EconomicJobDependencyOutput) (*EconomicReconciliation, error)
}

EconomicJobReconciler computes a pure reconciliation envelope over the exact immutable dependency outputs of provider-queue reconciliation work. It must not perform monetary posting or mutate customer state.

type EconomicJobRunSummary

type EconomicJobRunSummary struct {
	Queue      EconomicQueue
	Claimed    int
	Completed  int
	Retried    int
	Failed     int
	Superseded int
	Released   int
	Backlog    EconomicRevisionBacklog
}

EconomicJobRunSummary is the bounded outcome of one RunOnce invocation. The embedded backlog snapshot carries the queue age and incomplete-evidence diagnostics. Completed/Retried/Failed count durably recorded transitions; Superseded counts claims won by another worker; Released counts claims released unstarted because the caller context was canceled.

type EconomicJobRunner

type EconomicJobRunner struct {
	// contains filtered or unexported fields
}

EconomicJobRunner dispatches one bounded claim batch per queue by closed work kind to injected pure ports. Computation runs outside any database transaction; immutable outputs are persisted idempotently and the claim is finalized with its exact fence. No financial transition is performed here.

func NewEconomicJobRunner

func NewEconomicJobRunner(cfg EconomicJobRunnerConfig) (*EconomicJobRunner, error)

NewEconomicJobRunner validates and constructs the application runner.

func (*EconomicJobRunner) RunOnce

RunOnce claims and processes at most one bounded batch from the explicit queue. Per-item failures are recorded durably and counted in the summary; the returned error reports batch-level failures, cancellation or a release fault that could not be recorded.

type EconomicJobRunnerConfig

type EconomicJobRunnerConfig struct {
	Queue           EconomicJobQueueStore
	Backlog         EconomicRevisionBacklogReader
	Results         EconomicRevisionResultStore
	Dependencies    EconomicRevisionDependencyOutputReader
	Reconciliations EconomicRevisionReconciliationStore
	Rater           PostUsageRater
	Reconciler      EconomicJobReconciler
	Owner           string
	Batch           int
	Lease           time.Duration
	RetryBackoff    time.Duration
	Now             func() time.Time
}

EconomicJobRunnerConfig declares every port and bound of the application runner. All ports are required; the runner owns no goroutine and performs exactly one bounded claim batch per RunOnce call.

type EconomicObservationPosition

type EconomicObservationPosition struct {
	StreamID       string `json:"stream_id"`
	Sequence       uint64 `json:"sequence"`
	SourceEventKey string `json:"source_event_key"`
	ObservationID  string `json:"observation_id"`
	Revision       uint64 `json:"revision"`
}

EconomicObservationPosition is the decoded, authenticated keyset position of one observation in the canonical EconomicDetailObservationOrder. It is the continuation payload an authenticated cursor carries: the durable adapter verifies the opaque token and converts it to this position before assembly, and converts the assembled next position back into an opaque token. It is never trusted as caller input on its own.

func EconomicObservationPositionOf

func EconomicObservationPositionOf(observation metering.Observation) EconomicObservationPosition

EconomicObservationPositionOf returns the immutable keyset position of one observation in the canonical observation order.

func (EconomicObservationPosition) Validate

func (p EconomicObservationPosition) Validate() error

Validate checks the position is a usable keyset fragment. A malformed position fails closed instead of silently selecting a first or arbitrary page.

type EconomicQueue

type EconomicQueue string

EconomicQueue identifies the independently recoverable customer and provider economic queues. A worker is bound to one queue and therefore cannot accidentally process work owned by the other economic party.

const (
	EconomicQueueCustomer EconomicQueue = "customer"
	EconomicQueueProvider EconomicQueue = "provider"
)

func (EconomicQueue) String

func (q EconomicQueue) String() string

func (EconomicQueue) Validate

func (q EconomicQueue) Validate() error

type EconomicQueueHealth

type EconomicQueueHealth struct {
	Queue        string               `json:"queue"`
	Pending      int                  `json:"pending"`
	Processing   int                  `json:"processing"`
	Completed    int                  `json:"completed"`
	Processed    int                  `json:"processed"`
	Failed       int                  `json:"failed"`
	Other        int                  `json:"other"`
	OldestAgeSec float64              `json:"oldest_age_seconds"`
	MaxAttempts  int                  `json:"max_attempts"`
	Retries      []EconomicRetryCount `json:"retries,omitempty"`
}

EconomicQueueHealth is one bounded queue bucket. Only documented counters exist; per-request or per-account identities never appear here.

type EconomicQueueRow

type EconomicQueueRow struct {
	Queue             string
	Status            string
	Count             int
	OldestCreatedUnix int64
	MaxAttempts       int
}

EconomicQueueRow is one store-projected (queue, status) work aggregate. Queue carries the worker queue or work kind; Status carries the durable work state. Both are re-mapped through allowlists during summarization.

type EconomicReconciliation

type EconomicReconciliation struct {
	ID                string
	Version           uint64
	Subject           metering.SubjectRef
	Scope             string
	Basis             economics.ValuationBasis
	InputSetHash      string
	LocalInputHash    string
	ProviderInputHash string
	PolicyID          string
	PolicyVersion     string
	ResultJSON        json.RawMessage
	CreatedAt         time.Time
}

EconomicReconciliation is the pure reconciliation result associated with a revision. It intentionally mirrors the durable reconciliation envelope but remains in the billing domain so the worker has no infrastructure dependency.

func (EconomicReconciliation) Normalize

type EconomicRetryCount

type EconomicRetryCount struct {
	Reason string `json:"reason"`
	Count  int    `json:"count"`
}

EconomicRetryCount is one bounded retry-reason bucket.

type EconomicRetryRow

type EconomicRetryRow struct {
	Queue    string
	Reason   string
	Count    int
	Attempts int
}

EconomicRetryRow is one store-projected (queue, retry reason) aggregate. Attempts carries the maximum attempt count in the bucket and classifies empty reasons: attempts without a recorded reason are unclassified.

type EconomicRevisionAdmittedOwnerResolver

type EconomicRevisionAdmittedOwnerResolver interface {
	ResolveEconomicRevisionPostingOwner(context.Context, EconomicRevisionWork) (string, error)
}

EconomicRevisionAdmittedOwnerResolver returns the call-scoped durable posting owner admitted for one monetary work item (customer pin owner for its account/call). Implementations must prefer this admitted owner over any unbound global marker read; when no admitted owner exists they fall back to the current marker (V2 in v2_active, else V1). The relay consumes it so fresh V2 observations are not misclassified as V1 after activation.

type EconomicRevisionBacklog

type EconomicRevisionBacklog struct {
	Queue                  EconomicQueue
	Pending                int
	Processing             int
	Completed              int
	Failed                 int
	IncompleteDependencies int
	OldestPendingAt        time.Time
	OldestPendingAge       time.Duration
	NextAttemptAt          time.Time
}

EconomicRevisionBacklog is a bounded operational snapshot for one queue. It exposes backlog age, next-attempt timing and incomplete-evidence counts without mutating any job.

type EconomicRevisionBacklogReader

type EconomicRevisionBacklogReader interface {
	EconomicRevisionQueueBacklog(context.Context, EconomicQueue) (EconomicRevisionBacklog, error)
	EconomicRevisionDependencyChecks(context.Context, EconomicRevisionWork) ([]EconomicJobDependencyCheck, error)
}

EconomicRevisionBacklogReader exposes bounded operational backlog evidence and per-work dependency completeness.

type EconomicRevisionClaimedWork

type EconomicRevisionClaimedWork struct {
	Work  EconomicRevisionWork
	Claim EconomicRevisionWorkClaim
}

EconomicRevisionClaimedWork pairs one immutable job with the exclusive lease/fence token a worker must present to complete, retry, fail or heartbeat it.

type EconomicRevisionDependencyOutputReader

type EconomicRevisionDependencyOutputReader interface {
	LoadEconomicRevisionDependencyOutput(context.Context, EconomicJobDependency) (economics.Valuation, error)
}

EconomicRevisionDependencyOutputReader loads one immutable dependency rating output by its exact revision identity. A missing output must fail with ErrEconomicRevisionDependencyOutputMissing.

type EconomicRevisionIdentity

type EconomicRevisionIdentity struct {
	Queue            EconomicQueue
	HeadKey          string
	EvidenceRevision uint64
	InputSetHash     string
	// DerivationHash is the full allocation-aware valuation input identity. It
	// is empty for legacy no-allocation work so the historical key preimage is
	// byte-for-byte unchanged.
	DerivationHash   string
	DependenciesHash string
}

EconomicRevisionIdentity is the stable identity of one pure valuation attempt. The key deliberately includes queue, head, evidence revision and input-set hash, so corrected evidence is a new immutable work item. DerivationHash additionally binds the allocation coverage input set, so an allocation-only correction with unchanged observations is also a distinct, actionable revision. Dependency-anchored work additionally carries the canonical dependency hash so a changed immutable output set is a new actionable revision.

func NewEconomicRevisionIdentity

func NewEconomicRevisionIdentity(queue EconomicQueue, headKey string, revision uint64, inputHash string) (EconomicRevisionIdentity, error)

NewEconomicRevisionIdentity validates and constructs the domain identity.

func (EconomicRevisionIdentity) Key

Key returns a bounded opaque identity suitable for durable work IDs. Legacy rating identities keep their queue/head/revision/input-set preimage exactly; dependency-anchored work extends that preimage with the canonical dependency hash so distinct immutable output sets cannot collide.

func (EconomicRevisionIdentity) Less

Less provides the deterministic identity ordering used when evidence sets are equal or cannot be compared. Durable head stores must compare their retained observation references first so this lexical fallback can never discard a strict evidence superset at the same revision.

func (EconomicRevisionIdentity) ReconciliationKey

func (i EconomicRevisionIdentity) ReconciliationKey() string

ReconciliationKey returns the immutable reconciliation ID derived from this revision. Reconciliation and valuation identities remain distinct records, while both are tied to the same work identity.

func (EconomicRevisionIdentity) Validate

func (i EconomicRevisionIdentity) Validate() error

Validate checks that every member required to derive a durable revision key is present and canonical.

func (EconomicRevisionIdentity) ValuationKey

func (i EconomicRevisionIdentity) ValuationKey() string

ValuationKey returns the immutable valuation ID derived from this revision.

type EconomicRevisionInputMismatchError

type EconomicRevisionInputMismatchError struct {
	Expected string
	Actual   string
}

EconomicRevisionInputMismatchError reports a valuation whose input identity does not match the canonical identity expected at the worker boundary. It unwraps to ErrEconomicRevisionInputMismatch so callers can retain the existing sentinel classification while using errors.As for the hashes.

func (*EconomicRevisionInputMismatchError) Error

func (*EconomicRevisionInputMismatchError) Unwrap

type EconomicRevisionJobQueueStore

EconomicRevisionJobQueueStore owns mutable job-queue delivery state for bounded worker consumption. Claim, heartbeat, retry and fail all compare the owner and fence so a stale worker cannot overwrite a newer worker's progress. None of these operations reads or mutates an account balance, exposure or financial head.

type EconomicRevisionReconciler

type EconomicRevisionReconciler interface {
	Reconcile(context.Context, EconomicRevisionWork, economics.Valuation) (*EconomicReconciliation, error)
}

EconomicRevisionReconciler computes a pure reconciliation envelope. It is optional; valuation remains independently durable when no reconciler exists.

type EconomicRevisionReconciliationStore

type EconomicRevisionReconciliationStore interface {
	AppendEconomicRevisionReconciliation(context.Context, EconomicRevisionWork, EconomicReconciliation) error
	HasEconomicRevisionReconciliation(context.Context, EconomicRevisionIdentity) (bool, error)
}

EconomicRevisionReconciliationStore persists dependency-anchored reconciliation output idempotently and probes whether it already exists. Persistence must never touch a customer balance, journal or financial head.

type EconomicRevisionResult

type EconomicRevisionResult struct {
	Valuation      economics.Valuation     `json:"valuation"`
	Reconciliation *EconomicReconciliation `json:"reconciliation,omitempty"`
}

EconomicRevisionResult contains only pure derived records. Persisting it must never call a balance, exposure, settlement or journal mutation API.

type EconomicRevisionResultProbe

type EconomicRevisionResultProbe interface {
	HasEconomicRevisionResult(context.Context, EconomicRevisionIdentity) (bool, error)
}

EconomicRevisionResultProbe is optional. Durable implementations use it to avoid invoking an expensive rater again after restart/replay.

type EconomicRevisionResultStore

type EconomicRevisionResultStore interface {
	AppendEconomicRevisionResult(context.Context, EconomicRevisionWork, EconomicRevisionResult) error
}

EconomicRevisionResultStore persists pure results and advances the rebuildable current head atomically. It must not mutate monetary balances.

type EconomicRevisionValuationLoader

type EconomicRevisionValuationLoader interface {
	LoadEconomicRevisionValuation(context.Context, EconomicRevisionIdentity) (economics.Valuation, error)
}

EconomicRevisionValuationLoader is optional. Durable implementations use it to recover the exact immutable valuation identity for provider-posting replay without re-rating. The loaded valuation must carry the full allocation-aware InputSetHash persisted on the fresh path; callers must not substitute an ID-only placeholder or fall back to the observation-only work hash. Stores that persist the lenient legacy work/output seam must return that exact persisted valuation so fresh and recovered provider source keys stay byte-identical.

type EconomicRevisionWork

type EconomicRevisionWork struct {
	Queue            EconomicQueue                  `json:"queue"`
	Kind             EconomicWorkKind               `json:"kind,omitempty"`
	HeadKey          string                         `json:"head_key"`
	Subject          metering.SubjectRef            `json:"subject"`
	EvidenceRevision uint64                         `json:"evidence_revision"`
	InputSetHash     string                         `json:"input_set_hash"`
	Dependencies     []EconomicJobDependency        `json:"dependencies,omitempty"`
	Input            economics.PostUsageRatingInput `json:"input"`
	CreatedAt        time.Time                      `json:"created_at"`
	// PostingOwner records explicit monetary intent for F2B cutover fencing.
	// Empty preserves legacy inference (monetary provider_rating defaults to
	// V1); "v1"/"v2" marks explicit monetary ownership (V2 requires v2_active
	// authorization). Evidence-only work must use EvidenceOnly instead.
	PostingOwner string `json:"posting_owner,omitempty"`
	// EvidenceOnly forces evidence-only delivery for work that would otherwise
	// infer monetary (e.g. shadow provider observations, pure workers without
	// a posting adapter). Drain never inventories, pins, counts, or fences
	// these rows; workers never post provider money for them.
	EvidenceOnly bool `json:"evidence_only,omitempty"`
}

EconomicRevisionWork is the durable, immutable input to pure economic computation. Input contains only provider-neutral immutable observations; no account balance or journal operation is present in this envelope. Kind identifies the pure computation; separated reconciliation work additionally declares the immutable rating outputs it depends on.

func OverlayAuthoritativeEconomicWork

func OverlayAuthoritativeEconomicWork(work EconomicRevisionWork, providerPosting bool, postingOwner string) EconomicRevisionWork

OverlayAuthoritativeEconomicWork returns the authoritative work view for production list/claim/worker consumption: immutable evidence identity is preserved (queue/head/revision/input hash), while delivery intent comes from mutable state. Monetary state overlays owner and clears any stale evidence-only flag so split payload/state can never disagree; evidence state returns the stored payload unchanged (still non-posting).

func (EconomicRevisionWork) Identity

func (EconomicRevisionWork) Normalize

Normalize validates the durable work and fills the canonical input-set hash. It returns a deep copy so callers cannot mutate queued work through shared observation slices.

type EconomicRevisionWorkAppender

type EconomicRevisionWorkAppender interface {
	AppendEconomicRevisionWork(context.Context, EconomicRevisionWork) error
}

EconomicRevisionWorkAppender is the narrow durable queue seam used by the observation relay. Implementations must retain the immutable work marker and treat an exact identity replay as a no-op.

type EconomicRevisionWorkClaim

type EconomicRevisionWorkClaim struct {
	Owner      string
	Fence      uint64
	LeaseUntil time.Time
}

EconomicRevisionWorkClaim is the fencing token for one bounded pure-work attempt. A finite lease lets another worker recover abandoned processing; Fence prevents the old owner from retiring the recovered work.

type EconomicRevisionWorkCutoverClaimer

type EconomicRevisionWorkCutoverClaimer interface {
	ClaimEconomicRevisionWorkWithCutover(ctx context.Context, work EconomicRevisionWork, owner string, lease time.Duration) (EconomicRevisionWorkClaim, *CutoverClaimMetadata, bool, error)
}

EconomicRevisionWorkCutoverClaimer is the production token-carrying lease port for monetary economic revisions. Implementations must atomically lease the work (owner/fence) and issue a current-marker cutover token for monetary provider work; evidence-only work returns a nil cutover. They must fail closed on operational/cancellation/malformed errors and withhold ineligible monetary work without consuming attempts.

type EconomicRevisionWorkEvidenceAppender

type EconomicRevisionWorkEvidenceAppender interface {
	AppendEvidenceEconomicRevisionWork(context.Context, EconomicRevisionWork) error
}

EconomicRevisionWorkEvidenceAppender persists explicitly evidence-only work that drain never inventories as monetary (shadow, pure workers without a posting adapter). Implementations must not create pins or fences for these rows.

type EconomicRevisionWorkPostingAppender

type EconomicRevisionWorkPostingAppender interface {
	AppendProviderPostingEconomicRevisionWork(context.Context, EconomicRevisionWork, string) error
}

EconomicRevisionWorkPostingAppender persists monetary provider work with an explicit posting owner (V1 pre-boundary, V2 authorized). Implementations must fence new V1 in draining/active and require v2_active for V2.

type EconomicRevisionWorkReader

type EconomicRevisionWorkReader interface {
	ListPendingEconomicRevisionWork(context.Context, EconomicQueue, int) ([]EconomicRevisionWork, error)
}

EconomicRevisionWorkReader supplies immutable revisions from durable queue state. Implementations must filter by queue before returning work.

type EconomicRevisionWorkStateStore

type EconomicRevisionWorkStateStore interface {
	ClaimEconomicRevisionWork(context.Context, EconomicRevisionWork, string, time.Duration) (EconomicRevisionWorkClaim, bool, error)
	CompleteEconomicRevisionWork(context.Context, EconomicRevisionWork, EconomicRevisionWorkClaim) error
	RetryEconomicRevisionWork(context.Context, EconomicRevisionWork, EconomicRevisionWorkClaim, string, time.Time) error
}

EconomicRevisionWorkStateStore owns mutable delivery state separately from immutable evidence markers. Implementations must compare Owner and Fence when completing or retrying a claim so a stale worker cannot overwrite a newer worker's progress.

type EconomicRevisionWorker

type EconomicRevisionWorker struct {
	// contains filtered or unexported fields
}

EconomicRevisionWorker performs bounded valuation/reconciliation over durable revisions. An optional provider-cost port may apply an independently stable operator COGS delta for provider-queue work; customer settlement and customer balance mutation remain outside this worker.

func NewEconomicRevisionWorker

func NewEconomicRevisionWorker(work EconomicRevisionWorkReader, results EconomicRevisionResultStore, rater PostUsageRater, queue EconomicQueue, batch int) (*EconomicRevisionWorker, error)

NewEconomicRevisionWorker constructs a pure worker for one independent customer or provider queue. Test-only: preserves pure doubles without a claim port. Production provider-queue posting must use the WithClaim variant.

func NewEconomicRevisionWorkerWithProviderCost

func NewEconomicRevisionWorkerWithProviderCost(work EconomicRevisionWorkReader, results EconomicRevisionResultStore, rater PostUsageRater, providerCost ProviderCostRevisionStore, queue EconomicQueue, batch int) (*EconomicRevisionWorker, error)

NewEconomicRevisionWorkerWithProviderCost adds the independent operator COGS posting seam. Provider posting is deliberately after pure valuation persistence and is scoped to one authoritative B-leg revision; customer queues never call this dependency. Test-only: production provider posting must use NewEconomicRevisionWorkerWithProviderCostWithClaim or the reconciler+claim variant.

func NewEconomicRevisionWorkerWithProviderCostWithClaim

func NewEconomicRevisionWorkerWithProviderCostWithClaim(work EconomicRevisionWorkReader, results EconomicRevisionResultStore, rater PostUsageRater, providerCost ProviderCostRevisionStore, claimProvider ProviderCostWorkClaimStore, queue EconomicQueue, batch int) (*EconomicRevisionWorker, error)

NewEconomicRevisionWorkerWithProviderCostWithClaim constructs the production provider-queue worker with a required B2a claim port. A nil claim provider is rejected. Lookup failures other than authorized first acquisition fail closed without posting.

func NewEconomicRevisionWorkerWithProviderCostWithCutover

func NewEconomicRevisionWorkerWithProviderCostWithCutover(work EconomicRevisionWorkReader, results EconomicRevisionResultStore, rater PostUsageRater, providerCost ProviderCostRevisionStore, claimer EconomicRevisionWorkCutoverClaimer, queue EconomicQueue, batch int) (*EconomicRevisionWorker, error)

NewEconomicRevisionWorkerWithProviderCostWithCutover constructs the F6+F8 production provider-queue worker with a required token-carrying lease port. Each monetary lease atomically carries its current-marker cutover token.

func NewEconomicRevisionWorkerWithReconciler

func NewEconomicRevisionWorkerWithReconciler(work EconomicRevisionWorkReader, results EconomicRevisionResultStore, rater PostUsageRater, reconciler EconomicRevisionReconciler, queue EconomicQueue, batch int) (*EconomicRevisionWorker, error)

NewEconomicRevisionWorkerWithReconciler adds an optional pure reconciliation calculation to the valuation worker. Reconciliation output is persisted in the same local transaction as its valuation and head transition. Test-only for provider posting; production provider posting must use the WithClaim variant.

func NewEconomicRevisionWorkerWithReconcilerAndProviderCost

func NewEconomicRevisionWorkerWithReconcilerAndProviderCost(work EconomicRevisionWorkReader, results EconomicRevisionResultStore, rater PostUsageRater, reconciler EconomicRevisionReconciler, providerCost ProviderCostRevisionStore, queue EconomicQueue, batch int) (*EconomicRevisionWorker, error)

NewEconomicRevisionWorkerWithReconcilerAndProviderCost combines pure reconciliation with the independent operator COGS posting seam. Test-only: production provider posting must use the WithClaim variant below.

func NewEconomicRevisionWorkerWithReconcilerAndProviderCostWithClaim

func NewEconomicRevisionWorkerWithReconcilerAndProviderCostWithClaim(work EconomicRevisionWorkReader, results EconomicRevisionResultStore, rater PostUsageRater, reconciler EconomicRevisionReconciler, providerCost ProviderCostRevisionStore, claimProvider ProviderCostWorkClaimStore, queue EconomicQueue, batch int) (*EconomicRevisionWorker, error)

NewEconomicRevisionWorkerWithReconcilerAndProviderCostWithClaim combines pure reconciliation with the production provider COGS posting seam and a required B2a claim port. A nil claim provider is rejected.

func NewEconomicRevisionWorkerWithReconcilerAndProviderCostWithCutover

func NewEconomicRevisionWorkerWithReconcilerAndProviderCostWithCutover(work EconomicRevisionWorkReader, results EconomicRevisionResultStore, rater PostUsageRater, reconciler EconomicRevisionReconciler, providerCost ProviderCostRevisionStore, claimer EconomicRevisionWorkCutoverClaimer, queue EconomicQueue, batch int) (*EconomicRevisionWorker, error)

NewEconomicRevisionWorkerWithReconcilerAndProviderCostWithCutover combines reconciliation with the F6+F8 production token-carrying lease port.

func (*EconomicRevisionWorker) ProcessOnce

func (w *EconomicRevisionWorker) ProcessOnce(ctx context.Context) error

ProcessOnce claims a bounded queue snapshot and computes each revision. A durable result probe is used when available so restart/replay does not call the rater again for an already persisted immutable result.

func (*EconomicRevisionWorker) Start

Start runs bounded polling until the supplied context is canceled.

func (*EconomicRevisionWorker) Stop

Stop cancels polling and waits for the worker goroutine to leave.

type EconomicStatementHealth

type EconomicStatementHealth struct {
	Matched   int `json:"matched"`
	Unmatched int `json:"unmatched"`
	Other     int `json:"other"`
}

EconomicStatementHealth counts retained statement lines by outcome.

type EconomicStatementRow

type EconomicStatementRow struct {
	Outcome string
	Count   int
}

EconomicStatementRow is one store-projected statement outcome aggregate.

type EconomicStatusCount

type EconomicStatusCount struct {
	Status string `json:"status"`
	Count  int    `json:"count"`
}

EconomicStatusCount is one bounded comparison-state bucket.

type EconomicValuationHead

type EconomicValuationHead struct {
	Queue                 EconomicQueue
	HeadKey               string
	Subject               metering.SubjectRef
	EvidenceRevision      uint64
	InputSetHash          string
	WorkID                string
	ValuationID           string
	ValuationVersion      uint32
	ReconciliationID      string
	ReconciliationVersion uint64
	Fingerprint           string
	HeadVersion           uint64
	Fence                 uint64
	UpdatedAt             time.Time
}

EconomicValuationHead is the rebuildable current pointer for one queue/head. Immutable valuation and reconciliation history remains authoritative.

func (EconomicValuationHead) IsOlderThan

func (h EconomicValuationHead) IsOlderThan(identity EconomicRevisionIdentity) bool

IsOlderThan reports whether a candidate revision should replace this head. A malformed existing head is treated as older so recovery can repair it.

type EconomicWorkKind

type EconomicWorkKind string

EconomicWorkKind identifies the pure computation a durable economic job performs. Rating kinds map one-to-one onto the customer/provider queues; separated reconciliation work is supplier-side computation that may depend on the immutable rating outputs of either queue without holding a customer balance lock.

const (
	EconomicWorkKindCustomerRating EconomicWorkKind = "customer_rating"
	EconomicWorkKindProviderRating EconomicWorkKind = "provider_rating"
	EconomicWorkKindReconciliation EconomicWorkKind = "reconciliation"
)

func AllEconomicWorkKinds

func AllEconomicWorkKinds() []EconomicWorkKind

AllEconomicWorkKinds returns every documented work kind in stable order.

func EconomicWorkKindForQueue

func EconomicWorkKindForQueue(queue EconomicQueue) EconomicWorkKind

EconomicWorkKindForQueue returns the rating kind derived from a queue.

func (EconomicWorkKind) IsRating

func (k EconomicWorkKind) IsRating() bool

IsRating reports whether the kind computes a rating valuation output that other work may depend on.

func (EconomicWorkKind) Queue

func (k EconomicWorkKind) Queue() (EconomicQueue, error)

Queue returns the single economic queue that owns the kind. Customer and provider rating remain strictly separated; separated reconciliation work is supplier computation and therefore belongs to the provider queue.

func (EconomicWorkKind) String

func (k EconomicWorkKind) String() string

func (EconomicWorkKind) Validate

func (k EconomicWorkKind) Validate() error

type EconomicWorkReason

type EconomicWorkReason string

EconomicWorkReason is the bounded, closed reason vocabulary recorded for a retry or a terminal failure. Free-form error text is never the durable reason; it is bounded separately in last_error.

const (
	EconomicWorkReasonUnclassified       EconomicWorkReason = "unclassified"
	EconomicWorkReasonTransientFailure   EconomicWorkReason = "transient_failure"
	EconomicWorkReasonRaterFailure       EconomicWorkReason = "rater_failure"
	EconomicWorkReasonReconcilerFailure  EconomicWorkReason = "reconciler_failure"
	EconomicWorkReasonPersistenceFailure EconomicWorkReason = "persistence_failure"
	EconomicWorkReasonDependencyPending  EconomicWorkReason = "dependency_pending"
	EconomicWorkReasonLeaseExpired       EconomicWorkReason = "lease_expired"
	EconomicWorkReasonPermanentFailure   EconomicWorkReason = "permanent_failure"
)

func AllEconomicWorkReasons

func AllEconomicWorkReasons() []EconomicWorkReason

AllEconomicWorkReasons returns every documented reason in stable order.

func (EconomicWorkReason) String

func (r EconomicWorkReason) String() string

func (EconomicWorkReason) Validate

func (r EconomicWorkReason) Validate() error

type EconomicWorkStatus

type EconomicWorkStatus string

EconomicWorkStatus is the closed delivery-state vocabulary for durable economic job queue state. Completed and failed are terminal.

const (
	EconomicWorkStatusPending    EconomicWorkStatus = "pending"
	EconomicWorkStatusProcessing EconomicWorkStatus = "processing"
	EconomicWorkStatusCompleted  EconomicWorkStatus = "completed"
	EconomicWorkStatusFailed     EconomicWorkStatus = "failed"
)

func AllEconomicWorkStatuses

func AllEconomicWorkStatuses() []EconomicWorkStatus

AllEconomicWorkStatuses returns every documented work status in stable order.

func (EconomicWorkStatus) IsTerminal

func (s EconomicWorkStatus) IsTerminal() bool

func (EconomicWorkStatus) String

func (s EconomicWorkStatus) String() string

func (EconomicWorkStatus) Validate

func (s EconomicWorkStatus) Validate() error

type EvidenceAuthority

type EvidenceAuthority string
const (
	EvidenceAuthorityUnknown       EvidenceAuthority = ""
	EvidenceAuthorityAuthoritative EvidenceAuthority = "authoritative"
	EvidenceAuthorityDelegated     EvidenceAuthority = "delegated"
	EvidenceAuthorityEstimated     EvidenceAuthority = "estimated"
	EvidenceAuthorityUnavailable   EvidenceAuthority = "unavailable"
)

type EvidenceConflict

type EvidenceConflict struct {
	Identity               string                   `json:"identity"`
	ExistingHash           string                   `json:"existing_hash"`
	IncomingHash           string                   `json:"incoming_hash"`
	ExistingCoverage       EconomicEvidenceCoverage `json:"existing_coverage,omitempty"`
	ExistingCoverageReason string                   `json:"existing_coverage_reason,omitempty"`
	IncomingCoverage       EconomicEvidenceCoverage `json:"incoming_coverage,omitempty"`
	IncomingCoverageReason string                   `json:"incoming_coverage_reason,omitempty"`
}

EvidenceConflict records a source-event identity that was delivered with a changed payload. Exact identity/revision replays are collapsed; a changed payload is retained as a visible conflict instead of being silently merged. The conflict is diagnostic evidence and never becomes a charge by itself.

func (EvidenceConflict) HasCoverageMetadata

func (c EvidenceConflict) HasCoverageMetadata() bool

type EvidenceSource

type EvidenceSource string
const (
	EvidenceSourceUnknown          EvidenceSource = ""
	EvidenceSourceProviderReported EvidenceSource = "provider_reported"
	EvidenceSourceProviderCountAPI EvidenceSource = "provider_count_api"
	EvidenceSourceLocalTokenizer   EvidenceSource = "local_tokenizer"
	EvidenceSourceLocalEstimator   EvidenceSource = "local_estimator"
	EvidenceSourceUnavailable      EvidenceSource = "unavailable"
)

type ExposureAdmissionStore

type ExposureAdmissionStore interface {
	AdmitExposure(context.Context, AdmitExposureInput) (CallExposure, error)
}

type ExposureBasis

type ExposureBasis struct {
	BalanceNano            int64
	CreditFloorNano        int64
	OpenExposureNano       int64
	SettledHeadroomNano    int64
	SafetyMarginBeforeNano int64
	SafetyMarginAfterNano  int64
}

type ExposurePage

type ExposurePage struct {
	Items      []ExposureReport
	NextCursor string
}

type ExposureReconciliationReport

type ExposureReconciliationReport struct {
	AccountID string
	Currency  string
	Open      Money
	Rows      int
	OK        bool
	Issues    []ReconciliationIssue
}

type ExposureRecovery

type ExposureRecovery interface {
	RepairExposureNoCharge(ctx context.Context, callID BillingCallID, sourceKey string) (CallSettlement, error)
	RepairIncompleteCallNoCharge(ctx context.Context, callID BillingCallID, sourceKey string) (CallSettlement, error)
}

type ExposureReport

type ExposureReport struct {
	AccountID       string
	CallID          string
	Status          ExposureStatus
	Max             Money
	PricingRef      VersionRef
	ChargePolicyRef VersionRef
	Fingerprint     string
	CreatedAt       time.Time
	ClosedAt        time.Time
	Basis           ExposureBasis
	ALegID          string
	SessionID       string
}

type ExposureStatus

type ExposureStatus string
const (
	ExposureOpen   ExposureStatus = "open"
	ExposureClosed ExposureStatus = "closed"
)

type ExposureStore

type ExposureStore = ExposureAdmissionStore

ExposureStore is an alias for ExposureAdmissionStore to align with canonical store naming.

type FinalBillingEvidence

type FinalBillingEvidence struct {
	InputTokens      Quantity
	OutputTokens     Quantity
	CacheReadTokens  Quantity
	CacheWriteTokens Quantity
	ReasoningTokens  Quantity
	TotalTokens      Quantity
	Cost             MoneyEvidence
	Source           EvidenceSource
	Authority        EvidenceAuthority
	DedupeKey        string
}

type FinancialAdjustmentClaimStore

type FinancialAdjustmentClaimStore interface {
	GetCutoverClaimMetadata(ctx context.Context, kind PostingOperationKind, operationKey string) (CutoverClaimMetadata, error)
}

FinancialAdjustmentClaimStore is the narrow claim port workers consume to pass claim-time owner/epoch to posting-time validation. DurableStore implements it via GetCutoverClaimMetadata; test doubles may implement it explicitly. Selected-cost adjustments are synchronous nonqueued commands: they validate the current marker at execution; any future queued adjustment worker must be constructed with a non-nil claim provider so missing metadata fails fast instead of silently bypassing the fence.

type FundingInput

type FundingInput struct {
	AccountID string
	Amount    Money
	SourceKey string
	Reason    string
}

func (FundingInput) Fingerprint

func (in FundingInput) Fingerprint() (string, error)

func (FundingInput) Validate

func (in FundingInput) Validate() error

type HistoricalV1CallBundle

type HistoricalV1CallBundle struct {
	Call          HistoricalV1CallView
	Legs          []HistoricalV1LegView
	WriterVersion string
}

HistoricalV1CallBundle groups one V1 call with its V1 legs under a single explicit writer version. Mixed-version bundles are rejected as ambiguous.

func (HistoricalV1CallBundle) Validate

func (b HistoricalV1CallBundle) Validate() error

Validate fails closed on mixed-version or malformed bundles.

type HistoricalV1CallView

type HistoricalV1CallView struct {
	Key             string
	Fingerprint     string
	PayloadSHA256   string
	CallID          BillingCallID
	AccountID       string
	ALegID          string
	SessionID       string
	LegacySemantics string
	WriterVersion   string
}

HistoricalV1CallView is the legacy-opaque projection of one baseline V1 call record. It preserves key/fingerprint/payload hash and explicit writer version without inventing component detail.

func ProjectHistoricalV1Call

func ProjectHistoricalV1Call(call CallUsageRecord) (HistoricalV1CallView, error)

ProjectHistoricalV1Call preserves one sealed baseline V1 call record with explicit V1 writer ownership and legacy pricing semantics. The call schema version alone does not prove writer provenance; callers needing ownership must also resolve the call's legs (as ReadHistoricalV1CallBundle does).

func (HistoricalV1CallView) Validate

func (v HistoricalV1CallView) Validate() error

Validate fails closed on any malformed V1 call view.

type HistoricalV1LegView

type HistoricalV1LegView struct {
	Key                       string
	Fingerprint               string
	PayloadSHA256             string
	CallID                    BillingCallID
	BLegID                    string
	Evidence                  FinalBillingEvidence
	LegacySemantics           string
	WriterVersion             string
	BreakdownAvailable        bool
	SourceSeparationAvailable bool
}

HistoricalV1LegView is the legacy-opaque projection of one baseline V1 call-leg record. It preserves the exact durable key, semantic fingerprint and payload hash and carries the scalar FinalBillingEvidence verbatim. It never carries V2 observations, E/Q/P/S/R breakdown, or source separation.

func ProjectHistoricalV1Leg

func ProjectHistoricalV1Leg(leg CallLegUsageRecord) (HistoricalV1LegView, error)

ProjectHistoricalV1Leg preserves one sealed baseline V1 leg byte-for-byte: it verifies durable replay identity (key/fingerprint) and returns a legacy-opaque view with explicit writer version and legacy pricing semantics. V2-native observations, breakdown, or source separation are never synthesized; a V2 or ambiguous record fails closed.

func (HistoricalV1LegView) Validate

func (v HistoricalV1LegView) Validate() error

Validate fails closed on any malformed or ambiguous V1 leg view.

type IncludedAllowanceDecision

type IncludedAllowanceDecision struct {
	Key                   CustomerUnitKey
	Entitlement           CustomerEntitlementStatus
	Requested             metering.Decimal
	Available             metering.Decimal
	Included              metering.Decimal
	Uncovered             metering.Decimal
	FallbackRequired      bool
	MonetaryFallbackBound *Money
}

IncludedAllowanceDecision preserves exact included and uncovered quantities. A non-nil bound is carried only when a bounded monetary fallback is needed.

func EvaluateIncludedAllowance

func EvaluateIncludedAllowance(in IncludedAllowanceInput) (IncludedAllowanceDecision, error)

EvaluateIncludedAllowance performs a pure exact evaluation. It never writes the balance; the caller must submit a debit/reservation operation through CustomerUnitLedger for the final atomic decision.

func (IncludedAllowanceDecision) Validate

func (d IncludedAllowanceDecision) Validate() error

Validate checks the internal exact-quantity and fallback invariants.

type IncludedAllowanceInput

type IncludedAllowanceInput struct {
	Key                   CustomerUnitKey
	Balance               CustomerUnitBalance
	Requested             metering.Decimal
	MonetaryFallbackBound *Money
}

IncludedAllowanceInput asks how much of a requested customer quantity can be covered by one complete customer-owned entitlement. MonetaryFallbackBound is a maximum monetary exposure for only the uncovered quantity; this domain does not convert units to money.

type IndependentValuations

type IndependentValuations struct {
	Expected         *economics.Valuation
	ProviderQuantity *economics.Valuation
	ProviderReported *economics.Valuation
}

IndependentValuations retains the locally-derived expected (E), provider-quantity local (Q), and provider-reported (P) planes separately. A nil plane means its source evidence did not exist; it is never an implicit zero valuation.

func RateIndependentValuations

func RateIndependentValuations(ctx context.Context, rater PostUsageRater, base economics.PostUsageRatingInput) (IndependentValuations, error)

RateIndependentValuations invokes each applicable plane independently. The provider's monetary charge cannot suppress E or Q, and missing provider money cannot manufacture P.

type JournalBook

type JournalBook string
const JournalBookFinancial JournalBook = "financial"

type JournalEntry

type JournalEntry struct {
	LedgerAccount string
	Side          JournalSide
	Amount        Money
}

type JournalSide

type JournalSide string
const (
	JournalDebit  JournalSide = "debit"
	JournalCredit JournalSide = "credit"
)

type JournalStore

type JournalStore interface {
	JournalTransactions(ctx context.Context, accountID string) ([]JournalTransaction, error)
}

JournalStore is the query port for reading an account's posted journals.

type JournalTransaction

type JournalTransaction struct {
	ID                    string
	Book                  JournalBook
	Currency              string
	SourceKey             string
	SemanticFingerprint   string
	AccountID             string
	TurnID                string
	ALegID                string
	BLegID                string
	AccountSequence       uint64
	ReversalOf            string
	CorrectsTransactionID string
	CorrectionGroupID     string
	OperationKind         string
	BalanceBefore         int64
	BalanceAfter          int64
	SpendableBefore       int64
	SpendableAfter        int64
	CreditFloor           int64
	CreditLimit           int64
	Mode                  string
	SnapshotVersionBefore uint64
	SnapshotVersionAfter  uint64
	// RecordedAt is assigned by the persistence database and is excluded from
	// semantic identity. It is the provider/report ordering timestamp.
	RecordedAt time.Time
	Entries    []JournalEntry
}

func AdjustmentJournalIntent

func AdjustmentJournalIntent(input AdjustmentInput) (JournalTransaction, error)

func FundingJournalIntent

func FundingJournalIntent(input FundingInput) (JournalTransaction, error)

func PaymentJournalIntent

func PaymentJournalIntent(input PaymentInput) (JournalTransaction, error)

func (JournalTransaction) CanonicalFingerprint

func (j JournalTransaction) CanonicalFingerprint() (string, error)

func (JournalTransaction) Detached

func (JournalTransaction) Seal

func (JournalTransaction) Validate

func (j JournalTransaction) Validate() error

type LegOutcome

type LegOutcome string
const (
	LegOutcomeWinner       LegOutcome = "winner"
	LegOutcomeLoser        LegOutcome = "loser"
	LegOutcomeFailed       LegOutcome = "failed"
	LegOutcomeCanceled     LegOutcome = "canceled"
	LegOutcomeSwallowed    LegOutcome = "swallowed_failure"
	LegOutcomeRejected     LegOutcome = "rejected"
	LegOutcomeNeverStarted LegOutcome = "never_started"
	LegOutcomeUnknown      LegOutcome = "unknown"
)

type LegacyHoldReconciliationReport

type LegacyHoldReconciliationReport struct {
	OpenHolds       int
	BlockedAccounts int
	Ready           bool
}

type MaxChargeInput

type MaxChargeInput struct {
	Currency            string
	InputTokens         int64
	InputTokensPresent  bool
	Policy              ChargePolicy
	Routes              []ChargeRoute
	ConservativeCeiling *Money
	Strict              bool
}

type MaxCostBound

type MaxCostBound struct {
	Amount          Money
	PricingRef      VersionRef
	ChargePolicyRef VersionRef
	Basis           []BoundComponent
	// RouteTariffs carries the frozen per-route customer tariff bindings
	// actually used to form a rich quote. Empty on the legacy scalar path
	// and on strict-ceiling fallback bounds, which carry no tariff material.
	RouteTariffs []RouteTariffBinding
}

func EstimateMaxCustomerCharge

func EstimateMaxCustomerCharge(in MaxChargeInput) (MaxCostBound, error)

func EstimateRichCustomerCharge

func EstimateRichCustomerCharge(in RichQuoteInput) (MaxCostBound, error)

EstimateRichCustomerCharge quotes a richer customer offer using the same rule evaluation, rounding and price-version binding as post-usage settlement. Unknown duration/tool counts (missing or non-enforceable bounds), missing required evidence capabilities, period/conversion uncertainty, and precision or overflow uncertainty all fail closed with a typed error before provider execution. A bare configured money ceiling is not an enforceable work bound and never converts these failures into admission; this path takes no Strict/ceiling fallback by design (the legacy scalar path keeps its own pre-existing ceiling behavior). It never fabricates a bound.

type ModelCustomerPricing

type ModelCustomerPricing struct {
	BackendID string
	ModelID   string
	Pricing   PricingSnapshot
}

type ModelCustomerTariff

type ModelCustomerTariff struct {
	BackendID string
	ModelID   string
	Tariff    economics.TariffSnapshot
}

ModelCustomerTariff carries the immutable component tariff selected for a backend/model route. It is separate from the legacy scalar pricing card so callers cannot accidentally substitute one valuation basis for another.

type MonetaryCause

type MonetaryCause string

MonetaryCause is a suspected, non-definitive attribution. A non-zero reported-price residual is always suspected_pricing_difference because this comparison holds no provider rate detail that could prove a tariff error.

const (
	MonetaryCauseNone                       MonetaryCause = ""
	MonetaryCauseQuantityDifference         MonetaryCause = "quantity_difference"
	MonetaryCauseSuspectedPricingDifference MonetaryCause = "suspected_pricing_difference"
)

type MonetaryDiscrepancyComparison

type MonetaryDiscrepancyComparison struct {
	Status     MonetaryDiscrepancyStatus    `json:"status"`
	Reason     MonetaryDiscrepancyReason    `json:"reason,omitempty"`
	Subject    metering.SubjectRef          `json:"subject"`
	Rows       []MonetaryDiscrepancyRow     `json:"rows"`
	Valuations []MonetaryValuationEvidence  `json:"valuations"`
	Quantity   *ComponentQuantityComparison `json:"quantity,omitempty"`
}

MonetaryDiscrepancyComparison is the bounded, deterministic result. All alternative valuations remain stored; no source-selection field exists here.

func DecomposeMonetaryDiscrepancies

func DecomposeMonetaryDiscrepancies(in MonetaryDiscrepancyInput) (MonetaryDiscrepancyComparison, error)

DecomposeMonetaryDiscrepancies compares exact E/Q/P valuation totals per native currency. Terms are computed only when the compared valuations are present, have exact amounts and share subject, payer, coverage, currency and (for E/Q) frozen tariff/rater/measurement context. Anything else returns a typed partial/incomparable outcome; missing values are never zero-filled.

type MonetaryDiscrepancyInput

type MonetaryDiscrepancyInput struct {
	Valuations         []economics.Valuation
	QuantityComparison *ComponentQuantityComparison
}

MonetaryDiscrepancyInput is the frozen valuation set for one economic subject. QuantityComparison is the optional pure Task 12.1 comparison for the same subject; it cannot supply monetary terms but its status prevents a partial/missing quantity evidence set from being reported reconciled.

type MonetaryDiscrepancyReason

type MonetaryDiscrepancyReason string

MonetaryDiscrepancyReason is the typed explanation for a non-complete term or result. Every absent amount keeps an explicit reason.

const (
	MonetaryReasonNone                         MonetaryDiscrepancyReason = ""
	MonetaryReasonMissingE                     MonetaryDiscrepancyReason = "missing_e"
	MonetaryReasonMissingQ                     MonetaryDiscrepancyReason = "missing_q"
	MonetaryReasonMissingP                     MonetaryDiscrepancyReason = "missing_p"
	MonetaryReasonAmountUnavailable            MonetaryDiscrepancyReason = "amount_unavailable"
	MonetaryReasonCurrencyMissing              MonetaryDiscrepancyReason = "currency_missing"
	MonetaryReasonSubjectMismatch              MonetaryDiscrepancyReason = "subject_mismatch"
	MonetaryReasonPayerMismatch                MonetaryDiscrepancyReason = "payer_mismatch"
	MonetaryReasonTariffMismatch               MonetaryDiscrepancyReason = "tariff_mismatch"
	MonetaryReasonContextMismatch              MonetaryDiscrepancyReason = "context_mismatch"
	MonetaryReasonCoverageMismatch             MonetaryDiscrepancyReason = "coverage_mismatch"
	MonetaryReasonCurrencyMismatch             MonetaryDiscrepancyReason = "currency_mismatch"
	MonetaryReasonValuationIncomplete          MonetaryDiscrepancyReason = "valuation_incomplete"
	MonetaryReasonValuationConflict            MonetaryDiscrepancyReason = "valuation_conflict"
	MonetaryReasonQuantityEvidencePartial      MonetaryDiscrepancyReason = "quantity_evidence_partial"
	MonetaryReasonQuantityEvidenceIncomparable MonetaryDiscrepancyReason = "quantity_evidence_incomparable"
	MonetaryReasonQuantityEvidenceConflict     MonetaryDiscrepancyReason = "quantity_evidence_conflict"
)

func (MonetaryDiscrepancyReason) IsKnown

func (r MonetaryDiscrepancyReason) IsKnown() bool

IsKnown reports whether the reason is part of the supported vocabulary.

type MonetaryDiscrepancyRole

type MonetaryDiscrepancyRole string

MonetaryDiscrepancyRole is one E/Q/P valuation plane.

const (
	MonetaryRoleE MonetaryDiscrepancyRole = "e"
	MonetaryRoleQ MonetaryDiscrepancyRole = "q"
	MonetaryRoleP MonetaryDiscrepancyRole = "p"
)

type MonetaryDiscrepancyRow

type MonetaryDiscrepancyRow struct {
	Currency              string                  `json:"currency"`
	MeteringCostEffect    MonetaryDiscrepancyTerm `json:"metering_cost_effect"`
	ReportedPriceResidual MonetaryDiscrepancyTerm `json:"reported_price_residual"`
	EndToEndCostDelta     MonetaryDiscrepancyTerm `json:"end_to_end_cost_delta"`
}

MonetaryDiscrepancyRow is one currency-scoped decomposition:

MeteringCostEffect    = Q - E
ReportedPriceResidual = P - Q
EndToEndCostDelta     = P - E

type MonetaryDiscrepancyStatus

type MonetaryDiscrepancyStatus string

MonetaryDiscrepancyStatus is the overall decomposition state. It never declares incomplete or incomparable evidence reconciled.

const (
	MonetaryDiscrepancyComplete     MonetaryDiscrepancyStatus = "complete"
	MonetaryDiscrepancyPartial      MonetaryDiscrepancyStatus = "partial"
	MonetaryDiscrepancyIncomparable MonetaryDiscrepancyStatus = "incomparable"
	MonetaryDiscrepancyConflict     MonetaryDiscrepancyStatus = "conflict"
)

func (MonetaryDiscrepancyStatus) IsKnown

func (s MonetaryDiscrepancyStatus) IsKnown() bool

type MonetaryDiscrepancyTerm

type MonetaryDiscrepancyTerm struct {
	Status MonetaryTermStatus        `json:"status"`
	Reason MonetaryDiscrepancyReason `json:"reason,omitempty"`
	Cause  MonetaryCause             `json:"cause,omitempty"`
	Amount *MonetaryExactAmount      `json:"amount,omitempty"`
}

MonetaryDiscrepancyTerm is one exact formula outcome. Amount is absent whenever the term is missing, incomparable or lacks a comparable value.

type MonetaryExactAmount

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

MonetaryExactAmount is one signed exact native-currency amount. Exactly one representation is present: a canonical bounded decimal, or reduced rational parts within the bounded exact-arithmetic contract. All Phase12 ingresses must call Validate (or Rat, which validates) before using a value.

func (MonetaryExactAmount) NormalizeCanonical

func (a MonetaryExactAmount) NormalizeCanonical() (MonetaryExactAmount, error)

NormalizeCanonical validates and returns the canonical representation. It never repairs a noncanonical value.

func (MonetaryExactAmount) Rat

func (a MonetaryExactAmount) Rat() (*big.Rat, error)

Rat returns the exact rational value for further exact arithmetic. It validates first, so unvalidated or noncanonical input never reaches arithmetic.

func (MonetaryExactAmount) Validate

func (a MonetaryExactAmount) Validate() error

Validate enforces the canonical exact-amount contract: a normalized uppercase currency code or a canonical lowercase unit key, exactly one decimal or rational representation, a canonical bounded decimal, and a gcd-reduced rational with canonical nonnegative-integer parts within the existing 128-digit bound.

type MonetaryTermStatus

type MonetaryTermStatus string

MonetaryTermStatus is the state of one cost-effect/residual formula.

const (
	MonetaryTermComplete     MonetaryTermStatus = "complete"
	MonetaryTermPartial      MonetaryTermStatus = "partial"
	MonetaryTermIncomparable MonetaryTermStatus = "incomparable"
	MonetaryTermMissing      MonetaryTermStatus = "missing"
)

type MonetaryValuationEvidence

type MonetaryValuationEvidence struct {
	Role      MonetaryDiscrepancyRole `json:"role"`
	Valuation economics.Valuation     `json:"valuation"`
}

MonetaryValuationEvidence preserves one alternative E/Q/P valuation with its role, immutable source refs and completeness labels.

type Money

type Money struct {
	Nano     int64
	Currency string
}

func NewMoney

func NewMoney(nano int64, currency string) (Money, error)

func OpenExposure

func OpenExposure(currency string, exposures []CallExposure) (Money, error)

func ReportDifference

func ReportDifference(currency string, left, right int64) (Money, error)

func ReportMargin

func ReportMargin(currency string, revenue, cost int64) (Money, error)

func SafetyMargin

func SafetyMargin(account Account, exposures []CallExposure) (Money, error)

func SettledHeadroom

func SettledHeadroom(account Account) (Money, error)

func (Money) Add

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

func (Money) IsNonNegative

func (m Money) IsNonNegative() bool

func (Money) Neg

func (m Money) Neg() (Money, error)

func (Money) Sub

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

func (Money) Validate

func (m Money) Validate() error

type MoneyEvidence

type MoneyEvidence struct {
	NanoUnits int64
	Currency  string
	Present   bool
}

type NormalizedStatement

type NormalizedStatement struct {
	Identity    economics.StatementIdentity
	Fingerprint string
	Scope       TrustedStatementScope
	Batch       economics.StatementBatch
	Lines       []NormalizedStatementLine
}

NormalizedStatement is the canonical, scope-checked statement revision ready for atomic durable retention. Observations are statement-line evidence only: no request, A-leg or B-leg allocation is invented here, and unmatched lines remain explicit rather than being attached to a guessed charge.

func NormalizeStatement

func NormalizeStatement(scope TrustedStatementScope, batch economics.StatementBatch) (NormalizedStatement, error)

NormalizeStatement validates an authenticated normalized statement, applies the trusted scope, canonicalizes its evidence and derives deterministic statement/line replay identities. It performs no persistence.

func (NormalizedStatement) Clone

Clone returns a deep copy safe for durable adapters that hand the record to another owner.

func (NormalizedStatement) Validate

func (n NormalizedStatement) Validate() error

Validate re-derives identity and fingerprints from the canonical batch so tampered retained records are rejected before they can drive matching or posting.

type NormalizedStatementLine

type NormalizedStatementLine struct {
	Identity    economics.StatementLineIdentity
	Fingerprint string
	Line        economics.StatementLine
}

NormalizedStatementLine is one canonical statement line with its immutable line identity and deterministic replay fingerprint.

type ObservationEconomicWorkBuilder

type ObservationEconomicWorkBuilder interface {
	BuildEconomicRevisionWork(context.Context, []metering.Observation) ([]EconomicRevisionWork, error)
}

ObservationEconomicWorkBuilder converts an immutable observation set into independently recoverable customer/provider work. It performs no valuation, reconciliation, balance, exposure, or journal operation.

func NewObservationEconomicWorkBuilder

func NewObservationEconomicWorkBuilder(cfg ObservationEconomicWorkBuilderConfig) (ObservationEconomicWorkBuilder, error)

NewObservationEconomicWorkBuilder constructs the production observation bridge. The default provider factory creates provider-reported P work; a nil customer factory deliberately leaves customer work disabled rather than fabricating an invalid derived snapshot context.

type ObservationEconomicWorkBuilderConfig

type ObservationEconomicWorkBuilderConfig struct {
	ProviderInput ObservationEconomicWorkInputFactory
	CustomerInput ObservationEconomicWorkInputFactory
	Now           func() time.Time
}

ObservationEconomicWorkBuilderConfig configures the provider/customer input factories. Provider-reported P is enabled by default because it needs no local tariff or policy snapshot. Customer-policy R is enabled when the composition root supplies an immutable snapshot-bound factory.

type ObservationEconomicWorkInputFactory

type ObservationEconomicWorkInputFactory func(context.Context, metering.SubjectRef, []metering.Observation) (economics.PostUsageRatingInput, error)

ObservationEconomicWorkInputFactory constructs the immutable rating input for one economic plane. The bridge supplies a cloned, deterministically ordered observation set and a stable B-leg subject.

type OperationSnapshot

type OperationSnapshot struct {
	OperationKey  string
	OperationKind string
	SourceKey     string
	Fingerprint   string
	Currency      string
	Mode          AccountMode
	Before        AccountSnapshot
	After         AccountSnapshot
	SequenceStart uint64
	SequenceEnd   uint64
	CreatedAt     time.Time
}

type OperatorCOGSResult

type OperatorCOGSResult struct {
	KnownSubtotalByCurrency map[string]Money
	KnownSubtotal           Money
	Completeness            CostCompleteness
	Payable                 bool
	IncludedLegKeys         []string
	UnknownLegKeys          []string
	ExcludedLegKeys         []string
	PendingCoverage         []metering.ChargeCoverageRef
	// AllocatedCostLines are source-preserving resource/account cost lines.
	// They are deliberately separate from B-leg keys and inference evidence;
	// an allocation target never creates a synthetic leg.
	AllocatedCostLines []AllocatedCostLine
	// PendingAllocations keeps unresolved immutable allocation ancestry visible
	// so a known subtotal is never mistaken for a complete payable result.
	PendingAllocations []economics.AllocationRef
}

OperatorCOGSResult is the operator COGS attribution result. It intentionally contains a known subtotal and the identities that kept it incomplete rather than converting an unknown attempted leg into zero. Subtotals are keyed by native currency; no implicit FX conversion is performed. Optional source-preserving allocation lines are kept separate from B-leg identities.

func AttributeOperatorCOGS

func AttributeOperatorCOGS(legs []CallLegUsageRecord, rates OperatorRateSet, currency string) (OperatorCOGSResult, error)

AttributeOperatorCOGS selects all executed operator-payable B-leg costs, independently of retail leg selection. It supports legacy V1 provider cost evidence and V2 reported charges; a V2 charge set takes precedence for its leg so the compatibility projection cannot double count it.

The currency argument selects the requested V1 authoritative-money currency for the legacy compatibility subtotal (Task 18.2, Migration Strategy step 8). The retired scalar token-to-money fallback no longer consumes it: V2 charges remain visible in their native currencies in KnownSubtotalByCurrency with no implicit FX. Operator migration: request the V1 money currency for draining/history; V2 COGS uses native currencies. No resource or account-window observation is accepted here: those subjects require a separately conserved allocation before they can be attributed to a call.

func AttributeOperatorCOGSWithAllocations

func AttributeOperatorCOGSWithAllocations(legs []CallLegUsageRecord, allocations []economics.AllocationRecord, rates OperatorRateSet, currency string) (OperatorCOGSResult, error)

AttributeOperatorCOGSWithAllocations attributes all operator-payable provider costs and then adds explicit, conserved monetary allocations from non-request resource or statement subjects. The supplied legs are the only concrete call/B-leg targets eligible for attribution; allocation lines are retained in full (including unallocated remainders), but never become inference evidence or entries in IncludedLegKeys.

Allocation records must already be scoped by the caller to the relevant reporting set. A target that is neither an unallocated remainder nor a real BillingCallID/B-leg in legs fails closed. Pending allocation supersession is retained in PendingAllocations and makes the result non-payable while known resolved lines remain visible for reporting.

func (OperatorCOGSResult) Subtotal

func (r OperatorCOGSResult) Subtotal(currency string) Money

Subtotal returns a caller-owned native-currency subtotal. An absent currency is represented by a zero amount with that currency and does not imply that the cost was known.

type OperatorCostCandidate

type OperatorCostCandidate struct {
	Basis            OperatorCostSelectionBasis `json:"basis"`
	ValuationID      string                     `json:"valuation_id"`
	ValuationVersion uint32                     `json:"valuation_version"`
	Currency         string                     `json:"currency"`
	Amount           *MonetaryExactAmount       `json:"amount"`
	Completeness     economics.Completeness     `json:"completeness"`
	Payer            metering.PaymentParty      `json:"payer,omitzero"`
	Scope            string                     `json:"scope,omitempty"`
	CoverageKey      string                     `json:"coverage_key,omitempty"`
	ContextKey       string                     `json:"context_key,omitempty"`
	FX               *OperatorCostFXBasis       `json:"fx,omitempty"`
	SourceRefs       []metering.ObservationRef  `json:"source_refs,omitempty"`
}

OperatorCostCandidate is one frozen alternative. The amount stays exact.

type OperatorCostFXBasis

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

OperatorCostFXBasis is one explicit frozen conversion basis. It binds the exact source and destination currencies, direction and bounded positive exact rate material; there is no implicit conversion.

func (OperatorCostFXBasis) Clone

func (OperatorCostFXBasis) Validate

func (b OperatorCostFXBasis) Validate() error

type OperatorCostHead

type OperatorCostHead = ProviderCostHead

OperatorCostHead is the descriptive operator-side spelling.

type OperatorCostPayerClass

type OperatorCostPayerClass string

OperatorCostPayerClass is the trusted credential payer classification.

const (
	OperatorCostPayerOperator     OperatorCostPayerClass = "operator"
	OperatorCostPayerCustomerBYOK OperatorCostPayerClass = "customer_byok"
	OperatorCostPayerUnallocated  OperatorCostPayerClass = "unallocated"
	OperatorCostPayerUnknown      OperatorCostPayerClass = "unknown"
)

func (OperatorCostPayerClass) IsKnown

func (c OperatorCostPayerClass) IsKnown() bool

type OperatorCostPostingState

type OperatorCostPostingState string

OperatorCostPostingState records that this task never posts. It is a separate field from the selection status.

const (
	OperatorCostPostingUnposted OperatorCostPostingState = "unposted"
	OperatorCostPostingPending  OperatorCostPostingState = "pending"
)

type OperatorCostProvenance

type OperatorCostProvenance string

OperatorCostProvenance is the explicit execution basis of the work.

const (
	OperatorCostProvenanceAttempted    OperatorCostProvenance = "attempted"
	OperatorCostProvenanceNeverStarted OperatorCostProvenance = "never_started"
	OperatorCostProvenanceNotBillable  OperatorCostProvenance = "not_billable"
)

func (OperatorCostProvenance) IsExplicitKnownZero

func (p OperatorCostProvenance) IsExplicitKnownZero() bool

func (OperatorCostProvenance) IsKnown

func (p OperatorCostProvenance) IsKnown() bool

type OperatorCostReconciliationRef

type OperatorCostReconciliationRef struct {
	ID          string `json:"id,omitempty"`
	Version     uint64 `json:"version,omitempty"`
	Fingerprint string `json:"fingerprint,omitempty"`
}

OperatorCostReconciliationRef preserves the durable reconciliation identity.

type OperatorCostReconciliationState

type OperatorCostReconciliationState struct {
	Ref      OperatorCostReconciliationRef  `json:"ref"`
	Status   ReconciliationComparisonStatus `json:"status"`
	Complete bool                           `json:"complete"`
}

OperatorCostReconciliationState binds comparison status and completeness separately from the selection outcome.

type OperatorCostReport

type OperatorCostReport struct {
	Rows              []OperatorCostRow
	CustomerRevenue   Money
	ProviderCost      Money
	GrossMargin       Money
	UnreconciledCosts int
	NextCursor        uint64
	NextKey           string
	Issues            []ReconciliationIssue
}

type OperatorCostResult

type OperatorCostResult struct {
	LURKey             string
	Amount             Money
	AmountPresent      bool
	Reconciled         bool
	Authoritative      bool
	UnreconciledReason string
}

func RateProviderCost

func RateProviderCost(leg CallLegUsageRecord, rates OperatorRateSet, currency string) (OperatorCostResult, error)

RateProviderCost selects the V1 provider cost for one sealed B-leg. Only provider-reported authoritative money is eligible; provider-accepted token evidence without provider money is explicitly unreconciled. The scalar token-to-money fallback was retired in Task 18.1 (Migration Strategy step 8): estimates belong to the V2 provider-quantity valuation. The rates argument is retained for signature compatibility and is ignored.

func (OperatorCostResult) SemanticFingerprint

func (c OperatorCostResult) SemanticFingerprint() (string, error)

func (OperatorCostResult) ValidateProviderAuthority

func (r OperatorCostResult) ValidateProviderAuthority() error

ValidateProviderAuthority rejects a legacy result that would otherwise be mistaken for provider-reported money. Local rates and estimates remain usable as advisory valuation results, but they cannot cross the monetary provider COGS boundary.

type OperatorCostRevisionInput

type OperatorCostRevisionInput = ProviderCostRevisionInput

OperatorCostRevisionInput is the descriptive operator-side spelling.

type OperatorCostRevisionResult

type OperatorCostRevisionResult = ProviderCostRevisionResult

OperatorCostRevisionResult is the descriptive operator-side spelling.

type OperatorCostRevisionStore

type OperatorCostRevisionStore = ProviderCostRevisionStore

OperatorCostRevisionStore is the descriptive operator-side spelling.

type OperatorCostRow

type OperatorCostRow struct {
	TURKey      string
	TurnID      string
	ALegID      string
	BLegID      string
	ProviderID  string
	ModelID     string
	Workload    WorkloadIdentity
	Transaction JournalTransaction
	Amount      Money
}

type OperatorCostSelectionBasis

type OperatorCostSelectionBasis string

OperatorCostSelectionBasis is one comparable evidence plane.

const (
	OperatorCostBasisNone OperatorCostSelectionBasis = ""
	OperatorCostBasisE    OperatorCostSelectionBasis = "e"
	OperatorCostBasisQ    OperatorCostSelectionBasis = "q"
	OperatorCostBasisP    OperatorCostSelectionBasis = "p"
	OperatorCostBasisS    OperatorCostSelectionBasis = "s"
)

func (OperatorCostSelectionBasis) IsKnown

func (b OperatorCostSelectionBasis) IsKnown() bool

type OperatorCostSelectionInput

type OperatorCostSelectionInput struct {
	Subject        metering.SubjectRef             `json:"subject"`
	Scope          string                          `json:"scope,omitempty"`
	CoverageKey    string                          `json:"coverage_key,omitempty"`
	ContextKey     string                          `json:"context_key,omitempty"`
	Currency       string                          `json:"currency"`
	FX             *OperatorCostFXBasis            `json:"fx,omitempty"`
	PayerClass     OperatorCostPayerClass          `json:"payer_class"`
	Provenance     OperatorCostProvenance          `json:"provenance"`
	Reconciliation OperatorCostReconciliationState `json:"reconciliation"`
	Candidates     []OperatorCostCandidate         `json:"candidates,omitempty"`
	AsOf           time.Time                       `json:"as_of,omitzero"`
}

OperatorCostSelectionInput is the frozen selection context.

type OperatorCostSelectionPolicy

type OperatorCostSelectionPolicy struct {
	Version             uint32                      `json:"version"`
	Ref                 VersionRef                  `json:"ref"`
	Rules               []OperatorCostSelectionRule `json:"rules"`
	KnownZeroProvenance []OperatorCostProvenance    `json:"known_zero_provenance,omitempty"`
}

OperatorCostSelectionPolicy is the versioned immutable selection policy. A final rule must require complete evidence; known-zero is only authorized by an explicit provenance list.

func (OperatorCostSelectionPolicy) Clone

Clone makes the policy independent of caller memory.

func (OperatorCostSelectionPolicy) Validate

func (p OperatorCostSelectionPolicy) Validate() error

Validate rejects malformed versions, duplicate rule ids, unknown bases or statuses, final rules that accept partial evidence and malformed known-zero authorization.

type OperatorCostSelectionReason

type OperatorCostSelectionReason string

OperatorCostSelectionReason is the typed explanation of a non-final selection.

const (
	OperatorCostReasonNone                   OperatorCostSelectionReason = ""
	OperatorCostReasonNoPayableEvidence      OperatorCostSelectionReason = "no_payable_evidence"
	OperatorCostReasonKnownZeroAuthorized    OperatorCostSelectionReason = "known_zero_authorized"
	OperatorCostReasonKnownZeroNotAuthorized OperatorCostSelectionReason = "known_zero_not_authorized"
	OperatorCostReasonPayerCustomerBYOK      OperatorCostSelectionReason = "payer_customer_byok"
	OperatorCostReasonPayerUnallocated       OperatorCostSelectionReason = "payer_unallocated"
	OperatorCostReasonPayerNotOperator       OperatorCostSelectionReason = "payer_not_operator"
	OperatorCostReasonCurrencyMismatch       OperatorCostSelectionReason = "currency_mismatch"
	OperatorCostReasonCandidateIncompatible  OperatorCostSelectionReason = "candidate_incompatible"
	OperatorCostReasonComparisonConflict     OperatorCostSelectionReason = "comparison_conflict"
	OperatorCostReasonIncomparableComparison OperatorCostSelectionReason = "incomparable_comparison"
	OperatorCostReasonIncompleteEvidence     OperatorCostSelectionReason = "incomplete_evidence"
)

type OperatorCostSelectionResult

type OperatorCostSelectionResult struct {
	Policy             VersionRef                     `json:"policy"`
	Subject            metering.SubjectRef            `json:"subject"`
	Scope              string                         `json:"scope,omitempty"`
	PayerClass         OperatorCostPayerClass         `json:"payer_class"`
	Provenance         OperatorCostProvenance         `json:"provenance"`
	Currency           string                         `json:"currency"`
	FX                 *OperatorCostFXBasis           `json:"fx,omitempty"`
	Status             OperatorCostSelectionStatus    `json:"status"`
	Basis              OperatorCostSelectionBasis     `json:"basis,omitempty"`
	Reason             OperatorCostSelectionReason    `json:"reason,omitempty"`
	Amount             *MonetaryExactAmount           `json:"amount,omitempty"`
	NativeAmount       *MonetaryExactAmount           `json:"native_amount,omitempty"`
	KnownZeroBasis     OperatorCostProvenance         `json:"known_zero_basis,omitempty"`
	ComparisonStatus   ReconciliationComparisonStatus `json:"comparison_status"`
	ComparisonComplete bool                           `json:"comparison_complete"`
	Reconciliation     OperatorCostReconciliationRef  `json:"reconciliation"`
	PostingState       OperatorCostPostingState       `json:"posting_state"`
	Candidates         []OperatorCostCandidate        `json:"candidates"`
	AsOf               time.Time                      `json:"as_of,omitzero"`
}

OperatorCostSelectionResult preserves all alternatives and all state planes.

func SelectOperatorCost

SelectOperatorCost chooses one basis under the explicit ordered policy. It is pure: it never mutates the policy or input, never deletes alternatives and never claims reconciliation success from source selection alone.

type OperatorCostSelectionRule

type OperatorCostSelectionRule struct {
	ID                          string                      `json:"id"`
	Basis                       OperatorCostSelectionBasis  `json:"basis"`
	Status                      OperatorCostSelectionStatus `json:"status"`
	RequireOperatorPayer        bool                        `json:"require_operator_payer"`
	AllowPartialEvidence        bool                        `json:"allow_partial_evidence"`
	RequireComparableComparison bool                        `json:"require_comparable_comparison"`
}

OperatorCostSelectionRule is one ordered, conditional policy step. The first matching rule and candidate wins.

type OperatorCostSelectionStatus

type OperatorCostSelectionStatus string

OperatorCostSelectionStatus is the selection outcome. It is deliberately separate from comparison status, evidence completeness and posting state.

const (
	OperatorCostSelectionStatusFinal              OperatorCostSelectionStatus = "final"
	OperatorCostSelectionStatusProvisional        OperatorCostSelectionStatus = "provisional"
	OperatorCostSelectionStatusKnownZero          OperatorCostSelectionStatus = "known_zero"
	OperatorCostSelectionStatusUnknown            OperatorCostSelectionStatus = "unknown"
	OperatorCostSelectionStatusIncomparable       OperatorCostSelectionStatus = "incomparable"
	OperatorCostSelectionStatusConflict           OperatorCostSelectionStatus = "conflict"
	OperatorCostSelectionStatusNotOperatorPayable OperatorCostSelectionStatus = "not_operator_payable"
)

type OperatorRateSet

type OperatorRateSet []OperatorRateSnapshot

type OperatorRateSnapshot

type OperatorRateSnapshot struct {
	Ref                      VersionRef
	Currency                 string
	InputPerMillionNano      int64
	OutputPerMillionNano     int64
	CacheReadPerMillionNano  int64
	CacheWritePerMillionNano int64
	ReasoningPerMillionNano  int64
	InputRatePresent         bool
	OutputRatePresent        bool
	CacheReadRatePresent     bool
	CacheWriteRatePresent    bool
	ReasoningRatePresent     bool
}

OperatorRateSnapshot is a historical V1 compatibility record (Migration Strategy step 8, Task 18.2). The scalar token-to-money fallback was retired in Task 18.1: live estimates belong to the V2 provider-quantity valuation, and RateProviderCost ignores rate bodies. Retained records support historical replay and OperatorRateRef lineage on sealed B-legs. Operator migration: stop publishing operator rates for live rating; V2 tariffs own estimates; historical bodies remain readable.

func (OperatorRateSnapshot) Validate

func (r OperatorRateSnapshot) Validate() error

type OwnerAwareCallRatingResolver

type OwnerAwareCallRatingResolver interface {
	ResolveCallRatingForOwner(ctx context.Context, complete CompleteCall, exposure CallExposure, owner string) (CallRatingResult, error)
}

OwnerAwareCallRatingResolver is the production customer-rating port that carries the durable B1 pin owner into rating selection. Workers must use it with the claim owner so V2-owned work can never silently select the scalar live engine. Production/cutover V2 requires this port: a resolver exposing only the legacy CallRatingResolver fails closed for V2 before any money. The legacy port survives only for V1 drain and test-only non-cutover paths.

type PageRequest

type PageRequest struct {
	AfterSequence uint64
	AfterKey      string
	Limit         int
}

func (PageRequest) Normalize

func (p PageRequest) Normalize() (PageRequest, error)

type PaymentInput

type PaymentInput struct {
	AccountID string
	Amount    Money
	SourceKey string
	Reason    string
}

func (PaymentInput) Fingerprint

func (in PaymentInput) Fingerprint() (string, error)

func (PaymentInput) Validate

func (in PaymentInput) Validate() error

type PolicyChange

type PolicyChange struct {
	OperationKey string
	Before       AccountSnapshot
	After        AccountSnapshot
	Replayed     bool
}

type PostUsageRater

type PostUsageRater interface {
	Rate(context.Context, economics.PostUsageRatingInput) (economics.Valuation, error)
}

PostUsageRater is the billing-owned seam for deterministic monetary rating. It is intentionally not part of pkg/lipsdk/economics: stream-time SDK consumers must not acquire a public financial rater contract.

type Posting

type Posting struct {
	OperationKey string
	Transaction  JournalTransaction
	Before       AccountSnapshot
	After        AccountSnapshot
	Replayed     bool
}

type PostingOperationKind

type PostingOperationKind string
const (
	PostingOperationCustomerSettlement  PostingOperationKind = "customer_call_settlement"
	PostingOperationProviderCharge      PostingOperationKind = "provider_charge"
	PostingOperationFinancialAdjustment PostingOperationKind = "financial_adjustment"
)

func (PostingOperationKind) Valid

func (k PostingOperationKind) Valid() bool

Valid reports whether the operation kind is one of the three approved pin namespaces.

type PostingPin

type PostingPin struct {
	StoreID                 string
	Kind                    PostingOperationKind
	OperationKey            string
	AccountID               string
	CallID                  BillingCallID
	BLegID                  string
	ProviderChargeID        string
	HeadKey                 string
	Subject                 metering.SubjectRef
	Owner                   string
	MarkerVersion           uint64
	MarkerEpoch             uint64
	MarkerGeneration        int
	MarkerState             AccountingCutoverState
	Status                  PostingPinStatus
	CompletionOperationKey  string
	CompletionTransactionID string
	CreatedAtUnix           int64
	UpdatedAtUnix           int64
	CompletedAtUnix         int64
}

PostingPin is the durable per-operation ownership record.

func (PostingPin) IsCompleted

func (p PostingPin) IsCompleted() bool

IsCompleted reports whether the pin carries a durable posting outcome.

func (PostingPin) Validate

func (p PostingPin) Validate() error

Validate fails closed on any malformed or inconsistent pin. OperationKey must equal the canonical derivation for the pin identity so weak or cross-kind keys cannot become durable. Financial adjustment has three versioned shapes sharing one kind: selected-cost head pins ("financial-adjustment:v1:", B2b3, account/call/head/subject), cost-pass-through per-head pins ("financial-adjustment-cost-pass-through:v1:", B2b4, account/call/head, no subject) and direct per-source pins ("financial-adjustment-direct:v1:", B2b4, account/source in head_key, no call/subject).

type PostingPinStatus

type PostingPinStatus string
const (
	PostingPinPinned    PostingPinStatus = "pinned"
	PostingPinCompleted PostingPinStatus = "completed"
)

func (PostingPinStatus) Valid

func (s PostingPinStatus) Valid() bool

Valid reports whether the pin status is pinned or completed.

type PricingSnapshot

type PricingSnapshot struct {
	Ref                  VersionRef
	Currency             string
	InputPerMillionNano  int64
	OutputPerMillionNano int64
	InputRatePresent     bool
	OutputRatePresent    bool
	FixedCharges         []ChargeComponent
	ResourceCharges      []ChargeComponent
}

func (PricingSnapshot) Validate

func (p PricingSnapshot) Validate(currency string) error

type ProviderChargeClaimInput

type ProviderChargeClaimInput struct {
	Owner string
	Claim *CutoverClaimMetadata
}

ProviderChargeClaimInput carries the resolved owner/claim pair a worker passes to the durable posting seam.

type ProviderCost

type ProviderCost = CostPassThroughProviderCost

ProviderCost is a short compatibility alias for callers that already use a provider-cost vocabulary.

type ProviderCostAuthorityError

type ProviderCostAuthorityError = ProviderCostRevisionAuthorityError

ProviderCostAuthorityError is the typed authority failure returned when a legacy provider-cost result is not provider-authoritative. It aliases the existing revision error type so callers can inspect either boundary using errors.As without introducing a second error shape.

type ProviderCostFailureStore

type ProviderCostFailureStore interface {
	MarkProviderCostUnreconciled(context.Context, ApplyProviderCostInput, string) error
}

type ProviderCostHead

type ProviderCostHead struct {
	AccountID        string
	CallID           BillingCallID
	HeadKey          string
	Subject          metering.SubjectRef
	EvidenceRevision uint64
	InputSetHash     string
	ValuationID      string
	CurrentAmount    Money
	HeadVersion      uint64
	Fence            uint64
	LastOperationKey string
	// OriginalTransactionID is the first durable provider-cost journal in this
	// head's correction group. LastTransactionID is the most recent journal and
	// is the target for the next chained adjustment.
	OriginalTransactionID string
	LastTransactionID     string
	UpdatedAt             time.Time
}

ProviderCostHead is the rebuildable selected-cost pointer. Immutable work, valuation and journal rows remain the audit history; HeadVersion/Fence protect this pointer from late or concurrent workers.

type ProviderCostHeadReader

type ProviderCostHeadReader interface {
	GetProviderCostHead(context.Context, string, BillingCallID, string) (ProviderCostHead, error)
}

ProviderCostHeadReader reads the current selected-cost pointer without changing any accounting state.

type ProviderCostOperationKey

type ProviderCostOperationKey struct {
	CallID BillingCallID
	BLegID string
}

func NewProviderCostOperationKey

func NewProviderCostOperationKey(callID BillingCallID, bLegID string) (ProviderCostOperationKey, error)

func (ProviderCostOperationKey) String

func (k ProviderCostOperationKey) String() string

type ProviderCostResolver

type ProviderCostResolver interface {
	ResolveProviderCost(context.Context, CallLegUsageRecord) (OperatorCostResult, error)
}

type ProviderCostRevisionAuthorityError

type ProviderCostRevisionAuthorityError struct {
	Field    string
	Value    string
	Expected string
}

ProviderCostRevisionAuthorityError is returned when a provider-cost revision crosses the monetary posting boundary without the required provider-origin, observed evidence. Field and Expected contain bounded schema labels; Value is restricted to a bounded enum/absence description so malformed input cannot make secrets part of an accounting error.

func (*ProviderCostRevisionAuthorityError) Error

func (*ProviderCostRevisionAuthorityError) Unwrap

Unwrap preserves both the specific authority classification and the generic malformed-revision classification used by older callers.

type ProviderCostRevisionInput

type ProviderCostRevisionInput struct {
	AccountID string
	CallID    BillingCallID
	Subject   metering.SubjectRef
	// ALegID and BLegID are compact compatibility fields. Subject is the
	// authoritative tagged lineage when it is supplied; these fields only fill
	// its corresponding empty ancestry fields at normalization.
	ALegID           string
	BLegID           string
	HeadKey          string
	EvidenceRevision uint64
	Revision         uint64
	InputSetHash     string
	ValuationID      string
	Cost             OperatorCOGSResult
	// Evidence is the immutable provider-neutral rating input that authorizes
	// a payable operator COGS selection. It is intentionally retained at this
	// boundary instead of reducing authority to a caller-controlled boolean.
	Evidence      economics.PostUsageRatingInput
	Amount        Money
	AmountPresent bool
	Authoritative bool
	// PostingOwner selects the B1 pin owner for the provider charge fence.
	// Empty preserves the legacy V1 default for backward compatibility.
	// Draining requires a classified V1 pin plus matching claim metadata;
	// v2_active permits only V2.
	PostingOwner string
	// Claim carries the B2a worker-claim metadata (owner/epoch) captured at
	// claim time. When present, posting validates it against the current
	// marker and pin to close TOCTOU between claim and posting. Nil preserves
	// legacy direct calls in v1_active/shadow; draining fences unpinned/stale
	// work even without a claim, and B2b2 draining requires a matching claim
	// for new postings.
	Claim *CutoverClaimMetadata
}

ProviderCostRevisionInput is the durable-store boundary for one selected provider-cost revision. Cost is the all-attributable B-leg COGS result; it is intentionally separate from customer retail selection. Amount and Revision are compatibility conveniences for direct adapters: normalized callers should prefer Cost and EvidenceRevision.

func BuildProviderCostRevisionInput

func BuildProviderCostRevisionInput(work EconomicRevisionWork, valuation economics.Valuation) (ProviderCostRevisionInput, error)

BuildProviderCostRevisionInput derives an operator-payable selected-cost revision from the immutable observations carried by economic work. It uses the same coverage/payer reducer as AttributeOperatorCOGS and therefore never promotes BYOK/customer-payable or unknown charges into COGS.

func BuildProviderCostRevisionInputFromWork

func BuildProviderCostRevisionInputFromWork(work EconomicRevisionWork) (ProviderCostRevisionInput, error)

BuildProviderCostRevisionInputFromWork is used on worker restart when the immutable pure valuation has already been persisted. Work still carries the original observations and revision identity, so no rater call or valuation read is needed to retry the provider posting.

func (ProviderCostRevisionInput) Normalize

Normalize validates and returns a copy of the provider revision envelope.

func (ProviderCostRevisionInput) SemanticFingerprint

func (in ProviderCostRevisionInput) SemanticFingerprint() (string, error)

SemanticFingerprint is the immutable operation identity. Payer and completeness are included so a previously ignored/unreconciled result can never be silently replayed as payable under the same revision.

type ProviderCostRevisionResult

type ProviderCostRevisionResult struct {
	AccountID      string
	CallID         BillingCallID
	HeadKey        string
	ALegID         string
	BLegID         string
	Revision       uint64
	PreviousAmount Money
	CurrentAmount  Money
	Delta          Money
	Posting        Posting
	Applied        bool
	Replayed       bool
	Stale          bool
	Ignored        bool
}

ProviderCostRevisionResult reports one fenced current-head transition. A negative Delta is a reversal of previously accrued COGS; it never mutates a customer balance. Ignored marks a complete but non-payable payer selection (for example BYOK/customer-payable provider charges).

type ProviderCostRevisionStore

type ProviderCostRevisionStore interface {
	ApplyProviderCostRevision(context.Context, ProviderCostRevisionInput) (ProviderCostRevisionResult, error)
}

ProviderCostRevisionStore owns the only monetary writer for provider COGS revisions. Implementations must atomically fence the head and journal delta and must not lock or update customer balance state for pure provider COGS.

type ProviderCostStore

type ProviderCostStore interface {
	ApplyProviderCost(context.Context, ApplyProviderCostInput) (Posting, error)
}

type ProviderCostWork

type ProviderCostWork struct {
	AccountID string
	CallID    BillingCallID
	Leg       CallLegUsageRecord
}

type ProviderCostWorkClaimStore

type ProviderCostWorkClaimStore interface {
	GetCutoverClaimMetadata(ctx context.Context, kind PostingOperationKind, operationKey string) (CutoverClaimMetadata, error)
}

ProviderCostWorkClaimStore is the narrow claim port workers consume to pass claim-time owner/epoch to posting-time validation. DurableStore implements it via GetCutoverClaimMetadata; test doubles may implement it explicitly. Production workers must be constructed with a non-nil claim provider (see NewCallProviderCostWorkerWithClaim); the legacy constructor remains test-only.

type ProviderCostWorkCutoverStore

type ProviderCostWorkCutoverStore interface {
	ClaimProviderCostWorkForRevision(context.Context, ProviderCostWork) (bool, error)
}

ProviderCostWorkCutoverStore atomically acknowledges legacy work that is already owned by the durable revision posting authority. It lets a stale legacy worker retire its queue item without invoking a resolver or emitting an unreconciled marker after a revision has won the same B-leg lineage.

type ProviderCostWorkFailureStore

type ProviderCostWorkFailureStore interface {
	DeferProviderCostWork(context.Context, ProviderCostWork, string) error
}

type ProviderCostWorkReader

type ProviderCostWorkReader interface {
	ListPendingProviderCostWork(context.Context, int) ([]ProviderCostWork, error)
}

type ProviderCostWorkStore

type ProviderCostWorkStore interface {
	ProviderCostWorkReader
	ProviderCostWorkFailureStore
}

ProviderCostWorkStore combines reader and failure handling for provider cost work.

type ProviderMaintenanceUsage

type ProviderMaintenanceUsage struct {
	OperationID string
	ALegID      string
	TargetID    string
	BackendID   string
	ModelID     string
	RecordedAt  time.Time
	Evidence    FinalBillingEvidence
}

ProviderMaintenanceUsage is provider-authoritative usage from a control-plane maintenance call. It is intentionally not a CallLegUsageRecord: maintenance must retain its operation identity without masquerading as a foreground B-leg.

func (ProviderMaintenanceUsage) Fingerprint

func (u ProviderMaintenanceUsage) Fingerprint() (string, error)

func (ProviderMaintenanceUsage) Validate

func (u ProviderMaintenanceUsage) Validate() error

type ProviderMaintenanceUsageObserver

type ProviderMaintenanceUsageObserver interface {
	ObserveProviderMaintenance(context.Context, ProviderMaintenanceUsage) error
}

ProviderMaintenanceUsageObserver delivers immutable maintenance evidence to its durable owner. Errors stay visible to the keep-warm lifecycle so delivery failures are not silently mistaken for successful accounting.

type ProviderMaintenanceUsageObserverFunc

type ProviderMaintenanceUsageObserverFunc func(context.Context, ProviderMaintenanceUsage) error

func (ProviderMaintenanceUsageObserverFunc) ObserveProviderMaintenance

func (f ProviderMaintenanceUsageObserverFunc) ObserveProviderMaintenance(ctx context.Context, usage ProviderMaintenanceUsage) error

type ProviderMaintenanceUsageStore

type ProviderMaintenanceUsageStore interface {
	AppendProviderMaintenance(context.Context, ProviderMaintenanceUsage) error
}

ProviderMaintenanceUsageStore is the durable provider-billable persistence boundary for control-plane maintenance usage.

type Quantity

type Quantity struct {
	Value   int64
	Present bool
}

type Rater

type Rater = PostUsageRater

Rater is a concise internal alias retained for billing composition. Its package location makes post-usage ownership visible to architecture checks.

type ReconciliationAggregate

type ReconciliationAggregate struct {
	Policy   VersionRef                   `json:"policy"`
	Findings []ReconciliationFinding      `json:"findings"`
	Rows     []ReconciliationAggregateRow `json:"rows"`
}

ReconciliationAggregate is the immutable projection result. It retains the policy reference, every classified finding and its source refs.

func AggregateReconciliationFindings

func AggregateReconciliationFindings(policy ReconciliationTolerancePolicy, findings []ReconciliationFinding) (ReconciliationAggregate, error)

AggregateReconciliationFindings applies the tolerance policy to every comparable finding, retains all classified evidence and produces deterministic per-scope/currency/unit rows. Gross absolute discrepancy sums absolute deltas without offsetting; the signed net is reported separately.

type ReconciliationAggregateRow

type ReconciliationAggregateRow struct {
	Scope    string `json:"scope,omitempty"`
	Currency string `json:"currency,omitempty"`
	Unit     string `json:"unit,omitempty"`

	GrossAbsoluteDiscrepancy      *MonetaryExactAmount `json:"gross_absolute_discrepancy"`
	DiscrepantAbsoluteDiscrepancy *MonetaryExactAmount `json:"discrepant_absolute_discrepancy"`
	NetSignedDiscrepancy          *MonetaryExactAmount `json:"net_signed_discrepancy"`

	AffectedCount          int `json:"affected_count"`
	EstimatedAffectedCount int `json:"estimated_affected_count"`

	StatusCounts    []ReconciliationStatusCount `json:"status_counts"`
	MissingIDs      []string                    `json:"missing_ids,omitempty"`
	IncomparableIDs []string                    `json:"incomparable_ids,omitempty"`
	ConflictIDs     []string                    `json:"conflict_ids,omitempty"`
}

ReconciliationAggregateRow is one scope/currency/unit projection. Gross absolute discrepancy never nets offsets; the signed net is separate.

type ReconciliationComparisonReason

type ReconciliationComparisonReason string

ReconciliationComparisonReason is the typed explanation for a non-compared component. An empty reason accompanies matched/discrepant items.

const (
	ReconciliationReasonNone                     ReconciliationComparisonReason = ""
	ReconciliationReasonSubjectMismatch          ReconciliationComparisonReason = "subject_mismatch"
	ReconciliationReasonPeriodMismatch           ReconciliationComparisonReason = "period_mismatch"
	ReconciliationReasonPayerMismatch            ReconciliationComparisonReason = "payer_mismatch"
	ReconciliationReasonCurrencyMismatch         ReconciliationComparisonReason = "currency_mismatch"
	ReconciliationReasonScopeMismatch            ReconciliationComparisonReason = "scope_mismatch"
	ReconciliationReasonChargeMismatch           ReconciliationComparisonReason = "charge_mismatch"
	ReconciliationReasonCoverageMismatch         ReconciliationComparisonReason = "coverage_mismatch"
	ReconciliationReasonContextMismatch          ReconciliationComparisonReason = "measurement_context_mismatch"
	ReconciliationReasonSchemaMismatch           ReconciliationComparisonReason = "schema_mismatch"
	ReconciliationReasonQualifierMismatch        ReconciliationComparisonReason = "qualifier_mismatch"
	ReconciliationReasonTokenizerMismatch        ReconciliationComparisonReason = "tokenizer_mismatch"
	ReconciliationReasonTokenizerMissing         ReconciliationComparisonReason = "tokenizer_missing"
	ReconciliationReasonTokenizerRequired        ReconciliationComparisonReason = "tokenizer_required"
	ReconciliationReasonSemanticsMismatch        ReconciliationComparisonReason = "semantics_mismatch"
	ReconciliationReasonValueUnavailableLocal    ReconciliationComparisonReason = "value_unavailable_local"
	ReconciliationReasonValueUnavailableProvider ReconciliationComparisonReason = "value_unavailable_provider"
	ReconciliationReasonValueUnavailableBoth     ReconciliationComparisonReason = "value_unavailable_both"
	ReconciliationReasonDuplicateLocal           ReconciliationComparisonReason = "duplicate_local"
	ReconciliationReasonDuplicateProvider        ReconciliationComparisonReason = "duplicate_provider"
	ReconciliationReasonConflictingLocal         ReconciliationComparisonReason = "conflicting_local"
	ReconciliationReasonConflictingProvider      ReconciliationComparisonReason = "conflicting_provider"
	// ReconciliationReasonBasisMismatch identifies a valuation basis that is
	// known but not independently comparable as local-versus-provider
	// evidence (for example retail/customer-policy selected from provider
	// data). It is an explicit incomparable cause, never a match.
	ReconciliationReasonBasisMismatch ReconciliationComparisonReason = "basis_mismatch"
)

func (ReconciliationComparisonReason) IsKnown

IsKnown reports whether the reason is part of the supported reconciliation vocabulary across the Phase12 comparison, tolerance and aggregation surfaces.

type ReconciliationComparisonStatus

type ReconciliationComparisonStatus string

ReconciliationComparisonStatus is the comparison outcome for one component. It is deliberately separate from cost selection or posting state.

const (
	ReconciliationStatusMatched         ReconciliationComparisonStatus = "matched"
	ReconciliationStatusDiscrepant      ReconciliationComparisonStatus = "discrepant"
	ReconciliationStatusPartial         ReconciliationComparisonStatus = "partial"
	ReconciliationStatusIncomparable    ReconciliationComparisonStatus = "incomparable"
	ReconciliationStatusMissingLocal    ReconciliationComparisonStatus = "missing_local"
	ReconciliationStatusMissingProvider ReconciliationComparisonStatus = "missing_provider"
	ReconciliationStatusConflict        ReconciliationComparisonStatus = "conflict"
)

type ReconciliationEvidenceSet

type ReconciliationEvidenceSet struct {
	Subject             metering.SubjectRef          `json:"subject"`
	Payer               metering.PaymentParty        `json:"payer,omitzero"`
	Currency            string                       `json:"currency,omitempty"`
	Scope               string                       `json:"scope,omitempty"`
	PeriodID            string                       `json:"period_id,omitempty"`
	ChargeItemID        string                       `json:"charge_item_id,omitempty"`
	Tokenizer           string                       `json:"tokenizer,omitempty"`
	Coverage            []metering.ChargeCoverageRef `json:"coverage,omitempty"`
	EffectiveQualifiers []metering.Dimension         `json:"effective_qualifiers,omitempty"`
	Observations        []metering.Observation       `json:"observations,omitempty"`
}

ReconciliationEvidenceSet is one frozen side of a quantity comparison. The side-level fields are the join context; observations supply component measures. It retains no account balance, journal handle or provider SDK. Tokenizer is the explicitly declared effective tokenizer semantics identity. A declaration on one side and none on the other is incomparable (tokenizer_missing), two different declarations are incomparable (tokenizer_mismatch) and a token-measured component with no declaration on either side is incomparable (tokenizer_required); only non-token native units stay comparable without declarations. Per-measure method references remain informational labels because local and provider measurement pipelines are expected to differ.

type ReconciliationFinding

type ReconciliationFinding struct {
	ID              string                         `json:"id"`
	Scope           string                         `json:"scope,omitempty"`
	Direction       metering.FlowDirection         `json:"direction,omitempty"`
	Unit            string                         `json:"unit,omitempty"`
	Currency        string                         `json:"currency,omitempty"`
	Component       string                         `json:"component,omitempty"`
	SchemaID        string                         `json:"schema_id,omitempty"`
	Context         string                         `json:"context,omitempty"`
	Status          ReconciliationComparisonStatus `json:"status"`
	Reason          ReconciliationComparisonReason `json:"reason,omitempty"`
	LocalQuality    string                         `json:"local_quality,omitempty"`
	ProviderQuality string                         `json:"provider_quality,omitempty"`

	Expected *MonetaryExactAmount `json:"expected,omitempty"`
	Reported *MonetaryExactAmount `json:"reported,omitempty"`

	SourceObservationRefs []metering.ObservationRef `json:"source_observation_refs,omitempty"`
	ValuationIDs          []string                  `json:"valuation_ids,omitempty"`

	EvaluatedStatus  ReconciliationComparisonStatus     `json:"evaluated_status"`
	EvaluationReason ReconciliationComparisonReason     `json:"evaluation_reason,omitempty"`
	Evaluation       *ReconciliationToleranceEvaluation `json:"evaluation,omitempty"`
}

ReconciliationFinding is one comparable or non-comparable evidence item. Expected/Reported are quantity or monetary exact values; the amount's Currency field carries the exact unit key. Quality labels and source refs are retained verbatim.

func ReconciliationFindingsFromMonetaryComparison

func ReconciliationFindingsFromMonetaryComparison(scope string, comparison MonetaryDiscrepancyComparison) ([]ReconciliationFinding, error)

ReconciliationFindingsFromMonetaryComparison projects Task 12.2 outcomes into aggregate findings. E totals are the expected side and P totals the reported side; missing/incomparable end-to-end terms keep their status.

func ReconciliationFindingsFromQuantityComparison

func ReconciliationFindingsFromQuantityComparison(scope string, comparison ComponentQuantityComparison) ([]ReconciliationFinding, error)

ReconciliationFindingsFromQuantityComparison projects Task 12.1 outcomes into aggregate findings. Local values are the expected side and provider values the reported side.

type ReconciliationIssue

type ReconciliationIssue struct {
	Code     string
	Sequence uint64
	Detail   string
}

func SummarizeJournalForReport

func SummarizeJournalForReport(transactions []JournalTransaction, currency string) (int64, int64, []ReconciliationIssue)

type ReconciliationQuantityEvidence

type ReconciliationQuantityEvidence struct {
	Key         metering.ComponentKey   `json:"key"`
	Value       *metering.Decimal       `json:"value,omitempty"`
	Quality     string                  `json:"quality"`
	MethodRef   string                  `json:"method_ref,omitempty"`
	Observation metering.ObservationRef `json:"observation"`
}

ReconciliationQuantityEvidence retains one side's component quantity with its certainty label and immutable source observation reference.

type ReconciliationReport

type ReconciliationReport struct {
	AccountID             string
	OK                    bool
	Current               AccountSnapshot
	Rebuilt               AccountSnapshot
	FirstMismatchSequence uint64
	Issues                []ReconciliationIssue
}

func ReplayAccount

func ReplayAccount(account Account, openingBalance int64, journals []JournalTransaction) ReconciliationReport

func (*ReconciliationReport) AddIssue

func (r *ReconciliationReport) AddIssue(code string, sequence uint64, detail string)

type ReconciliationRetentionDiagnostic

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

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

type ReconciliationRetentionResult

type ReconciliationRetentionResult struct {
	SchemaVersion  uint32                       `json:"schema_version"`
	ID             string                       `json:"id"`
	ResultRevision uint64                       `json:"result_revision"`
	Subject        metering.SubjectRef          `json:"subject"`
	Scope          string                       `json:"scope,omitempty"`
	Payer          metering.PaymentParty        `json:"payer,omitzero"`
	CoverageRefs   []metering.ChargeCoverageRef `json:"coverage_refs,omitempty"`
	Policy         VersionRef                   `json:"policy"`

	InputSetHash      string `json:"input_set_hash,omitempty"`
	LocalInputHash    string `json:"local_input_hash,omitempty"`
	ProviderInputHash string `json:"provider_input_hash,omitempty"`

	ValuationIDs    []string                  `json:"valuation_ids,omitempty"`
	ObservationRefs []metering.ObservationRef `json:"observation_refs,omitempty"`

	Quantity  *ComponentQuantityComparison   `json:"quantity,omitempty"`
	Monetary  *MonetaryDiscrepancyComparison `json:"monetary,omitempty"`
	Aggregate *ReconciliationAggregate       `json:"aggregate,omitempty"`

	Diagnostics []ReconciliationRetentionDiagnostic `json:"diagnostics,omitempty"`
	CreatedAt   time.Time                           `json:"created_at"`
}

ReconciliationRetentionResult is the canonical full reconciliation result: identity/revision, economic scope, policy version, comparison input hashes and refs, the 12.1 quantity comparison, the 12.2 monetary decomposition with its alternative valuations, the 12.3 aggregate projection and safe diagnostics. Exact decimals and source refs are preserved verbatim.

func ParseReconciliationRetentionResult

func ParseReconciliationRetentionResult(payload []byte) (ReconciliationRetentionResult, error)

ParseReconciliationRetentionResult decodes a stored payload and verifies it is exactly canonical before returning it.

func (ReconciliationRetentionResult) CanonicalJSON

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

CanonicalJSON returns the deterministic durable payload with sorted object keys, exactly matching the storage canonicalization contract.

func (ReconciliationRetentionResult) Fingerprint

func (r ReconciliationRetentionResult) Fingerprint() string

Fingerprint returns the SHA-256 hex digest of the canonical payload. It is an accelerator; stored bytes remain the authoritative identity.

func (ReconciliationRetentionResult) Normalize

Normalize validates, deep-copies and deterministically orders the result so the same evidence produces one durable identity regardless of input order.

func (ReconciliationRetentionResult) Validate

func (r ReconciliationRetentionResult) Validate() error

Validate checks the durable identity, scope, policy binding, evidence references and payload bound without mutating the value.

type ReconciliationStatusCount

type ReconciliationStatusCount struct {
	Status ReconciliationComparisonStatus `json:"status"`
	Count  int                            `json:"count"`
}

ReconciliationStatusCount keeps deterministic per-status counts.

type ReconciliationToleranceEvaluation

type ReconciliationToleranceEvaluation struct {
	PolicyID      string                        `json:"policy_id"`
	PolicyVersion string                        `json:"policy_version"`
	RuleID        string                        `json:"rule_id,omitempty"`
	Target        ReconciliationToleranceTarget `json:"target"`

	Expected *MonetaryExactAmount `json:"expected,omitempty"`
	Reported *MonetaryExactAmount `json:"reported,omitempty"`

	SignedDelta   *MonetaryExactAmount `json:"signed_delta,omitempty"`
	AbsoluteDelta *MonetaryExactAmount `json:"absolute_delta,omitempty"`

	RelativeDifference *MonetaryExactAmount `json:"relative_difference,omitempty"`
	RelativePresent    bool                 `json:"relative_present"`
	ZeroDenominator    bool                 `json:"zero_denominator"`

	AbsoluteLimit *metering.Decimal    `json:"absolute_limit,omitempty"`
	RelativeLimit *metering.Decimal    `json:"relative_limit,omitempty"`
	Threshold     *MonetaryExactAmount `json:"threshold,omitempty"`

	WithinTolerance bool                           `json:"within_tolerance"`
	Status          ReconciliationComparisonStatus `json:"status"`
	Reason          ReconciliationComparisonReason `json:"reason,omitempty"`
}

ReconciliationToleranceEvaluation retains the exact signed and absolute deltas even when the difference is within tolerance.

func EvaluateReconciliationTolerance

func EvaluateReconciliationTolerance(policy ReconciliationTolerancePolicy, target ReconciliationToleranceTarget, expected, reported MonetaryExactAmount) (ReconciliationToleranceEvaluation, error)

EvaluateReconciliationTolerance applies abs(P-E) <= max(absolute_limit, relative_limit*abs(E)) with exact arithmetic. When E is zero only the absolute limit applies and the relative difference is absent with a typed zero_denominator reason.

type ReconciliationTolerancePolicy

type ReconciliationTolerancePolicy struct {
	Version uint32                        `json:"version"`
	Ref     VersionRef                    `json:"ref"`
	Rules   []ReconciliationToleranceRule `json:"rules"`
}

ReconciliationTolerancePolicy is a versioned set of disjoint tolerance rules. Scopes must be unambiguous: no rule may overlap another.

func (ReconciliationTolerancePolicy) Validate

func (p ReconciliationTolerancePolicy) Validate() error

Validate rejects duplicate rules, ambiguous overlap, missing or negative limits and limits outside the bounded exact decimal contract.

type ReconciliationToleranceRule

type ReconciliationToleranceRule struct {
	ID            string                       `json:"id"`
	Scope         ReconciliationToleranceScope `json:"scope"`
	AbsoluteLimit *metering.Decimal            `json:"absolute_limit,omitempty"`
	RelativeLimit *metering.Decimal            `json:"relative_limit,omitempty"`
}

ReconciliationToleranceRule bounds one scope. At least one limit is required; limits are exact non-negative bounded decimals.

type ReconciliationToleranceScope

type ReconciliationToleranceScope struct {
	Unit      string `json:"unit,omitempty"`
	Currency  string `json:"currency,omitempty"`
	Component string `json:"component,omitempty"`
	SchemaID  string `json:"schema_id,omitempty"`
	Context   string `json:"context,omitempty"`
}

ReconciliationToleranceScope is a wildcard pattern: an empty field matches any target value, a non-empty field must match exactly.

type ReconciliationToleranceTarget

type ReconciliationToleranceTarget = ReconciliationToleranceScope

ReconciliationToleranceTarget is the evaluation identity a policy matches.

type ReferenceRater

type ReferenceRater struct {
	// contains filtered or unexported fields
}

ReferenceRater is a deterministic post-usage evaluator over one immutable tariff snapshot. It has no provider, SQL or stream lifecycle dependency.

program is the frozen component-schema inclusion graph compiled ONCE here into integer node ids. Rate only reads it; it never rediscovers topology or re-derives canonical key strings per call.

func NewReferenceRater

func NewReferenceRater(snapshot economics.TariffSnapshot) (*ReferenceRater, error)

NewReferenceRater validates and freezes the supplied tariff. Subsequent caller mutations cannot change replay behavior.

func (*ReferenceRater) Rate

Rate evaluates one explicit basis after post-usage evidence is durable. Provider-reported P uses provider charges directly; E and Q use only their respective source quantities and never fall back to P.

func (*ReferenceRater) Snapshot

func (r *ReferenceRater) Snapshot() economics.TariffSnapshot

Snapshot returns a caller-owned immutable material copy for durable binding and replay diagnostics.

type ReleaseReason

type ReleaseReason string

type ReportFilter

type ReportFilter struct {
	AccountID string
	Currency  string
	Book      JournalBook
	AfterKey  string
	From      time.Time
	To        time.Time
	Page      PageRequest
}

func (ReportFilter) Normalize

func (f ReportFilter) Normalize() (ReportFilter, error)

type ReportingStore

type ReportingStore interface {
	AccountReport(context.Context, string, PageRequest) (AccountReport, error)
	CallExplanation(context.Context, string) (CallExplanation, error)
	OperatorCostReport(context.Context, ReportFilter) (OperatorCostReport, error)
	TrialBalanceReport(context.Context, ReportFilter) (TrialBalanceReport, error)
	QueryOpenExposures(context.Context, string, PageRequest) (ExposurePage, error)
	QueryReconcileRequired(context.Context, PageRequest) (AccountStatePage, error)
}

type ReportsStore

type ReportsStore = ReportingStore

ReportsStore is an alias for ReportingStore to align with canonical store naming.

type RetailBLegSelection

type RetailBLegSelection struct {
	CallID          BillingCallID
	ALegID          string
	BLegID          string
	AttemptSeq      int
	Outcome         LegOutcome
	Surfaced        SurfacedState
	ObservationRefs []metering.ObservationRef
}

RetailBLegSelection is an immutable value copy of one selected B-leg and its source observation references. Observation payloads are intentionally not copied into the result: downstream quantity raters must resolve the exact immutable references.

type RetailCommercialBasis

type RetailCommercialBasis string

RetailCommercialBasis identifies the commercial interpretation of the selected B-leg set. Cost pass-through is explicit; it is never inferred from provider cost readiness or from the number of runtime attempts.

const (
	RetailBasisIndependent     RetailCommercialBasis = "independent_retail"
	RetailBasisCostPassThrough RetailCommercialBasis = "cost_pass_through"
)

type RetailProxyServiceInput

type RetailProxyServiceInput struct {
	Tariff          economics.TariffSnapshot
	Observations    []metering.Observation
	ObservationRefs []metering.ObservationRef
	Qualifiers      []metering.Dimension
	Scope           string
}

RetailProxyServiceInput is an explicit customer-boundary service charge input. These observations remain separate from policy-selected B-leg inference quantities and are rated with their own customer tariff.

type RetailRatingInput

type RetailRatingInput struct {
	Call                 CallUsageRecord
	Legs                 []CallLegUsageRecord
	Selection            RetailSelectionResult
	Policy               ChargePolicy
	Tariff               economics.TariffSnapshot
	ModelTariffs         []ModelCustomerTariff
	Qualifiers           []metering.Dimension
	QualifierSnapshotRef *economics.SnapshotContentRef
	Payer                metering.PaymentParty
	AsOf                 time.Time
	ProxyService         *RetailProxyServiceInput
	// ProviderCost is accepted only for the explicit cost-pass-through basis.
	// Independent retail ignores supplier cost entirely and never reaches this
	// branch.
	ProviderCost *CostPassThroughProviderCost
}

RetailRatingInput binds one frozen B-leg selection to an independent customer tariff. ModelTariffs, when present, are route-specific customer tariffs; they never contain or resolve supplier rates.

type RetailRatingResult

type RetailRatingResult struct {
	CallID                BillingCallID
	SubmissionID          string
	CustomerCharge        Money
	Fingerprint           string
	Valuation             economics.Valuation
	InferenceValuation    economics.Valuation
	CommercialValuation   economics.Valuation
	ProxyServiceValuation *economics.Valuation
	CostPassThrough       *CostPassThroughSettlement
}

RetailRatingResult contains a customer-facing composite valuation and the independently retained inference, commercial, and proxy-service views. Supplier/COGS valuations are intentionally not embedded here.

func RateSelectedRetailBLegs

func RateSelectedRetailBLegs(ctx context.Context, in RetailRatingInput) (RetailRatingResult, error)

RateSelectedRetailBLegs rates only the immutable B-leg references carried by RetailSelectionResult. Quantity lines are evaluated in one pass per selected tariff; call and submission fees are evaluated once at their own trusted scope. A partial valuation is returned with a typed error whenever a required rate, qualifier, quantity, or identity is unavailable.

type RetailSelectionCapability

type RetailSelectionCapability string

RetailSelectionCapability identifies the evidence capability used by a successful selection. The selector requires source-separated V2 B-leg observations and never substitutes customer-boundary measurements.

const (
	RetailCapabilityV2BLegObservations RetailSelectionCapability = "v2_b_leg_observations"
)

type RetailSelectionCompleteness

type RetailSelectionCompleteness string

RetailSelectionCompleteness describes whether the returned reference set is complete enough to feed request-scoped customer quantity rating.

const (
	RetailSelectionComplete RetailSelectionCompleteness = "complete"
)

type RetailSelectionInput

type RetailSelectionInput struct {
	Call     CallUsageRecord
	Legs     []CallLegUsageRecord
	Policy   ChargePolicy
	TenantID string
}

RetailSelectionInput binds selection to one BillingCallID and its durable B-leg records. TenantID is an optional trusted scope constraint; when empty, a consistent tenant scope is still required across all selected evidence.

type RetailSelectionMode

type RetailSelectionMode string

RetailSelectionMode identifies the request-scoped B-leg set used for customer inference quantities. It is deliberately independent from supplier COGS, which continues to attribute every executed B-leg.

const (
	RetailSelectionSurfacedWinner  RetailSelectionMode = "surfaced_winner"
	RetailSelectionNamedOutcomes   RetailSelectionMode = "named_outcomes"
	RetailSelectionAllAttributable RetailSelectionMode = "all_attributable"
)

type RetailSelectionPolicy

type RetailSelectionPolicy struct {
	Mode            RetailSelectionMode
	OutcomeSubset   []LegOutcome
	Basis           RetailCommercialBasis
	CostPassThrough *CostPassThroughPolicy
}

RetailSelectionPolicy is the frozen customer-side B-leg selection portion of a ChargePolicy. It does not contain supplier rates or calculate COGS.

func ResolveRetailSelectionPolicy

func ResolveRetailSelectionPolicy(policy ChargePolicy) (RetailSelectionPolicy, error)

ResolveRetailSelectionPolicy maps the legacy Scope to the explicit retail selector when no newer selection mode is present. This preserves the existing offer scope during migration while making the new decision visible to callers that need B-leg observation references.

func (RetailSelectionPolicy) Clone

Clone returns a detached policy value. ChargePolicy snapshots use this when crossing the catalog boundary so a caller cannot mutate a published policy.

func (RetailSelectionPolicy) Validate

func (p RetailSelectionPolicy) Validate() error

type RetailSelectionResult

type RetailSelectionResult struct {
	CallID          BillingCallID
	PolicyRef       VersionRef
	Mode            RetailSelectionMode
	Basis           RetailCommercialBasis
	Reason          RetailSelectionMode
	Completeness    RetailSelectionCompleteness
	Capability      RetailSelectionCapability
	SelectedBLegs   []RetailBLegSelection
	ObservationRefs []metering.ObservationRef
}

RetailSelectionResult is a frozen selection decision. Clone can be used by infrastructure adapters when handing the result to another owner.

func SelectRetailBLegEvidence

func SelectRetailBLegEvidence(in RetailSelectionInput) (RetailSelectionResult, error)

SelectRetailBLegEvidence resolves one frozen customer-side B-leg set and returns only immutable B-leg/observation references. It never consults provider rates or costs and never changes supplier COGS attribution.

func (RetailSelectionResult) Clone

Clone returns a detached result, including all selected reference slices.

type RichComponentBound

type RichComponentBound struct {
	Key         metering.ComponentKey
	Upper       metering.Decimal
	Enforceable bool
}

RichComponentBound is one finite enforceable candidate/work upper bound for a concrete component instance. Upper must be non-negative and Enforceable must be true: a configuration number without an enforceable execution limit is not proof of a bound on uninterruptible provider work and must not be quoted.

type RichQuoteInput

type RichQuoteInput struct {
	Currency             string
	Policy               ChargePolicy
	BaseTariff           economics.TariffSnapshot
	Routes               []RichQuoteRoute
	Bounds               []RichComponentBound
	RequiredCapabilities []string
}

RichQuoteInput conservatively quotes unit, fixed, minimum, credit and resource charges from the same immutable tariff semantics used for settlement. Bounds are finite enforceable work limits and RequiredCapabilities are evidence capabilities every candidate route must prove. Effective qualifiers come only from each canonical frozen tariff snapshot: this path accepts no external qualifier overlay, so conditional rule selection provably matches terminal settlement under the same tariff.

type RichQuoteRoute

type RichQuoteRoute struct {
	ID           string
	Backend      string
	Model        string
	Tariff       economics.TariffSnapshot
	Capabilities []string
}

RichQuoteRoute is one candidate execution leg for a richer customer offer. An empty Tariff means the base tariff applies to this route. Backend and Model identify the route for tariff resolution and binding; ID carries the planned leaf key for basis attribution. Capabilities are the route's provable evidence capabilities (for example tool-count or duration capture); a route missing a required capability cannot be bounded.

type RouteTariffBinding

type RouteTariffBinding struct {
	RouteID       string `json:"route_id"`
	TariffID      string `json:"tariff_id"`
	TariffVersion string `json:"tariff_version"`
	ContentHash   string `json:"content_hash"`
}

RouteTariffBinding freezes the exact customer tariff material used to quote one candidate route: the canonical route key plus the tariff VersionRef identity and its canonical content hash. It detects both version changes and same-version content mutation. Bindings are sorted by route for deterministic fingerprints and replay identity.

func AttestNoUsageRoutes

func AttestNoUsageRoutes(admitted []RouteTariffBinding, legs []CallLegUsageRecord) ([]RouteTariffBinding, error)

AttestNoUsageRoutes builds the explicit no-usage attestation for a terminal repair outcome: one entry per distinct executed leg route, each carrying the admitted frozen tariff for that route. A leg route with no admitted binding fails closed; with no legs there is no defensible attestation and the terminal check rejects the empty list. Legacy empty admission attests nothing and stays compatible.

func (RouteTariffBinding) Validate

func (b RouteTariffBinding) Validate() error

type SelectedCostAdjustmentInput

type SelectedCostAdjustmentInput struct {
	AccountID string
	CallID    BillingCallID
	HeadKey   string
	Subject   metering.SubjectRef
	Expected  SelectedCostHeadExpectation
	Selected  SelectedCostValuation
	// PostingOwner selects the B1 pin owner for the financial adjustment fence.
	// Empty preserves the legacy V1 default for backward compatibility.
	// Draining requires a classified V1 pin plus matching claim metadata;
	// v2_active permits only V2.
	PostingOwner string
	// Claim carries the B2a worker-claim metadata (owner/epoch) captured at
	// claim time. When present, posting validates it against the current
	// marker and pin to close TOCTOU between claim and posting. Nil preserves
	// legacy direct calls in v1_active/shadow; draining fences unpinned/stale
	// work even without a claim, and B2b3 draining requires a matching claim
	// for new postings.
	Claim *CutoverClaimMetadata
}

SelectedCostAdjustmentInput is the durable-store boundary for one selected cost head compare-and-swap. Expected is the caller's durable read (version plus previously posted selected valuation); Selected is the new frozen valuation revision.

func (SelectedCostAdjustmentInput) Normalize

Normalize validates and returns a detached copy of the adjustment envelope.

type SelectedCostAdjustmentResult

type SelectedCostAdjustmentResult struct {
	AccountID string
	CallID    BillingCallID
	HeadKey   string

	Status     SelectedCostHeadTransitionStatus
	Reason     SelectedCostHeadTransitionReason
	Comparison SelectedCostComparisonStatus
	Posting    SelectedCostPostingStatus

	SelectionStatus OperatorCostSelectionStatus
	SelectionReason OperatorCostSelectionReason

	Previous      *SelectedCostValuationRef
	Current       SelectedCostValuationRef
	Delta         *MonetaryExactAmount
	OperationKey  string
	LinkKey       string
	Fingerprint   string
	HeadVersion   uint64
	TransactionID string
}

SelectedCostAdjustmentResult is the durable transition outcome. Applied and NoOp carry the operation/link identity and the appended journal transaction; Replay reproduces the original stable identity from the durable adjustment operation. Pending, Stale and Conflict are zero-effect outcomes.

type SelectedCostAdjustmentStore

type SelectedCostAdjustmentStore interface {
	ApplySelectedCostAdjustment(context.Context, SelectedCostAdjustmentInput) (SelectedCostAdjustmentResult, error)
}

SelectedCostAdjustmentStore owns the only transactional writer for selected- cost head adjustments. Implementations must atomically fence the head and append the immutable valuation link, balanced journal delta and head transition; pure operator COGS never locks or updates a customer balance.

type SelectedCostComparisonStatus

type SelectedCostComparisonStatus string

SelectedCostComparisonStatus is the monetary comparability of the previously posted selected valuation and the new selected valuation.

const (
	SelectedCostComparisonNotEvaluated SelectedCostComparisonStatus = "not_evaluated"
	SelectedCostComparisonComparable   SelectedCostComparisonStatus = "comparable"
	SelectedCostComparisonPending      SelectedCostComparisonStatus = "pending"
	SelectedCostComparisonIncomparable SelectedCostComparisonStatus = "incomparable"
)

func (SelectedCostComparisonStatus) IsKnown

func (c SelectedCostComparisonStatus) IsKnown() bool

IsKnown reports whether c is a documented comparison status.

type SelectedCostHead

type SelectedCostHead struct {
	AccountID string
	CallID    BillingCallID
	HeadKey   string
	Subject   metering.SubjectRef
	Version   uint64
	Selected  *SelectedCostValuation
	// LastOperationKey is the transition operation that most recently advanced
	// this head. OriginalTransactionID/LastTransactionID reference the durable
	// correction journal chain; both are assigned by the persistence adapter.
	LastOperationKey      string
	OriginalTransactionID string
	LastTransactionID     string
	// PostingState is the exact persisted financial posting state of this head,
	// separate from the selection and comparison planes. It is populated from
	// the durable head row by the persistence adapter; the empty value is only
	// valid for a caller-built in-memory head that was never read from durable
	// storage.
	PostingState SelectedCostPostingStatus
}

SelectedCostHead is the current selected/posted valuation pointer for one economic charge. Version is the compare-and-swap token a writer must fence against; the immutable operation link and journal rows remain the audit history.

func (SelectedCostHead) Clone

Clone returns a detached copy of the head.

func (SelectedCostHead) Validate

func (h SelectedCostHead) Validate() error

Validate checks the request-scoped selected-cost head identity.

type SelectedCostHeadExpectation

type SelectedCostHeadExpectation struct {
	Version  uint64
	Previous *SelectedCostValuation
}

SelectedCostHeadExpectation is the caller's compare-and-swap read: the head version and the previously posted selected valuation the caller planned against. Version zero and a nil previous valuation are required together.

func (SelectedCostHeadExpectation) Validate

func (e SelectedCostHeadExpectation) Validate() error

Validate checks CAS read consistency.

type SelectedCostHeadReader

type SelectedCostHeadReader interface {
	GetSelectedCostHead(context.Context, string, BillingCallID, string) (SelectedCostHead, error)
}

SelectedCostHeadReader reads the current selected/posted valuation pointer, including the exact frozen valuation identity, dual-dialect adapter identity and posting state, without changing any accounting state.

type SelectedCostHeadTransition

type SelectedCostHeadTransition struct {
	AccountID string
	CallID    BillingCallID
	HeadKey   string
	Subject   metering.SubjectRef

	Status SelectedCostHeadTransitionStatus
	Reason SelectedCostHeadTransitionReason

	SelectionStatus OperatorCostSelectionStatus
	SelectionReason OperatorCostSelectionReason
	Comparison      SelectedCostComparisonStatus
	Posting         SelectedCostPostingStatus

	Previous *SelectedCostValuation
	Selected *SelectedCostValuation
	Delta    *MonetaryExactAmount
	Link     *SelectedCostValuationLink
	Journal  *BalancedJournalIntent
	NextHead *SelectedCostHead

	OperationKey string
	Fingerprint  string
}

SelectedCostHeadTransition is the deterministic correction plan. Status, Reason and the separate selection/comparison/posting planes report the outcome; Previous/Selected/Delta/Link/Journal/NextHead are populated only when the corresponding effect is permitted.

func PlanSelectedCostHeadTransition

func PlanSelectedCostHeadTransition(input SelectedCostHeadTransitionInput) (SelectedCostHeadTransition, error)

PlanSelectedCostHeadTransition plans one compare-and-swap transition of the current selected/posted valuation head. Monetary delta is computed as new selected minus previously posted only when both selected valuations share the same native currency or the exact same explicit frozen FX conversion basis. Otherwise the correction stays pending with no valuation link, journal delta or head transition.

A durable head that already carries the exact new selected valuation is an idempotent replay. A stale caller version and a same-version identity or revision conflict return typed zero-effect results.

func (SelectedCostHeadTransition) HasEffects

func (t SelectedCostHeadTransition) HasEffects() bool

HasEffects reports whether the plan writes financial or selected-head state.

type SelectedCostHeadTransitionInput

type SelectedCostHeadTransitionInput struct {
	Current  SelectedCostHead
	Expected SelectedCostHeadExpectation
	Selected SelectedCostValuation
}

SelectedCostHeadTransitionInput is the pure transition request: the durable current head, the caller compare-and-swap read and the new frozen selected valuation.

type SelectedCostHeadTransitionReason

type SelectedCostHeadTransitionReason string

SelectedCostHeadTransitionReason is the typed explanation of a transition outcome. It never erases the separate selection, comparison and posting planes carried by the result.

const (
	SelectedCostReasonNone                   SelectedCostHeadTransitionReason = ""
	SelectedCostReasonInitialPosting         SelectedCostHeadTransitionReason = "initial_posting"
	SelectedCostReasonSameNativeCurrency     SelectedCostHeadTransitionReason = "same_native_currency"
	SelectedCostReasonFrozenFXBasis          SelectedCostHeadTransitionReason = "frozen_fx_basis"
	SelectedCostReasonZeroDelta              SelectedCostHeadTransitionReason = "zero_delta"
	SelectedCostReasonAlreadyApplied         SelectedCostHeadTransitionReason = "already_applied"
	SelectedCostReasonProvisionalSelection   SelectedCostHeadTransitionReason = "provisional_selection"
	SelectedCostReasonUnknownSelection       SelectedCostHeadTransitionReason = "unknown_selection"
	SelectedCostReasonMissingAttemptedUsage  SelectedCostHeadTransitionReason = "missing_attempted_usage"
	SelectedCostReasonNotOperatorPayable     SelectedCostHeadTransitionReason = "not_operator_payable"
	SelectedCostReasonIncomparableSelection  SelectedCostHeadTransitionReason = "incomparable_selection"
	SelectedCostReasonSelectionConflict      SelectedCostHeadTransitionReason = "selection_conflict"
	SelectedCostReasonPostedCurrencyMismatch SelectedCostHeadTransitionReason = "posted_currency_mismatch"
	SelectedCostReasonFrozenFXBasisMismatch  SelectedCostHeadTransitionReason = "frozen_fx_basis_mismatch"
	SelectedCostReasonStaleHeadVersion       SelectedCostHeadTransitionReason = "stale_head_version"
	SelectedCostReasonStaleRevision          SelectedCostHeadTransitionReason = "stale_revision"
	SelectedCostReasonHeadIdentityConflict   SelectedCostHeadTransitionReason = "head_identity_conflict"
	SelectedCostReasonRevisionConflict       SelectedCostHeadTransitionReason = "revision_conflict"
)

func (SelectedCostHeadTransitionReason) IsKnown

IsKnown reports whether r is a documented transition reason.

type SelectedCostHeadTransitionStatus

type SelectedCostHeadTransitionStatus string

SelectedCostHeadTransitionStatus is the correction outcome. Only Applied, NoOp and Replay may carry effects; Pending, Stale and Conflict are always zero-effect results.

const (
	SelectedCostTransitionApplied  SelectedCostHeadTransitionStatus = "applied"
	SelectedCostTransitionNoOp     SelectedCostHeadTransitionStatus = "no_op"
	SelectedCostTransitionReplay   SelectedCostHeadTransitionStatus = "replay"
	SelectedCostTransitionPending  SelectedCostHeadTransitionStatus = "pending"
	SelectedCostTransitionStale    SelectedCostHeadTransitionStatus = "stale"
	SelectedCostTransitionConflict SelectedCostHeadTransitionStatus = "conflict"
)

func (SelectedCostHeadTransitionStatus) IsKnown

IsKnown reports whether s is a documented transition status.

type SelectedCostPostingStatus

type SelectedCostPostingStatus string

SelectedCostPostingStatus is the financial posting state of the planned transition, separate from the selection and comparison planes.

const (
	SelectedCostPostingUnposted SelectedCostPostingStatus = "unposted"
	SelectedCostPostingPending  SelectedCostPostingStatus = "pending"
	SelectedCostPostingApplied  SelectedCostPostingStatus = "applied"
	SelectedCostPostingReplayed SelectedCostPostingStatus = "replayed"
)

func (SelectedCostPostingStatus) IsKnown

func (s SelectedCostPostingStatus) IsKnown() bool

IsKnown reports whether s is a documented posting status.

type SelectedCostValuation

SelectedCostValuation is one frozen selected valuation in the operator postings plane: the Phase 12 selection outcome plus its valuation identity. Currency/Amount are the posted/view-currency values; FX and NativeAmount are present only when an explicit frozen conversion produced them.

func NewSelectedCostValuation

func NewSelectedCostValuation(ref SelectedCostValuationRef, selection OperatorCostSelectionResult) (SelectedCostValuation, error)

NewSelectedCostValuation freezes one Phase 12 operator cost selection result onto a valuation identity. It never re-rates and never repairs an inconsistent selection.

func (SelectedCostValuation) Clone

Clone returns a detached copy of the frozen valuation.

func (SelectedCostValuation) IdentityEqual

func (v SelectedCostValuation) IdentityEqual(other SelectedCostValuation) bool

IdentityEqual reports whether two selected valuations are the same immutable semantic payload: identity, selection plane, posted/native amounts and frozen FX basis. It is stricter than Ref equality so a changed amount under the same revision is an identity conflict rather than a replay.

func (SelectedCostValuation) Validate

func (v SelectedCostValuation) Validate() error

Validate checks the frozen valuation contract: known selection state, canonical currency, nonnegative selected amount, and a frozen FX basis only with matching native amount and target currency.

type SelectedCostValuationLink struct {
	AccountID          string
	CallID             BillingCallID
	HeadKey            string
	Subject            metering.SubjectRef
	Previous           *SelectedCostValuationRef
	Current            SelectedCostValuationRef
	Currency           string
	FX                 *OperatorCostFXBasis
	AdjustmentRevision uint64
	OperationKey       string
}

SelectedCostValuationLink is the immutable linkage from the previously posted selected valuation to the newly selected valuation. It is inserted atomically with the journal delta and head transition.

func (SelectedCostValuationLink) Key

Key returns the stable link identity. Economic charge identity, both selected valuation identities, the delta currency or frozen FX basis, and the adjustment revision are the unique members.

type SelectedCostValuationRef

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

SelectedCostValuationRef is the immutable identity of one frozen selected valuation revision. InputSetHash is the canonical evidence input identity, so a replay can be recognized without re-reading the rater.

func (SelectedCostValuationRef) Validate

func (r SelectedCostValuationRef) Validate() error

Validate checks the immutable valuation identity.

type SettleExposureInput

type SettleExposureInput struct {
	CallID string
	Actual Money
	Now    time.Time
}

type SettleExposureResult

type SettleExposureResult struct {
	Account            Account
	Exposure           CallExposure
	SafetyMarginBefore Money
	SafetyMarginAfter  Money
	// Breached reports that the actual incurred charge exceeded the admitted
	// maximum. The actual amount is retained and settled under the account
	// policy; it is never truncated to the quote. OverrunNano carries the
	// exact excess (actual minus max) and is zero when not breached.
	Breached    bool
	OverrunNano int64
}

func EvaluateSettle

func EvaluateSettle(account Account, exposures []CallExposure, in SettleExposureInput) (SettleExposureResult, error)

type ShadowEvidenceSink

type ShadowEvidenceSink interface {
	AppendObservations(context.Context, []metering.Observation) error
}

ShadowEvidenceSink is the capture-only persistence port for V2 shadow observations. Implementations persist immutable observations with stable source identity and idempotent replay through existing V2 observation storage. They must not create usage call/leg rows, claim state, provider-cost work, exposures, journals, unit operations, balance mutations, adjustments, or any payable intent. The method shape matches the metering journal writer, which satisfies it without a new store; it can never be satisfied by, or accidentally route through, the ordinary terminal handoff.

type StatementChargeEvidence

type StatementChargeEvidence struct {
	Ref                metering.ChargeRef
	State              StatementEvidenceState
	ReconciliationID   string
	TenantID           string
	ProviderAccountKey string
	PeriodID           string
	Kind               metering.ChargeKind
	Component          *metering.ComponentKey
	Currency           string
	Payer              metering.PaymentParty
	// Covers is the retained charge's own coverage graph. Inclusive edges are
	// used to detect duplicate parent/child coverage; they are never expanded
	// into new per-request charges.
	Covers []metering.ChargeCoverageRef
}

StatementChargeEvidence is one eligible retained charge or reconciliation record that a statement line may reference explicitly or cover completely by account/period/SKU aggregate scope. It contains no request, A-leg or B-leg lineage: the covered charge identity and the retained reconciliation identity are the only linkage retained.

func (StatementChargeEvidence) Validate

func (e StatementChargeEvidence) Validate() error

Validate checks one bounded eligible evidence entry.

type StatementCoverageLink struct {
	StatementKey      string
	StatementID       string
	StatementRevision uint64
	Kind              StatementMatchKind
	LineKeys          []string
	LineIDs           []string
	Charges           []metering.ChargeRef
	EvidenceIDs       []string
}

StatementCoverageLink is the immutable coverage link of one statement line: every covered statement line identity plus every covered retained charge and evidence identity. It deliberately contains no request/B-leg allocation.

func (StatementCoverageLink) Clone

Clone returns a detached copy safe to hand to another owner.

func (StatementCoverageLink) Equal

Equal reports whether two links describe the same immutable coverage.

func (StatementCoverageLink) Key

func (l StatementCoverageLink) Key() string

Key returns a deterministic bounded immutable coverage identity. Every semantic member participates in the SHA-256 preimage.

type StatementEvidenceState

type StatementEvidenceState string

StatementEvidenceState records whether retained evidence is currently eligible to be covered by an imported statement. Ineligible evidence is retained and reported, never silently covered.

const (
	StatementEvidenceEligible   StatementEvidenceState = "eligible"
	StatementEvidenceIneligible StatementEvidenceState = "ineligible"
)

func (StatementEvidenceState) IsKnown

func (s StatementEvidenceState) IsKnown() bool

IsKnown reports whether s is a documented evidence state.

func (StatementEvidenceState) Validate

func (s StatementEvidenceState) Validate() error

Validate checks the evidence state vocabulary.

type StatementImportConflictError

type StatementImportConflictError struct {
	StatementKey string
	LineIDs      []string
}

StatementImportConflictError reports an immutable statement or line identity whose submitted content differs from the retained revision. LineIDs is populated when a specific line revision conflicts and is empty for a statement-level envelope conflict. It unwraps to ErrStatementImportConflict.

func (*StatementImportConflictError) Error

func (*StatementImportConflictError) Unwrap

func (e *StatementImportConflictError) Unwrap() error

type StatementImportLedger

type StatementImportLedger interface {
	LookupStatementRevision(context.Context, economics.StatementIdentity) (string, bool, error)
	LookupStatementLines(context.Context, []economics.StatementLineIdentity) (map[string]string, error)
	AppendStatementRevision(context.Context, NormalizedStatement) error
}

StatementImportLedger is the consumer-owned durable port for normalized statement ingestion. Lookups are exact: an identity is either absent or retained with one fingerprint. AppendStatementRevision must atomically retain the statement revision and its line revisions, treat an exact replay as a no-op, and fail closed with ErrStatementImportConflict when a retained identity has different content; a partial write must be impossible.

type StatementImportService

type StatementImportService struct {
	// contains filtered or unexported fields
}

StatementImportService applies statement import policy over a durable ledger. It contains no persistence, matching, journal or worker behavior.

func NewStatementImportService

func NewStatementImportService(ledger StatementImportLedger) (*StatementImportService, error)

NewStatementImportService constructs the domain service with an explicit ledger. A nil or typed-nil port is rejected before any statement is trusted.

func (*StatementImportService) Import

Import validates one authenticated normalized statement, classifies each statement-line revision as accepted, replayed or unmatched, and appends the statement once. A changed payload under an existing immutable identity returns ErrStatementImportConflict with no durable change.

type StatementImporter

type StatementImporter interface {
	Import(context.Context, TrustedStatementScope, economics.StatementBatch) (economics.ImportResult, error)
}

StatementImporter is the host-side consumer-owned port for one authenticated statement import. Unlike the frozen external-module economics.StatementImporter seam, it requires the trusted scope explicitly at every call so a single service can serve many authenticated callers.

type StatementMatchAmbiguityError

type StatementMatchAmbiguityError struct {
	StatementIDs []string
}

StatementMatchAmbiguityError reports statement identities that appear with more than one revision in one matching batch.

func (*StatementMatchAmbiguityError) Error

func (*StatementMatchAmbiguityError) Unwrap

func (e *StatementMatchAmbiguityError) Unwrap() error

type StatementMatchKind

type StatementMatchKind string

StatementMatchKind distinguishes the two permitted matching mechanisms.

const (
	// StatementMatchKindExplicitCharge is an exact explicit charge-ID match.
	StatementMatchKindExplicitCharge StatementMatchKind = "explicit_charge"
	// StatementMatchKindAggregateSKU is complete compatible account/period/SKU
	// aggregate coverage. It retains every covered charge without asserting a
	// per-request allocation.
	StatementMatchKindAggregateSKU StatementMatchKind = "aggregate_sku"
)

func (StatementMatchKind) IsKnown

func (k StatementMatchKind) IsKnown() bool

IsKnown reports whether k is a documented match kind.

type StatementMatchLine

type StatementMatchLine struct {
	LineID          string
	LineKey         string
	LineRevision    uint64
	Status          StatementMatchStatus
	Reason          StatementMatchReason
	UnmatchedReason string
	LinkKey         string
}

StatementMatchLine is one typed statement-line matching outcome.

type StatementMatchReason

type StatementMatchReason string

StatementMatchReason is the typed explanation of one match status.

const (
	StatementMatchReasonNone                   StatementMatchReason = ""
	StatementMatchReasonExplicitCharge         StatementMatchReason = "explicit_charge"
	StatementMatchReasonAggregateSKUCoverage   StatementMatchReason = "aggregate_sku_coverage"
	StatementMatchReasonNoChargeLink           StatementMatchReason = "no_charge_link"
	StatementMatchReasonChargeNotFound         StatementMatchReason = "charge_not_found"
	StatementMatchReasonAccountScopedTotal     StatementMatchReason = "account_scoped_total"
	StatementMatchReasonEvidenceIneligible     StatementMatchReason = "evidence_ineligible"
	StatementMatchReasonPartialSKUCoverage     StatementMatchReason = "partial_sku_coverage"
	StatementMatchReasonDanglingCoverageRef    StatementMatchReason = "dangling_coverage_ref"
	StatementMatchReasonStoreMismatch          StatementMatchReason = "store_mismatch"
	StatementMatchReasonTenantMismatch         StatementMatchReason = "tenant_mismatch"
	StatementMatchReasonAccountMismatch        StatementMatchReason = "account_mismatch"
	StatementMatchReasonPeriodMismatch         StatementMatchReason = "period_mismatch"
	StatementMatchReasonCurrencyMismatch       StatementMatchReason = "currency_mismatch"
	StatementMatchReasonUnitMismatch           StatementMatchReason = "unit_mismatch"
	StatementMatchReasonSKUMismatch            StatementMatchReason = "sku_mismatch"
	StatementMatchReasonGranularityMismatch    StatementMatchReason = "granularity_mismatch"
	StatementMatchReasonCrossRevisionAmbiguity StatementMatchReason = "cross_revision_ambiguity"
	StatementMatchReasonDuplicateParentChild   StatementMatchReason = "duplicate_parent_child"
	StatementMatchReasonOverlappingCoverage    StatementMatchReason = "overlapping_coverage"
)

func (StatementMatchReason) IsKnown

func (r StatementMatchReason) IsKnown() bool

IsKnown reports whether r is a documented match reason.

type StatementMatchResult

type StatementMatchResult struct {
	StatementKey      string
	StatementID       string
	StatementRevision uint64
	Lines             []StatementMatchLine
	Links             []StatementCoverageLink
}

StatementMatchResult is the deterministic per-statement matching outcome. Unmatched lines and their declared reasons are preserved.

type StatementMatchSet

type StatementMatchSet struct {
	Results []StatementMatchResult
}

StatementMatchSet is the deterministic result of one matching batch.

func MatchStatements

func MatchStatements(statements []NormalizedStatement, evidence []StatementChargeEvidence) (StatementMatchSet, error)

MatchStatements matches normalized imported statement revisions against an explicitly eligible retained charge/reconciliation evidence set. Matching is exact explicit charge-ID identity or complete compatible account/period/SKU aggregate coverage. Missing join keys stay unmatched; no timestamp-nearest, proportional, heuristic or guessed per-request/B-leg allocation is produced. The function is pure and deterministic across input order.

type StatementMatchStatus

type StatementMatchStatus string

StatementMatchStatus is the typed per-line matching state. It is separate from posting and selection state.

const (
	// StatementMatchStatusMatched is a complete, unambiguous coverage link.
	StatementMatchStatusMatched StatementMatchStatus = "matched"
	// StatementMatchStatusPartial is incomplete coverage; it is never matched.
	StatementMatchStatusPartial StatementMatchStatus = "partial"
	// StatementMatchStatusIncomparable is incompatible scope/currency/unit/SKU
	// granularity; it is never matched.
	StatementMatchStatusIncomparable StatementMatchStatus = "incomparable"
	// StatementMatchStatusConflict is duplicate, overlapping or ambiguous
	// coverage; it is never matched.
	StatementMatchStatusConflict StatementMatchStatus = "conflict"
	// StatementMatchStatusUnmatched is retained without any attachment.
	StatementMatchStatusUnmatched StatementMatchStatus = "unmatched"
)

func (StatementMatchStatus) IsKnown

func (s StatementMatchStatus) IsKnown() bool

IsKnown reports whether s is a documented match status.

type SubmissionFeeClaim

type SubmissionFeeClaim struct {
	SubmissionID string
	Amount       Money

	ContextFingerprint string
	TariffID           string
	TariffVersion      string
	TariffContentRef   string
	TariffContentHash  string
	PolicyID           string
	PolicyVersion      string
	PolicyContentRef   string
	PolicyContentHash  string
}

SubmissionFeeClaim is the immutable commercial context needed by durable settlement to charge one submission fee while retaining every call fee. SubmissionID is trusted from CallUsageRecord; it is never read from a client-provided valuation subject.

func SubmissionFeeClaimForValuation

func SubmissionFeeClaimForValuation(call CallUsageRecord, valuation economics.Valuation) (SubmissionFeeClaim, bool, error)

SubmissionFeeClaimForValuation extracts one durable claim from a complete customer valuation. A valuation without a submission fixed-fee line is not a claim, which preserves legacy/per-call settlement behavior.

func (SubmissionFeeClaim) Validate

func (c SubmissionFeeClaim) Validate() error

type SurfacedState

type SurfacedState string
const (
	SurfacedYes     SurfacedState = "yes"
	SurfacedNo      SurfacedState = "no"
	SurfacedUnknown SurfacedState = "unknown"
)

type TerminalUsageSink

type TerminalUsageSink interface {
	AppendLeg(context.Context, CallLegUsageRecord) error
	AppendCall(context.Context, CallUsageRecord) error
}

TerminalUsageSink is the single runtime terminal handoff. Implementations durably append immutable current call/leg records locally; they do not rate, authorize, or write financial journals.

The context passed to AppendLeg/AppendCall carries the persistence deadline for the append and must not be derived from the caller's request context. Implementations must return success only after the record is durably committed (or, for replay-safe stores, provably already present with an identical fingerprint); a returned error means the record must be retried and never silently dropped. The same key may be appended more than once: replay must be idempotent and conflicting fingerprints must surface as a typed conflict rather than overwriting prior evidence.

type TrialBalanceReport

type TrialBalanceReport struct {
	AccountID    string
	Currency     string
	From         time.Time
	To           time.Time
	Debit        Money
	Credit       Money
	Imbalance    Money
	ByBook       map[JournalBook]TrialBalanceTotals
	PageBalanced bool
	Balanced     bool
	Transactions int
	NextCursor   uint64
	Issues       []ReconciliationIssue
	Integrity    *ReconciliationReport
}

type TrialBalanceTotals

type TrialBalanceTotals struct {
	Debit     Money
	Credit    Money
	Imbalance Money
	Valid     bool
}

type TrustedStatementScope

type TrustedStatementScope struct {
	StoreID             string
	TenantID            string
	PrincipalID         string
	ProviderAccountKeys []string
}

TrustedStatementScope is the explicit authorization context of one import. Every field is copied from authenticated caller state, never from the statement payload; a statement cannot choose or widen its own scope. A scope must carry tenant or provider-account authority; a store-only scope is rejected so an import cannot silently authorize every account.

func (TrustedStatementScope) AuthorizedProviderAccounts

func (s TrustedStatementScope) AuthorizedProviderAccounts() []string

AuthorizedProviderAccounts returns a detached copy of the authorized account list so callers cannot widen the scope after construction.

func (TrustedStatementScope) AuthorizesProviderAccount

func (s TrustedStatementScope) AuthorizesProviderAccount(account string) bool

AuthorizesProviderAccount reports whether the trusted scope covers one provider account. An empty account list means tenant-scoped authority.

func (TrustedStatementScope) Clone

Clone returns a detached scope value.

func (TrustedStatementScope) Validate

func (s TrustedStatementScope) Validate() error

Validate checks the trusted scope before any statement content is trusted.

type TurnOutcome

type TurnOutcome string
const (
	TurnOutcomeCompleted TurnOutcome = "completed"
	TurnOutcomeFailed    TurnOutcome = "failed"
	TurnOutcomeCanceled  TurnOutcome = "canceled"
	TurnOutcomeUnknown   TurnOutcome = "unknown"
)

type TurnResultSummary

type TurnResultSummary struct {
	CustomerCharge Money
	ProviderCost   Money
	GrossMargin    Money
	Processed      bool
}

type UsageAppendKind

type UsageAppendKind string

UsageAppendKind and UsageAppendWork are immutable migration records used by the explicit Phase-2 legacy outbox drain. They are not runtime delivery ports; terminal traffic uses TerminalUsageSink.

const (
	UsageAppendCall UsageAppendKind = "call"
	UsageAppendLeg  UsageAppendKind = "leg"
)

type UsageAppendWork

type UsageAppendWork struct {
	Key  string
	Kind UsageAppendKind
	Call *CallUsageRecord
	Leg  *CallLegUsageRecord
}

type VersionRef

type VersionRef struct {
	ID          string
	Version     string
	EffectiveAt time.Time
	FetchedAt   time.Time
}

type WorkloadClass

type WorkloadClass string

WorkloadClass is a bounded, content-free classification of a billable call. It is deliberately metadata only: pricing and rating remain selected by the existing route/model policy snapshots.

const (
	WorkloadClassPrimary   WorkloadClass = "primary"
	WorkloadClassAuxiliary WorkloadClass = "auxiliary"
)

type WorkloadIdentity

type WorkloadIdentity struct {
	Class WorkloadClass `json:"class,omitempty"`
	Role  WorkloadRole  `json:"role,omitempty"`
}

WorkloadIdentity is safe-to-persist correlation metadata. It contains no prompt, completion, provider payload, credential, or header content.

func WorkloadIdentityFromAuxiliaryRole

func WorkloadIdentityFromAuxiliaryRole(role string) (WorkloadIdentity, error)

WorkloadIdentityFromAuxiliaryRole projects trusted auxiliary lineage into the bounded billing/report identity. Unknown roles fail closed rather than persisting arbitrary plugin or request text.

func (WorkloadIdentity) IsAuxiliary

func (w WorkloadIdentity) IsAuxiliary() bool

func (WorkloadIdentity) IsZero

func (w WorkloadIdentity) IsZero() bool

func (WorkloadIdentity) Validate

func (w WorkloadIdentity) Validate() error

type WorkloadRole

type WorkloadRole string

WorkloadRole identifies a trusted auxiliary role. Keep this allowlisted so request content cannot become a durable billing/report label.

Source Files

Jump to

Keyboard shortcuts

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