template

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Feb 7, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrCorrupt         = errors.New("template: corrupt payload")
	ErrMissingTemplate = errors.New("template: missing template")
)
View Source
var (
	ErrCorruptTemplateDef = errors.New("template: corrupt template def")
)

Functions

func AppendRoutingFingerprints

func AppendRoutingFingerprints(dst []uint64, value []byte, cfg Config) []uint64

AppendRoutingFingerprints appends deterministic routing fingerprints into dst. It avoids winnowing and favors a few fixed segment hashes (plus length).

func BucketFingerprints

func BucketFingerprints(value []byte, cfg Config) []uint64

BucketFingerprints returns fingerprints for bucketing (prefix-only by default).

func BucketKey

func BucketKey(fps []uint64) uint64

BucketKey computes a deterministic bucket key from fingerprints.

func DecodePayload

func DecodePayload(payload []byte, lookup func(id uint64) ([]byte, error), opts DecodeOptions) ([]byte, error)

DecodePayload decodes a TemplateValue payload using the provided lookup. If payload is not template-encoded, it is returned as-is.

func DecodePayloadAppend

func DecodePayloadAppend(dst, payload []byte, lookup func(id uint64) (TemplateDef, error), opts DecodeOptions) ([]byte, error)

DecodePayloadAppend decodes a TemplateValue payload and appends the decoded bytes to dst.

If payload is not template-encoded, it is appended as-is.

func EncodeMaskPayload

func EncodeMaskPayload(templateID uint64, mask []byte, vars []byte) ([]byte, error)

EncodeMaskPayload builds a TemplateValue payload for mask templates.

func EncodePayload

func EncodePayload(templateID uint64, gaps [][]byte) ([]byte, error)

EncodePayload builds a TemplateValue payload from template ID and gaps.

func EncodeTemplateDef

func EncodeTemplateDef(def TemplateDef, cfg Config) ([]byte, error)

EncodeTemplateDef serializes anchors into the TemplateDefBytes format.

func Fingerprints

func Fingerprints(value []byte, cfg Config) []uint64

Fingerprints computes deterministic winnowed fingerprints for value.

func IsEncodedPayload

func IsEncodedPayload(payload []byte) bool

IsEncodedPayload reports whether payload looks like a template-encoded value.

func RouteFingerprints

func RouteFingerprints(anchors [][]byte, cfg Config) []uint64

RouteFingerprints returns deterministic routing fingerprints for template anchors.

func RoutingFingerprints

func RoutingFingerprints(value []byte, cfg Config) []uint64

RoutingFingerprints returns fingerprints used for routing/bucketing. Prefer AppendRoutingFingerprints to avoid allocations.

func RoutingFingerprintsLegacy

func RoutingFingerprintsLegacy(value []byte, cfg Config) []uint64

RoutingFingerprintsLegacy returns deterministic winnowed routing fingerprints. It prefers prefix+suffix slices to avoid random middle bytes dominating.

func TemplateID

func TemplateID(defBytes []byte, salt byte) uint64

TemplateID computes a deterministic ID for TemplateDefBytes.

Types

type BatchPublisher

type BatchPublisher interface {
	PutTemplateDefs(ctx context.Context, defs []PublishSpec) ([]uint64, error)
}

BatchPublisher is an optional extension to Store that allows publishing multiple templates in a single durable batch.

type Candidate

type Candidate struct {
	ID   uint64
	Size int
}

Candidate represents a routing candidate from templatedb.

type Config

type Config struct {
	// Encoding/decoding caps.
	MinSavingsBytes       int
	MaxGaps               int
	MaxDecodedBytes       int
	MaxAnchorsPerTemplate int
	MinAnchorLen          int
	MaxAnchorLen          int
	MaxAnchorBytesTotal   int
	MaxAnchorSearchOps    int

	// Fingerprinting (routing).
	FingerprintK          int
	FingerprintW          int
	MaxFingerprints       int
	MaxFPReads            int
	MaxTemplateFetch      int
	MaxCandidatesPerFP    int
	MaxCandidateListBytes int
	RoutePrefixBytes      int
	RouteSuffixBytes      int
	LengthBucketMinLen    int
	DefCacheSize          int
	RecentTemplates       int
	FastPathMinSavings    int
	FastPathMinHits       int
	FastPathSavingsSlack  int
	FastPathMaxMisses     int
	// ColdSearchAfter controls when Encode enters a "cold" mode after a long
	// stretch of non-kept values. In cold mode, Encode skips expensive candidate
	// lookup/matching for most values and only probes periodically.
	//
	// Values <= 0 use a default.
	ColdSearchAfter int
	// ColdSearchProbeEvery controls how often Encode probes candidates while in
	// cold mode (every N values). Values <= 0 use a default.
	ColdSearchProbeEvery int

	// Training / publishing bounds.
	MaxBuckets                   int
	MaxValuesPerBucket           int
	MaxBytesPerBucket            int
	TrainSampleStride            int
	SynthesizeEverySamples       int
	MaxAnchorScanPerSynthesis    int
	MaxValuesScannedPerSynthesis int
	MaskMaxValuesScanned         int
	MinAnchorFreq                int
	MinPresenceRatio             float64
	AmbiguityPct                 float64
	MinPublishSavingsBytes       int
	MinPublishRatio              float64
	MinActivateHits              int
	MinActivateSavedBytes        int
	RouteFPCount                 int
	DisableMaskTemplates         bool
	MaskMinPresenceRatio         float64
	MaskMinConstBytes            int
	MaskMinConstFrac             float64
	CooldownValues               int
	MaxTemplatesPerBucket        int
	MaxTemplatesTotal            int

	// Async training / publishing.
	//
	// These settings control the background pipeline used to ingest samples,
	// synthesize templates, and publish them without stalling writers.
	TrainShards         int
	TrainRouters        int
	TrainQueueSize      int
	TrainShardQueueSize int
	TrainMaxValueBytes  int
	PublishBatchSize    int
	PublishFlushEvery   time.Duration
}

Config controls template encoding, routing, and training behavior. Zero values use defaults via NormalizeConfig.

func NormalizeConfig

func NormalizeConfig(cfg Config) Config

NormalizeConfig applies defaults and bounds for a config.

type DecodeOptions

type DecodeOptions struct {
	MaxDecodedBytes int
	MaxGaps         int

	// DefCacheSize controls the maximum number of decoded template definitions
	// cached by value-log readers. Values <= 0 disable caching.
	DefCacheSize int
}

DecodeOptions control TemplateValue decoding limits.

type Engine

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

Engine implements schema-blind template compression.

func NewEngine

func NewEngine(cfg Config) *Engine

NewEngine creates a template engine with normalized config.

func (*Engine) Close

func (e *Engine) Close()

Close stops background training/publishing workers.

func (*Engine) Encode

func (e *Engine) Encode(ctx context.Context, value []byte, store Store) ([]byte, bool)

Encode attempts to template-encode value using templatedb candidates.

func (*Engine) StatsSnapshot

func (e *Engine) StatsSnapshot() map[string]string

StatsSnapshot returns a copy of current stats.

type Mode

type Mode uint8

Mode selects template compression behavior.

const (
	TemplateOff Mode = iota
	TemplateOnly
	TemplatePrepass
)

type PublishSpec

type PublishSpec struct {
	DefBytes []byte
	RouteFPs []uint64
}

PublishSpec describes a template definition publish request.

type Store

type Store interface {
	GetCandidates(ctx context.Context, fp uint64, max int) ([]Candidate, error)
	GetTemplateDef(ctx context.Context, templateID uint64) ([]byte, error)
	PutTemplateDef(ctx context.Context, defBytes []byte, routeFPs []uint64) (uint64, error)
}

Store provides access to template definitions and routing candidates.

type TemplateDef

type TemplateDef struct {
	Kind           TemplateKind
	Anchors        [][]byte
	Mask           []byte
	Base           []byte
	VarPositions   []uint16
	ConstPositions []uint16
	// contains filtered or unexported fields
}

TemplateDef is an ordered list of anchors.

func DecodeTemplateDef

func DecodeTemplateDef(buf []byte) (TemplateDef, error)

DecodeTemplateDef parses TemplateDefBytes.

type TemplateKind

type TemplateKind uint8

TemplateKind indicates how a template encodes its payload.

const (
	TemplateAnchors TemplateKind = iota + 1
	TemplateMask
)

type TemplateStats

type TemplateStats struct {
	Attempted                    atomic.Uint64
	Matched                      atomic.Uint64
	Kept                         atomic.Uint64
	BytesSaved                   atomic.Uint64
	CandidateFPReads             atomic.Uint64
	CandidateTemplatesConsidered atomic.Uint64
	TemplateFetches              atomic.Uint64
	TemplatesPublished           atomic.Uint64
	MaskSparseUsed               atomic.Uint64
	MaskFullUsed                 atomic.Uint64

	TrainEnqueueAttempts  atomic.Uint64
	TrainEnqueued         atomic.Uint64
	TrainDroppedQueueFull atomic.Uint64
	TrainDroppedTooLarge  atomic.Uint64
	TrainRouted           atomic.Uint64
	TrainDroppedShardFull atomic.Uint64
	TrainProcessed        atomic.Uint64
	PublishBatches        atomic.Uint64
	PublishDefs           atomic.Uint64
	PublishErrors         atomic.Uint64
	// contains filtered or unexported fields
}

TemplateStats tracks template compression outcomes.

func (*TemplateStats) Snapshot

func (s *TemplateStats) Snapshot() map[string]string

Snapshot returns a copy of stats suitable for reporting.

Jump to

Keyboard shortcuts

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