Documentation
¶
Overview ¶
Package recordengine is the shared storage engine for **record-shaped** signals — logs and traces (later, profiles' sample table). A record-shaped signal is a stream (a Resource+Scope identity, indexed by the postings layer) of rows that each carry a primary timestamp plus a fixed set of typed columns. The engine is the structural twin of package engine (metrics) but generic over a Schema: it owns the in-memory head, columnar flush to immutable parts, the durable bucket-index + identity-index stateless read path, append-only merge with retention, per-part column blooms, lazy column decode, and the fetch.Fetcher contract — none of which is signal-specific. A signal package supplies the column Schema and projects its model into the engine's column vectors; the engine treats the columns opaquely.
The timestamp (the sort key) and the int128 stream id (the Resource+Scope hash) are implicit and not part of the Schema; the schema lists only the per-record columns.
Index ¶
- Constants
- Variables
- func EncodeWAL(b *Batch) []byte
- type AppendLimits
- type AppendResult
- type Batch
- type BloomMode
- type CardinalityStat
- type Column
- type ColumnCostStat
- type ColumnStat
- type Config
- type Engine
- func (e *Engine) AdoptWants(ws []bucketindex.Want)
- func (e *Engine) AppendBatch(b *Batch, limits AppendLimits) (AppendResult, error)
- func (e *Engine) ApplyPrimary(data []byte, limits AppendLimits) (accepted []byte, res AppendResult, err error)
- func (e *Engine) ApplyReplicated(data []byte) error
- func (e *Engine) Cardinality(topN int) CardinalityStat
- func (e *Engine) Close(ctx context.Context) (retErr error)
- func (e *Engine) CloseWAL() error
- func (e *Engine) ColumnValues(ctx context.Context, req ValuesRequest) ([][]byte, error)
- func (e *Engine) Fetch(ctx context.Context, r fetch.Request) (_ fetch.Iterator, rerr error)
- func (e *Engine) Flush(ctx context.Context) error
- func (e *Engine) HasWants() bool
- func (e *Engine) HeadBytes() int64
- func (e *Engine) HeadRecordCount() int
- func (e *Engine) Holes() []bucketindex.Entry
- func (e *Engine) IdentityBytes() int64
- func (e *Engine) IndexFenced() bool
- func (e *Engine) Keys(start, end int64) []KeyInfo
- func (e *Engine) KeysContext(ctx context.Context, start, end int64) []KeyInfo
- func (e *Engine) LoadParts(ctx context.Context) error
- func (e *Engine) LoadPartsReadOnly(ctx context.Context) error
- func (e *Engine) LoadPartsUnclaimed(ctx context.Context) error
- func (e *Engine) LostParts() uint64
- func (e *Engine) Merge(ctx context.Context, retainFrom int64) error
- func (e *Engine) MergeBacklog() int
- func (e *Engine) MergeDeferred() bool
- func (e *Engine) MergeRunning() bool
- func (e *Engine) MergeShape() MergeShape
- func (e *Engine) MergeShapeWith(opts MergeOptions) MergeShape
- func (e *Engine) MergeStep(ctx context.Context, opts MergeOptions) (changed bool, err error)
- func (e *Engine) MergeWith(ctx context.Context, opts MergeOptions) error
- func (e *Engine) PartCount() int
- func (e *Engine) Parts() []PartStat
- func (e *Engine) PartsDetailed(ctx context.Context) ([]PartDetailStat, error)
- func (e *Engine) PruneIdentities(ctx context.Context) (int, error)
- func (e *Engine) PruneIdentitiesWith(ctx context.Context, opts PruneOptions) (int, error)
- func (e *Engine) ReadSide(start, end int64, head func(live SideStore)) *SideRead
- func (e *Engine) RefreshReplica(ctx context.Context) error
- func (e *Engine) ReloadFenced(ctx context.Context) error
- func (e *Engine) RepairStats() RepairStats
- func (e *Engine) Replay(ctx context.Context, dir string) error
- func (e *Engine) Reset(ctx context.Context) error
- func (e *Engine) Series(matchers []fetch.Matcher, start, end int64) []signal.Series
- func (e *Engine) Stats() Stats
- func (e *Engine) StreamCost(ctx context.Context, opts StreamCostOptions) ([]StreamCostStat, error)
- func (e *Engine) StreamCount() int
- func (e *Engine) SyncWAL() error
- func (e *Engine) WALState() (segments int, bytes int64, epoch uint64, ok bool)
- func (e *Engine) WantOverlaps(start, end int64) bool
- type FetchResult
- type KeyInfo
- type KeyScope
- type Kind
- type LabelCard
- type MergeOptions
- type MergeShape
- type PartDetailStat
- type PartFetcher
- type PartStat
- type PruneOptions
- type RepairStats
- type RetentionBound
- type Schema
- type SidePart
- type SideRead
- type SideStore
- type Stats
- type StreamCostOptions
- type StreamCostStat
- type ValuesRequest
Constants ¶
const ( // RetentionBoundNone means no retention bound is set. RetentionBoundNone = retention.BoundNone // RetentionBoundAge means the signal age binds. RetentionBoundAge = retention.BoundAge // RetentionBoundSignalBytes means the signal byte budget binds. RetentionBoundSignalBytes = retention.BoundSignalBytes // RetentionBoundPooledBytes means the tenant pooled byte budget binds. RetentionBoundPooledBytes = retention.BoundPooledBytes )
const DefaultStreamCostSketchGroups = 4096
DefaultStreamCostSketchGroups is StreamCostOptions.MaxSketchGroups's default: 4096 groups, i.e. 32 MiB of transient sketch state. It is set to cover a real store's group count (a corpus grouped by a pod-suffixed service.name produced 2256) rather than to ration the sketches — 8 KiB per group is negligible against the column decode the pass is already doing. The cap exists for the pathological case, grouping a million-stream store by raw stream id.
const SidecarHeadBytes = 32
SidecarHeadBytes is how much of each stored sidecar SideStore.UnionBytes is shown.
Variables ¶
var ErrCorruptKeys = errors.New("recordengine: corrupt record-keys footer")
ErrCorruptKeys is returned when a serialized record-keys footer fails to parse.
var ErrNoSuchColumn = errors.New("recordengine: no such byte column")
ErrNoSuchColumn is returned when a ValuesRequest names a column the schema does not have or one that is not byte-typed. Numeric columns hold no dictionary to enumerate — a signal's numeric enums (a span kind, a status code) are a static set the caller already knows.
Functions ¶
func EncodeWAL ¶
EncodeWAL frames a batch as a replication/WAL payload — a stream-identity record followed by the batch's records — exactly the form Engine.ApplyPrimary and Engine.ApplyReplicated replay. The cluster write path builds a tenant's payload by concatenating EncodeWAL over its streams and routing it to the ring primary.
Types ¶
type AppendLimits ¶ added in v0.4.0
type AppendLimits struct {
// MinTimestamp is the inclusive timestamp floor when EnforceMinTimestamp is true.
MinTimestamp int64
// EnforceMinTimestamp enables the floor, including zero or negative timestamps.
EnforceMinTimestamp bool
// MaxSeries caps the number of distinct streams buffered in the head. A record that would
// register a new stream once the head already holds MaxSeries is rejected (the whole batch,
// since a batch is one stream); known streams are unaffected. 0 ⇒ unlimited.
MaxSeries int64
// MaxInFlightBytes caps the head's buffered record bytes. A record arriving while the head is
// at or over the cap is rejected (memory backpressure) until a flush drains it. 0 ⇒ unlimited.
MaxInFlightBytes int64
}
AppendLimits are the per-call admission limits the record head enforces while buffering a batch. The zero value imposes no limit; they are passed per Engine.AppendBatch call so a consumer's hot-reloaded tenant policy takes effect on the next write. The engine stays policy-agnostic — it sees only these numbers. They mirror the metric engine's limits so the facade maps one tenant.Limits to both.
type AppendResult ¶ added in v0.4.0
type AppendResult struct {
RejectedRetention int // older than MinTimestamp
Accepted int
RejectedOOO int // older than the out-of-order window
RejectedCardinality int // would exceed AppendLimits.MaxSeries (a new stream)
RejectedBytes int // head at or over AppendLimits.MaxInFlightBytes
}
AppendResult reports the disposition of an Engine.AppendBatch run by reason, so the caller can attribute an OTLP partial-success precisely.
func (AppendResult) Rejected ¶ added in v0.4.0
func (r AppendResult) Rejected() int
Rejected returns the total number of rejected records across all reasons.
type Batch ¶
type Batch struct {
Stream signal.SeriesID
Identity func() signal.Series // materialized only when the stream is newly seen
Ts []int64
Ints [][]int64 // len == schema int count; Ints[k][row]
Bytes [][][]byte // len == schema byte count; Bytes[k][row]
// Side is an optional encoded side-store delta (the content-addressed symbols this batch's
// records reference, and nothing else: a fully accepted batch's delta is flushed without a
// reachability walk) absorbed by [Config.SideStore]. nil when the engine has no side store.
Side []byte
}
Batch is one stream's projected records in the engine's column layout: the primary timestamps plus the int and byte column vectors in the schema's per-kind order. The signal package builds it; the engine treats the columns opaquely. Byte slices may alias the source batch (the head clones them on append).
type BloomMode ¶
type BloomMode uint8
BloomMode says whether and how a column feeds its per-part bloom for predicate pruning.
const ( // BloomNone builds no bloom for the column. BloomNone BloomMode = iota // BloomFullText tokenizes the column's value (lowercased words) so a `contains token` // condition can prune a part whose bloom lacks the token (e.g. a log body, a span name). BloomFullText // BloomAttrs treats the column as a serialized [signal.Attributes] blob and adds key-scoped // equality (`key‖value`) and full-text (`key‖word`) tokens, so per-record attribute equality // and contains conditions prune. BloomAttrs // BloomEquality adds the column's exact value as a token so a `column == value` condition can // prune (e.g. trace-by-id over the trace_id column). BloomEquality )
type CardinalityStat ¶ added in v0.12.0
type CardinalityStat struct {
TotalSeries int64 // distinct streams
DistinctLabelNames int
SymbolCount int
Top []LabelCard // sorted by Series desc, then Name; truncated to the requested top-N
}
CardinalityStat summarizes the engine's label cardinality (the head's index spans head ∪ flushed streams). TotalSeries and SymbolCount are exact; Top is the highest-cardinality label names.
type Column ¶
Column is one per-record column of a Schema: its name, physical kind, on-disk codec (zero ⇒ the kind's default), and bloom contribution.
type ColumnCostStat ¶ added in v0.37.0
type ColumnCostStat struct {
Name string
RawBytes int64
DiskBytes int64 // approximate, as [StreamCostStat.DiskBytes]
// Distinct estimates the distinct values the group's rows hold in this column (HyperLogLog,
// ~1.6% standard error). 0 for an int column and for a group outside the sketch budget.
Distinct int64
// DistinctNormalized is Distinct over values with every run of ASCII digits collapsed to '#'.
// It is what separates a genuinely high-entropy column from a templated one carrying an embedded
// timestamp or id: a group whose Distinct is large and whose DistinctNormalized is tiny is not a
// storage problem but a parsing one — the same line, repeated, never turned into fields.
DistinctNormalized int64
}
ColumnCostStat is one column's share of a group's cost.
type ColumnStat ¶ added in v0.12.0
type ColumnStat struct {
Name string
Kind string // physical type: int64 / float64 / bytes / int128
Codec string // value codec
Compress string // block-compression algorithm
Level int // block-compression level (0 ⇒ algorithm default or uncompressed)
Bytes int64 // size of the column's object; 0 for a constant-collapsed column, which has none
}
ColumnStat is one part column's physical description (from the manifest).
type Config ¶
type Config struct {
// Schema is the per-record column set this engine stores (required; the signal supplies it).
Schema *Schema
// OOOWindow is a per-stream lateness bound: a record older than OOOWindow (nanoseconds) behind
// the stream's own newest admitted record is rejected. 0 disables.
OOOWindow int64
// WAL, when non-nil, durably logs streams and records for crash recovery. nil ⇒ ephemeral.
WAL *wal.SegmentWriter
// Backend stores flushed parts. Required for [Engine.Flush]; nil ⇒ head-only.
Backend backend.Backend
// Prefix is the backend key prefix under which this engine's parts are written.
Prefix string
// OrphanGrace is how long after its id was minted a part no index entry names is spared by the
// orphan sweep a load runs. A part's objects are written before the index commit that names them,
// so over a shared store an unnamed part younger than this may be another writer's flush or merge
// still in flight. It must outlast the longest write-to-commit window, a merge sized by
// [Config.MaxPartBytes] and [Config.MergeMemoryBytes] written at the backend's sustained
// throughput, plus the clock skew between the writers of the prefix. 0 ⇒ one hour.
OrphanGrace time.Duration
// Now is the clock for orphan grace and background retention rewrites. nil ⇒ [time.Now].
Now func() time.Time
// Term reports this writer's current ownership term for Prefix — which tenure of the shard
// this engine is writing as. It is stamped into every bucket index written, so a reader can
// order two indexes of the same prefix even when neither the part names nor FlushedEpoch
// moved; see [github.com/oteldb/storage/backend/bucketindex.Generation]. nil is a writer with
// no cluster, whose generation is then a plain local counter.
Term func() uint64
// WriterID is this writer's stable identity — the cluster node id — under which its WAL flush
// watermark is kept in the bucket index. It matters because that index is *shared*: over a
// shared object store every replica of a shard commits one index object under one prefix, and
// the watermark is a per-node count of that node's own flushes, so one scalar in a shared
// object is meaningless to whichever node did not write it (see
// [github.com/oteldb/storage/backend/bucketindex.WriterEpoch]).
//
// Empty is the anonymous writer: a single-writer engine, which keeps the sole pre-v4 slot.
// Leaving it empty where two engines do share a prefix makes them share one slot, which is
// the defect the slots exist to prevent.
WriterID string
// SideStore, when non-nil, is a signal-supplied content-addressed auxiliary store (e.g. the
// profiles symbol store) that the engine persists as part sidecars on flush and unions on merge.
// nil ⇒ no side data (logs, traces).
SideStore SideStore
// Obs is the observability handle (spans + metrics). nil ⇒ a no-op handle.
Obs *obs.Obs
// Signal is the signal label for this engine's metrics ("log"/"trace"/"profile"); the facade
// sets it per signal. Empty ⇒ "record".
Signal string
// MaxPartBytes bounds flushed parts in decoded bytes. Zero disables flush splitting.
MaxPartBytes int64
// MergeCeilingBytes bounds merged parts in stored bytes, independently of flush size and memory.
// Zero derives the cap from free space, up to 16 GiB; negative disables disk sealing.
MergeCeilingBytes int64
// MergeMemoryBytes bounds resident merge state. Zero derives a process share; negative is unbounded.
MergeMemoryBytes int64
// MergeConcurrency reports how many merges may run concurrently in this process — the caller's
// fan-out, which *caps* how many the memory budget admits rather than dividing it. nil or ≤ 1 ⇒
// no cap beyond one.
//
// [MergeMemoryBytes] is what divides the allowance: it decides how many merges each get a usable
// share, and taking the divisor from a number that tracks the core count instead would price a
// memory quantity in CPUs. Nothing here enforces the division — that is [Config.MergeAdmission].
MergeConcurrency func() int
// MergeAdmission gates a merge on the memory it intends to hold: it is called once a merge has
// selected its sources, with the bytes that merge may hold resident, and returns the function
// that hands them back. A division of one budget across concurrent merges is only real if
// something stops more than that many from starting.
//
// wait reports whether this caller may block for the budget. Every caller waits except the
// maintenance loop's own merges ([MergeOptions.Background]), which run on goroutines the loop
// must reclaim before it can service flush pressure — they take what is free and defer to the
// next cycle otherwise. ok=false with a nil error is that deferral, not a failure.
//
// It is called *after* selection, so a cycle with nothing to compact never consults it at all.
// nil admits every merge, which is the single-engine and test default.
MergeAdmission func(ctx context.Context, bytes int64, wait bool) (release func(), ok bool, err error)
// FlushAdmission reserves the estimated resident flush working set. A non-nil callback enables
// one flush build alongside one merge build; nil retains serialized maintenance. An oversized
// flush must run alone, and the callback must release its reservation on every error.
FlushAdmission func(ctx context.Context, bytes int64) (release func(), err error)
// MergeCompression block-compresses the columns of merged (compacted) parts on top of their chunk
// codecs — the cold, long-lived data. Flushed parts stay codec-only so ingest is cheap; the
// background merge is where recompression is amortized. Record byte columns are dict-coded but not
// entropy-coded, so ZSTD here is a large on-disk win (≈10× on log-shaped data). AlgorithmNone (the
// default) keeps the legacy uncompressed behavior. When ordinary compaction has no work, parts
// below this compression profile are rewritten in a bounded group, including sealed singletons.
MergeCompression compress.Algorithm
// MergeCompressionLevel is the level for MergeCompression (ZSTD only). 0 ⇒ the algorithm default.
MergeCompressionLevel compress.Level
// MinFreeBytes is the headroom the engine leaves unused on a backend that reports its free
// space: a flush is refused, and the ingest path starts rejecting, once the medium holds less
// than the pending part plus this. It leaves a merge room for its output — a merge must write
// before it can retire the inputs it frees. 0 ⇒ [diskguard.DefaultReserveBytes]; negative ⇒ the
// byte axis is not checked.
MinFreeBytes int64
// MinFreeInodes is the same headroom on the object-count axis, for a backend that reports free
// inodes. It is checked separately because a part is many small objects: an inode table can
// exhaust with the disk half empty, and byte accounting cannot see it. 0 ⇒
// [diskguard.DefaultReserveInodes]; negative ⇒ the inode axis is not checked.
MinFreeInodes int64
// Repair pulls a part this engine holds in its index but cannot read back from a peer that
// still has it, and says whether the part is gone from every owner. The cluster layer supplies
// it over its transport; a single-node store supplies one that fetches nothing and answers for
// an owner set of one. nil concludes nothing, so an outstanding want stays outstanding. See
// [PartFetcher].
Repair PartFetcher
}
Config configures an Engine.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine is one tenant's record store for a signal. Safe for concurrent use.
func (*Engine) AdoptWants ¶ added in v0.45.2
func (e *Engine) AdoptWants(ws []bucketindex.Want)
AdoptWants records repair obligations discovered outside the engine: parts a peer holds that this engine's index does not account for and cannot learn of on its own, since a part it never named is one it can never report losing. The next commit publishes them and the repair pass fetches the objects; one already outstanding or already satisfied is dropped.
func (*Engine) AppendBatch ¶
func (e *Engine) AppendBatch(b *Batch, limits AppendLimits) (AppendResult, error)
AppendBatch ingests one stream's records: it registers the stream on first sight, appends each record through the admission limits (OOO window, cardinality, in-flight bytes), and logs accepted records to the WAL. It returns an AppendResult breaking accepted/rejected down by reason, so the caller can report an exact OTLP partial-success. Safe for concurrent use.
func (*Engine) ApplyPrimary ¶
func (e *Engine) ApplyPrimary(data []byte, limits AppendLimits) (accepted []byte, res AppendResult, err error)
ApplyPrimary applies a write as the stream's **primary**: it runs each record through the admission-checked append path (the single OOO decision for the shard, plus the cardinality and in-flight-memory valves from limits) and re-frames the *accepted* records into a WAL payload to replicate to the secondary owners. It returns that accepted payload and an AppendResult breaking the disposition down by reason, so the clustered ingest path attributes OTLP partial-success exactly like the single-node path. Every replica converges on the same data. Safe for concurrent use.
Like Engine.AppendBatch it decides the accepted set, logs it, and only then applies it, so an error leaves no row in the head that the log does not hold. Side deltas lead the accepted payload for the same reason: they are idempotent to re-absorb, records are not, so a log write that stops part-way must not have committed records ahead of their delta.
func (*Engine) ApplyReplicated ¶
ApplyReplicated applies a replicated write from the primary verbatim (no OOO re-check — the primary already decided the accepted set), so all replicas hold identical data. Safe for concurrent use.
func (*Engine) Cardinality ¶ added in v0.12.0
func (e *Engine) Cardinality(topN int) CardinalityStat
Cardinality summarizes the engine's label cardinality from the head's inverted index (which spans every stream ever seen, flushed or not). topN bounds the returned Top slice (≤0 returns all label names). It takes a read lock and does no backend I/O.
func (*Engine) Close ¶
Close flushes any buffered records to a part and closes the WAL. It does not stop a background loop — the owner ([storage.Storage]) does that before calling Close.
func (*Engine) CloseWAL ¶ added in v0.4.0
CloseWAL releases WAL and part-reader ownership without flushing or checkpointing. WAL segments remain for replay; active fetches keep their readers until release.
func (*Engine) ColumnValues ¶ added in v0.42.0
ColumnValues enumerates the distinct values a byte column — or one per-record attribute key — takes within [start, end], without materializing rows. A flushed part answers from its column dictionary (O(distinct), no row decode); only the unflushed head is scanned, bounded by its size.
The result is sorted, deduplicated, and owned by the caller. It is a **superset** for the window: a part whose bounds overlap the window contributes its whole dictionary, so a value that occurs only outside the window may be returned. That matches the fetch contract and is what tag/label autocomplete wants. Empty values are omitted. Limit truncates the sorted union, so the result is the lexicographically smallest Limit values — truncation is not otherwise signaled.
Attribute values are the canonical text projection (signal.Value.AppendText), the same form the matching layer compares against. Safe for concurrent use.
func (*Engine) Fetch ¶
Fetch implements fetch.Fetcher over head ∪ flushed parts: it resolves matchers to streams, gathers each stream's in-window records (decoding only the referenced columns), applies the column conditions and projection, and returns one batch per stream sorted by timestamp.
func (*Engine) Flush ¶
Flush writes the head's buffered records to a new immutable part and clears the buffers. No-op if the head is empty. Requires a Config.Backend.
func (*Engine) HasWants ¶ added in v0.45.0
HasWants reports whether any repair obligation is outstanding, without a window — the read seam's build-time check, so a fully repaired shard keeps the bare engine as its fetcher.
func (*Engine) HeadBytes ¶ added in v0.4.0
HeadBytes returns the engine's buffered record bytes — the in-flight memory measure for AppendLimits.MaxInFlightBytes. It counts the live head plus the buffers an in-flight flush has detached but not yet published: those stay resident, so the measure must not dip to zero (and let a second head in) for the duration of a slow flush.
func (*Engine) HeadRecordCount ¶
HeadRecordCount returns the number of records buffered in the head across all streams.
func (*Engine) Holes ¶ added in v0.45.0
func (e *Engine) Holes() []bucketindex.Entry
Holes returns the acknowledged losses this engine's index carries, in prefix order.
func (*Engine) IdentityBytes ¶ added in v0.37.0
IdentityBytes returns the resident bytes of the engine's identity state — the symbol table, the stream index, the postings lists and the per-stream out-of-order watermarks. It is reported separately from Engine.HeadBytes because a flush does not drain it: identities outlive their records and are cleared only by Engine.Reset, so this number tracks the engine's all-time stream count, not its buffered data.
func (*Engine) IndexFenced ¶ added in v0.49.0
IndexFenced reports whether the last index load failed, so the engine refuses every commit and its part set may be missing what the stored index names.
func (*Engine) Keys ¶ added in v0.5.0
Keys enumerates the distinct attribute keys present across the engine's streams (head ∪ flushed parts) with at least one record in [start, end], each tagged with the scope(s) it appears in. A zero start AND end disables the time filter. Stream-identity keys (resource/scope) come from the authoritative series index; record-attribute keys come from the head buffers and each in-window part's persisted key footer. Window precision is part-granular and best-effort: a key whose records all fall outside the window may still be returned (harmless). Safe for concurrent use.
func (*Engine) KeysContext ¶ added in v0.50.2
KeysContext is Engine.Keys with tracing attached to ctx.
func (*Engine) LoadParts ¶
LoadParts reconstructs the engine's durable state from the object store: the part set from the bucket index and the stream identity index from the persisted object. A head-only engine is a no-op. Replaces current parts. It assumes this node owns the prefix — it sweeps the part objects the index does not name (see [Engine.sweepOrphansLocked]) and commits a want for each part the index names that is not there.
func (*Engine) LoadPartsReadOnly ¶ added in v0.46.0
LoadPartsReadOnly is Engine.LoadParts for an engine that must never mutate its prefix: it sweeps no orphan objects and commits no index, so opening over a data directory leaves every object in it untouched. A part the index names but the backend lacks becomes a pending want that reads disclaim (Engine.WantOverlaps), never a repair commit. It is what backs storage.WithReadOnly (backup, verification, offline inspection).
func (*Engine) LoadPartsUnclaimed ¶ added in v0.45.0
LoadPartsUnclaimed is Engine.LoadParts for a node whose authority over the prefix is not yet established (a cluster node recovering before it holds any claim): a part the index names but the backend lacks becomes a pending want, committed by the first commit this engine makes as a writer rather than now. Reads over it disclaim meanwhile (Engine.WantOverlaps).
func (*Engine) LostParts ¶ added in v0.45.0
LostParts is the shard's monotone data-loss count: the holes its writers have ever committed. It lives in the bucket index, so it survives a restart and every owner reads the same number.
func (*Engine) Merge ¶
Merge compacts one bounded group and applies retention (unix-nanosecond cutoff; ≤ 0 disables it). Records sharing a timestamp remain in source order; compaction does not deduplicate them.
func (*Engine) MergeBacklog ¶ added in v0.12.0
MergeBacklog returns the parts a merge may still take — the flushed parts less the sealed ones, which no merge reconsiders. It is MergeShape.Backlog; use Engine.MergeShape for the rest of the selector's inputs.
func (*Engine) MergeDeferred ¶ added in v0.48.0
MergeDeferred reports whether the last merge selected parts but could not claim the process merge budget, so it compacted nothing. The maintenance loop schedules such an engine ahead of the others on its next pass; it is also the signal an operator wants when part counts climb while merges look idle.
func (*Engine) MergeRunning ¶ added in v0.12.0
MergeRunning reports whether a merge/compaction is currently executing on this engine (an in-memory liveness flag for introspection).
func (*Engine) MergeShape ¶ added in v0.37.0
func (e *Engine) MergeShape() MergeShape
MergeShape is Engine.MergeShapeWith without retention.
func (*Engine) MergeShapeWith ¶ added in v0.49.0
func (e *Engine) MergeShapeWith(opts MergeOptions) MergeShape
MergeShapeWith returns the selector's view of the engine's parts under the retention a merge would run with (opts.Force is ignored; ForceCandidates sets it). It takes a brief read lock, does no backend I/O and decodes nothing, so it is safe to poll at dashboard cadence.
func (*Engine) MergeStep ¶ added in v0.49.1
MergeStep is Engine.MergeWith, reporting whether a successful pass compacted or retired parts. Retention may change parts even when compaction is deferred.
func (*Engine) MergeWith ¶ added in v0.37.0
func (e *Engine) MergeWith(ctx context.Context, opts MergeOptions) error
MergeWith is Engine.Merge with the merge parameterized: the one background-merge entry point, so compaction, retention, and a forced compaction are the same pass over the immutable parts.
func (*Engine) Parts ¶ added in v0.12.0
Parts returns an in-memory snapshot of the parts the engine can serve — its own, plus the ones it adopted from a rival writer's index — under a read lock, with no backend I/O and no decode, so it is safe to poll. It is the servable set rather than this writer's own, because that is what a read answers from and what the completeness accounting has to measure. For byte sizes, codecs, and chunk counts, use Engine.PartsDetailed.
func (*Engine) PartsDetailed ¶ added in v0.12.0
func (e *Engine) PartsDetailed(ctx context.Context) ([]PartDetailStat, error)
PartsDetailed augments Engine.Parts with each part's on-backend byte size, column/codec layout, and chunk (granule) count. It reads object sizes from the backend, so unlike Parts it is not hot-path-free — call it for a drill-down view, not a high-frequency poll. Each part is ref-held for the duration so a concurrent merge cannot reclaim its objects mid-read.
func (*Engine) PruneIdentities ¶ added in v0.37.0
PruneIdentities drops the stream identities no live data names any more — those the retention side of a merge left behind — rebuilding the resident index around the survivors. It returns the number removed (0 when nothing could have died, or when too little has).
Every node may call it, owner or replica: identity is scoped to the part that holds it, so the live set is derived from *this node's* parts and means exactly "what this node can still serve". A part a replica has not yet synced brings its identities with it when it arrives. It takes the same flush/merge exclusion as those paths, so no publish can add an identity underneath it.
func (*Engine) PruneIdentitiesWith ¶ added in v0.37.0
PruneIdentitiesWith is Engine.PruneIdentities with explicit options.
func (*Engine) ReadSide ¶ added in v0.49.0
ReadSide pins the side data a read over [start, end] needs (a zero start AND end selects every part) and calls head with the live side store under the engine's read lock, where the caller snapshots the unflushed side data; head must not retain it. The read is empty and head is not called when the engine has no side store. Safe for concurrent use.
func (*Engine) RefreshReplica ¶
RefreshReplica brings a replica node's view up to date with the shared object store: it reconstructs the flushed parts and trims its head to the still-unflushed window, stream by stream (see [head.trimBelowCovered]), and its side store to what that window references. With no shared store, a safe no-op. A part the index names but the store lacks is not an error: it leaves the part set and is counted as a pending want (Stats.WantedParts, Engine.WantOverlaps) until a refresh finds it again or this node commits as an owner.
func (*Engine) ReloadFenced ¶ added in v0.49.0
ReloadFenced retries the index load of an engine whose last load failed, lifting the commit fence once one succeeds; a no-op when the engine is not fenced. It loads like Engine.RefreshReplica but trims no head: an owner's head holds records that are in no part yet.
func (*Engine) RepairStats ¶ added in v0.45.0
func (e *Engine) RepairStats() RepairStats
RepairStats returns a snapshot of what repair has done.
func (*Engine) Replay ¶
Replay rebuilds the head (and side store) from the WAL segments in dir (durable restart). It skips segments at or below the flush watermark recovered by Engine.LoadParts (call LoadParts first), so records already in a flushed part are not re-applied — exactly-once recovery. A damaged segment does not fail it: the unreadable regions are skipped, counted and logged.
func (*Engine) Reset ¶
Reset discards all data (head + parts, including the records an in-flight flush detached) and deletes this engine's objects, returning it to the empty state without reallocating. It waits for an in-flight flush or merge to finish first, so that operation cannot publish its part into the reset engine. Objects of parts a concurrent fetch is still reading are left for the deferred reclaim ([reclaimRetired], run by the next flush/merge cycle) rather than deleted underneath the reader. Safe for concurrent use.
func (*Engine) Series ¶
Series returns the identities of the streams matching matchers that hold at least one record in [start, end] — the enumeration primitive behind profile-type / label listing. A zero start AND end disables the time filter (return every matching stream). The time filter is part-overlap granular (a returned stream is guaranteed to match the matchers; its in-window records are a superset check). Safe for concurrent use.
func (*Engine) Stats ¶ added in v0.10.0
Stats returns an in-memory snapshot of the engine's state under a single read lock (no backend I/O, no decode), safe to poll at dashboard cadence. Part byte sizes are not included.
func (*Engine) StreamCost ¶ added in v0.37.0
func (e *Engine) StreamCost(ctx context.Context, opts StreamCostOptions) ([]StreamCostStat, error)
StreamCost attributes the engine's flushed parts to streams (or, with StreamCostOptions.GroupBy, to a label's values): rows, decoded bytes, an approximate compressed share, and per-column distinct estimates.
It answers "which service is costing me, and why" — the diagnosis the label-cardinality and per-part views cannot give, since neither attributes bytes to a stream nor says anything about the cardinality of the values inside the columns, which is what drives the cost.
It is the heaviest introspection call in the engine: every accounted byte column of every live part is read and decoded once (int columns and the timestamp are accounted arithmetically, with no decode). Run it as an operator drill-down, not on a schedule, and narrow it with StreamCostOptions.Columns when only one column is in question. Each part is ref-held for the duration, so a concurrent merge cannot reclaim it mid-read.
func (*Engine) StreamCount ¶
StreamCount returns the number of distinct streams in the head.
func (*Engine) SyncWAL ¶ added in v0.3.0
SyncWAL fsyncs the engine's WAL, if any (the background WALSyncInterval path). No-op without a WAL.
func (*Engine) WALState ¶ added in v0.12.0
WALState returns the WAL segments on disk, the bytes they hold, and the active flush epoch. ok is false when the engine has no WAL (ephemeral). It takes a read lock, excluding concurrent appends (which hold the write lock).
func (*Engine) WantOverlaps ¶ added in v0.45.0
WantOverlaps reports whether an outstanding repair obligation covers any of [start, end]: the engine holds an index entry for a part in that range that it cannot read and has not got back, so a read of that window here is short by whatever the part held.
Pending wants count: a want a load discovered but no commit has published yet names data that is already unreadable. A hole does not — acknowledging a loss discharges its want, which is what lets reads resume once repair or an operator accepts the loss.
type FetchResult ¶ added in v0.45.0
type FetchResult = bucketindex.FetchResult
FetchResult is one want's outcome from a PartFetcher.
type KeyInfo ¶ added in v0.5.0
KeyInfo is a distinct attribute key and the union of the scopes it was observed in. Key aliases engine-owned bytes (a head identity or a decoded part-footer entry); copy it to retain.
type KeyScope ¶ added in v0.5.0
type KeyScope uint8
KeyScope is a bitset of the scopes an attribute key was observed in. A key can appear in more than one — e.g. as a resource attribute on one stream and a per-record attribute on another — and the bitset records every scope, so a caller can tell a stream label from a record attribute (or both).
const ( // KeyScopeResource marks a resource attribute (part of the stream identity, postings-indexed). KeyScopeResource KeyScope = 1 << iota // KeyScopeScope marks an instrumentation-scope attribute (also stream identity). KeyScopeScope // KeyScopeRecord marks a per-record attribute (the serialized attrs column). KeyScopeRecord // KeyScopeSeries marks a signal-level identity attribute — [signal.Series].Attributes, which sits // alongside resource and scope in the stream identity and is postings-indexed like them. Logs, // traces and profiles leave it empty (their per-record attributes are a column); exemplars carry // the metric's data-point attributes and reserved labels (__name__, …) there. KeyScopeSeries )
type Kind ¶
type Kind uint8
Kind is a column's physical type. Records use only int64 and byte-string columns (floats live in the metrics engine); a typed value is projected onto one of these at the language edge.
type LabelCard ¶ added in v0.12.0
LabelCard is one label name's cardinality: how many streams carry it and how many distinct values it takes across them.
type MergeOptions ¶ added in v0.37.0
type MergeOptions struct {
// RetainFrom drops records older than this absolute unix-nanosecond cutoff (retention);
// ≤ 0 disables it.
RetainFrom int64
// RetentionBoundBy is the policy bound behind RetainFrom, for observability only.
RetentionBoundBy RetentionBound
// Background marks this merge as the maintenance loop's own, where declining costs nothing: if
// the process merge budget ([Config.MergeAdmission]) is fully committed the merge is skipped and
// the next cycle retries it, rather than waiting.
//
// It is opt-in because waiting is the safe default. A caller that asked for a merge — an
// operator command, a test, an embedder driving the engine itself — must get one, not a silent
// no-op; the maintenance loop is the only caller for which the opposite is true, because it runs
// on one goroutine that also services flush pressure and must not park on a busy budget.
// Partial-retention rewrites are coalesced for one hour; Force bypasses that interval.
Background bool
// Force waives the write-amplification guards immediately. Disk size, memory admission,
// source count and the time-bucket ladder still bound the merge.
Force bool
// contains filtered or unexported fields
}
MergeOptions parameterizes a merge. The zero value is a plain compaction.
type MergeShape ¶ added in v0.37.0
type MergeShape struct {
// Parts is the flushed parts; Sealed those excluded from size compaction at the cap;
// Backlog the rest. Retention and compression rewrites may also take sealed parts.
Parts int
Sealed int
Backlog int
// Bytes is what the flushed parts occupy on disk. Divided by Parts it is the average part size,
// which is what says whether a rising part count is a merge that stopped or an ingest that grew.
Bytes int64
// Candidates counts the next merge's inputs, including retention drops and compression rewrites.
// ForceCandidates applies the idle waiver immediately; the time ladder still bounds both.
Candidates int
ForceCandidates int
// CapBytes is the stored-byte seal threshold of the last merge (0 before the first merge).
CapBytes int64
// Tiers and LargestTierParts describe stored-byte sizes; they do not govern eligibility.
Tiers int
LargestTierParts int
// MinTierParts is the minimum ordinary merge input count (retained for compatibility).
MinTierParts int
// BestMultiplier is the best output-to-largest-input ratio; IdleRounds reaches WaiveAfter
// before selection waives the write-amplification guard. Tiers are diagnostic only.
BestMultiplier float64
IdleRounds int
WaiveAfter int
// NonReducingMerges counts rejected ordinary rewrites, not durable part changes.
NonReducingMerges uint64
}
MergeShape describes compaction eligibility without reading or decoding backend objects.
type PartDetailStat ¶ added in v0.12.0
type PartDetailStat struct {
PartStat
Bytes int64 // sum of the part's backend object sizes
Chunks int // sparse-index granules: ceil(RowCount / GranuleSize)
Columns []ColumnStat // per-column physical layout
// OtherBytes is every non-column object's size, keyed by its name under the part prefix
// (manifest, marks, and the engine's own indexes). With the columns' Bytes it sums to Bytes.
OtherBytes map[string]int64
}
PartDetailStat augments PartStat with fields that need a backend read: the on-backend byte size (summed over the part's objects) and the column/codec layout and chunk count from the manifest (cached on the open part, so only Bytes incurs additional I/O).
type PartFetcher ¶ added in v0.45.0
type PartFetcher = bucketindex.PartFetcher
PartFetcher is the repair seam to the cluster; see bucketindex.PartFetcher.
type PartStat ¶ added in v0.12.0
type PartStat struct {
ID string // the part's backend key prefix
MinTime int64 // inclusive unix-ns bounds of the part's records
MaxTime int64
Series int // distinct streams in the part (len of its row-range index)
Rows int64 // total records (sum of the per-stream row spans)
// SizeBytes is the decoded footprint from the manifest, or zero for legacy parts.
SizeBytes int64
// DiskBytes is the stored column size used by merge selection and sealing.
DiskBytes int64
}
PartStat is one flushed part's in-memory shape (no backend I/O, no decode): identity, time bounds, and the stream/row counts from the part's in-memory row-range index.
func (PartStat) LogicalBytes ¶ added in v0.44.1
LogicalBytes is the part's uncompressed size for a compression ratio: PartStat.SizeBytes when the manifest recorded it, and otherwise the same per-row estimate the engine falls back to internally, so a store still holding pre-manifest parts reports an approximate ratio rather than none at all.
type PruneOptions ¶ added in v0.37.0
type PruneOptions struct {
// Force runs the prune even when the background thresholds would skip it — an engine that has
// merged nothing away since the last pass, or one whose dead set is too small to pay for the
// rebuild. It is what an operator-triggered sweep wants.
Force bool
}
PruneOptions tunes an identity prune.
type RepairStats ¶ added in v0.45.0
type RepairStats = bucketindex.RepairStats
RepairStats counts what repair has done over this engine's lifetime.
type RetentionBound ¶ added in v0.52.0
RetentionBound identifies the policy bound behind a requested retention cutoff.
type Schema ¶
type Schema struct {
// contains filtered or unexported fields
}
Schema is the ordered set of per-record columns a signal stores. It is immutable after construction and shared by every engine, part, and record batch of that signal.
type SidePart ¶ added in v0.49.0
type SidePart struct {
// Key is the part prefix. No other part reuses it and a part never changes, so it keys a cache
// of the decoded side data.
Key string
// contains filtered or unexported fields
}
SidePart is one readable part's side data.
type SideRead ¶ added in v0.49.0
type SideRead struct {
// Flushing is the side snapshot of the records an in-flight flush detached: they are fetchable
// and in no part yet. nil when no flush is in flight.
Flushing map[string][]byte
// Parts are the readable parts overlapping the window, newest first.
Parts []SidePart
// contains filtered or unexported fields
}
SideRead is the side data a read over a window needs, besides the live accumulator. Its parts stay readable until SideRead.Release.
type SideStore ¶
type SideStore interface {
// Absorb merges one batch's encoded side delta ([Batch.Side]) into the live accumulator.
Absorb(delta []byte) error
// Encode serializes the accumulated side data into named sidecar payloads (name → bytes),
// written as {prefix}/sym-{name}.bin at flush.
Encode() map[string][]byte
// Reset clears the live accumulator (after a flush drains the head).
Reset()
// RefColumn names the byte column whose cells are the ids the records reference in this store.
RefColumn() string
// Retain drops every accumulated entry that the refs (the [SideStore.RefColumn] cells of the
// records left in the head) do not reach, directly or transitively.
Retain(refs iter.Seq[[]byte])
// Restore merges an [SideStore.Encode] snapshot back into the live accumulator. The engine calls
// it when a flush fails after the snapshot+Reset: the records return to the head, so their side
// data must too. Content-addressing makes the merge a plain dedup with whatever the accumulator
// gained meanwhile.
Restore(snapshot map[string][]byte) error
// Names returns the sidecar names to read back for a part on merge (the keys [SideStore.Encode]
// may produce). A part missing a named sidecar is skipped.
Names() []string
// Union merges the loaded sidecars of the compacted parts (one map per part) and returns the
// named payloads to write under the new part: only the entries the refs (the [SideStore.RefColumn]
// cells of that part) reach, directly or transitively. Pure; ignores the live accumulator.
Union(parts []map[string][]byte, refs iter.Seq[[]byte]) (map[string][]byte, error)
// Stored re-encodes named payloads in their on-disk form. The engine applies it to exactly what
// it writes as sidecars, so [SideStore.Encode] and [SideStore.Union] can return a form that is
// cheap to decode again in memory. Pure, like Union.
Stored(tables map[string][]byte) (map[string][]byte, error)
// UnionBytes bounds what Union, whatever its refs keep, and then Stored hold at once, beside the
// loaded sidecars themselves, over stored sidecars of the given byte lengths whose first bytes
// are heads (at most [SidecarHeadBytes] each). A merge reserves it for each part it writes before
// reading a sidecar, so it must not undercount.
UnionBytes(sizes []int64, heads [][]byte) (int64, error)
}
SideStore is an optional per-engine auxiliary store that rides the part lifecycle. A signal whose records reference content-addressed side data (e.g. the profiles symbol store: strings, functions, locations, stacks) supplies one via Config.SideStore; the engine then absorbs each batch's delta (Batch.Side) into a live accumulator, persists the accumulator as part sidecars on flush, and unions the sidecars of compacted parts on merge. The engine treats the data opaquely — only the signal package knows the table formats.
Content-addressing is the load-bearing assumption: an entry's id is a hash of its content, so the same entry has the same id everywhere and SideStore.Union is a plain dedup with no id remap.
All methods are called under the engine's lock, so an implementation need not be safe for concurrent use. SideStore.Union must be a pure function of its arguments and must not read or mutate the live accumulator (it merges already-flushed part data, independent of the head).
type Stats ¶ added in v0.10.0
type Stats struct {
// RetainFrom is the last authorized requested cutoff; cleanup may still be pending.
RetainFrom int64
// RetentionBoundBy identifies the bound behind RetainFrom.
RetentionBoundBy RetentionBound
Streams int64 // distinct streams ever seen (index span: head ∪ flushed)
HeadRecords int64 // records currently buffered in the head (unflushed)
HeadBytes int64 // buffered record bytes, head + in-flight flush (the in-flight memory measure)
// ReusableBytes is idle head-buffer capacity, evicted before it can block record admission.
ReusableBytes int64
// HeadAge is how long the head has been accumulating since its last flush (0 when empty) —
// the flush lag, which no data-time field here reports (backfill makes record timestamps
// useless as a measure of it).
HeadAge time.Duration
// IdentityBytes is the resident identity state (symbols + stream index + postings + OOO
// watermarks) — memory a flush does not drain, and which no other counter here reports.
IdentityBytes int64
Parts int // flushed immutable parts
MinTime int64 // oldest flushed record time (unix ns); 0 when no parts
MaxTime int64 // newest record time across parts and the head (unix ns); 0 when empty
// OutOfSpace is set while the engine refuses writes because its backend is out of bytes or
// inodes. Reads still answer from what is on disk; it clears when a flush finds room again.
OutOfSpace bool
// WantedParts is the repair obligations outstanding right now: parts the index names that this
// node cannot read and has not yet got back. Non-zero means the shard is not fully repaired.
WantedParts int
// Holes is the index entries that stand for an acknowledged loss rather than a part (see
// [bucketindex.Entry.Hole]). A read overlapping one is short by whatever that part held, so a
// hole is reported apart from Parts and never counted among them.
Holes int
// LostParts is the shard's monotone data-loss count as its index records it: the holes its
// writers have ever committed, including ones since revoked. It never decreases, and every
// owner of the shard reads the same number.
LostParts uint64
// IndexFenced is set while the last index load failed: the engine refuses every commit, so
// flushes keep their records in the head, and it retries the load until one succeeds.
IndexFenced bool
// IndexLoadErr is the error of the failed load behind IndexFenced, nil while not fenced.
IndexLoadErr error
// TenureUnestablished is set while this clustered engine holds the shard's claim but its
// tenure's first commit has not landed: it commits nothing, so flushes keep their rows in the
// head, and every flush and merge tries again.
TenureUnestablished bool
}
Stats is an in-memory snapshot of a record engine's state for introspection (no backend I/O).
type StreamCostOptions ¶ added in v0.37.0
type StreamCostOptions struct {
// GroupBy is the stream label (a resource or scope attribute name, e.g. "service.name") whose
// value keys the report. Empty groups by raw stream id. Grouping by label is the useful form:
// what an operator can act on is a service, and stream identity is a field policy that can
// change under them.
GroupBy string
// Columns restricts the byte columns that are decoded and attributed (nil ⇒ every byte column).
// The int columns and the timestamp are always accounted — they need no decode — so a narrowed
// request still reports complete row counts, and RawBytes/DiskBytes cover exactly the columns
// listed in each group's Columns.
Columns []string
// TopN keeps only the N costliest groups by RawBytes (≤0 ⇒ every group).
TopN int
// MaxSketchGroups bounds how many groups carry distinct estimates, which cost 8 KiB of sketch
// each for the duration of one column's pass (≤0 ⇒ [DefaultStreamCostSketchGroups]). The budget
// goes to the groups with the most rows; the rest report DistinctEstimated false.
MaxSketchGroups int
}
StreamCostOptions selects what Engine.StreamCost attributes and how much of it to estimate.
type StreamCostStat ¶ added in v0.37.0
type StreamCostStat struct {
Key string // the GroupBy label's value, or the stream id; empty ⇒ the label is absent
Streams int // distinct streams folded into this group
Rows int64
// RawBytes is the decoded footprint of the group's rows over the accounted columns.
RawBytes int64
// DiskBytes is APPROXIMATE. Compression is per column per frame and a frame spans whatever
// streams its rows fall in, so a group's compressed footprint is not directly measurable: each
// frame's compressed size is apportioned across the groups holding its rows by their raw-byte
// share. Rows are (stream, ts)-ordered, so most frames hold one stream and the estimate is
// close; a group narrower than a frame is the case where it is not.
DiskBytes int64
// DistinctEstimated reports whether the distinct counts below were computed for this group — see
// [StreamCostOptions.MaxSketchGroups]. False ⇒ Distinct/DistinctNormalized are 0, not zero.
DistinctEstimated bool
Columns []ColumnCostStat
}
StreamCostStat is one group's (one label value's, or one stream's) share of the engine's flushed parts. The head is not included — it holds no compressed bytes to attribute.
type ValuesRequest ¶ added in v0.42.0
ValuesRequest selects a distinct-value enumeration. Exactly one of Column (a byte column of the schema) and AttrKey (one key inside the serialized per-record attributes column) must be set. Start/End bound the window, a zero start AND end disabling the time filter; Limit ≤ 0 is unlimited.
Source Files
¶
- admission.go
- append.go
- blockid.go
- bloom.go
- budget.go
- bytecol.go
- cols.go
- compact.go
- engine.go
- fetchbudgeted.go
- fetchcond.go
- fetcheval.go
- fetchlazy.go
- fetchmemory.go
- flush.go
- granule.go
- head.go
- headreuse.go
- index.go
- introspect.go
- keys.go
- limitscan.go
- lost.go
- maintenance.go
- merge.go
- mergebound.go
- mergecap.go
- mergedecode.go
- mergefeedback.go
- mergeheap.go
- mergeshape.go
- mergesink.go
- mergesource.go
- mergewriter.go
- part.go
- partidentity.go
- prune.go
- range.go
- reclaim.go
- recompress.go
- recordkeys.go
- recs.go
- repair.go
- replicate.go
- retention.go
- retention_observe.go
- schema.go
- sidecarcache.go
- sidestore.go
- space.go
- streamcost.go
- timebucket.go
- values.go
- waldamage.go
- walenc.go
- wants.go