boundsort

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2026 License: MIT Imports: 15 Imported by: 0

README

Boundsort

Boundsort is a Go framework for budget-governed ordering: you can run an ordering algorithm under a deterministic, explicit Budget, stop early when the budget is exhausted, and still return a safe partial result plus an auditable Receipt.

It's designed for systems where "sorting" isn't free:

  • comparisons can be expensive (risk engines, compliance checks, remote calls, cache misses)
  • strict SLAs require graceful degradation instead of timeouts
  • operators/auditors need to know what work was done and why it stopped

Key guarantees

  • Guarantee A (framework-level): Safe partial result
    Every engine returns a permutation of the input (no loss/duplication), even on budget exhaustion or errors.

  • Guarantee B (engine-specific): Monotonic improvement in inversion count
    For the adjacent-swap engine with a strict weak ordering comparator: each swap reduces the inversion count by at least 1, so the inversion count is non-increasing over time and strictly decreases with each swap. This provides a minimal "progress" property: more budget never makes the result worse in the sense of inversions.

  • Guarantee C (engine-specific): Sorted suffix after a completed pass
    For the adjacent-swap engine, after completing a full pass over indices 0..m-1: the maximum element (under the comparator) among indices 0..m is placed at position m (equivalently, at least one element is established in its final position). With the last-swap index optimization, all positions strictly beyond lastSwap form a fixed suffix that never changes again. Important caveat: if the budget is exhausted mid-pass, this guarantee does not apply; you only have the monotonic inversion property (Guarantee B) and whatever domain-specific evidence your receipt provides.

  • Guarantee D (engine-specific): Stability under strict swap condition
    For the adjacent-swap engine: if the comparator is based on a key and the engine swaps only when key[i] > key[i+1] (not >=), then the engine is stable with respect to equal keys, preserving the relative order of items with equal keys.


Docs

The application hypothesis is exercised on Kubernetes scheduling, Ethereum client (Go), and MEV-Boost (builder/relay).


Concepts

  • Comparator / Before function: your domain-specific ordering logic, returning both an ordering decision and a cost to charge.
  • Budget: tracks remaining spend and decides when to stop.
  • Receipt: records what happened (cost + events) and can be tamper-evident (hash chain + optional signature).

In this repo the canonical comparator shape used by engines is:

  • BeforeFunc[T]: func(a, b T) (aBeforeB bool, cost float64, err error)

And budgets implement:

  • Budget: Charge(cost float64) bool and Remaining() float64

Quick start

package main

import (
	"fmt"

	"github.com/bogwi/boundsort"
)

func main() {
	items := []int{5, 1, 4, 2, 3}

	// A simple comparator: ascending order.
	// Here we model "each comparison costs 1".
	before := func(a, b int) (bool, float64, error) {
		return a < b, 1.0, nil
	}

	b := boundsort.NewSimpleBudget(6) // allow ~6 comparisons total

	cfg := boundsort.EngineConfig{
		Kind: boundsort.EngineAdjacentSwap,
		AdjacentSwap: boundsort.AdjacentSwapConfig{
			ReceiptMode: boundsort.ReceiptModeFull,
			SwapCost:    0, // optional: charge extra cost per swap
		},
	}

	out, receipt, completed, err := boundsort.Boundsort(cfg, items, before, b)
	if err != nil {
		panic(err)
	}

	fmt.Println("completed:", completed)
	fmt.Println("out:", out)
	fmt.Println("stop:", receipt.Stop)
	fmt.Println("totalCost:", receipt.TotalCost)
	fmt.Println("tamperEvident:", receipt.Sealed && receipt.Verify())
}

Advanced boundsort example (policy + preflight + caching + signed receipts)

Full runnable program: examples/advanced_contracts/main.go

Run it:

go run ./examples/advanced_contracts

This example demonstrates:

  • Policy-driven budgets (PolicyBudgetParametersBudget)
  • Preflight to avoid known-unaffordable expensive comparisons (CompareUpperBound + WithPreflightBefore)
  • Comparator memoization (NewCachedComparator)
  • Engine selection via the uniform dispatcher (EngineAdaptive)
  • Receipt integrity + signing (Verify(), Sign(), VerifySignature())

Guarantees demo (AdjacentSwap engine)

Full runnable program: examples/guarantees_abcd/main.go

Run it:

go run ./examples/guarantees_abcd

This example demonstrates:

  • A (safe partial result): every tick returns a permutation even when budget is exhausted
  • B (monotonic progress): inversion count is non-increasing across ticks as more budget is spent
  • C (pass-level guarantees): once a full pass completes, the worst element is at the end and a suffix becomes fixed (via last-swap optimization)
  • D (stability): equal-priority items preserve FIFO order (stable adjacent swaps)
  • Receipt integrity: uses ReceiptModeFull and checks receipt.Sealed && receipt.Verify()

Engines

Boundsort provides multiple engines. You can call them directly, or use the uniform dispatcher Boundsort(cfg, ...).

Adjacent-swap (anytime baseline)
  • Function: AdjacentSwapBounded(...) (full receipts, backward-compatible)
  • Function: AdjacentSwapBoundedWithReceiptMode(...) (choose receipt detail level)
  • Strengths: strong anytime behavior; engine-specific guarantees B/C/D
  • Notes:
    • Optional swapCost can model swaps as real spend.
    • Budget exhaustion mid-pass is expected: the algorithm stops and returns the current permutation.
Bounded quicksort
  • Function: BoundedQuickSort(...)
  • Strengths: average-case (O(n \log n)) work under sufficient budget
  • Notes: preserves Guarantee A; does not provide adjacent-swap-specific guarantees
Bounded heapsort (full sort or top-k)
  • Function: BoundedHeapSort(items, k, ...)
  • Strengths: worst-case (O(n \log n)); good for top‑k use cases
  • Important output detail (top‑k):
    • if k > 0, the engine extracts the k largest elements and places them at the end of the slice (positions [n-k:n]), in sorted order under your comparator.
Adaptive selection
  • Kind: EngineAdaptive (via Boundsort dispatcher)
  • What it does: deterministically chooses an engine from input size + remaining budget + objective hints in EngineConfig.Adaptive.
  • What it does NOT do: it does not "probe" by executing unaccounted comparisons.

Receipts, tamper-evidence, and signing

Receipt modes (adjacent-swap family)
  • ReceiptModeFull: full event log + incremental hash chain; engine calls Seal() before returning
    • Tamper-evident: receipt.Verify() detects mutation of events; when sealed it also binds the terminal Stop.
  • ReceiptModeSummary: totals + stop only (no per-event log)
    • Not tamper-evident (intentional trade-off).
  • ReceiptModeNone: minimal receipt with Stop only
    • No audit trail (intentional trade-off).
Hash-chain semantics

Receipts maintain a stateful, incremental event hash chain:

  • while unsealed, Verify() checks event integrity only (the Stop field is not bound)
  • after Seal(), the final digest binds the event-chain head and Stop

Most engines in this repo call Seal() before returning; if you build receipts manually, call Seal() once the terminal fields (like Stop) are final.

Signatures

Receipt supports optional signing and verification:

  • receipt.Sign(privateKey) supports RSA / ECDSA / Ed25519
  • receipt.VerifySignature(publicKey) verifies both the receipt hash chain and the signature

For meaningful signatures, sign sealed receipts (i.e., call Seal() first, or use engines/modes that seal).


Budgeting details (edge cases)

To keep the cost model robust under adversarial or buggy comparators, engines and budgets treat costs conservatively:

  • negative cost → treated as 0
  • NaN → treated as 0
  • +Inf → treated as immediate budget exhaustion (the operation is not charged)

Preflight (skip unaffordable expensive comparisons)

Some workloads have a cheap way to compute a conservative upper bound on comparison cost (e.g., "this will require a remote call"). Boundsort provides additive wrappers that can avoid executing a known-unaffordable expensive comparison:

  • WithPreflightBefore(b, before, upperBound)
  • WithPreflightComparator(b, cmp, upperBound)

If the upper bound is known and b.Remaining() < bound, the wrapper returns cost = +Inf and err = nil. Existing engines interpret +Inf cost as immediate budget exhaustion and stop without charging.

Helpers exist to scale bounds by policy:

  • ScaleCompareUpperBound(base, multiplier)
  • PolicyCompareUpperBound(p, ctx, base)

Policy (deterministic budget selection)

Boundsort includes a simple, deterministic Policy abstraction for mapping system context → BudgetParameters, plus a reproducible input log for auditability:

  • Policy.DetermineBudget(ctx) BudgetParameters
  • Policy.LogInput(ctx) string

This is intentionally kept separate from engine APIs: you compose policy → budget at the call site.


Where Boundsort fits

Boundsort is a pattern for systems that must choose "best effort ordering under a cost cap," for example:

  • scheduling / dispatch: ordering candidate nodes/jobs under per-cycle budgets (think Kubernetes-style scheduling loops)
  • crypto / sequencing / block building: ordering transactions/bids under strict time and verification budgets (e.g., Ethereum clients, builder/relay selection)
  • financial services: ranking portfolios/orders under expensive risk/compliance comparisons with regulatory auditability

Testing and benchmarks for development

Run the test suite:

go test

There is also a benchmark harness under benchmarks/ (see benchmarks/README.md). This is used for tracking regressions when extending boundsort with new features or making general improvements an optimizations.

boundsort has a great optimization potential especially if implemented in languages like C/C++, Rust, Zig, or Odin.

go run ./benchmarks/cmd/run

Project status and scope

This repo is a research-to-production implementation of:

  • budget-governed ordering engines
  • deterministic budgeting primitives
  • receipts with verifiable, incremental integrity (and optional signatures)

Non-goals (by design):

  • claiming a single "best" ordering algorithm for all domains
  • silently spending work beyond budget
  • weakening receipt integrity without making it explicit (use ReceiptModeSummary/None only when you accept reduced auditability)

Documentation

Overview

Package boundsort provides budget-governed ordering algorithms with safe partial results and auditable receipts.

Boundsort is designed for systems where comparisons are expensive (risk engines, compliance checks, remote calls) and strict SLAs require graceful degradation instead of timeouts. It provides deterministic, explicit budgets, early stopping when the budget is exhausted, and returns safe partial results plus auditable receipts.

See the README for usage examples and guarantees.

Index

Constants

This section is empty.

Variables

View Source
var ErrUnknownEngine = errors.New("unknown engine")

ErrUnknownEngine indicates EngineConfig.Kind is not a recognized engine.

Functions

func EngineName

func EngineName(kind EngineKind) string

EngineName returns a stable, human-readable identifier for an EngineKind.

func PolicyCompareUpperBound

func PolicyCompareUpperBound[T any](p Policy, ctx SystemContext, base CompareUpperBound[T]) (params BudgetParameters, inputLog string, upper CompareUpperBound[T])

PolicyCompareUpperBound is a convenience helper that computes budget parameters via Policy, logs the input for auditability, and returns a scaled upper-bound oracle.

The returned oracle uses:

upper(a,b) = baseUpper(a,b) * params.CompareMultiplier

This helper does not modify Policy, Budget, Receipt, or comparator types; it is purely composition at the call site.

Types

type AdaptiveConfig

type AdaptiveConfig struct {
	// Objective specifies whether the caller wants a full ordering or top-k behavior.
	Objective AdaptiveObjective

	// TopK is the desired k when Objective is AdaptiveObjectiveTopK.
	// If TopK <= 0, HeapSort.K is used as a hint instead.
	TopK int

	// AssumedCompareCost is a caller-supplied estimate of the typical cost of a
	// comparison. It converts "remaining budget" into an approximate upper bound
	// on the number of comparisons affordable.
	//
	// If AssumedCompareCost <= 0, a default of 1.0 is used.
	AssumedCompareCost float64
}

AdaptiveConfig configures the adaptive engine selection policy.

The selector is deterministic and performs no hidden "probing" comparisons (i.e., no unaccounted budget spend). It selects an engine using a simple cost model based on input size, remaining budget, and objective hints.

type AdaptiveObjective

type AdaptiveObjective uint8

AdaptiveObjective describes the ordering objective for the adaptive engine.

const (
	// AdaptiveObjectiveUnspecified means "use EngineConfig fields as hints"
	// (e.g., HeapSort.K > 0 implies top-k).
	AdaptiveObjectiveUnspecified AdaptiveObjective = iota
	// AdaptiveObjectiveFullOrder aims to maximize global ordering quality.
	AdaptiveObjectiveFullOrder
	// AdaptiveObjectiveTopK aims to place the top-k elements correctly (when k is provided).
	AdaptiveObjectiveTopK
)

type AdjacentSwapConfig

type AdjacentSwapConfig struct {
	// ReceiptMode controls the receipt detail level (Full/Summary/None).
	ReceiptMode ReceiptMode
	// SwapCost is the cost to charge for each swap operation.
	SwapCost float64
}

AdjacentSwapConfig configures the adjacent-swap engine family.

type BeforeFunc

type BeforeFunc[T any] func(a, b T) (aBeforeB bool, cost float64, err error)

BeforeFunc is the comparator shape consumed by Boundsort engine implementations. It returns: - aBeforeB: whether a should come before b - cost: the cost to charge to the budget - err: comparator failure

func WithPreflightBefore

func WithPreflightBefore[T any](b Budget, before BeforeFunc[T], upper CompareUpperBound[T]) BeforeFunc[T]

WithPreflightBefore wraps an existing engine comparator with a cheap preflight guard.

It avoids executing an expensive comparator when it is known (conservatively) that the remaining budget cannot afford it, without changing Budget, Receipt, or comparator types.

How it works:

  • Before executing `before(a,b)`, it asks `upper(a,b)` for a conservative upper bound.
  • If the bound is known and remaining budget < bound, it returns cost=+Inf and err=nil. Existing engines interpret +Inf comparison cost as immediate budget exhaustion and stop without charging the budget.

Notes: - This wrapper still incurs the cost of calling `upper` and `b.Remaining()` (both should be cheap). - If the bound is loose, the engine may stop earlier than necessary (conservative behavior).

type Budget

type Budget interface {
	Charge(cost float64) bool // true if still within budget after charge
	Remaining() float64
}

Budget tracks resource consumption and determines when to stop.

type BudgetParameters

type BudgetParameters struct {
	Limit             float64       // budget limit
	CompareMultiplier float64       // multiplier for compare operations
	SwapMultiplier    float64       // multiplier for swap operations
	StopThreshold     float64       // threshold at which to stop early
	TimeLimit         time.Duration // time-based limit (if applicable)
}

BudgetParameters contains the budget configuration determined by Policy.

type CachedComparator

type CachedComparator[T comparable] struct {
	// contains filtered or unexported fields
}

CachedComparator wraps a Comparator with caching/memoization support.

func NewCachedComparator

func NewCachedComparator[T comparable](base Comparator[T]) *CachedComparator[T]

NewCachedComparator creates a new cached comparator wrapper. The comparator is enabled by default. Use Disable() to turn off caching.

func (*CachedComparator[T]) Clear

func (c *CachedComparator[T]) Clear()

Clear clears the cache.

func (*CachedComparator[T]) Compare

func (c *CachedComparator[T]) Compare(a, b T) ComparatorResult

Compare performs a comparison with caching support.

func (*CachedComparator[T]) Disable

func (c *CachedComparator[T]) Disable()

Disable disables caching (comparisons still work, just not cached).

func (*CachedComparator[T]) Enable

func (c *CachedComparator[T]) Enable()

Enable enables caching. Clears the cache when re-enabling to ensure fresh entries.

type Comparator

type Comparator[T any] func(a, b T) ComparatorResult

Comparator is a function type that returns a decision, cost, and optional evidence.

func WithPreflightComparator

func WithPreflightComparator[T any](b Budget, cmp Comparator[T], upper CompareUpperBound[T]) Comparator[T]

WithPreflightComparator is the Comparator[T] analogue of WithPreflightBefore. It returns a Comparator that can be used by callers who work with Comparator[T].

Evidence is intentionally left nil in the preflight-deny case; the goal is to avoid the expensive work, and existing engines do not consume Evidence.

type ComparatorResult

type ComparatorResult struct {
	BeforeB  bool      // decision: a should come before b
	Cost     float64   // measured/estimated cost
	Evidence *Evidence // optional evidence (nil if not provided)
	Error    error     // error if comparison failed
}

ComparatorResult contains the decision, cost, and optional evidence from a comparison.

type CompareUpperBound

type CompareUpperBound[T any] func(a, b T) (upperBound float64, ok bool)

CompareUpperBound returns a conservative upper bound on the cost of comparing a and b.

Contract: - If ok == true, upperBound must be >= the cost that the wrapped comparator would return. - It must be cheap relative to the wrapped comparator. - It must be deterministic for a given (a, b) under the caller's policy model.

If ok == false, no bound is available and the wrapped comparator will be invoked.

func ScaleCompareUpperBound

func ScaleCompareUpperBound[T any](base CompareUpperBound[T], multiplier float64) CompareUpperBound[T]

ScaleCompareUpperBound applies a multiplicative factor to a base upper-bound oracle.

Callers supply a domain-specific base bound, and policy-derived parameters scale it:

upper(a,b) = baseUpper(a,b) * params.CompareMultiplier

If base is nil, nil is returned.

type EngineConfig

type EngineConfig struct {
	Kind         EngineKind
	AdjacentSwap AdjacentSwapConfig
	HeapSort     HeapSortConfig
	Adaptive     AdaptiveConfig
}

EngineConfig is a tagged configuration for engine selection.

The intent is a single, uniform entrypoint (`Boundsort`) for tests/benchmarks/selection while keeping the canonical engine functions (`AdjacentSwapBounded...`, `BoundedQuickSort`, `BoundedHeapSort`) as the primary API.

Configuration is explicit and type-checked (no generic "options bag"):

  • `Kind` selects the engine family
  • The corresponding sub-config struct carries only the parameters meaningful to that engine (e.g., heap-sort's top-k objective).

type EngineKind

type EngineKind uint8

EngineKind identifies an ordering engine (algorithm family).

This is used for selection and uniform benchmarking without turning engines into allocated objects or requiring interface-based dispatch.

const (
	// EngineAdjacentSwap selects the adjacent-swap anytime ordering engine.
	EngineAdjacentSwap EngineKind = iota
	// EngineBoundedQuickSort selects the quicksort-based bounded ordering engine.
	EngineBoundedQuickSort
	// EngineBoundedHeapSort selects the heap-based bounded ordering engine.
	EngineBoundedHeapSort
	// EngineAdaptive selects an adaptive, deterministic engine chooser.
	// It dispatches to one of the concrete engines based on a cost model.
	EngineAdaptive
)

type Evidence

type Evidence struct {
	CacheHit bool   // true if result came from cache
	Source   string // "cache", "remote", "local", etc.
	Latency  time.Duration
	Metadata map[string]any // additional domain-specific evidence
}

Evidence provides optional metadata about a comparison operation.

type GuaranteeSet

type GuaranteeSet uint8

GuaranteeSet is a compact, allocation-free representation of guarantees.

Engines can publish which guarantees they provide without allocating slices.

const (
	// GuaranteeA: Safe partial result (permutation safety under early stop).
	GuaranteeA GuaranteeSet = 1 << iota
	// GuaranteeB: Adjacent-swap monotonic inversion improvement (engine-specific).
	GuaranteeB
	// GuaranteeC: Sorted suffix after a completed pass (engine-specific).
	GuaranteeC
	// GuaranteeD: Stability under strict swap condition (engine-specific).
	GuaranteeD
)

func EngineGuarantees

func EngineGuarantees(kind EngineKind) GuaranteeSet

EngineGuarantees reports the guarantees provided by an EngineKind.

Note: Guarantees B/C/D are specific to the adjacent-swap engine family.

type HeapSortConfig

type HeapSortConfig struct {
	K int // top-k (0 = full sort, <=0 treated as full sort by engine)
}

HeapSortConfig configures the heap-based engine family.

Heap-based bounded ordering supports top-k as a first-class objective; the parameter lives here (instead of being a generic option) to keep configuration explicit and algorithm-specific.

type Policy

type Policy interface {
	// DetermineBudget computes budget parameters from system context.
	// Must be deterministic: same context → same parameters.
	DetermineBudget(ctx SystemContext) BudgetParameters

	// LogInput logs the context input for auditability.
	// Returns a log entry that can be used to verify determinism.
	LogInput(ctx SystemContext) string
}

Policy maps system context to budget parameters. Must be deterministic given logged inputs for auditability.

type Receipt

type Receipt struct {
	TotalCost float64
	Events    []ReceiptEvent
	Stop      string // "completed", "budget_exhausted", "error"

	// Tamper-evident fields (optional)
	// HashChain semantics:
	// - When Sealed == false: HashChain is the head of the incremental event-chain: H_n.
	// - When Sealed == true:  HashChain is the sealed digest: SHA256(H_n || encode(Stop) || ...).
	//
	// Rule of thumb:
	// - Verify() on an unsealed receipt validates event integrity only.
	// - Seal() is required to cryptographically bind Stop into the receipt.
	HashChain []byte
	Signature []byte // optional signature of the receipt
	Sealed    bool   // true if receipt has been sealed (no more events can be added)
}

Receipt is an audit trail of the ordering operation. It is append-only and optionally tamper-evident.

func AdjacentSwapBounded

func AdjacentSwapBounded[T any](
	items []T,
	before func(a, b T) (aBeforeB bool, cost float64, err error),
	b Budget,
	swapCost ...float64,
) (out []T, receipt Receipt, completed bool, err error)

AdjacentSwapBounded is a baseline "anytime ordering" engine. It is intentionally simple: swap adjacent out-of-order pairs until budget is exhausted. swapCost is the cost to charge for each swap operation (defaults to 0.0 if not provided). This function always generates full receipts (ReceiptModeFull) for backward compatibility.

func AdjacentSwapBoundedWithReceiptMode

func AdjacentSwapBoundedWithReceiptMode[T any](
	items []T,
	before func(a, b T) (aBeforeB bool, cost float64, err error),
	b Budget,
	mode ReceiptMode,
	swapCost ...float64,
) (out []T, receipt Receipt, completed bool, err error)

AdjacentSwapBoundedWithReceiptMode is a variant of AdjacentSwapBounded that allows choosing the receipt detail level via ReceiptMode.

Modes:

  • ReceiptModeFull: Full event log + hash chain (tamper-evident, full audit trail)
  • ReceiptModeSummary: Track TotalCost and Stop only (no per-event log, not tamper-evident)
  • ReceiptModeNone: Empty receipt except Stop (no audit trail)

Note: ReceiptModeSummary and ReceiptModeNone intentionally weaken auditability by omitting the per-event log and hash chain. Use these modes only when full auditability is not required.

swapCost is the cost to charge for each swap operation (defaults to 0.0 if not provided).

func BoundedHeapSort

func BoundedHeapSort[T any](
	items []T,
	k int,
	before func(a, b T) (aBeforeB bool, cost float64, err error),
	b Budget,
) (out []T, receipt Receipt, completed bool, err error)

BoundedHeapSort is a heapsort-based ordering engine with budget tracking. It provides O(n log n) worst case performance and is optimized for top-k scenarios. Can stop early after extracting k elements when k > 0, or complete full sort when k == 0. Preserves Guarantee A (safe partial result - no loss/duplication even when budget exhausted).

func BoundedQuickSort

func BoundedQuickSort[T any](
	items []T,
	before func(a, b T) (aBeforeB bool, cost float64, err error),
	b Budget,
) (out []T, receipt Receipt, completed bool, err error)

BoundedQuickSort is a quicksort-based ordering engine with budget tracking. It provides average case O(n log n) performance vs O(n²) for adjacent-swap algorithms. Can stop early at partition boundaries when budget is exhausted. Preserves Guarantee A (safe partial result - no loss/duplication even when budget exhausted).

func Boundsort

func Boundsort[T any](cfg EngineConfig, items []T, before BeforeFunc[T], b Budget) ([]T, Receipt, bool, error)

Boundsort runs a selected ordering engine under a budget and returns an anytime result plus a receipt.

This is the uniform dispatch entrypoint; it calls the canonical engine functions in this package.

func (*Receipt) AppendEvent

func (r *Receipt) AppendEvent(event ReceiptEvent) error

AppendEvent appends an event to the receipt and updates the hash chain. Returns error if receipt is sealed.

func (*Receipt) Seal

func (r *Receipt) Seal()

Seal seals the receipt, preventing further modifications. After sealing, AppendEvent will return an error. Multiple calls to Seal() are idempotent and will not change the hash.

func (*Receipt) Sign

func (r *Receipt) Sign(privateKey crypto.PrivateKey) error

Sign signs the receipt's hash chain using the provided private key. The signature is stored in the receipt's Signature field. The receipt should be sealed before signing to ensure the hash chain is final. Supports RSA, ECDSA, and Ed25519 private keys.

func (*Receipt) Verify

func (r *Receipt) Verify() bool

Verify verifies the integrity of the receipt by recomputing the hash chain. Returns true if the receipt is valid (not tampered with).

Note: Verify() has two modes: - Unsealed receipts: Verify() checks event-chain integrity only (Stop is NOT bound). - Sealed receipts: Verify() checks event-chain integrity AND binds Stop via the sealed digest.

func (*Receipt) VerifySignature

func (r *Receipt) VerifySignature(publicKey crypto.PublicKey) (bool, error)

VerifySignature verifies the receipt's signature using the provided public key. Returns true if the signature is valid, false otherwise. Returns an error if verification cannot be performed (e.g., no signature, unsupported key type). Supports RSA, ECDSA, and Ed25519 public keys.

type ReceiptEvent

type ReceiptEvent struct {
	Kind string // "compare", "swap", "cache_miss", ...
	Cost float64
	Note string // optional human/debug note; avoid sensitive payloads
}

ReceiptEvent records a single charged operation.

type ReceiptMode

type ReceiptMode int

ReceiptMode controls the level of detail in receipt generation. ReceiptModeFull: Full event log + hash chain behavior (tamper-evident, full audit trail) ReceiptModeSummary: Track TotalCost and Stop, but omit per-event log (not tamper-evident, reduced auditability) ReceiptModeNone: Return an empty receipt (still set Stop; explicitly no audit trail)

const (
	ReceiptModeFull    ReceiptMode = iota // Full event log + hash chain (default, tamper-evident)
	ReceiptModeSummary                    // Track TotalCost and Stop only (no per-event log, not tamper-evident)
	ReceiptModeNone                       // Empty receipt except Stop (no audit trail)
)

type ReceiptSealedError

type ReceiptSealedError struct{}

ReceiptSealedError is returned when attempting to modify a sealed receipt.

func (*ReceiptSealedError) Error

func (e *ReceiptSealedError) Error() string

type SimpleBudget

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

SimpleBudget is a basic budget implementation. It is thread-safe and provides deterministic accounting.

func NewSimpleBudget

func NewSimpleBudget(limit float64) *SimpleBudget

NewSimpleBudget creates a new budget with the given limit.

func (*SimpleBudget) Charge

func (b *SimpleBudget) Charge(cost float64) bool

Charge attempts to charge the budget. Returns true if successful. Negative costs are treated as 0 (no-op) to prevent budget manipulation. NaN and Inf costs are handled explicitly: NaN is treated as 0, Inf causes immediate exhaustion. Thread-safe: uses mutex to ensure deterministic accounting in concurrent scenarios.

func (*SimpleBudget) Remaining

func (b *SimpleBudget) Remaining() float64

Remaining returns the remaining budget. Thread-safe: uses mutex to ensure consistent reads in concurrent scenarios.

type SimplePolicy

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

SimplePolicy is a basic policy implementation.

func NewSimplePolicy

func NewSimplePolicy(baseLimit float64, compareMultiplier, swapMultiplier, stopThreshold float64, timeLimit time.Duration) *SimplePolicy

NewSimplePolicy creates a new simple policy.

func (*SimplePolicy) DetermineBudget

func (p *SimplePolicy) DetermineBudget(ctx SystemContext) BudgetParameters

DetermineBudget computes budget parameters deterministically from context.

func (*SimplePolicy) LogInput

func (p *SimplePolicy) LogInput(ctx SystemContext) string

LogInput logs the context for auditability.

type SystemContext

type SystemContext struct {
	QueueDepth    int            // current queue depth
	CPULoad       float64        // CPU load (0.0-1.0)
	TimeRemaining time.Duration  // time remaining in current tick
	MemoryUsage   float64        // memory usage (0.0-1.0)
	Custom        map[string]any // custom context fields
}

SystemContext represents the system context used by Policy to determine budget parameters.

type TimeBasedBudget

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

TimeBasedBudget is a budget that tracks remaining time in a tick. It supports both hard ceilings and time-based budgets.

func NewTimeBasedBudget

func NewTimeBasedBudget(hardLimit float64, timeLimit time.Duration) *TimeBasedBudget

NewTimeBasedBudget creates a new time-based budget. hardLimit is the absolute maximum cost allowed. timeLimit is the maximum time allowed for operations.

func (*TimeBasedBudget) Charge

func (b *TimeBasedBudget) Charge(cost float64) bool

Charge attempts to charge the budget. Returns true if successful. Checks both hard limit and time limit.

func (*TimeBasedBudget) Remaining

func (b *TimeBasedBudget) Remaining() float64

Remaining returns the remaining budget (minimum of hard limit and time-based budget).

func (*TimeBasedBudget) TimeRemaining

func (b *TimeBasedBudget) TimeRemaining() time.Duration

TimeRemaining returns the remaining time in the tick.

Directories

Path Synopsis
benchmarks
cmd/format command
cmd/run command
examples
guarantees_abcd command

Jump to

Keyboard shortcuts

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