checkpoint

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

Documentation

Index

Constants

View Source
const IngressSequence int64 = 1

IngressSequence is the deterministic stream sequence for the single ingress fact on a customer-request or operator-attempt stream (task 3.3 / D6).

Variables

View Source
var ErrUnmeasuredWidening = fmt.Errorf("metering/checkpoint: unmeasured post-authorization widening")

ErrUnmeasuredWidening is returned when a call changes billable content after the authorized backend-ingress freeze (requirement 7.5).

Functions

func AssertNotWidened

func AssertNotWidened(authorized, current lipapi.Call) error

AssertNotWidened returns ErrUnmeasuredWidening when current differs from authorized.

func AssertWireNotWidened

func AssertWireNotWidened(authorized, current WireAttemptEvidence) error

AssertWireNotWidened returns ErrUnmeasuredWidening when current wire attempt evidence differs from authorized or has widened max output tokens (Requirements 10, 15.3, 19).

func BackendEgressCheckpoint

func BackendEgressCheckpoint(ingress Snapshot, outcome metering.AttemptOutcome, surfaced metering.SurfacedState) metering.Checkpoint

BackendEgressCheckpoint templates a public checkpoint for one B-leg egress fact.

func BackendIngressIdentity

func BackendIngressIdentity(attemptID string) (factID, sourceID string, seq int64)

BackendIngressIdentity returns restart-stable FactID, SourceID, and Sequence for one operator-attempt BE ingress (independent of retry count).

func BillableFingerprint

func BillableFingerprint(c lipapi.Call) ([]byte, error)

BillableFingerprint is a stable encoding of billable call content used to detect unmeasured widening after an authorized backend-ingress freeze. It avoids json.Marshal of json.RawMessage fields (tool Parameters) so invalid or non-JSON parameter bytes do not fail Open.

func BillableWidened

func BillableWidened(authorized, current lipapi.Call) (bool, error)

BillableWidened reports whether current has billable content beyond authorized. Lowering MaxOutputTokens (authority/preflight clamp) is narrowing, not widening. Raising MaxOutputTokens or removing an authorized bound is widening; introducing a bound when the freeze had none is narrowing, not widening.

func BillableWireWidened

func BillableWireWidened(authorized, current WireAttemptEvidence) (bool, error)

BillableWireWidened reports whether current wire attempt evidence has widened beyond authorized.

func ComputeAttemptDigest

func ComputeAttemptDigest(sourceDigest, rewriteDigest [32]byte, model string) [32]byte

ComputeAttemptDigest derives a deterministic attempt digest from the source digest, rewrite digest, and effective model name (Requirements 10, 15.3, 19).

func ComputeRewriteDigest

func ComputeRewriteDigest(offset, length int64, replacementToken string) [32]byte

ComputeRewriteDigest derives a deterministic rewrite digest for a model replacement token and span, or returns a zero digest if there is no rewrite (Requirements 9, 15.3).

func FactFromEgress

func FactFromEgress(in EgressFactInput) (metering.Fact, error)

FactFromEgress drafts a Fact from an egress observation (requirements 2.3, 2.4).

func FactFromFrontendIngress

func FactFromFrontendIngress(in IngressFactInput) (metering.Fact, error)

FactFromFrontendIngress drafts a Fact from a frontend-ingress checkpoint (reqs 5.1, 5.5).

func FactFromIngress

func FactFromIngress(in IngressFactInput) (metering.Fact, error)

FactFromIngress drafts a Fact from a backend-ingress freeze (requirements 2.2, 5.2).

func FrontendEgressCheckpoint

func FrontendEgressCheckpoint(feIngress Snapshot) metering.Checkpoint

FrontendEgressCheckpoint templates a public checkpoint for logical-request egress.

func FrontendIngressIdentity

func FrontendIngressIdentity(requestID string) (factID, sourceID string, seq int64)

FrontendIngressIdentity returns restart-stable FactID, SourceID, and Sequence for one logical-request FE ingress (independent of retry count).

func MaxOutputTokensWidened

func MaxOutputTokensWidened(authMO, curMO *int) bool

MaxOutputTokensWidened reports whether curMO widens authMO. A nil pointer represents an unbounded (infinite) max output token limit. Lowering MaxOutputTokens is narrowing, not widening. Raising MaxOutputTokens or removing an authorized bound (making it nil/unbounded) is widening. Introducing a bound when authorized had none (nil -> non-nil) is narrowing, not widening.

func MergeQuantities

func MergeQuantities(base, additions []metering.Quantity) []metering.Quantity

MergeQuantities merges additions into base by component while preserving checkpoint identity elsewhere. An existing Present output_token bound is never replaced by an addition (conservative exposure / req 7.2–7.3). Other Present additions fill missing components or refresh non-output values (deferred input counting).

func QuantitiesFromCall

func QuantitiesFromCall(call lipapi.Call) []metering.Quantity

QuantitiesFromCall derives legal ingress quantities from a frozen Call WITHOUT tokenization. Always emits request/count=1. When Options.MaxOutputTokens is set, emits output_token with that value Present:true. Does not invent input_token. Does not emit output_token=0 when max is omitted (req 7.2). Deferred counting merges input_token later via MergeQuantities.

func QuantitiesFromCountAndMaxOutput

func QuantitiesFromCountAndMaxOutput(maxOutputTokens *int) []metering.Quantity

QuantitiesFromCountAndMaxOutput derives legal ingress quantities without a Call. Always emits request/count=1. When maxOutputTokens is non-nil, emits output_token with that value Present:true. Does not invent input_token (req 7.2).

func QuantitiesFromCountAndMaxOutput64

func QuantitiesFromCountAndMaxOutput64(maxOutputTokens *int64) []metering.Quantity

QuantitiesFromCountAndMaxOutput64 derives legal ingress quantities without a Call using an int64 max output token bound.

func QuantitiesFromTokenCounts

func QuantitiesFromTokenCounts(input, output, cacheRead, cacheWrite, reasoning, total int64, totalPresent bool) []metering.Quantity

QuantitiesFromTokenCounts maps token components to metering quantities using the default inclusion schema vocabulary. Zero counts remain Present when present is true; omitted totals leave PresenceUnknown on the checkpoint.

func QuantityComponentValue

func QuantityComponentValue(qs []metering.Quantity, component string) (int64, bool)

QuantityComponentValue returns the Present value for component, if any.

func SanitizeCall

func SanitizeCall(c lipapi.Call) lipapi.Call

SanitizeCall clears resume secrets and other bearer material from a Call clone so memory-held metering snapshots never retain raw resume tokens (req 2.7).

Types

type BackendIngressInput

type BackendIngressInput struct {
	Call         lipapi.Call
	Scope        scope.PrincipalScopeView
	AttemptID    string
	BLegID       string
	ALegID       string
	BackendID    string
	Model        string
	CheckpointID string
	StreamID     string
	TraceID      string // runtime trace; defaults to Call.ID when empty (never FE stream id)
	Perspective  metering.EconomicPerspective
	Now          time.Time
}

BackendIngressInput captures a backend-attempt freeze immediately before Open.

type EgressFactInput

type EgressFactInput struct {
	Checkpoint      metering.Checkpoint // boundary/lifecycle/correlation template
	FactID          string
	Sequence        int64
	Kind            metering.FactKind
	Quantities      []metering.Quantity
	Outcome         metering.AttemptOutcome
	Surfaced        metering.SurfacedState
	Presence        metering.Presence
	Source          metering.Source
	Authority       metering.Authority
	Now             time.Time
	Money           *metering.MoneyObservation
	SourceID        string
	IdentityVersion int
	SourceEventKind string
	SourceRevision  int64
}

EgressFactInput builds a metering fact for backend or frontend egress.

type FrontendIngressInput

type FrontendIngressInput struct {
	Call         lipapi.Call
	Scope        scope.PrincipalScopeView
	FrontendID   string
	CheckpointID string
	StreamID     string
	TraceID      string // runtime trace; defaults to Call.ID when empty
	Perspective  metering.EconomicPerspective
	Now          time.Time
}

FrontendIngressInput captures a logical-request frontend-ingress checkpoint.

type IngressFactInput

type IngressFactInput struct {
	Checkpoint      metering.Checkpoint
	FactID          string
	Sequence        int64
	Kind            metering.FactKind
	Quantities      []metering.Quantity
	Presence        metering.Presence
	Source          metering.Source
	Authority       metering.Authority
	Now             time.Time
	SourceID        string
	IdentityVersion int
	SourceEventKind string
	SourceRevision  int64
}

IngressFactInput builds a metering fact for a frozen backend-ingress checkpoint.

type RequestHolder

type RequestHolder struct {
	FrontendIngress *Snapshot
	BackendIngress  map[string]*Snapshot // keyed by AttemptID
	// contains filtered or unexported fields
}

RequestHolder retains the single frontend-ingress snapshot for one logical request and per-attempt backend-ingress freezes. Methods are safe for concurrent use by parallel racing attempts that store distinct AttemptID keys.

func (*RequestHolder) BackendIngressFactID

func (h *RequestHolder) BackendIngressFactID(attemptID string) string

BackendIngressFactID returns the bound journal FactID for an attempt, if any.

func (*RequestHolder) BackendIngressFor

func (h *RequestHolder) BackendIngressFor(attemptID string) *Snapshot

BackendIngressFor returns the frozen snapshot for an attempt, if any.

func (*RequestHolder) BindBackendIngressFactID

func (h *RequestHolder) BindBackendIngressFactID(attemptID, factID string)

BindBackendIngressFactID records the journal FactID for a frozen attempt.

func (*RequestHolder) BindFrontendIngressFactID

func (h *RequestHolder) BindFrontendIngressFactID(factID string)

BindFrontendIngressFactID records the journal FactID for the FE ingress fact.

func (*RequestHolder) CaptureOrReuseFrontendIngress

func (h *RequestHolder) CaptureOrReuseFrontendIngress(in FrontendIngressInput) (Snapshot, error)

CaptureOrReuseFrontendIngress returns the existing FE ingress snapshot when set, otherwise captures and stores a new one (requirement 2.8).

func (*RequestHolder) CaptureOrReuseWireFrontendIngress

func (h *RequestHolder) CaptureOrReuseWireFrontendIngress(in WireFrontendIngressInput) (Snapshot, error)

CaptureOrReuseWireFrontendIngress returns the existing FE ingress snapshot when set, otherwise captures and stores a new wire-native one without retaining a Call (Requirements 15.1–15.3, 16, 19).

func (*RequestHolder) FrontendIngressFactID

func (h *RequestHolder) FrontendIngressFactID() string

FrontendIngressFactID returns the bound FE ingress journal FactID, if any.

func (*RequestHolder) MergeBackendIngressQuantities

func (h *RequestHolder) MergeBackendIngressQuantities(attemptID string, additions []metering.Quantity) bool

MergeBackendIngressQuantities merges deferred counts into a stored BE snapshot.

func (*RequestHolder) MergeFrontendIngressQuantities

func (h *RequestHolder) MergeFrontendIngressQuantities(additions []metering.Quantity)

MergeFrontendIngressQuantities merges deferred counts into the FE snapshot without changing CheckpointID or the frozen Call (design deferred counting).

func (*RequestHolder) NextSequence

func (h *RequestHolder) NextSequence() int64

NextSequence returns a monotonically increasing fact sequence for this request.

func (*RequestHolder) ReserveSequenceFloor

func (h *RequestHolder) ReserveSequenceFloor(seq int64)

ReserveSequenceFloor ensures later NextSequence values stay above reserved deterministic ingress sequences on this holder.

func (*RequestHolder) StoreBackendIngress

func (h *RequestHolder) StoreBackendIngress(in BackendIngressInput) (Snapshot, error)

StoreBackendIngress captures and retains a backend-ingress snapshot for an attempt.

func (*RequestHolder) StoreWireBackendIngress

func (h *RequestHolder) StoreWireBackendIngress(in WireBackendIngressInput) (Snapshot, error)

StoreWireBackendIngress captures and retains a wire-native backend-ingress snapshot for an attempt (Requirements 10, 15.1–15.3, 19).

type Snapshot

type Snapshot struct {
	Public   metering.Checkpoint
	Call     lipapi.Call
	Evidence *WireAttemptEvidence
}

Snapshot is an in-memory metering checkpoint: public journal-safe fields plus a sanitized Call clone used for recount/rerate. The Call body is never written to the metering journal by default (requirement 2.7).

func CaptureBackendIngress

func CaptureBackendIngress(in BackendIngressInput) (Snapshot, error)

CaptureBackendIngress freezes the final provider-neutral attempt call (requirements 2.2, 5.1). Callers must AssertNotWidened before Open if the working call may still mutate.

func CaptureFrontendIngress

func CaptureFrontendIngress(in FrontendIngressInput) (Snapshot, error)

CaptureFrontendIngress clones the call before submit mutation, strips resume secrets, and builds a public Checkpoint (requirements 2.1, 2.5–2.8). It does not create usage-authority reservations.

func CaptureWireBackendIngress

func CaptureWireBackendIngress(in WireBackendIngressInput) (Snapshot, error)

CaptureWireBackendIngress builds an immutable backend-attempt checkpoint strictly from bounded wire facts, sharing exact quantity and checkpoint validation logic with canonical execution while guaranteeing that no lipapi.Call is cloned or retained (Requirements 10, 15.1–15.3, 19).

func CaptureWireFrontendIngress

func CaptureWireFrontendIngress(in WireFrontendIngressInput) (Snapshot, error)

CaptureWireFrontendIngress builds an immutable frontend-ingress checkpoint strictly from bounded wire facts, sharing exact quantity and checkpoint validation logic with canonical execution while guaranteeing that no lipapi.Call is cloned or retained (Requirements 15.1–15.3, 16.1–16.6, 19).

func (*Snapshot) ApplyQuantities

func (s *Snapshot) ApplyQuantities(qs []metering.Quantity)

ApplyQuantities sets Public.Quantities and updates Presence. It does not mutate CheckpointID, StreamID, Boundary, Lifecycle, Correlation, or Call.

func (*Snapshot) BindScope

func (s *Snapshot) BindScope(sc scope.PrincipalScopeView)

BindScope updates Public.Scope without mutating the immutable Call clone.

func (*Snapshot) DeriveAndApplyIngressQuantities

func (s *Snapshot) DeriveAndApplyIngressQuantities()

DeriveAndApplyIngressQuantities derives ingress quantities from the frozen Call and applies them to Public.

func (*Snapshot) IsWire

func (s *Snapshot) IsWire() bool

IsWire reports whether this snapshot was captured from bounded wire facts without retaining a canonical lipapi.Call (Requirements 15.1–15.3, 19).

func (*Snapshot) MergeQuantities

func (s *Snapshot) MergeQuantities(additions []metering.Quantity)

MergeQuantities merges additions into Public.Quantities without changing CheckpointID, StreamID, Boundary, Lifecycle, Correlation, or Call.

func (*Snapshot) WireAttemptEvidence

func (s *Snapshot) WireAttemptEvidence() (WireAttemptEvidence, bool)

WireAttemptEvidence returns the bounded wire attempt evidence for this snapshot, if captured via CaptureWireBackendIngress (Requirements 10, 15.3, 19).

type WireAttemptEvidence

type WireAttemptEvidence struct {
	SourceDigest    [32]byte
	RewriteDigest   [32]byte
	AttemptDigest   [32]byte
	Model           string
	MaxOutputTokens *int
}

WireAttemptEvidence captures bounded cryptographic and quantity evidence for an attempt on the wire path, used to assert integrity and detect widening without retaining or re-reading prompt trees (Requirements 10, 15.3, 19).

type WireBackendIngressInput

type WireBackendIngressInput struct {
	RequestID       string
	TraceID         string // runtime trace; defaults to RequestID when empty
	AttemptID       string
	BLegID          string // defaults to AttemptID when empty
	ALegID          string
	SessionID       string // authoritative session ID or correlation ID
	Scope           scope.PrincipalScopeView
	BackendID       string
	Model           string
	CheckpointID    string // defaults to "operator-attempt:" + AttemptID
	StreamID        string // defaults to "operator-attempt:" + AttemptID
	MaxOutputTokens *int   // optional max output token bound
	Perspective     metering.EconomicPerspective
	Now             time.Time

	// Digest evidence (Req 15.3, Design 10):
	SourceDigest  [32]byte // SHA-256 digest of captured source payload
	RewriteDigest [32]byte // digest of model rewrite token / splice (or zero if no rewrite)
	AttemptDigest [32]byte // composite attempt digest
}

WireBackendIngressInput captures an immutable backend-attempt freeze from bounded wire facts immediately before Open, without requiring or retaining a lipapi.Call (Requirements 10, 15.1–15.3, 19).

type WireFrontendIngressInput

type WireFrontendIngressInput struct {
	RequestID       string
	TraceID         string // runtime trace; defaults to RequestID when empty
	CheckpointID    string // defaults to "customer-request:" + RequestID
	StreamID        string // defaults to "customer-request:" + RequestID
	Scope           scope.PrincipalScopeView
	FrontendID      string
	ALegID          string
	SessionID       string // authoritative session ID or correlation ID
	MaxOutputTokens *int   // optional max output token bound
	Perspective     metering.EconomicPerspective
	Now             time.Time
}

WireFrontendIngressInput captures a logical-request frontend-ingress checkpoint from bounded facts on the wire path without requiring or retaining a lipapi.Call (Requirements 15.1–15.3, 16.1–16.6, 19).

Jump to

Keyboard shortcuts

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