Documentation
¶
Overview ¶
Package metering defines provider-neutral public contracts for dual-plane metering facts, quantities, and journal append/query ports.
These types are storage- and transport-agnostic. Implementations live in internal packages; enterprise and OSS adapters may depend on this package without importing internal/core.
Boundary rules:
- Must not import internal/*, database/sql, net/http, or provider SDKs.
- May import pkg/lipsdk/scope for safe principal attribution on facts.
Compatibility (requirement 12.8): see CompatibilityPolicy and UnknownEnum. Validate() rejects unknown enums for local strict construction; wire decode may preserve unknowns via IsKnown/UnknownEnum without mapping them to known constants. Optional fields and unknown JSON keys are additive.
Index ¶
- Constants
- Variables
- func FactMatchesQuery(f Fact, q Query) bool
- func FactRefsFactIDs(refs []FactRef) []string
- func HasSelectiveBound(q Query) bool
- func IsInputSubcomponent(component string) bool
- func IsOutputSubcomponent(component string) bool
- func IsRegisteredComponent(component string) bool
- func SameFactIdentity(a, b Fact) bool
- func SameFactReplay(a, b Fact) bool
- func UnknownEnum(raw string, known bool) bool
- func ValidateChargeCoverage(observations []Observation) error
- func ValidateComponentSchemas(schemas []ComponentSchema) error
- func ValidateComponentSchemasWithTopology(schemas []ComponentSchema, enforced SchemaTopologyRuleSet) error
- func ValidateCoverageGraph(observations []Observation) error
- func ValidateQuery(q Query) error
- func ValidateSupersessionGraph(observations []Observation) error
- type AtomicObservationSink
- type AttemptOutcome
- type Authority
- type Boundary
- type ChargeCoverageRef
- type ChargeKind
- type ChargeRef
- type Checkpoint
- type ComponentKey
- func (k ComponentKey) CanonicalBytes() []byte
- func (k ComponentKey) CanonicalJSON() ([]byte, error)
- func (k ComponentKey) CanonicalKey() string
- func (k ComponentKey) Clone() ComponentKey
- func (k ComponentKey) Equal(other ComponentKey) bool
- func (k ComponentKey) Fingerprint() string
- func (k ComponentKey) Hash() string
- func (k ComponentKey) MarshalJSON() ([]byte, error)
- func (k ComponentKey) Normalize() (ComponentKey, error)
- func (k *ComponentKey) UnmarshalJSON(data []byte) error
- func (k ComponentKey) Validate() error
- type ComponentRelationship
- type ComponentSchema
- type Correlation
- type CorrelationV2
- type CoverageRelation
- type Decimal
- func (d Decimal) Canonical() (Decimal, error)
- func (d Decimal) CanonicalJSON() ([]byte, error)
- func (d Decimal) CanonicalString() string
- func (d Decimal) Equal(other Decimal) bool
- func (d Decimal) MarshalJSON() ([]byte, error)
- func (d Decimal) Normalize() (Decimal, error)
- func (d Decimal) Rat() (*big.Rat, error)
- func (d Decimal) String() string
- func (d Decimal) ToLedgerNanos() (int64, error)
- func (d Decimal) ToNanoUnits() (int64, error)
- func (d Decimal) ToRat() (*big.Rat, error)
- func (d *Decimal) UnmarshalJSON(data []byte) error
- func (d Decimal) Validate() error
- type Dimension
- type EconomicDirection
- type EconomicPerspective
- type Fact
- func (f Fact) EffectiveIdentityVersion() int
- func (f Fact) FactRef() FactRef
- func (f Fact) IdempotencyKey() string
- func (f Fact) LegacySourceEventKeyPhase31() string
- func (f Fact) SourceEventKey() string
- func (f Fact) SourceEventLookupKeys() []string
- func (f Fact) SourceEventRef() SourceEventRef
- func (f Fact) Validate() error
- type FactKind
- type FactRef
- type FlowDirection
- type LifecycleScope
- type Measure
- type MoneyObservation
- type Observation
- func (o Observation) Canonical() (Observation, error)
- func (o Observation) CanonicalJSON() ([]byte, error)
- func (o Observation) Clone() Observation
- func (o Observation) Fingerprint() string
- func (o Observation) IdempotencyKey() string
- func (o Observation) IdentityKey() string
- func (o Observation) MarshalJSON() ([]byte, error)
- func (o Observation) NormalizedLineageIdentity() string
- func (o Observation) Ref(storeID string) (ObservationRef, error)
- func (o Observation) ReplayFingerprint() (string, error)
- func (o Observation) SourceEventIdentity() string
- func (o Observation) SubjectIdentity() string
- func (o *Observation) UnmarshalJSON(data []byte) error
- func (o Observation) Validate() error
- type ObservationRef
- type ObservationSink
- type ObservationSource
- type Page
- type PaymentParty
- type PaymentPartyKind
- type Presence
- type ProviderDebit
- func (d ProviderDebit) Canonical() (ProviderDebit, error)
- func (d ProviderDebit) CanonicalJSON() ([]byte, error)
- func (d ProviderDebit) Clone() ProviderDebit
- func (d ProviderDebit) Fingerprint() string
- func (d ProviderDebit) IdentityKey() string
- func (d ProviderDebit) MarshalJSON() ([]byte, error)
- func (d ProviderDebit) Observation() (Observation, error)
- func (d ProviderDebit) Ref() (ProviderDebitRef, error)
- func (d ProviderDebit) ReplayFingerprint() string
- func (d ProviderDebit) ToObservation() (Observation, error)
- func (d ProviderDebit) Validate() error
- type ProviderDebitRef
- type Quantity
- type Querier
- type Query
- type QueryClass
- type Recorder
- type RelationshipKind
- type ReportedCharge
- type SafeEvidenceField
- type SchemaTopologyFinding
- type SchemaTopologyReport
- func (r SchemaTopologyReport) Err() error
- func (r SchemaTopologyReport) ErrFor(enforced SchemaTopologyRuleSet) error
- func (r SchemaTopologyReport) For(rule SchemaTopologyRule) []SchemaTopologyFinding
- func (r SchemaTopologyReport) Has(rule SchemaTopologyRule) bool
- func (r SchemaTopologyReport) Len() int
- func (r SchemaTopologyReport) Rules() []SchemaTopologyRule
- type SchemaTopologyRule
- type SchemaTopologyRuleSet
- type ScopeFilters
- type Source
- type SourceEventRef
- type SubjectKind
- type SubjectRef
- type SurfacedState
- type TimeRange
- type UnsupportedFilter
- type VersionRef
Constants ¶
const ( // Component identity bounds are deliberately independent of transport frame // limits. Adapters may negotiate lower limits but may not widen these ones. MaxComponentNameBytes = 256 MaxUnitNameBytes = 128 MaxSchemaIDBytes = 512 MaxDimensionNameBytes = 64 MaxDimensionValueBytes = 256 MaxDimensions = 16 // MaxComponentSchemaRelationships keeps schema-declared graph input // bounded without adding a separate batch-size policy. It is aligned with // the existing per-observation component-entry bound. MaxComponentSchemaRelationships = 128 // MaxComponentSchemas bounds the frozen schema set published with one // rating snapshot. It is independent of the per-schema relationship bound // so nested graphs stay reviewable without an unbounded publication size. MaxComponentSchemas = 64 )
const ( UnitImage = "image" UnitAudio = "audio" UnitVideo = "video" UnitDocument = "document" UnitFile = "file" UnitPage = "page" UnitTile = "tile" UnitSecond = "second" UnitMillisecond = "millisecond" UnitMinute = "minute" UnitHour = "hour" UnitFrame = "frame" UnitPixel = "pixel" UnitMegapixel = "megapixel" UnitMegapixelSecond = "megapixel_second" UnitByte = "byte" UnitByteSecond = "byte_second" UnitQuery = "query" UnitCredit = "credit" UnitPercent = "percent" UnitTokenSecond = "token_second" )
Native units used by current and anticipated provider families. A schema-qualified unknown unit is also valid, so this list is not a closed provider catalog.
const ( ComponentTextToken = "text_token" ComponentInputTokenUncached = "input_token_uncached" ComponentInputTokenTotal = "input_token_total" ComponentImage = "image" ComponentImageToken = "image_token" ComponentAudio = "audio" ComponentAudioToken = "audio_token" ComponentVideo = "video" ComponentVideoToken = "video_token" ComponentDocument = "document" ComponentDocumentToken = "document_token" ComponentFile = "file" ComponentToolQuery = "tool_query" ComponentCredit = "credit" ComponentStorage = "cache_storage" )
Common multimodal component names are vocabulary, not a closed provider registry. Namespaced additions remain valid when a schema is supplied.
const ( // MaxDecimalCoefficientDigits is the maximum number of significant base-10 // digits retained in a canonical Decimal. MaxDecimalCoefficientDigits = 38 // MaxDecimalScale is the maximum number of decimal places in a Decimal. MaxDecimalScale uint8 = 18 // LedgerNanoScale is the scale of the integer major-currency ledger unit. LedgerNanoScale uint8 = 9 // MaxDecimalLiteralBytes bounds work done by the scientific-notation parser. MaxDecimalLiteralBytes = 256 )
const ( // ObservationVersionV2 is the canonical evidence envelope version. ObservationVersionV2 uint32 = 2 MaxObservationIDBytes = 512 MaxSourceEventKeyBytes = 1024 MaxStreamIDBytes = 512 MaxMappingRefBytes = 512 MaxObservationMeasures = 128 MaxObservationCharges = 128 MaxObservationSupersedes = 128 MaxObservationEvidence = 256 MaxSafeEvidenceBytes = 64 * 1024 MaxSafeEvidenceFieldBytes = 1024 )
const ( OriginLocal = "local" OriginProvider = "provider" OriginStatement = "statement" )
Origins identify the independent evidence plane. A derived valuation must reference its inputs instead of claiming a new observation origin.
const ( AcquisitionLocalTokenizer = "local_tokenizer" AcquisitionLocalTransport = "local_transport_measurement" AcquisitionLocalEstimator = "local_estimator" AcquisitionProviderCountAPI = "provider_count_api" AcquisitionProviderResponse = "provider_response" AcquisitionProviderHeader = "provider_header" AcquisitionProviderFinalizer = "provider_finalizer" AcquisitionStatementImporter = "statement_importer" // Short aliases retain the vocabulary used by adapter contracts. AcquisitionProviderCount = AcquisitionProviderCountAPI AcquisitionLocalMeasurement = AcquisitionLocalTransport )
Acquisition identifies how an observation was acquired. Unknown namespaced values may be retained by additive decoders, while strict construction uses one of these known channels.
const ( AuthorityObservedClaim = "observed_claim" AuthorityEstimatedClaim = "estimated" AuthorityVerifiedStatement = "verified_statement" )
const ( SemanticsDelta = "delta" SemanticsCumulative = "cumulative" SemanticsGauge = "gauge" SemanticsReplacement = "replacement" SemanticsCorrection = "correction" )
const ( QualityObserved = "observed" QualityEstimated = "estimated" QualityNotApplicable = "not_applicable" QualityUnknown = "unknown" )
Measure quality describes certainty/presence independently of origin.
const ( SubjectALeg SubjectKind = "a_leg" SubjectRequest SubjectKind = "logical_request" SubjectBillingCall SubjectKind = "billing_call" SubjectBLeg SubjectKind = "b_leg" SubjectSubmission SubjectKind = "submission" SubjectProviderCharge SubjectKind = "provider_charge" // SubjectProviderDebit is a nonmonetary, provider-reported request debit. // It carries the provider account/pool/window identity and one concrete // request/B-leg owner; it is intentionally distinct from both // SubjectAccountWindow gauges and SubjectProviderCharge money. SubjectProviderDebit SubjectKind = "provider_debit" SubjectResource SubjectKind = "resource_interval" SubjectAccountWindow SubjectKind = "account_window" SubjectStatementLine SubjectKind = "statement_line" // Common spelling aliases are intentionally the same tagged values. SubjectAleg = SubjectALeg SubjectLogicalRequest = SubjectRequest SubjectLogicalCall = SubjectRequest SubjectCall = SubjectBillingCall SubjectBleg = SubjectBLeg SubjectBackendAttempt = SubjectBLeg SubjectResourceInterval = SubjectResource SubjectAccountPeriod = SubjectAccountWindow SubjectTrustedSubmission = SubjectSubmission )
const ( CoverageInclusive CoverageRelation = "inclusive" CoverageAdditive CoverageRelation = "additive" CoverageRelationInclusive = CoverageInclusive CoverageRelationAdditive = CoverageAdditive )
const ( // LegacyV1MappingRef marks an observation that was losslessly lifted from // the historical Fact DTO. It is explicit about the loss of richer V2 // provenance rather than inventing provider/local distinctions. LegacyV1MappingRef = "legacy_v1_fact" LegacyV1StoreID = "legacy_v1" LegacyV1UnknownHash = "legacy_v1_unknown_payload" )
const ( // ProviderDebitVersionV1 is the version of the typed, nonmonetary provider // request-debit contract. It is deliberately separate from the V2 // observation-envelope version so the evidence shape can evolve without // changing the journal envelope. ProviderDebitVersionV1 uint32 = 1 // ProviderDebitMappingRef identifies the canonical V2 projection produced // by ToObservation. It is a mapping identity, not a provider price/rate. ProviderDebitMappingRef = "provider_debit_v1" )
const ( ComponentRequest = "request" ComponentInputToken = "input_token" ComponentOutputToken = "output_token" ComponentCacheReadInputToken = "cache_read_input_token" ComponentCacheWriteInputToken = "cache_write_input_token" ComponentReasoningOutputToken = "reasoning_output_token" ComponentTotalToken = "total_token" )
Registered quantity component identifiers (requirement 3.9).
const ( UnitCount = "count" UnitToken = "token" )
Registered quantity units.
const CompatibilityPolicy = "additive_v1"
Compatibility documents additive versioning rules for public metering contracts (requirement 12.8). Economics and authority packages follow the same policy for their public enums and optional fields.
Enum values:
- Local construction and Validate() reject unknown enum strings so strict admission cannot silently reinterpret new semantics as a known value.
- Additive wire decode (JSON from a newer peer) MUST preserve unrecognized non-empty enum strings for round-trip; consumers MUST NOT map them onto a documented constant. Use IsKnown() to detect unknowns without failing the entire decode when only observation/logging is required.
Optional fields:
- Omitted optional JSON fields mean absent / zero value.
- Decoders MUST ignore unknown JSON object keys (forward compatible).
- New optional fields may be added without breaking older consumers.
Contract identity:
- Packages version additively; removing or redefining a documented enum value or required field is a breaking change.
const DefaultInclusionSchemaID = "lip.default.token_inclusion.v1"
DefaultInclusionSchemaID names the default component inclusion rules aligned with Phase 2 core accounting. This package does not infer totals at runtime; callers and journal aggregators apply the schema explicitly.
Default inclusion:
input_token includes cache_read_input_token and cache_write_input_token output_token includes reasoning_output_token total_token = input_token + output_token
Subcomponents are separately priced but are not added again to total.
const IdentityVersionV1 = 1
IdentityVersionV1 is the current canonical source-event identity version. Historical producers that omit IdentityVersion (JSON zero) are treated as V1.
const MaxQueryLimit = 500
const MaxSanitizerMarkerBytes = 128
MaxSanitizerMarkerBytes bounds the sanitizer identity/version marker.
const MaxSourceEventFieldLen = 512
MaxSourceEventFieldLen bounds lifecycle ID, source ID, and event-kind strings in SourceEventRef encodings (design Deterministic Identity: bounded key).
Variables ¶
var ( ErrInvalidComponentKey = errors.New("metering: invalid component key") ErrInvalidComponentSchema = errors.New("metering: invalid component schema") // ErrInvalidUnit is wrapped when a unit is unknown or incompatible with a // registered component. ErrInvalidUnit = errors.New("metering: invalid unit") // ErrInvalidSchema is wrapped when a schema identifier is required or // malformed. ErrInvalidSchema = errors.New("metering: invalid schema") )
var ( // ErrInvalidDecimal identifies malformed or non-canonical decimal input. ErrInvalidDecimal = errors.New("metering: invalid decimal") // ErrDecimalOverflow identifies a decimal that cannot be represented within // the bounded coefficient/scale contract or as checked ledger nanos. ErrDecimalOverflow = errors.New("metering: decimal overflow") // ErrDecimalPrecision identifies a value with more precision than the // destination contract can represent exactly. ErrDecimalPrecision = errors.New("metering: decimal precision unsupported") )
var ( ErrInvalidObservation = errors.New("metering: invalid observation") ErrInvalidSubject = errors.New("metering: invalid subject") ErrInvalidCoverage = errors.New("metering: invalid charge coverage") ErrInvalidRevision = errors.New("metering: invalid observation revision") ErrV1Projection = errors.New("metering: V1 projection is non-authoritative") )
var ( ErrInvalidProviderDebit = errors.New("metering: invalid provider debit") ErrProviderDebitAbsent = errors.New("metering: provider debit absent") )
var ErrComponentSchemaTopology = errors.New("metering: invalid component schema topology")
ErrComponentSchemaTopology is wrapped by every component-schema topology finding. It is a separate sentinel from ErrInvalidComponentSchema so a caller can accept a graph that is structurally describable but topologically incompatible, and report it, without confusing it with a malformed edge.
var ErrInvalidFact = errors.New("metering: invalid fact")
ErrInvalidFact classifies public fact validation failures (D5/D14-safe messages).
var ErrQueryLimitExceeded = errors.New("metering: query limit exceeded")
var ErrQueryTooBroad = errors.New("metering: query too broad")
ErrQueryTooBroad is returned when List lacks a required selective bound so the store cannot safely page without scanning (requirements 14.4, 14.8).
var ErrQueryUnsupported = errors.New("metering: query unsupported")
ErrQueryUnsupported is returned when the query class or filter shape is not supported by the metering journal querier (requirements 14.5, 14.8).
var ErrUnrepresentableV1 = fmt.Errorf("%w: V2 value is not representable by V1", ErrV1Projection)
ErrUnrepresentableV1 identifies a V2 value that cannot be losslessly exposed through the integer/token-only V1 DTO.
var SchemaTopologyAllRules = SchemaTopologyRuleSet{/* contains filtered or unexported fields */}
SchemaTopologyAllRules is the full rule set. Enforcing it rejects every topology this package can report.
var SchemaTopologyRuleNone = SchemaTopologyRuleSet{}
SchemaTopologyRuleNone is the empty rule set: inspect only, enforce nothing.
Functions ¶
func FactMatchesQuery ¶
FactMatchesQuery applies every supported filter to one fact.
func FactRefsFactIDs ¶
FactRefsFactIDs returns FactID values in order.
func HasSelectiveBound ¶
HasSelectiveBound reports whether q carries at least one indexed selective filter so a store can page without scanning the full journal.
func IsInputSubcomponent ¶
IsInputSubcomponent reports whether component is included in input_token under the default inclusion schema (cache ⊂ input). Pure documentation helper.
func IsOutputSubcomponent ¶
IsOutputSubcomponent reports whether component is included in output_token under the default inclusion schema (reasoning ⊂ output). Pure documentation helper.
func IsRegisteredComponent ¶
IsRegisteredComponent reports whether component is in the built-in registry.
func SameFactIdentity ¶
SameFactIdentity reports whether a and b share FactID, StreamID, and Sequence (ordered stream membership). Matching identity alone is not sufficient for an idempotent Append replay; stores also require SameFactReplay content equality.
func SameFactReplay ¶
SameFactReplay reports whether a and b share stream membership (SameFactIdentity) and equal semantic payloads. Quantities and Supersedes compare as multisets (order-independent). RecordedAt is intentionally excluded because journal stores assign it when producers omit it; that store-assigned timestamp does not change the producer fact being replayed.
func UnknownEnum ¶
UnknownEnum reports whether raw is a non-empty value that is not among the documented constants for a public enum. Callers use this when preserving wire unknowns (requirement 12.8) instead of calling Validate().
func ValidateChargeCoverage ¶
func ValidateChargeCoverage(observations []Observation) error
ValidateChargeCoverage is a compatibility alias for ValidateCoverageGraph.
func ValidateComponentSchemas ¶
func ValidateComponentSchemas(schemas []ComponentSchema) error
ValidateComponentSchemas validates a bounded, frozen set of component schemas. Beyond each schema's own edge bound and self/unit rules it enforces set-level semantics: schema IDs are unique, relationship edges form an acyclic directed graph, and no ordered parent/child pair is declared with more than one meaning. It additionally rejects every structurally-knowable containment impossibility listed in EnforcedComponentSchemaTopologyRules, so an unsatisfiable complete coverage is refused at publication instead of being rediscovered per rated call. Nil or empty input is valid and preserves legacy publication identity.
To choose a different topology gate, or to report findings without rejecting them, use ValidateComponentSchemasWithTopology and InspectComponentSchemaTopology.
func ValidateComponentSchemasWithTopology ¶
func ValidateComponentSchemasWithTopology(schemas []ComponentSchema, enforced SchemaTopologyRuleSet) error
ValidateComponentSchemasWithTopology is ValidateComponentSchemas plus an explicit choice of which topology rules to enforce. The structural, unit, optionality, duplicate, ambiguity, acyclicity and bound checks always run and are unaffected by enforced; only the topology rules are selected.
A caller that wants the widest possible gate passes SchemaTopologyAllRules. A caller that must accept already-published inert schemas passes the rule subset it can live with, and can still consult InspectComponentSchemaTopology for the findings it chose not to enforce.
func ValidateCoverageGraph ¶
func ValidateCoverageGraph(observations []Observation) error
ValidateCoverageGraph validates cross-observation charge references, cycles, contradictory edges and overlapping inclusive parents. Unresolved references are allowed here because late statement/charge observations can arrive in a later batch; callers requiring a closed graph should check their resolver.
func ValidateQuery ¶
ValidateQuery rejects too-broad or unsupported metering journal queries before store access (requirements 14.4, 14.5, 14.8).
func ValidateSupersessionGraph ¶
func ValidateSupersessionGraph(observations []Observation) error
ValidateSupersessionGraph checks known revision links without requiring all referenced revisions to be present in the current batch. A late correction may therefore remain pending, while a resolved link must retain the same subject and origin and must name the referenced payload hash exactly (legacy V1 links use the explicit unknown-hash marker).
Types ¶
type AtomicObservationSink ¶
type AtomicObservationSink interface {
ObservationSink
AppendObservations(ctx context.Context, observations []Observation) error
}
AtomicObservationSink is the retry-safe batch capability for durable checkpoint capture. AppendObservations must atomically process the complete batch: it must not expose a successful prefix when returning an error. Exact replays of a previously accepted observation must be idempotent no-ops, and a changed payload for an existing source identity must reject the complete batch without exposing any new observation. These guarantees let callers retry the same batch after an error, including an ambiguous commit result, without duplicating or losing observations. An empty batch performs no durable operation.
Implementations also satisfy ObservationSink for compatibility. Runtime economic checkpoint flushing uses AppendObservations exclusively after verifying this capability; a plain ObservationSink is not sufficient.
type AttemptOutcome ¶
type AttemptOutcome string
AttemptOutcome classifies the terminal role of a backend attempt.
const ( AttemptOutcomeWinner AttemptOutcome = "winner" AttemptOutcomeLoser AttemptOutcome = "loser" AttemptOutcomeCanceled AttemptOutcome = "canceled" AttemptOutcomeFailed AttemptOutcome = "failed" AttemptOutcomeUnknown AttemptOutcome = "unknown" )
func (AttemptOutcome) IsKnown ¶
func (o AttemptOutcome) IsKnown() bool
IsKnown reports whether o is a documented attempt outcome.
func (AttemptOutcome) Validate ¶
func (o AttemptOutcome) Validate() error
Validate returns an error when o is not a known attempt outcome.
type Authority ¶
type Authority string
Authority is evidence provenance for a fact (design: authoritative, delegated, estimated, advisory, unavailable). Independent of EconomicPerspective.
type Boundary ¶
type Boundary string
Boundary is a legal metering measurement boundary on the proxy data path. Derived bases such as "derived:<id>" are rule/exposure concerns and are not known Boundary values here.
type ChargeCoverageRef ¶
type ChargeCoverageRef struct {
Ref ChargeRef `json:"ref"`
Relation CoverageRelation `json:"relation"`
}
ChargeCoverageRef is one typed edge in the provider charge coverage graph.
func (*ChargeCoverageRef) UnmarshalJSON ¶
func (r *ChargeCoverageRef) UnmarshalJSON(data []byte) error
func (ChargeCoverageRef) Validate ¶
func (r ChargeCoverageRef) Validate() error
type ChargeKind ¶
type ChargeKind string
ChargeKind classifies provider monetary evidence without implying a component decomposition.
const ( ChargeKindComponent ChargeKind = "component" ChargeKindAggregate ChargeKind = "aggregate" ChargeKindSurcharge ChargeKind = "surcharge" ChargeKindTax ChargeKind = "tax" ChargeKindAdjustment ChargeKind = "adjustment" ChargeKindCredit ChargeKind = "credit" )
func (ChargeKind) IsKnown ¶
func (k ChargeKind) IsKnown() bool
type ChargeRef ¶
type ChargeRef struct {
StoreID string `json:"store_id"`
ObservationID string `json:"observation_id"`
Revision uint64 `json:"revision"`
ChargeItemID string `json:"charge_item_id"`
}
ChargeRef resolves a charge item to one exact observation revision.
func (*ChargeRef) UnmarshalJSON ¶
type Checkpoint ¶
type Checkpoint struct {
CheckpointID string `json:"checkpoint_id"`
StreamID string `json:"stream_id"`
Boundary Boundary `json:"boundary"`
Lifecycle LifecycleScope `json:"lifecycle"`
Perspective EconomicPerspective `json:"perspective"`
Correlation Correlation `json:"correlation"`
Scope scope.PrincipalScopeView `json:"scope"`
FrontendID string `json:"frontend_id,omitempty"`
BackendID string `json:"backend_id,omitempty"`
Model string `json:"model,omitempty"`
Quantities []Quantity `json:"quantities,omitempty"`
Presence Presence `json:"presence"`
Source Source `json:"source,omitempty"`
Authority Authority `json:"authority,omitempty"`
CapturedAt time.Time `json:"captured_at"`
}
Checkpoint is the public, journal-safe metering checkpoint DTO. It carries boundary identity, correlation, scope, and quantities only — never raw prompts, responses, headers, credentials, or resume tokens (requirement 2.7).
func (Checkpoint) Validate ¶
func (c Checkpoint) Validate() error
Validate checks required identity and enums for a checkpoint record. Boundary/lifecycle pairing is enforced for the four legal capture sites.
type ComponentKey ¶
type ComponentKey struct {
Direction FlowDirection `json:"direction" yaml:"direction"`
Component string `json:"component" yaml:"component"`
Unit string `json:"unit" yaml:"unit"`
SchemaID string `json:"schema_id,omitempty" yaml:"schema_id,omitempty"`
Dimensions []Dimension `json:"dimensions,omitempty" yaml:"dimensions,omitempty"`
}
ComponentKey is the complete canonical identity of one economic measure. Direction, unit and schema are all significant, while dimensions are a sorted set for identity purposes.
func (ComponentKey) CanonicalBytes ¶
func (k ComponentKey) CanonicalBytes() []byte
CanonicalBytes returns deterministic JSON for a normalized key. It is safe to use as a content-addressing preimage because dimensions are sorted and all field names are explicit.
func (ComponentKey) CanonicalJSON ¶
func (k ComponentKey) CanonicalJSON() ([]byte, error)
CanonicalJSON is the error-returning form of CanonicalBytes.
func (ComponentKey) CanonicalKey ¶
func (k ComponentKey) CanonicalKey() string
CanonicalKey returns the UTF-8 canonical JSON identity. Invalid keys return an empty string; use CanonicalJSON when the validation error is required.
func (ComponentKey) Clone ¶
func (k ComponentKey) Clone() ComponentKey
Clone returns a deep copy of k.
func (ComponentKey) Equal ¶
func (k ComponentKey) Equal(other ComponentKey) bool
Equal compares normalized keys, so dimension order does not matter.
func (ComponentKey) Fingerprint ¶
func (k ComponentKey) Fingerprint() string
Fingerprint returns SHA-256 over the canonical key JSON. Invalid keys return an empty fingerprint rather than hashing an unsafe representation.
func (ComponentKey) Hash ¶
func (k ComponentKey) Hash() string
Hash is an explicit alias for Fingerprint used by storage adapters.
func (ComponentKey) MarshalJSON ¶
func (k ComponentKey) MarshalJSON() ([]byte, error)
MarshalJSON keeps direct ComponentKey encoding on the same canonical path as observation and valuation serializers. Callers that need the validation error should use CanonicalJSON.
func (ComponentKey) Normalize ¶
func (k ComponentKey) Normalize() (ComponentKey, error)
Normalize returns a deep-copied key with dimensions sorted by name. It rejects duplicate names and never silently trims or rewrites identity.
func (*ComponentKey) UnmarshalJSON ¶
func (k *ComponentKey) UnmarshalJSON(data []byte) error
func (ComponentKey) Validate ¶
func (k ComponentKey) Validate() error
Validate checks bounded identity and contradiction rules without changing caller-owned slices. Dimension order is not significant to validation.
type ComponentRelationship ¶
type ComponentRelationship struct {
Kind RelationshipKind `json:"kind"`
Parent ComponentKey `json:"parent"`
Child ComponentKey `json:"child"`
Optional bool `json:"optional,omitempty"`
}
ComponentRelationship is one schema-declared parent/child or transform edge. Parent and child may retain different native units only for an explicitly declared transform relationship.
Optional marks a member of a complete aggregate/partition coverage that the provider may omit. When the member is present it is a required part of the coverage and must be complete and rateable; when it is absent the parent's coverage is still proven by the remaining members. It is therefore the truthful encoding of a wire family that reports a disjoint detail member conditionally, keeping absence distinct from an explicit provider zero. Optional is only meaningful for an aggregate or partition relationship; a subset is already a partial containment and a transform is a separately governed unit derivation.
func (ComponentRelationship) Clone ¶
func (r ComponentRelationship) Clone() ComponentRelationship
Clone returns a deep copy of r, including both component keys.
func (*ComponentRelationship) UnmarshalJSON ¶
func (r *ComponentRelationship) UnmarshalJSON(data []byte) error
func (ComponentRelationship) Validate ¶
func (r ComponentRelationship) Validate() error
type ComponentSchema ¶
type ComponentSchema struct {
ID string `json:"id"`
Version string `json:"version"`
Relationships []ComponentRelationship `json:"relationships,omitempty"`
}
ComponentSchema declares versioned inclusion/partition/transform semantics.
func (ComponentSchema) Clone ¶
func (s ComponentSchema) Clone() ComponentSchema
Clone returns a deep copy of s, including relationship keys and dimensions.
func (*ComponentSchema) UnmarshalJSON ¶
func (s *ComponentSchema) UnmarshalJSON(data []byte) error
func (ComponentSchema) Validate ¶
func (s ComponentSchema) Validate() error
type Correlation ¶
type Correlation struct {
RequestID string `json:"request_id,omitempty"`
ALegID string `json:"a_leg_id,omitempty"`
BLegID string `json:"b_leg_id,omitempty"`
AttemptID string `json:"attempt_id,omitempty"`
TraceID string `json:"trace_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
}
Correlation carries safe lifecycle identifiers without raw payloads (requirements 2.6, 2.7, 13.2).
type CorrelationV2 ¶
type CorrelationV2 struct {
StoreID string `json:"store_id"`
TenantID string `json:"tenant_id,omitempty"`
RequestID string `json:"request_id,omitempty"`
CallID string `json:"call_id,omitempty"`
BillingCallID string `json:"billing_call_id,omitempty"`
ALegID string `json:"a_leg_id,omitempty"`
BLegID string `json:"b_leg_id,omitempty"`
AttemptID string `json:"attempt_id,omitempty"`
AttemptSeq uint64 `json:"attempt_seq,omitempty"`
SubmissionID string `json:"submission_id,omitempty"`
ProviderAccountKey string `json:"provider_account_key,omitempty"`
ProviderRequestID string `json:"provider_request_id,omitempty"`
ProviderChargeID string `json:"provider_charge_id,omitempty"`
ParentWorkID string `json:"parent_work_id,omitempty"`
ResourceID string `json:"resource_id,omitempty"`
PeriodID string `json:"period_id,omitempty"`
}
CorrelationV2 carries trusted lineage and store scope alongside the tagged subject. Runtime attribution fields are never sourced from an untrusted provider header.
func (*CorrelationV2) UnmarshalJSON ¶
func (c *CorrelationV2) UnmarshalJSON(data []byte) error
func (CorrelationV2) Validate ¶
func (c CorrelationV2) Validate() error
type CoverageRelation ¶
type CoverageRelation string
CoverageRelation describes whether a referenced child is already included in a parent charge or remains separately payable.
func (CoverageRelation) IsKnown ¶
func (r CoverageRelation) IsKnown() bool
type Decimal ¶
Decimal is a bounded exact base-10 value. Its value is Coefficient * 10^-Scale. Coefficient is a signed canonical base-10 integer; negative zero and insignificant trailing fractional zeroes are normalized away before a value is used in an identity or calculation.
func DecimalFromNanoUnits ¶
DecimalFromNanoUnits constructs an exact Decimal from checked ledger nanos.
func ParseDecimal ¶
ParseDecimal parses a bounded decimal or scientific-notation literal without using floating point. Whitespace, NaN, infinity and unbounded exponent expansion are rejected. The result is canonical.
func (Decimal) Canonical ¶
Canonical is a descriptive alias for Normalize used by serializers that treat the normalized value as the canonical decimal contract.
func (Decimal) CanonicalJSON ¶
CanonicalJSON returns deterministic JSON for the normalized Decimal.
func (Decimal) CanonicalString ¶
CanonicalString returns the unambiguous coefficient/scale form used in diagnostics and tests (for example, 123/2 represents 1.23).
func (Decimal) MarshalJSON ¶
MarshalJSON serializes only the normalized exact representation.
func (Decimal) Normalize ¶
Normalize returns the unique canonical representation of d. It accepts leading zeroes, signed zero, and trailing fractional zeroes as input but never returns them. It does not round.
func (Decimal) String ¶
String implements fmt.Stringer using CanonicalString. Invalid values return an empty string rather than exposing an untrusted raw lexeme.
func (Decimal) ToLedgerNanos ¶
ToLedgerNanos is an explicit spelling of ToNanoUnits for ledger adapters.
func (Decimal) ToNanoUnits ¶
ToNanoUnits converts d to checked integer ledger nanos without rounding. Values with finer-than-nano precision are rejected unless the discarded digits are all zero.
func (*Decimal) UnmarshalJSON ¶
UnmarshalJSON accepts the object representation and normalizes it. Unknown object fields are ignored by encoding/json for additive compatibility.
type Dimension ¶
type Dimension struct {
Name string `json:"name" yaml:"name"`
Value string `json:"value" yaml:"value"`
}
Dimension is a bounded price-relevant qualifier. Names are unique within a ComponentKey; arbitrary customer text is not a supported qualifier.
func (*Dimension) UnmarshalJSON ¶
type EconomicDirection ¶
type EconomicDirection = FlowDirection
EconomicDirection is retained as a source-compatible alias for the parent design's name. It has the refined three-value meaning of FlowDirection.
type EconomicPerspective ¶
type EconomicPerspective string
EconomicPerspective identifies whose economics a fact or authority decision represents. Customer and operator perspectives are independent even when values happen to match (requirements 1.1, 1.4).
const ( PerspectiveCustomer EconomicPerspective = "customer" PerspectiveOperator EconomicPerspective = "operator" PerspectiveNone EconomicPerspective = "none" // pure technical metrics )
func (EconomicPerspective) IsKnown ¶
func (p EconomicPerspective) IsKnown() bool
IsKnown reports whether p is a documented economic perspective.
func (EconomicPerspective) Validate ¶
func (p EconomicPerspective) Validate() error
Validate returns an error when p is not a known perspective.
type Fact ¶
type Fact struct {
FactID string `json:"fact_id"`
StreamID string `json:"stream_id"`
// Sequence is the producer-stable ordinal within StreamID. It is not part of
// SourceEventKey; producers must keep it stable across retry/restart for the
// same stream membership (design Deterministic Identity).
Sequence int64 `json:"sequence"`
IdentityVersion int `json:"identity_version,omitempty"`
SourceRevision int64 `json:"source_revision,omitempty"`
SourceEventKind string `json:"source_event_kind,omitempty"`
SourceID string `json:"source_id,omitempty"`
Kind FactKind `json:"kind"`
Perspective EconomicPerspective `json:"perspective"`
Boundary Boundary `json:"boundary"`
Lifecycle LifecycleScope `json:"lifecycle"`
Correlation Correlation `json:"correlation"`
Scope scope.PrincipalScopeView `json:"scope"`
FrontendID string `json:"frontend_id,omitempty"`
BackendID string `json:"backend_id,omitempty"`
Model string `json:"model,omitempty"`
AttemptOutcome AttemptOutcome `json:"attempt_outcome,omitempty"`
Surfaced SurfacedState `json:"surfaced,omitempty"`
Quantities []Quantity `json:"quantities,omitempty"`
Money *MoneyObservation `json:"money,omitempty"`
Source Source `json:"source"`
Authority Authority `json:"authority"`
Presence Presence `json:"presence"`
Supersedes []string `json:"supersedes,omitempty"`
PolicyVersion VersionRef `json:"policy_version,omitzero"`
RecordedAt time.Time `json:"recorded_at"`
}
Fact is one idempotent metering journal record (requirements 3.1–3.5, 13.2).
Idempotency: the same FactID within a StreamID must be treated as the same fact. Replaying Append with SameFactReplay is a no-op at the store; a different Sequence, Kind, or double-count-sensitive payload for the same FactID is a contract violation for store implementations to reject.
func FactFromObservation ¶
func FactFromObservation(o Observation) (Fact, error)
FactFromObservation is an explicit alias retained for callers that use the historical direction of the adapter name.
func ProjectObservationToFact ¶
func ProjectObservationToFact(o Observation) (Fact, error)
ProjectObservationToFact creates a one-way, nonfinancial V1 projection. It accepts only integer V1 components and marks the result so a later ObservationFromFact call cannot treat it as an independent observation.
func (Fact) EffectiveIdentityVersion ¶
EffectiveIdentityVersion returns the V1-compatible identity version for f.
func (Fact) IdempotencyKey ¶
IdempotencyKey returns the stable journal key for this fact identity (requirement 3.1): StreamID + FactID. It intentionally excludes quantities, money, and other payload fields so replays with identical identity collide. Sequence is checked separately via SameFactIdentity for ordered stream membership; payload equality for idempotent replay is SameFactReplay.
func (Fact) LegacySourceEventKeyPhase31 ¶
LegacySourceEventKeyPhase31 returns the exact NUL-delimited SourceEventKey encoding written by task 3.1 before length-prefixed CanonicalKey. It uses the literal IdentityVersion field (including 0), not EffectiveIdentityVersion.
func (Fact) SourceEventKey ¶
SourceEventKey returns the canonical SourceEventRef encoding (design Deterministic Identity / D6). Store uniqueness scopes this key by logical store_id. RecordedAt, Sequence, FactID (when SourceID is set), quantities, and money are excluded so retries stay stable.
func (Fact) SourceEventLookupKeys ¶
SourceEventLookupKeys returns durable lookup candidates in order: current canonical SourceEventKey, phase-3.1 NUL legacy key (literal IdentityVersion), bidirectional V0/V1 NUL aliases when EffectiveIdentityVersion is V1, then IdempotencyKey. IdentityVersion >= 2 adds no V0/V1 aliases. Duplicates are omitted while preserving order.
func (Fact) SourceEventRef ¶
func (f Fact) SourceEventRef() SourceEventRef
SourceEventRef builds the deterministic identity ref for this fact. Lifecycle ID is the durable stream identifier (StreamID). Empty SourceEventKind defaults to Kind; empty SourceID defaults to FactID (V1 producer compatibility).
type FactKind ¶
type FactKind string
FactKind classifies how a fact participates in aggregation (requirement 3.2).
func (FactKind) RequiresSupersedes ¶
RequiresSupersedes reports whether k must identify superseded fact identities.
type FactRef ¶
FactRef is a durable journal identity handle for rating and authority binding (design Deterministic Identity / D6). It excludes raw call content.
type FlowDirection ¶
type FlowDirection string
FlowDirection is the direction of a flow-valued measure. Subject scope is intentionally orthogonal: resource and account/window economics use DirectionNone plus a subject/component identity, never a fake direction.
const ( DirectionNone FlowDirection = "none" DirectionInput FlowDirection = "input" DirectionOutput FlowDirection = "output" )
func (FlowDirection) IsKnown ¶
func (d FlowDirection) IsKnown() bool
func (FlowDirection) Validate ¶
func (d FlowDirection) Validate() error
type LifecycleScope ¶
type LifecycleScope string
LifecycleScope identifies the lifecycle object a fact or rule applies to (requirement 1.2).
const ( LifecycleLogicalRequest LifecycleScope = "logical_request" LifecycleBackendAttempt LifecycleScope = "backend_attempt" LifecycleAuxiliaryRequest LifecycleScope = "auxiliary_request" )
func (LifecycleScope) IsKnown ¶
func (s LifecycleScope) IsKnown() bool
IsKnown reports whether s is a documented lifecycle scope.
func (LifecycleScope) Validate ¶
func (s LifecycleScope) Validate() error
Validate returns an error when s is not a known lifecycle scope.
type Measure ¶
type Measure struct {
Key ComponentKey `json:"key"`
Value *Decimal `json:"value,omitempty"`
Quality string `json:"quality"`
MethodRef string `json:"method_ref,omitempty"`
Reason string `json:"reason,omitempty"`
}
Measure is one independent component measure. A nil Value is absent and is never interpreted as an observed zero.
func (*Measure) UnmarshalJSON ¶
type MoneyObservation ¶
type MoneyObservation struct {
NanoUnits int64 `json:"nano_units"`
Currency string `json:"currency,omitempty"`
Present bool `json:"present"`
Source Source `json:"source,omitempty"`
}
MoneyObservation is an optional monetary observation attached to a fact. It is intentionally independent of pkg/lipsdk/economics.Money so metering does not import economics (import DAG: authority → economics → metering).
type Observation ¶
type Observation struct {
Version uint32 `json:"version"`
ID string `json:"id"`
SourceEventKey string `json:"source_event_key"`
Revision uint64 `json:"revision"`
StreamID string `json:"stream_id"`
Sequence uint64 `json:"sequence"`
Origin string `json:"origin"`
Acquisition string `json:"acquisition"`
Authority string `json:"authority"`
Perspective EconomicPerspective `json:"perspective"`
Boundary Boundary `json:"boundary"`
Lifecycle LifecycleScope `json:"lifecycle"`
Subject SubjectRef `json:"subject"`
Correlation CorrelationV2 `json:"correlation"`
Scope scope.PrincipalScopeView `json:"scope"`
Semantics string `json:"semantics"`
ObservedAt time.Time `json:"observed_at"`
ReceivedAt time.Time `json:"received_at"`
MappingRef string `json:"mapping_ref"`
Measures []Measure `json:"measures,omitempty"`
Charges []ReportedCharge `json:"charges,omitempty"`
Supersedes []ObservationRef `json:"supersedes,omitempty"`
Evidence []SafeEvidenceField `json:"evidence,omitempty"`
// contains filtered or unexported fields
}
Observation is the immutable V2 evidence envelope. Local measurements, provider claims and statement records use the same journal family but retain distinct Origin/Acquisition/Authority values.
func ObservationFromFact ¶
func ObservationFromFact(f Fact) (Observation, error)
ObservationFromFact lifts a historical Fact into an explicit V2 observation. It preserves Fact.SourceEventKey verbatim and marks all inferred identity fields as legacy. A Fact projected from V2 is rejected to prevent a nonfinancial compatibility view from becoming a second authority.
func ReadLegacyV1Observation ¶
func ReadLegacyV1Observation(data []byte) (Observation, error)
ReadLegacyV1Observation decodes a selected historical V1-lifted observation and restores its private provider/request compatibility allowance only after checking the versioned legacy marker, acquisition, origin, subject kind, and both legacy store-scope fields. The caller must establish that data was selected from the trusted durable historical record; JSON values do not authenticate provenance by themselves.
func V2ObservationFromFact ¶
func V2ObservationFromFact(f Fact) (Observation, error)
V2ObservationFromFact is an explicit compatibility spelling.
func (Observation) Canonical ¶
func (o Observation) Canonical() (Observation, error)
Canonical returns a normalized deep copy with semantically unordered sets sorted. Source sequence and revision remain explicit identity fields.
func (Observation) CanonicalJSON ¶
func (o Observation) CanonicalJSON() ([]byte, error)
CanonicalJSON serializes the normalized V2 envelope deterministically.
func (Observation) Clone ¶
func (o Observation) Clone() Observation
Clone returns a deep copy of all nested V2 fields.
func (Observation) Fingerprint ¶
func (o Observation) Fingerprint() string
Fingerprint returns SHA-256 over canonical JSON.
func (Observation) IdempotencyKey ¶
func (o Observation) IdempotencyKey() string
IdempotencyKey is an explicit journal spelling for the source identity.
func (Observation) IdentityKey ¶
func (o Observation) IdentityKey() string
IdentityKey returns a source-event identity preimage that excludes values; replay equality uses the full canonical payload/fingerprint.
func (Observation) MarshalJSON ¶
func (o Observation) MarshalJSON() ([]byte, error)
MarshalJSON uses canonical ordering so durable hashes do not depend on input slice order.
func (Observation) NormalizedLineageIdentity ¶
func (o Observation) NormalizedLineageIdentity() string
NormalizedLineageIdentity returns the canonical request/account/resource lineage after merging fields that may be carried by either trusted Subject or Correlation. The two carriers are intentionally accepted as a placement detail; a value present in only one carrier has the same effective identity as the equivalent value present in the other. Validation still rejects a contradictory value when both carriers provide one.
func (Observation) Ref ¶
func (o Observation) Ref(storeID string) (ObservationRef, error)
Ref returns the immutable store-scoped reference for this observation. The payload hash is computed from the canonical semantic envelope with receipt metadata normalized, not from a raw transport response.
func (Observation) ReplayFingerprint ¶
func (o Observation) ReplayFingerprint() (string, error)
ReplayFingerprint returns the canonical semantic payload hash used for replay identity and immutable observation references. ReceivedAt records transport arrival metadata and Subject/Correlation are approved alternate lineage carriers, so both are normalized before hashing; equivalent source evidence must retain one identity.
func (Observation) SourceEventIdentity ¶
func (o Observation) SourceEventIdentity() string
SourceEventIdentity is an alias used by journal adapters.
func (Observation) SubjectIdentity ¶
func (o Observation) SubjectIdentity() string
func (*Observation) UnmarshalJSON ¶
func (o *Observation) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes an observation without granting legacy provider authority. Historical V1-lifted records must pass through the explicit ReadLegacyV1Observation reader after trusted durable-record selection.
func (Observation) Validate ¶
func (o Observation) Validate() error
Validate checks identity, provenance, bounds, presence and coverage. It does not mutate caller-owned values; use Canonical for a normalized copy.
type ObservationRef ¶
type ObservationRef struct {
StoreID string `json:"store_id"`
ObservationID string `json:"observation_id"`
Revision uint64 `json:"revision"`
PayloadHash string `json:"payload_hash"`
}
ObservationRef identifies an immutable observation revision by store and payload hash. A bare provider-local ID is deliberately insufficient.
func (ObservationRef) Equal ¶
func (r ObservationRef) Equal(other ObservationRef) bool
func (*ObservationRef) UnmarshalJSON ¶
func (r *ObservationRef) UnmarshalJSON(data []byte) error
func (ObservationRef) Validate ¶
func (r ObservationRef) Validate() error
type ObservationSink ¶
type ObservationSink interface {
Append(ctx context.Context, observation Observation) error
}
ObservationSink is the compatibility single-observation durable-capture seam. Implementations own storage and transaction behavior; callers provide one complete immutable Observation and never pass provider-shaped or raw-content payloads. An Append error has unknown commit status: callers must not retry it unless the sink also implements AtomicObservationSink.
type ObservationSource ¶
type ObservationSource interface {
DrainEconomicObservations() []Observation
}
ObservationSource is the optional host-only sideband drain implemented by backend streams. A source returns canonical observations, never client events; callers own replay/conflict handling at the B-leg terminal boundary.
type Page ¶
type Page struct {
Facts []Fact `json:"facts"`
NextCursor string `json:"next_cursor,omitempty"`
Unsupported []UnsupportedFilter `json:"unsupported,omitempty"`
}
Page is one bounded page of facts plus continuation and unsupported-filter reporting.
type PaymentParty ¶
type PaymentParty struct {
Kind PaymentPartyKind `json:"kind,omitempty"`
ID string `json:"id,omitempty"`
}
PaymentParty is a provider-neutral payer classification. ID is an optional safe owner/account identity for known parties; no payer policy is evaluated while validating or decoding this DTO.
func (PaymentParty) IsUnknown ¶
func (p PaymentParty) IsUnknown() bool
func (*PaymentParty) UnmarshalJSON ¶
func (p *PaymentParty) UnmarshalJSON(data []byte) error
func (PaymentParty) Validate ¶
func (p PaymentParty) Validate() error
Validate accepts an absent party as unknown so incomplete provider evidence can be retained. Explicit unknown/unallocated values cannot carry an ID that might be mistaken for an attributable owner.
type PaymentPartyKind ¶
type PaymentPartyKind string
PaymentPartyKind identifies who is economically responsible for a reported charge. Empty is the absent/unknown state and is never interpreted as the operator by a consumer.
const ( PaymentPartyUnknown PaymentPartyKind = "unknown" PaymentPartyOperator PaymentPartyKind = "operator" PaymentPartyCustomer PaymentPartyKind = "customer" PaymentPartyUnallocated PaymentPartyKind = "unallocated" )
func (PaymentPartyKind) IsKnown ¶
func (k PaymentPartyKind) IsKnown() bool
type Presence ¶
type Presence string
Presence distinguishes authoritative zero/non-zero from absence/unknown.
type ProviderDebit ¶
type ProviderDebit struct {
Version uint32 `json:"version"`
ID string `json:"id"`
SourceEventKey string `json:"source_event_key"`
Revision uint64 `json:"revision"`
StreamID string `json:"stream_id"`
Sequence uint64 `json:"sequence"`
StoreID string `json:"store_id"`
TenantID string `json:"tenant_id,omitempty"`
ProviderAccountKey string `json:"provider_account_key"`
PoolID string `json:"pool_id"`
WindowID string `json:"window_id"`
ResetAt time.Time `json:"reset_at"`
RequestID string `json:"request_id"`
BillingCallID string `json:"billing_call_id"`
BLegID string `json:"b_leg_id"`
ALegID string `json:"a_leg_id,omitempty"`
CallID string `json:"call_id,omitempty"`
AttemptID string `json:"attempt_id,omitempty"`
AttemptSeq uint64 `json:"attempt_seq,omitempty"`
ProviderRequestID string `json:"provider_request_id,omitempty"`
Component ComponentKey `json:"component"`
Quantity *Decimal `json:"quantity"`
Quality string `json:"quality"`
MethodRef string `json:"method_ref,omitempty"`
MappingRef string `json:"mapping_ref,omitempty"`
Acquisition string `json:"acquisition"`
Authority string `json:"authority"`
Semantics string `json:"semantics"`
ObservedAt time.Time `json:"observed_at"`
ReceivedAt time.Time `json:"received_at"`
Supersedes []ProviderDebitRef `json:"supersedes,omitempty"`
Evidence []SafeEvidenceField `json:"evidence,omitempty"`
}
ProviderDebit is authoritative provider-reported, nonmonetary request economics. Quantity is a provider unit (normally a credit/allowance unit), never a currency amount. A debit is bound to exactly one request, billing call and B-leg, while retaining the provider account/pool/window context in which the provider reported it.
Account-window snapshots use SubjectAccountWindow and are intentionally not representable by this type. In particular, no field permits a caller to subtract two percentage/remaining gauges and manufacture a debit.
func ProviderDebitFromObservation ¶
func ProviderDebitFromObservation(observation Observation) (ProviderDebit, error)
ProviderDebitFromObservation accepts only the dedicated debit subject. An account-window observation, even one with a credit-looking measure, cannot be converted by differencing or request association.
func (ProviderDebit) Canonical ¶
func (d ProviderDebit) Canonical() (ProviderDebit, error)
Canonical returns a validated copy with exact quantity/component and semantically unordered supersession/evidence sets normalized.
func (ProviderDebit) CanonicalJSON ¶
func (d ProviderDebit) CanonicalJSON() ([]byte, error)
CanonicalJSON is the deterministic wire form for typed debit evidence.
func (ProviderDebit) Clone ¶
func (d ProviderDebit) Clone() ProviderDebit
Clone returns a deep copy suitable for durable handoff.
func (ProviderDebit) Fingerprint ¶
func (d ProviderDebit) Fingerprint() string
Fingerprint returns the hash of the canonical typed debit, including receipt metadata. Durable supersession references use ReplayFingerprint instead.
func (ProviderDebit) IdentityKey ¶
func (d ProviderDebit) IdentityKey() string
IdentityKey returns the source-event identity without the quantity payload. A changed payload under the same key is therefore a conflict, never a new debit.
func (ProviderDebit) MarshalJSON ¶
func (d ProviderDebit) MarshalJSON() ([]byte, error)
func (ProviderDebit) Observation ¶
func (d ProviderDebit) Observation() (Observation, error)
Observation is a convenience alias for ToObservation at adapter seams.
func (ProviderDebit) Ref ¶
func (d ProviderDebit) Ref() (ProviderDebitRef, error)
Ref returns the canonical immutable observation reference used by a later correction/replacement.
func (ProviderDebit) ReplayFingerprint ¶
func (d ProviderDebit) ReplayFingerprint() string
ReplayFingerprint excludes receipt arrival time while retaining source revision, subject/account-window binding and the complete quantity payload.
func (ProviderDebit) ToObservation ¶
func (d ProviderDebit) ToObservation() (Observation, error)
ToObservation projects the typed debit onto the canonical V2 journal. The projection has one measure and no ReportedCharge, so it cannot become provider money without an explicit later valuation/conversion operation.
func (ProviderDebit) Validate ¶
func (d ProviderDebit) Validate() error
Validate accepts only an authoritative, complete provider request debit. Missing, estimated, gauge or monetary evidence is rejected at this typed boundary instead of being made payable by a later reducer.
type ProviderDebitRef ¶
type ProviderDebitRef = ObservationRef
ProviderDebitRef is an immutable reference to a provider-debit observation revision. The alias keeps supersession identity identical to the canonical observation journal and prevents provider-local IDs from becoming authority on their own.
type Quantity ¶
type Quantity struct {
Component string `json:"component"`
Unit string `json:"unit"`
Value int64 `json:"value"`
Present bool `json:"present"`
Schema string `json:"schema,omitempty"`
}
Quantity is an extensible billable or countable component observation. Unknown components are allowed only when Schema is set (requirement 3.9).
type Query ¶
type Query struct {
Class QueryClass `json:"class,omitempty"`
Scope ScopeFilters `json:"scope,omitzero"`
TimeRange TimeRange `json:"time_range,omitzero"`
Perspective EconomicPerspective `json:"perspective,omitempty"`
Boundary Boundary `json:"boundary,omitempty"`
Lifecycle LifecycleScope `json:"lifecycle,omitempty"`
StreamID string `json:"stream_id,omitempty"`
RequestID string `json:"request_id,omitempty"`
TraceID string `json:"trace_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
ALegID string `json:"a_leg_id,omitempty"`
BLegID string `json:"b_leg_id,omitempty"`
AttemptID string `json:"attempt_id,omitempty"`
FrontendID string `json:"frontend_id,omitempty"`
BackendID string `json:"backend_id,omitempty"`
Model string `json:"model,omitempty"`
RouteID string `json:"route_id,omitempty"`
RuleID string `json:"rule_id,omitempty"`
Source Source `json:"source,omitempty"`
Authority Authority `json:"authority,omitempty"`
IdentityVersion int `json:"identity_version,omitempty"`
Limit int `json:"limit,omitempty"`
Cursor string `json:"cursor,omitempty"`
}
Query is a bounded filter for listing metering facts. Unsupported or too-broad filters return stable outcomes rather than scanning (14.4, 14.8).
type QueryClass ¶
type QueryClass string
QueryClass distinguishes historical metering from live authority views (requirement 14.5). The metering journal supports historical_metering only; other classes are unsupported on this querier.
const ( QueryClassHistoricalMetering QueryClass = "historical_metering" QueryClassLiveReservation QueryClass = "live_reservation" QueryClassActiveLease QueryClass = "active_lease" QueryClassRemainingAuthority QueryClass = "remaining_authority" QueryClassFinancialProjection QueryClass = "financial_projection" )
func (QueryClass) IsKnown ¶
func (c QueryClass) IsKnown() bool
IsKnown reports whether c is a documented query class.
type Recorder ¶
Recorder appends metering facts to a durable journal. Implementations must treat SameFactReplay replays as idempotent no-ops and must not mutate prior fact bodies in place; corrections use dedicated FactKind values. SameFactIdentity alone is stream membership; differing Kind or payload for the same FactID/stream/sequence is an identity collision.
type RelationshipKind ¶
type RelationshipKind string
RelationshipKind declares how a schema relates two component keys. The relationship is explicit; component names alone never imply inclusion.
RelationshipAggregate and RelationshipPartition are SYNONYMS: both declare that the declared children form a COMPLETE, additive coverage of the parent (the parent quantity equals the sum of the declared child quantities), and both are therefore treated identically by every consumer. RelationshipSubset declares only PARTIAL containment (child <= parent, no conservation claim). RelationshipTransform is a separately governed unit derivation and is never containment.
const ( RelationshipAggregate RelationshipKind = "aggregate" RelationshipSubset RelationshipKind = "subset" RelationshipPartition RelationshipKind = "partition" RelationshipTransform RelationshipKind = "transform" )
func (RelationshipKind) IsKnown ¶
func (k RelationshipKind) IsKnown() bool
func (RelationshipKind) String ¶
func (k RelationshipKind) String() string
func (RelationshipKind) Validate ¶
func (k RelationshipKind) Validate() error
type ReportedCharge ¶
type ReportedCharge struct {
ChargeItemID string `json:"charge_item_id"`
Component *ComponentKey `json:"component,omitempty"`
Amount *Decimal `json:"amount,omitempty"`
Currency string `json:"currency,omitempty"`
Kind ChargeKind `json:"kind"`
Payer PaymentParty `json:"payer,omitzero"`
Covers []ChargeCoverageRef `json:"covers,omitempty"`
}
ReportedCharge is provider/statement money or a charge claim. Component may be nil for a genuine aggregate; no lower-level allocation is invented.
func (ReportedCharge) Clone ¶
func (c ReportedCharge) Clone() ReportedCharge
func (*ReportedCharge) UnmarshalJSON ¶
func (c *ReportedCharge) UnmarshalJSON(data []byte) error
func (ReportedCharge) Validate ¶
func (c ReportedCharge) Validate(allowNegative bool) error
type SafeEvidenceField ¶
type SafeEvidenceField struct {
Path string `json:"path,omitempty"`
Name string `json:"name,omitempty"`
Lexeme string `json:"lexeme,omitempty"`
Value string `json:"value,omitempty"`
Present bool `json:"present"`
Null bool `json:"null,omitempty"`
Acquisition string `json:"acquisition"`
// Sanitizer is the optional identity/version marker stamped by the
// normalizer that produced sanitized evidence (name/version). It
// participates in the deterministic content hash when present.
Sanitizer string `json:"sanitizer,omitempty"`
}
SafeEvidenceField retains one bounded allowlisted lexeme/path without raw provider bodies. Lexeme is the preferred exact value; Value is a backwards- compatible alias for adapters that use that name.
func (*SafeEvidenceField) UnmarshalJSON ¶
func (e *SafeEvidenceField) UnmarshalJSON(data []byte) error
UnmarshalJSON rejects malformed transport bytes before encoding/json can replace them with U+FFFD and make a distinct evidence lexeme appear valid.
func (SafeEvidenceField) Validate ¶
func (e SafeEvidenceField) Validate() error
type SchemaTopologyFinding ¶
type SchemaTopologyFinding struct {
// Rule is the structural impossibility that was found.
Rule SchemaTopologyRule
// SchemaID names the schema that declared the offending edges. A finding
// is always attributable to one declared schema, even when the two
// interacting edges are declared in different schemas.
SchemaID string
// Parent is the canonical key of the common parent of the interacting
// complete siblings. It is empty for SchemaTopologyDirectionMismatch,
// which is an edge-local property and names no second edge.
Parent string
// Left is the canonical key of the first interacting complete child, or
// the edge's child for SchemaTopologyDirectionMismatch.
Left string
// Right is the canonical key of the second interacting complete child, or
// the edge's parent for SchemaTopologyDirectionMismatch.
Right string
// It is only set for SchemaTopologyCompleteSiblingSharedDescendant.
Shared string
// Detail is a human-readable rendering of the finding.
Detail string
}
SchemaTopologyFinding is one reported structural incompatibility. Every field is a canonical component key or a schema id, never a caller-owned pointer, so a finding is safe to log, persist or compare after the inspected slice is released.
func (SchemaTopologyFinding) String ¶
func (f SchemaTopologyFinding) String() string
type SchemaTopologyReport ¶
type SchemaTopologyReport struct {
// Findings is every structural incompatibility found, ordered by
// AllSchemaTopologyRules order and then by parent/left/right/shared so the
// report is deterministic for a given input.
Findings []SchemaTopologyFinding
}
SchemaTopologyReport is the complete, non-fatal result of inspecting a schema set for structurally-knowable impossibilities. A report is always returned in full: enforcement is a separate, explicit decision so that a caller can surface every finding at once instead of learning about them one rejected schema at a time.
func InspectComponentSchemaTopology ¶
func InspectComponentSchemaTopology(schemas []ComponentSchema) SchemaTopologyReport
InspectComponentSchemaTopology reports every structurally-knowable impossibility in a bounded schema set without enforcing any of them. The result is the non-fatal form of the same analysis ValidateComponentSchemas performs, so a caller can certify, warn or reject.
The analysis is decidable from the declared edges alone: it never consults an observation, a tariff or a price, and it is therefore stable for a given set of declarations regardless of what is later rated against it. A report is deterministic and its order does not depend on declaration order.
Shared complete ownership, where one node is a complete member of more than one parent, is deliberately NOT reported here. It is a per-observation classification rather than a static impossibility, and it stays with the rater.
func (SchemaTopologyReport) Err ¶
func (r SchemaTopologyReport) Err() error
Err returns a single error describing the whole report, or nil when the report is empty. The returned error wraps ErrComponentSchemaTopology and ErrInvalidComponentSchema, so it is catchable either as its own class or as the general malformed-schema class.
func (SchemaTopologyReport) ErrFor ¶
func (r SchemaTopologyReport) ErrFor(enforced SchemaTopologyRuleSet) error
ErrFor returns a single error describing the findings whose rule is a member of enforced, or nil when no such finding exists. Rules outside enforced are still reported by Len and Has, so a caller can widen enforcement without re-inspecting.
func (SchemaTopologyReport) For ¶
func (r SchemaTopologyReport) For(rule SchemaTopologyRule) []SchemaTopologyFinding
For returns only the findings carrying rule.
func (SchemaTopologyReport) Has ¶
func (r SchemaTopologyReport) Has(rule SchemaTopologyRule) bool
Has reports whether any finding carries rule.
func (SchemaTopologyReport) Len ¶
func (r SchemaTopologyReport) Len() int
Len returns the number of findings.
func (SchemaTopologyReport) Rules ¶
func (r SchemaTopologyReport) Rules() []SchemaTopologyRule
Rules returns the distinct rules present in the report, in AllSchemaTopologyRules order.
type SchemaTopologyRule ¶
type SchemaTopologyRule string
SchemaTopologyRule names one evidence-independent, structurally-knowable impossibility in a declared containment graph. Every rule is decidable from the declared edges alone: no observation, tariff or price is consulted, so a rule finding is a property of the published schema, not of a rated call.
const ( // SchemaTopologyDirectionMismatch rejects a containment edge whose parent // and child carry different economic directions. Aggregate, partition and // subset all assert that one quantity is contained in another, which is // only a meaningful claim within a single flow; an edge that crosses from // input to output (or to/from none) can never be discharged. Unit equality // is already required for every non-transform edge, so direction is the // remaining identity gap on the same seam. // // This rule is reported, not enforced by default: a cross-direction edge is // a legal, if inert, way to declare a provider vocabulary entry on the far // side of a flow, and the historical behaviour is to ignore such an edge // rather than refuse the whole schema. See EnforcedComponentSchemaTopologyRules. SchemaTopologyDirectionMismatch SchemaTopologyRule = "direction-mismatch" // SchemaTopologyCompleteSiblingContains rejects two complete // (aggregate/partition) siblings of the same parent where one transitively // contains the other. A complete coverage asserts the disjoint additive sum // parent = sum(children); a complete child that also contains its complete // sibling double-declares that sibling inside the same sum, so the declared // disjointness cannot be satisfied by any quantities. // // This rule is reported, not enforced by default: it rejects 80 of the 343 // generated three-node topologies, and the order-invariance regression // enumerates all 343 unconditionally. See EnforcedComponentSchemaTopologyRules. SchemaTopologyCompleteSiblingContains SchemaTopologyRule = "complete-sibling-contains-sibling" // (aggregate/partition) siblings of the same parent whose declared // containment descendant sets intersect: a node is reachable under both // branches. Each branch's additive sum therefore claims a share of the same // descendant, and a single declared quantity cannot satisfy both disjoint // sums. // // Reachability follows containment edges only (aggregate, partition and // subset). A transform is a separately governed unit derivation and is // never containment, so a transform-reachable node does not intersect. SchemaTopologyCompleteSiblingSharedDescendant SchemaTopologyRule = "complete-sibling-shared-descendant" )
func AllSchemaTopologyRules ¶
func AllSchemaTopologyRules() []SchemaTopologyRule
AllSchemaTopologyRules returns every rule this package can report, in a stable order. It exists so a caller can enumerate the rule space without depending on the order of declaration.
func (SchemaTopologyRule) IsKnown ¶
func (r SchemaTopologyRule) IsKnown() bool
IsKnown reports whether r is a rule this package can report.
type SchemaTopologyRuleSet ¶
type SchemaTopologyRuleSet struct {
// contains filtered or unexported fields
}
SchemaTopologyRuleSet is an immutable set of topology rules. The zero value is the empty set, which reports nothing and enforces nothing.
func EnforcedComponentSchemaTopologyRules ¶
func EnforcedComponentSchemaTopologyRules() SchemaTopologyRuleSet
EnforcedComponentSchemaTopologyRules returns the rules ValidateComponentSchemas currently rejects. It is a function rather than a variable so a caller cannot mutate package state, and it is the single place that decides publication-time enforcement.
func (SchemaTopologyRuleSet) Contains ¶
func (s SchemaTopologyRuleSet) Contains(r SchemaTopologyRule) bool
Contains reports whether r is a member of the set. An unknown rule is never a member.
func (SchemaTopologyRuleSet) Rules ¶
func (s SchemaTopologyRuleSet) Rules() []SchemaTopologyRule
Rules returns a copy of the set's members in AllSchemaTopologyRules order.
func (SchemaTopologyRuleSet) With ¶
func (s SchemaTopologyRuleSet) With(r SchemaTopologyRule) SchemaTopologyRuleSet
With returns a set containing r in addition to the receiver's rules. The receiver is not modified.
type ScopeFilters ¶
type ScopeFilters struct {
PrincipalID scope.Value `json:"principal_id,omitzero"`
CredentialID scope.Value `json:"credential_id,omitzero"`
TenantID scope.Value `json:"tenant_id,omitzero"`
OrganizationID scope.Value `json:"organization_id,omitzero"`
WorkspaceID scope.Value `json:"workspace_id,omitzero"`
ProjectID scope.Value `json:"project_id,omitzero"`
DepartmentID scope.Value `json:"department_id,omitzero"`
CostCenterID scope.Value `json:"cost_center_id,omitzero"`
}
ScopeFilters carries safe, presence-aware principal/scope filter dimensions.
type Source ¶
type Source string
Source identifies how a fact or quantity was obtained.
type SourceEventRef ¶
type SourceEventRef struct {
IdentityVersion int
LifecycleID string
Boundary Boundary
EventKind string
SourceID string
SourceRevision int64
}
SourceEventRef is the deterministic identity of one economic source event (design Deterministic Identity / D6): identity version, lifecycle ID, boundary, event kind, source ID, and revision. Sequence and FactID are stream membership fields, not part of this ref.
func (SourceEventRef) CanonicalKey ¶
func (r SourceEventRef) CanonicalKey() string
CanonicalKey returns a length-prefixed, delimiter-safe encoding of the ref. Field values may contain NUL or ':' without shifting later fields.
func (SourceEventRef) EffectiveIdentityVersion ¶
func (r SourceEventRef) EffectiveIdentityVersion() int
EffectiveIdentityVersion returns IdentityVersionV1 when IdentityVersion is 0 (historical producers) and otherwise the declared version.
type SubjectKind ¶
type SubjectKind string
SubjectKind is the tagged economic subject union. It prevents an account-window gauge or resource interval from being mistaken for a B-leg request meter.
func (SubjectKind) IsKnown ¶
func (k SubjectKind) IsKnown() bool
type SubjectRef ¶
type SubjectRef struct {
Kind SubjectKind `json:"kind"`
StoreID string `json:"store_id"`
TenantID string `json:"tenant_id,omitempty"`
AccountID string `json:"account_id,omitempty"`
ALegID string `json:"a_leg_id,omitempty"`
RequestID string `json:"request_id,omitempty"`
BillingCallID string `json:"billing_call_id,omitempty"`
CallID string `json:"call_id,omitempty"`
BLegID string `json:"b_leg_id,omitempty"`
AttemptID string `json:"attempt_id,omitempty"`
AttemptSeq uint64 `json:"attempt_seq,omitempty"`
SubmissionID string `json:"submission_id,omitempty"`
ProviderAccountKey string `json:"provider_account_key,omitempty"`
ProviderRequestID string `json:"provider_request_id,omitempty"`
ProviderChargeID string `json:"provider_charge_id,omitempty"`
ResourceID string `json:"resource_id,omitempty"`
PeriodID string `json:"period_id,omitempty"`
PoolID string `json:"pool_id,omitempty"`
WindowID string `json:"window_id,omitempty"`
StatementID string `json:"statement_id,omitempty"`
StatementLineID string `json:"statement_line_id,omitempty"`
ResetAt time.Time `json:"reset_at,omitzero"`
StartAt time.Time `json:"start_at,omitzero"`
EndAt time.Time `json:"end_at,omitzero"`
}
SubjectRef is a tagged union with trusted store scope and optional ancestry. Fields from a foreign subject kind are rejected by Validate.
func (SubjectRef) Clone ¶
func (s SubjectRef) Clone() SubjectRef
Clone returns a value copy. SubjectRef contains no mutable fields.
func (*SubjectRef) UnmarshalJSON ¶
func (s *SubjectRef) UnmarshalJSON(data []byte) error
func (SubjectRef) Validate ¶
func (s SubjectRef) Validate() error
Validate enforces the subject union and safe identity bounds.
type SurfacedState ¶
type SurfacedState string
SurfacedState records whether attempt output reached the client.
const ( SurfacedYes SurfacedState = "yes" SurfacedNo SurfacedState = "no" SurfacedUnknown SurfacedState = "unknown" )
func (SurfacedState) IsKnown ¶
func (s SurfacedState) IsKnown() bool
IsKnown reports whether s is a documented surfaced state.
func (SurfacedState) Validate ¶
func (s SurfacedState) Validate() error
Validate returns an error when s is not a known surfaced state.
type TimeRange ¶
TimeRange bounds a query by fact recorded time. Either bound may be omitted; time alone is not a selective bound (requirement 14.4, 14.8).
type UnsupportedFilter ¶
type UnsupportedFilter struct {
Field string `json:"field"`
Reason string `json:"reason,omitempty"`
}
UnsupportedFilter names a requested filter that recorded facts cannot apply.
func QueryUnsupported ¶
func QueryUnsupported(q Query) []UnsupportedFilter
QueryUnsupported returns filters requested on the metering journal that are not indexed or not applicable to historical facts.
type VersionRef ¶
type VersionRef struct {
ID string `json:"id,omitempty"`
Version string `json:"version,omitempty"`
EffectiveAt int64 `json:"effective_at_unix_ms,omitempty"` // unix ms; 0 = unset
FetchedAt int64 `json:"fetched_at_unix_ms,omitempty"` // unix ms; 0 = unset
}
VersionRef is an immutable identity for a bound policy, pricebook, or rule snapshot carried on metering facts. Richer snapshot envelopes live in pkg/lipsdk/economics.