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 ¶
- Variables
- func EngineName(kind EngineKind) string
- func PolicyCompareUpperBound[T any](p Policy, ctx SystemContext, base CompareUpperBound[T]) (params BudgetParameters, inputLog string, upper CompareUpperBound[T])
- type AdaptiveConfig
- type AdaptiveObjective
- type AdjacentSwapConfig
- type BeforeFunc
- type Budget
- type BudgetParameters
- type CachedComparator
- type Comparator
- type ComparatorResult
- type CompareUpperBound
- type EngineConfig
- type EngineKind
- type Evidence
- type GuaranteeSet
- type HeapSortConfig
- type Policy
- type Receipt
- func AdjacentSwapBounded[T any](items []T, before func(a, b T) (aBeforeB bool, cost float64, err error), ...) (out []T, receipt Receipt, completed bool, err error)
- func AdjacentSwapBoundedWithReceiptMode[T any](items []T, before func(a, b T) (aBeforeB bool, cost float64, err error), ...) (out []T, receipt Receipt, completed bool, err error)
- func BoundedHeapSort[T any](items []T, k int, before func(a, b T) (aBeforeB bool, cost float64, err error), ...) (out []T, receipt Receipt, completed bool, err error)
- func BoundedQuickSort[T any](items []T, before func(a, b T) (aBeforeB bool, cost float64, err error), ...) (out []T, receipt Receipt, completed bool, err error)
- func Boundsort[T any](cfg EngineConfig, items []T, before BeforeFunc[T], b Budget) ([]T, Receipt, bool, error)
- type ReceiptEvent
- type ReceiptMode
- type ReceiptSealedError
- type SimpleBudget
- type SimplePolicy
- type SystemContext
- type TimeBasedBudget
Constants ¶
This section is empty.
Variables ¶
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 ¶
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]) 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 ¶
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 ¶
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 ¶
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.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
benchmarks
|
|
|
cmd/format
command
|
|
|
cmd/run
command
|
|
|
examples
|
|
|
advanced_contracts
command
|
|
|
guarantees_abcd
command
|