Documentation
¶
Overview ¶
Package block implements the L2 immutable columnar part format (DESIGN.md §3, §14 M1): per-column streams with min/max stats and constant-column collapse, a sparse granule mark index, and an atomic manifest written last. Not yet implemented (M1).
Index ¶
- Constants
- Variables
- func BindManifest(ctx context.Context, b backend.Backend, prefix string) ([32]byte, error)
- func DeletePart(ctx context.Context, b backend.Backend, prefix string) error
- func ManifestDigest(ctx context.Context, b backend.Backend, prefix string) ([32]byte, error)
- func NewFrameCompressor(alg compress.Algorithm, level compress.Level) *compress.Compressor
- func PartPresent(ctx context.Context, b backend.Backend, prefix string) (bool, error)
- func WritePart(ctx context.Context, b backend.Backend, prefix string, w *PartWriter) error
- func WriteStreamPart(ctx context.Context, b backend.Backend, prefix string, w *StreamWriter) error
- func WriteStreamPartWithScratch(ctx context.Context, b backend.Backend, prefix string, w *StreamWriter, ...) error
- type Binding
- type BytesObserver
- type Column
- type ColumnDesc
- type ColumnInputSize
- type ColumnReader
- func (r *ColumnReader) BlockDecoder() (*Decoder, error)
- func (r *ColumnReader) BlockRows() (int, error)
- func (r *ColumnReader) Blocked() bool
- func (r *ColumnReader) Bytes() (*chunk.DictColumn, error)
- func (r *ColumnReader) BytesRaw() (blob []byte, width int, err error)
- func (r *ColumnReader) Const() (any, bool)
- func (r *ColumnReader) DecodeBlocksBytes(blocks []int) (*chunk.DictColumn, error)
- func (r *ColumnReader) DecodeBlocksBytesIntoColumn(blocks []int) (*chunk.DictColumn, error)
- func (r *ColumnReader) DecodeBlocksFloat64(dst []float64, blocks []int) ([]float64, error)
- func (r *ColumnReader) DecodeBlocksInt64(dst []int64, blocks []int) ([]int64, error)
- func (r *ColumnReader) Float64(dst []float64) ([]float64, error)
- func (r *ColumnReader) FloatCursor() (chunk.FloatDecoder, error)
- func (r *ColumnReader) Frames() ([]FrameExtent, error)
- func (r *ColumnReader) ID128(dst []chunk.U128) ([]chunk.U128, error)
- func (r *ColumnReader) Int64(dst []int64) ([]int64, error)
- func (r *ColumnReader) Kind() Kind
- func (r *ColumnReader) Len() int
- func (r *ColumnReader) ObjectBytes() int64
- func (r *ColumnReader) RangeFloat64(dst []float64, lo, hi int) ([]float64, error)
- func (r *ColumnReader) RangeInt64(dst []int64, lo, hi int) ([]int64, error)
- func (r *ColumnReader) TsCursor() (chunk.TsCursor, error)
- type ColumnSizing
- type DecodedGranule
- type Decoder
- func (d *Decoder) BlockForRow(row int) (int, error)
- func (d *Decoder) BlockRows() int
- func (d *Decoder) BlockSpan(blk int) (lo, hi int)
- func (d *Decoder) BlockTimeBounds(b int) (int64, int64, bool)
- func (d *Decoder) Clone(ctx context.Context) *Decoder
- func (d *Decoder) Close() error
- func (d *Decoder) DecodeBytes(blocks []int) (*chunk.DictColumn, error)
- func (d *Decoder) DecodeBytesBlock(blk int) (DecodedGranule, error)
- func (d *Decoder) DecodeFixedBytesBlock(blk int) ([]byte, int, error)
- func (d *Decoder) DecodeFloat64(blk int) ([]float64, error)
- func (d *Decoder) DecodeFloat64Into(blk int, dst []float64) ([]float64, error)
- func (d *Decoder) DecodeInt64(blk int) ([]int64, error)
- func (d *Decoder) DecodeInt64Into(blk int, dst []int64) ([]int64, error)
- func (d *Decoder) EncodedGranule(blk int) (EncodedGranule, error)
- func (d *Decoder) FloatCursor() (chunk.FloatDecoder, error)
- func (d *Decoder) Int64Cursor(blk int) (chunk.TsCursor, error)
- func (d *Decoder) Int64StreamBound() (retained, transient int64, ok bool)
- func (d *Decoder) MetadataBytes() int64
- func (d *Decoder) NumBlocks() int
- func (d *Decoder) ResidentBytes() int64
- func (d *Decoder) SharedEntries() ([][]byte, DictGen)
- func (d *Decoder) TsCursor() (chunk.TsCursor, error)
- func (d *Decoder) VisitEncodedGranule(blk int, visit func(float64)) (EncodedGranule, error)
- type DictGen
- type EncodedGranule
- type FrameExtent
- type Granule
- type GranuleStats
- type Kind
- type Manifest
- type Marks
- type PartOption
- func WithCompressBlockBytes(n int) PartOption
- func WithCompression(alg compress.Algorithm) PartOption
- func WithCompressionLevel(level compress.Level) PartOption
- func WithCompressors(cs ...*compress.Compressor) PartOption
- func WithFrameCompressors(cs ...*compress.Compressor) PartOption
- func WithGranuleSize(n int) PartOption
- func WithIndependentGroups() PartOption
- func WithPrimarySeriesIndex() PartOption
- func WithRawFloatGroupSelection(rows int) PartOption
- func WithRollup(r Rollup) PartOption
- func WithSharedDictBytes(n int64) PartOption
- func WithSharedRowGroups() PartOption
- func WithSizingStats() PartOption
- func WithSortKey(name string) PartOption
- type PartReader
- func (r *PartReader) AcquireReaders()
- func (r *PartReader) Close() error
- func (r *PartReader) Column(ctx context.Context, name string) (*ColumnReader, error)
- func (r *PartReader) ColumnBlocks(ctx context.Context, name string) (*Decoder, error)
- func (r *PartReader) ColumnDescByName(name string) (ColumnDesc, bool)
- func (r *PartReader) ColumnInputSize(name string) (ColumnInputSize, error)
- func (r *PartReader) ColumnNames() []string
- func (r *PartReader) ColumnScan(ctx context.Context, name string, window int64) (*Decoder, error)
- func (r *PartReader) Int64ScanBound(ctx context.Context, name string) (retained, transient int64, ok bool)
- func (r *PartReader) Manifest() Manifest
- func (r *PartReader) ManifestDigest() [32]byte
- func (r *PartReader) Marks(ctx context.Context) (Marks, error)
- func (r *PartReader) OpenColumnScan(ctx context.Context, name string, window int64) (*Decoder, error)
- func (r *PartReader) ReaderContext(ctx context.Context) context.Context
- func (r *PartReader) ReleaseReaders()
- func (r *PartReader) ResidentBytes() int64
- func (r *PartReader) RowCount() int
- func (r *PartReader) ScanBound(ctx context.Context, name string, window int64) (steady, open int64, ok bool)
- type PartSizes
- type PartWriter
- type ReadOption
- type Rollup
- type RollupTier
- type StreamBuildScratch
- type StreamWriter
- func (w *StreamWriter) Abort()
- func (w *StreamWriter) AddColumn(c Column) error
- func (w *StreamWriter) AppendBytes(i int, vals [][]byte) error
- func (w *StreamWriter) AppendBytesBlob(i int, blob []byte, offsets []int32) error
- func (w *StreamWriter) AppendEncodedGranule(col int, g EncodedGranule, stats GranuleStats) error
- func (w *StreamWriter) AppendEncodedRun(tsCol, valueCol int, ts, value EncodedGranule, stats GranuleStats) error
- func (w *StreamWriter) AppendFloat64(i int, vals []float64) error
- func (w *StreamWriter) AppendFloat64Group(i int, vals []float64, begin bool) error
- func (w *StreamWriter) AppendInt64(i int, vals []int64) error
- func (w *StreamWriter) AppendU128Run(i int, v chunk.U128, count int) error
- func (w *StreamWriter) AppendU128RunView(i int, v chunk.U128, count int) ([]chunk.U128Run, error)
- func (w *StreamWriter) Binding(i int) (*Binding, error)
- func (w *StreamWriter) EncodedBytes() int64
- func (w *StreamWriter) EndGroup() error
- func (w *StreamWriter) FinishBytes() int64
- func (w *StreamWriter) Marks() Marks
- func (w *StreamWriter) OmitConstColumn(v float64) error
- func (w *StreamWriter) RequirePagedCoverage()
- func (w *StreamWriter) ReserveU128Runs(i, n int) error
- func (w *StreamWriter) ResidentBytes() int64
- func (w *StreamWriter) Rows() int
- func (w *StreamWriter) U128Runs(i int) ([]chunk.U128Run, error)
Constants ¶
DefaultSharedDictBytes is the cap WithSharedDictBytes defaults to. The cap charges each entry its bytes and more, so a dictionary's raw bytes never exceed it.
const MaxStreamBuildScratchBytes = 4 << 20
MaxStreamBuildScratchBytes bounds scratch retained after a completed write.
Variables ¶
var ErrCorrupt = errors.New("block: corrupt metadata")
ErrCorrupt is returned when a manifest (or any part metadata) fails to parse: bad magic, CRC mismatch, truncation, or an out-of-range field.
var ErrUnsupportedVersion = errors.Wrap(ErrCorrupt, "newer than this reader")
ErrUnsupportedVersion is returned (wrapped) for a manifest newer than this reader: an intact part written by a later release. It wraps ErrCorrupt, so callers that only fail on corruption still do.
Functions ¶
func BindManifest ¶ added in v0.55.0
BindManifest gives an unpublished part a persistent identity and returns its manifest digest. It must run before the enclosing engine publishes the part in its catalog.
func DeletePart ¶ added in v0.47.0
DeletePart removes every object under the part at prefix. The manifest goes first and durably, which retires the part in one directory sync: the rest are deleted deferred, and a power cut that brings any of them back leaves an orphan with no manifest, which no reader takes for a part and the open-time sweep removes.
func ManifestDigest ¶ added in v0.55.0
ManifestDigest reads a part manifest's content digest without opening its columns.
func NewFrameCompressor ¶ added in v0.49.0
NewFrameCompressor returns a compressor sized for the frames a writer seals at the default compression block size. A frame seals at the first granule that takes it past the block size, so it is the block plus at most one granule's stream; frameCompressorInput covers that for granule streams of up to 960 KiB, and a frame that fits compresses to the same bytes a default compressor's would.
func PartPresent ¶ added in v0.45.1
PartPresent reports whether the part at prefix still exists, by probing its manifest — the object OpenPart reads first and the commit point of a part write, so its absence is the part's absence. It is the liveness check for an already-open part, which needs no reopening but must still be noticed when its objects go away.
func WritePart ¶
WritePart serializes the writer's columns and writes the part's objects under prefix on b. Column and marks objects are written first; the manifest is written LAST so the part only becomes readable once fully committed. The objects are written deferred: the caller runs backend.SyncPrefix on prefix before anything durable names the part.
func WriteStreamPart ¶ added in v0.37.0
WriteStreamPart serializes w and writes the part under prefix on b, in the same order and under the same keys as WritePart — manifest last, so the part becomes readable only once committed, and deferred, so the caller runs backend.SyncPrefix on prefix before anything durable names it.
For a writer from NewStreamWriterTo, b and prefix must be the ones it was given: its column objects commit here, and only the marks and manifest are written from memory. A failure leaves the part uncommitted (no manifest) but may leave column objects behind, exactly as a failure partway through WritePart does.
func WriteStreamPartWithScratch ¶ added in v0.55.0
func WriteStreamPartWithScratch(ctx context.Context, b backend.Backend, prefix string, w *StreamWriter, scratch *StreamBuildScratch) error
WriteStreamPartWithScratch reuses caller-owned metadata buffers while writing w. scratch must not be shared by concurrent writes; nil uses temporary buffers.
Types ¶
type Binding ¶ added in v0.49.0
type Binding struct {
// contains filtered or unexported fields
}
Binding appends a source column's dictionary-encoded rows to one StreamWriter bytes column without hashing a value per row: it caches, per entry of the table it is bound to, where that entry sits in the granule being staged and in the column dictionary.
A binding belongs to its writer and dies with it; it is not safe for concurrent use.
func (*Binding) AppendDict ¶ added in v0.49.0
func (b *Binding) AppendDict(g DecodedGranule, lo, hi int, keep []bool) error
AppendDict appends rows [lo,hi) of g, those keep marks when keep is non-nil (keep[j] for row lo+j), to the bound column. g's table must be the bound one, and g must still be live: a granule a later decode may have overwritten is refused.
func (*Binding) Bind ¶ added in v0.49.0
Bind points b at entries, named by gen. The writer copies each value it keeps, so entries need stay valid only until the next Bind.
func (*Binding) BindStable ¶ added in v0.49.0
BindStable is Binding.Bind over entries that are never overwritten, which the writer keeps by reference instead of copying: a decoder's shared dictionary, valid for the decoder's life, or a caller's own table. A self-granule table aliases a reused frame and is refused.
type BytesObserver ¶ added in v0.49.0
type BytesObserver interface {
// SelfGranule reports a granule that self-encoded rather than join the column dictionary: its
// distinct values and how many of its rows hold each.
SelfGranule(values [][]byte, counts []uint64)
// Dictionary reports the column dictionary and each entry's row count, once per column written
// with an object, before that object is committed. A column that collapses to a constant gets no
// call, though a streaming writer may already have reported its granules.
Dictionary(entries [][]byte, counts []uint64)
}
BytesObserver sees the values a writer encodes into a dictionary bytes column (Column.Observer): each declined granule's distinct values, then the column dictionary. Every value is reported at least once and the counts over all calls sum to the column's rows, so a consumer must be set-semantic.
Calls are synchronous, on the goroutine driving the writer, and stop at Abort. Slices alias writer memory and are valid only during the call.
type Column ¶
type Column struct {
Name string
Kind Kind
Int64 []int64
Float64 []float64
Bytes [][]byte
Int128 []chunk.U128
Codec chunk.Codec
Compress compress.Algorithm
// BytesBlob/BytesOffsets are the blob+offsets alternative to Bytes for a KindBytes column:
// cell i is BytesBlob[BytesOffsets[i]:BytesOffsets[i+1]], with len(BytesOffsets) == rows+1 —
// the head-buffer byte-column layout, accepted directly so a flush encodes straight from the
// blob without materializing a [][]byte view per row. Offsets index the whole blob and need not
// start at 0, so a row range of a larger column is a valid input. Used only when
// Bytes is nil; the encoded object is byte-identical to the equivalent Bytes input.
BytesBlob []byte
BytesOffsets []int32
// BytesDict/BytesIDs are the split (dictionary) alternative to Bytes for a KindBytes column:
// cell i is BytesDict[BytesIDs[i]] — the shape a merge already holds when it reads a
// dictionary-encoded byte column, accepted directly so the writers build their dictionaries by
// remapping entry indices instead of re-hashing every row. Used only when Bytes is nil and
// BytesOffsets is empty; the encoded object is byte-identical to the equivalent Bytes input.
//
// BytesDict must be distinct by value: the encoders deduplicate by index, so two entries holding
// equal bytes yield two dictionary entries — a valid stream, but not the same one. Only
// [chunk.CodecDict] accepts this form.
BytesDict [][]byte
BytesIDs []int32
// AutoCodec, when set on a float64 column with no explicit Codec, picks the smaller of the
// lossless float codecs (Gorilla XOR vs scaled-decimal+delta) by trial-encoding — so an
// integer-valued or low-precision column (e.g. a counter) takes the far denser decimal path
// while a high-entropy column keeps Gorilla. Lossless either way (see [chooseFloatCodec]).
AutoCodec bool
// FloatGroupEnds gives increasing group ends for [chunk.CodecFloatGroups], ending at the row count.
FloatGroupEnds []int
// FloatPrecisionBits, when in 1..63 on an AutoCodec float column, requests *lossy* encoding:
// the scaled-decimal codec retains only this many significant mantissa bits (fewer ⇒ denser,
// less accurate), competing against lossless Gorilla so the result is never worse than
// lossless. 0 (or ≥64) means lossless. The budget is recorded in the descriptor so the merge
// engine reaches a fixed point (it never re-applies a budget it has already met). Set per age
// tier by the merge engine so only old data trades accuracy for size.
FloatPrecisionBits uint8
// Block requests block-framed encoding: the column is split into blockRows-row blocks (the
// part's granule size), each an independent codec stream, so a reader can decode one block at a
// time (sub-part seek). Only the per-row sequential codecs (DoD/T64 int64, Gorilla/decimal
// float64) are blockable — the metric ts/value/sf columns. The zero value keeps the prior
// single-stream layout. See blockcolumn.go.
Block bool
// RawFallback keeps a framed byte column seekable when no granule can use the shared dictionary.
// Applies to dictionary byte columns supplied as rows or a blob.
RawFallback bool
// Observer, when set, is told the values the writer encodes. Valid only on a block-framed
// [KindBytes] [chunk.CodecDict] column.
Observer BytesObserver
}
Column is an input column for a part: a name, a physical Kind, and the matching typed slice (exactly one of Int64/Float64/Bytes per Kind). Codec and Compress are optional overrides; the zero values select the per-kind default codec and no block compression (the chunk codecs already compress well).
type ColumnDesc ¶
type ColumnDesc struct {
Name string
Kind Kind
Codec chunk.Codec
Compress compress.Algorithm
Const bool
// Constant value, set iff Const, by Kind.
ConstInt64 int64
ConstFloat64 float64
ConstBytes []byte
// Numeric min/max (KindInt64/KindFloat64). Unused for KindBytes.
MinInt64, MaxInt64 int64
MinFloat64, MaxFloat64 float64
// FloatPrecisionBits is the lossy precision budget a float column was encoded under (the
// significant mantissa bits retained): 0 ⇒ lossless. Persisted only when non-zero (a
// flag-gated byte), so lossless parts keep their byte-for-byte layout. The merge engine reads
// it as the fixed point for age-tiered precision — it never re-coarsens a part already at or
// below the target budget.
FloatPrecisionBits uint8
// Blocked marks a block-framed column: its object is a [blockDir] + per-block codec streams
// (see blockcolumn.go) instead of a single stream, so a reader can decode one block at a time.
// Persisted via [flagBlocked]; clear on the prior single-stream layout.
Blocked bool
// MaxBlockRows caps variable numeric chunks; zero selects fixed granules.
MaxBlockRows int
SharedRows bool
// TimeBounds records per-chunk int64 bounds in the variable directory.
TimeBounds bool
// Framed marks a blocked column written with the frame-packed directory, where a compression
// frame spans several decode granules so the compressor sees more than one granule of context.
// Persisted via [flagFramed]; clear on the older one-block-per-granule layout, which is still
// read. Set by the writer on every blocked column it produces.
Framed bool
// ahead of its frames, each granule holding ids into it or self-encoding. Persisted via
// [flagSharedDict].
SharedDict bool
// layout a streaming writer emits (see [flagFooter]). Persisted via [flagFooter]; clear on a
// column written whole, which keeps the directory-first layout byte for byte.
Footer bool
// Bytes is the size of the column's backend object, 0 when unknown (a constant column has no
// object, and a part written before [flagBytes] existed did not record one). Persisted only when
// non-zero. It exists so opening a column for ranged reads costs no round trip of its own.
Bytes int64
// Checked reports that the column's object carries CRC32C checksums over its data — per
// compression frame for a framed column, a trailing one over the whole object otherwise — which
// the read path verifies. It is not a persisted field of its own: it follows from the enclosing
// manifest's version, and the writer sets it on every column it produces.
Checked bool
// Level is the compression level the column's data was written at (0 ⇒ the algorithm default, or
// no compression). Persisted only when non-zero, via [flagLevel]. Decode ignores it; the merge
// engine reads it as the fixed point of the compression ladder.
Level compress.Level
// TrailerDict marks a [ColumnDesc.SharedDict] column laid out as frames, then its dictionary,
// then its footer directory. DictOff and DictLen locate the dictionary region, DictRaw is its
// decompressed size and DictEntries its entry count; all four are zero otherwise.
TrailerDict bool
DictOff, DictLen, DictRaw, DictEntries int64
// CompactDir stores a bounded compressed directory for independent numeric chunks.
CompactDir bool
// HasSizing reports that Sizing is set, which a writer given [WithSizingStats] does for every
// column with an object.
HasSizing bool
Sizing ColumnSizing
}
ColumnDesc describes one column in a part: its identity, codecs, constant value (if collapsed), and numeric min/max stats. Data offsets are absent — each column is its own backend object keyed by ordinal (DESIGN.md §14 M1 multi-key layout).
type ColumnInputSize ¶ added in v0.49.0
type ColumnInputSize struct {
// Resident is held for the whole walk: a shared dictionary, or the column decoded when it is
// read whole.
Resident int64
DictEntries int64
MaxFrameBytes int64
MaxFrameRaw int64
MaxGranuleRaw int64
// DirBytes bounds the parsed directory; constant geometry can use less.
DirBytes int64
// OpenBytes bounds transient bytes held while the column opens, including directory decompression.
OpenBytes int64
// WholeResident is the decoded footprint of the column read whole.
WholeResident int64
// WholeRead reports that the column can only be read whole: it is unframed, or its manifest
// records no sizing.
WholeRead bool
// SourceWide reports that Resident and WholeResident charge the whole part rather than this
// column, so a caller charges them once per part: a part without sizing is bounded only by its
// RawBytes.
SourceWide bool
}
ColumnInputSize is what reading one column of a part holds, derived from the manifest alone so a merge can be sized before it reads anything. Fields saturate at MaxInt64; a part whose manifest cannot bound its columns reports a saturated Resident and so never fits a budget.
type ColumnReader ¶
type ColumnReader struct {
// contains filtered or unexported fields
}
ColumnReader gives lazy, decode-on-demand access to one column of a part. Constant columns are synthesized from the manifest with no I/O; other columns are decompressed and decoded only when an accessor is called (DESIGN.md §7: decode only what the query touches). It is created by PartReader.Column.
func (*ColumnReader) BlockDecoder ¶ added in v0.20.0
func (r *ColumnReader) BlockDecoder() (*Decoder, error)
BlockDecoder returns a per-block decoder over a blocked column (parsing the directory once), for a caller that decodes individual blocks. It errors on an unblocked column.
func (*ColumnReader) BlockRows ¶ added in v0.20.0
func (r *ColumnReader) BlockRows() (int, error)
BlockRows returns the column's block size in rows, or 0 for an unblocked column.
func (*ColumnReader) Blocked ¶ added in v0.20.0
func (r *ColumnReader) Blocked() bool
Blocked reports whether the column is block-framed (and so supports DecodeBlocks*/BlockRows).
func (*ColumnReader) Bytes ¶
func (r *ColumnReader) Bytes() (*chunk.DictColumn, error)
Bytes decodes the column into its split chunk.DictColumn form (unique entries + a per-row id array), deferring the per-row gather to chunk.DictColumn.At. A constant column is synthesized as a single-entry dictionary. It errors if the column is not KindBytes.
func (*ColumnReader) BytesRaw ¶ added in v0.32.0
func (r *ColumnReader) BytesRaw() (blob []byte, width int, err error)
BytesRaw decodes a chunk.CodecBytesRaw-encoded KindBytes column into its flat fixed-width form: the contiguous rows×width blob and width, with no per-row [][]byte headers built over it (unlike ColumnReader.Bytes) — the shape a stride/SIMD equality scan (e.g. github.com/oteldb/storage/internal/simd.EqualFixed16) operates on directly. It errors if the column is not KindBytes, its codec is not chunk.CodecBytesRaw, or it is block-framed (no blocked encoder exists yet for byte columns — see ColumnReader.DecodeBlocksInt64 for the int64/float64 precedent this would follow).
func (*ColumnReader) Const ¶
func (r *ColumnReader) Const() (any, bool)
Const returns the column's constant value (int64/float64/[]byte per Kind) and true if the column was constant-collapsed; otherwise (nil, false).
func (*ColumnReader) DecodeBlocksBytes ¶ added in v0.37.0
func (r *ColumnReader) DecodeBlocksBytes(blocks []int) (*chunk.DictColumn, error)
DecodeBlocksBytes decodes only the named granules of a block-framed bytes column, merged into one chunk.DictColumn over their concatenated rows. It is the bytes counterpart of ColumnReader.DecodeBlocksInt64 — the seek primitive a time-pruned query uses to read a fraction of a column instead of all of it.
The returned column covers the selected rows *packed together*, not their positions in the part. Use ColumnReader.DecodeBlocksBytesIntoColumn when part row indices must stay valid.
func (*ColumnReader) DecodeBlocksBytesIntoColumn ¶ added in v0.37.0
func (r *ColumnReader) DecodeBlocksBytesIntoColumn(blocks []int) (*chunk.DictColumn, error)
DecodeBlocksBytesIntoColumn decodes the named granules into a column spanning *every* row of the part, each granule at its own row offset.
Unlike ColumnReader.DecodeBlocksBytes, which packs the selection, this keeps part row indices valid — the property the int64 path gets for free by decoding into the destination at absolute offsets. A fetch that located its rows through the part's row-range index and its marks can then prune the decode without renumbering anything it already resolved.
Rows outside the selected granules hold an **unspecified** value: the caller asked for these granules and reads only their rows. This matches ColumnReader.DecodeBlocksInt64, where unselected rows keep whatever the destination held. Zeroing them would cost a pass over the rows the pruning exists to avoid touching.
func (*ColumnReader) DecodeBlocksFloat64 ¶ added in v0.20.0
func (r *ColumnReader) DecodeBlocksFloat64(dst []float64, blocks []int) ([]float64, error)
DecodeBlocksFloat64 is the float64 analog of ColumnReader.DecodeBlocksInt64.
func (*ColumnReader) DecodeBlocksInt64 ¶ added in v0.20.0
func (r *ColumnReader) DecodeBlocksInt64(dst []int64, blocks []int) ([]int64, error)
DecodeBlocksInt64 decodes only the given block indices of a blocked column into dst (reused), and returns a full-length (Len()) slice with those blocks' row spans populated — the rest of dst is left as-is (a caller reads only the rows it selected, which fall in the requested blocks). An unblocked/const column has no blocks to skip, so it decodes whole. blocks must be in range.
func (*ColumnReader) Float64 ¶
func (r *ColumnReader) Float64(dst []float64) ([]float64, error)
Float64 decodes the column into dst (reusing its capacity) and returns the result. It errors if the column is not KindFloat64.
func (*ColumnReader) FloatCursor ¶ added in v0.15.0
func (r *ColumnReader) FloatCursor() (chunk.FloatDecoder, error)
FloatCursor returns a forward cursor over a KindFloat64 column (Gorilla or scaled-decimal). A constant-collapsed column yields a repeating cursor. It is the streaming-merge form of Float64.
func (*ColumnReader) Frames ¶ added in v0.37.0
func (r *ColumnReader) Frames() ([]FrameExtent, error)
Frames maps the column's rows onto its compression frames. A frame is the unit compression is applied to, so it is the finest granularity at which a caller can attribute a column's *compressed* bytes to a subset of its rows — nothing below it is separable, since the entropy coder shares state across the whole frame.
A column that is not block-framed (constant, or written as one stream) reports a single extent covering every row and the whole object. The extents' Bytes sum to the frames' bytes, which is less than ColumnReader.ObjectBytes by the directory (and, for a shared-dictionary column, by the dictionary) — neither belongs to any single frame.
func (*ColumnReader) ID128 ¶
ID128 decodes the column into dst (reusing its capacity) and returns the result. It errors if the column is not KindInt128. Id columns are never constant-collapsed, so the value always comes from the decoded RLE stream.
func (*ColumnReader) Int64 ¶
func (r *ColumnReader) Int64(dst []int64) ([]int64, error)
Int64 decodes the column into dst (reusing its capacity) and returns the result. It errors if the column is not KindInt64.
func (*ColumnReader) Kind ¶
func (r *ColumnReader) Kind() Kind
Kind reports the column's physical type.
func (*ColumnReader) ObjectBytes ¶ added in v0.37.0
func (r *ColumnReader) ObjectBytes() int64
ObjectBytes is the column object's size as stored on the backend, 0 for a constant column (which has no object).
func (*ColumnReader) RangeFloat64 ¶ added in v0.20.0
func (r *ColumnReader) RangeFloat64(dst []float64, lo, hi int) ([]float64, error)
RangeFloat64 decodes only rows [lo,hi) of a float64 column. See ColumnReader.RangeInt64.
func (*ColumnReader) RangeInt64 ¶ added in v0.20.0
func (r *ColumnReader) RangeInt64(dst []int64, lo, hi int) ([]int64, error)
RangeInt64 decodes only rows [lo,hi) of an int64 column into a buffer reusing dst's capacity. For a blocked column it decodes just the blocks spanning the range (sub-part seek); for an unblocked one it decodes the whole column and slices, so callers get a uniform seek API regardless of layout. Requires 0 ≤ lo < hi ≤ Len().
func (*ColumnReader) TsCursor ¶ added in v0.15.0
func (r *ColumnReader) TsCursor() (chunk.TsCursor, error)
TsCursor returns a forward cursor over a KindInt64 timestamp column (delta-of-delta). A constant-collapsed column yields a repeating cursor. It is the streaming-merge form of Int64: same decode, but one row at a time so a merge holds only one series range resident per part.
type ColumnSizing ¶ added in v0.49.0
type ColumnSizing struct {
// DirLen is the directory's encoded length, its checksum included and a footer's length word
// excluded.
DirLen int64
NumGranules int64
NumFrames int64
// MaxFrameBytes is the largest compressed frame; MaxFrameRaw the largest decompressed one.
MaxFrameBytes int64
MaxFrameRaw int64
MaxGranuleRaw int64
// StreamRaw is the granule streams' total, or an unframed column's decompressed stream.
StreamRaw int64
}
ColumnSizing is what bounds a column's decode, recorded so a merge can be sized from the manifest alone. An unframed column sets only StreamRaw. Readers verify it against the directory, so a manifest cannot understate the column it describes.
type DecodedGranule ¶ added in v0.49.0
type DecodedGranule struct {
// contains filtered or unexported fields
}
DecodedGranule is one decoded bytes granule together with what it indexes and whether it is still intact. The three are inseparable: a Binding takes the granule whole, so a column cannot be paired with another decode's validity. The zero value is not live.
func OwnedGranule ¶ added in v0.49.0
func OwnedGranule(dc *chunk.DictColumn, table DictGen) DecodedGranule
OwnedGranule wraps a column the caller built itself over a table named by NewDictGen, which stays valid while that table does. A token from a Decoder yields a granule that is never live: a decoder's columns come only from Decoder.DecodeBytesBlock.
func (DecodedGranule) Column ¶ added in v0.49.0
func (g DecodedGranule) Column() chunk.DictColumn
Column returns a copy of the decoded column's header; its slices alias the decoder's frame, so it is valid only while the granule is live. Being a copy, changing it cannot change what a Binding reads from g.
func (DecodedGranule) Table ¶ added in v0.49.0
func (g DecodedGranule) Table() DictGen
Table returns the token naming the entry table the column's ids index.
type Decoder ¶ added in v0.20.0
type Decoder struct {
// contains filtered or unexported fields
}
Decoder decodes individual blocks of a blocked column, parsing the directory once so a caller that decodes several blocks (e.g. a per-block cache filling its misses) does not re-parse it per block. Obtain one via [ColumnReader.Decoder]; it holds the column's already-read object.
func (*Decoder) BlockForRow ¶ added in v0.52.0
BlockForRow returns the chunk containing row.
func (*Decoder) BlockRows ¶ added in v0.20.0
BlockRows returns the column's nominal block size in rows.
func (*Decoder) BlockSpan ¶ added in v0.20.0
BlockSpan returns block blk's half-open row range [lo, hi) in the column.
func (*Decoder) BlockTimeBounds ¶ added in v0.52.0
BlockTimeBounds returns independently checked int64 chunk bounds when recorded.
func (*Decoder) Clone ¶ added in v0.50.2
Clone shares immutable metadata and creates independent decode state. Frame reads use ctx.
func (*Decoder) Close ¶ added in v0.53.1
Close releases an opened scan's handle and buffer; decoded views must no longer be used.
func (*Decoder) DecodeBytes ¶ added in v0.48.0
func (d *Decoder) DecodeBytes(blocks []int) (*chunk.DictColumn, error)
DecodeBytes decodes the named blocks of a bytes column, in ascending order, merged into one chunk.DictColumn over their concatenated rows; a nil selection decodes the whole column.
It takes a block set rather than a single block because each granule may carry its own dictionary, so ids only become comparable once chunk.DictMerger has remapped them into a shared one — the same reason ColumnReader.DecodeBlocksBytes has this shape and the int64/float64 paths do not.
func (*Decoder) DecodeBytesBlock ¶ added in v0.48.0
func (d *Decoder) DecodeBytesBlock(blk int) (DecodedGranule, error)
DecodeBytesBlock decodes one granule of a bytes column against the decoder's cached frame, which is what a forward walk wants: Decoder.DecodeBytes takes a block set because it merges their dictionaries, and merging is exactly what a caller consuming one granule at a time does not need.
The result **aliases the decoder's frame buffer** and is valid only until the next decode. That is the point — a merge reads a granule's ids and appends them, so copying every value to hand it back would be the per-row cost this path exists to avoid. A caller that retains the column past its next call must copy it.
For a granule on the column's shared dictionary the result carries that dictionary and the granule's ids unchanged, so its entries are the column's, not the granule's, and the token is the one Decoder.SharedEntries returns. Any other granule gets a token that dies at the next decode. The granule itself, whose ids alias the frame in either case, dies at the next decode too.
func (*Decoder) DecodeFixedBytesBlock ¶ added in v0.56.0
DecodeFixedBytesBlock returns a fixed-width raw granule without constructing byte views. The blob aliases the current frame and expires on the next decode. A variable-width granule returns a zero width, and can be read with Decoder.DecodeBytesBlock.
func (*Decoder) DecodeFloat64 ¶ added in v0.20.0
DecodeFloat64 decodes block blk into a fresh slice (for a float64 column).
func (*Decoder) DecodeFloat64Into ¶ added in v0.23.0
DecodeFloat64Into is the float64 analog of Decoder.DecodeInt64Into.
func (*Decoder) DecodeInt64 ¶ added in v0.20.0
DecodeInt64 decodes block blk into a fresh slice (for an int64 column).
func (*Decoder) DecodeInt64Into ¶ added in v0.23.0
DecodeInt64Into decodes block blk into dst (for an int64 column), reusing dst's backing array when it has room for the block's rows — so a caller drawing dst from a pool decodes without allocating the output. Passing a nil dst is equivalent to Decoder.DecodeInt64.
func (*Decoder) EncodedGranule ¶ added in v0.55.0
func (d *Decoder) EncodedGranule(blk int) (EncodedGranule, error)
EncodedGranule reads one checked independent granule without materializing its samples.
func (*Decoder) FloatCursor ¶ added in v0.49.0
func (d *Decoder) FloatCursor() (chunk.FloatDecoder, error)
FloatCursor is the float64 analog of Decoder.TsCursor.
func (*Decoder) Int64Cursor ¶ added in v0.51.0
Int64Cursor reads one granule; its bytes remain valid until the decoder opens another granule.
func (*Decoder) Int64StreamBound ¶ added in v0.51.0
Int64StreamBound recovers PartReader.Int64ScanBound for ranged decoders; whole-object decoders are unsupported.
func (*Decoder) MetadataBytes ¶ added in v0.50.2
MetadataBytes estimates retained directory and dictionary bytes, excluding decode scratch.
func (*Decoder) ResidentBytes ¶ added in v0.49.0
ResidentBytes bounds what a forward walk over the decoder holds at any point: the directory and shared dictionary, the read-ahead window (or the object, when the column was read whole), the decompressed frame buffer twice over while a larger frame replaces it, and one decoded granule. It is fixed when the decoder opens, so a caller may charge it before the walk touches a frame.
func (*Decoder) SharedEntries ¶ added in v0.48.0
SharedEntries returns the column's shared dictionary, nil for a column without one, and the one token that names it for the decoder's life. The entries are read-only and shared with every column this decoder produces.
func (*Decoder) TsCursor ¶ added in v0.49.0
TsCursor returns a forward cursor over an int64 timestamp column, walking its granules in order. It is ColumnReader.TsCursor over this decoder's frames, so under PartReader.ColumnScan a merge holds one read-ahead window of the column rather than its object.
func (*Decoder) VisitEncodedGranule ¶ added in v0.55.0
func (d *Decoder) VisitEncodedGranule(blk int, visit func(float64)) (EncodedGranule, error)
VisitEncodedGranule validates a borrowed stream and visits its float values in row order. A callback may observe a prefix before malformed input is rejected.
type DictGen ¶ added in v0.49.0
type DictGen struct {
// contains filtered or unexported fields
}
DictGen names one decoded dictionary table, so a Binding can tell the table it was bound to from any other. A token is scoped to its owner — a Decoder, or a table built by the caller — so two owners never produce equal tokens. The zero value is invalid.
A token also says whether its table is still intact. A decoder's shared-dictionary token lives as long as the decoder. A self-granule table aliases the decoder's frame buffer, so its token dies at the decoder's next decode, and a Binding refuses it from then on.
func NewDictGen ¶ added in v0.49.0
func NewDictGen() DictGen
NewDictGen mints a token for a table the caller builds itself and keeps intact while bound.
type EncodedGranule ¶ added in v0.55.0
type EncodedGranule struct {
Data []byte
Kind Kind
Codec chunk.Codec
Rows int
MinTime, MaxTime int64
Ordered bool
// contains filtered or unexported fields
}
EncodedGranule borrows a validated numeric stream until its decoder's next operation. Data is read-only; metadata must remain unchanged until appended.
func (EncodedGranule) FloatStats ¶ added in v0.55.0
func (g EncodedGranule) FloatStats() GranuleStats
FloatStats returns the validated granule's float bounds, ignoring NaN values.
type FrameExtent ¶ added in v0.37.0
type FrameExtent struct {
StartRow int // inclusive
EndRow int // exclusive
Bytes int64 // compressed size of the frame
}
FrameExtent is one compression frame of a column: the row span it covers and the compressed byte span it occupies in the column object.
type Granule ¶
Granule is one entry of the sparse mark index: the first row of a fixed-size run of rows, plus the min/max of the part's sort-key column over that run. The min/max let a query prune whole granules whose key range cannot intersect its window (_ref/docs/storage-engine.md §2, ClickHouse marks / Parquet row-group stats).
type GranuleStats ¶ added in v0.55.0
type GranuleStats struct {
MinFloat64, MaxFloat64 float64
}
GranuleStats supplies trusted bounds for encoded float values.
type Kind ¶
type Kind uint8
Kind is the physical type of a column's values (DESIGN.md §6). It selects which typed slice a Column carries and which codec family applies. Values are persisted in the manifest; never reorder.
const ( // KindInt64 is an int64 column (timestamps, counters, series ids). KindInt64 Kind = iota // KindFloat64 is a float64 column (gauge/sum values). KindFloat64 // KindBytes is a []byte column (low-cardinality attributes, strings). KindBytes // KindInt128 is a 128-bit id column ([chunk.U128]), e.g. the SeriesID sort key of a // metric part. RLE-coded; carries no min/max or constant value in the manifest. KindInt128 )
type Manifest ¶
type Manifest struct {
Version uint32
RowCount int
MinTime int64
MaxTime int64
GranuleSize int
Columns []ColumnDesc
// DiskBytes is the encoded size of the part's column and marks objects, excluding the manifest
// itself (which cannot size itself) and the engine's sidecars. The merge cap is denominated in
// it, so the cap means bytes on disk rather than a row estimate.
//
// Trailing, so a manifest without it reads as 0 and an older reader ignores it.
DiskBytes int64
// RawBytes is the part's *decoded* footprint: the bytes its column values occupy in memory,
// which is what a merge's working set is made of. DiskBytes cannot stand in for it — the ratio
// between them is the compression ratio, which varies per column and per dataset — so a merge
// bounded by memory is denominated in this instead.
//
// Trailing, like DiskBytes, and 0 in a manifest written before it existed.
RawBytes int64
// Rollup is the downsampling layout the part's rows have had applied. nil is unknown: what a
// manifest without it, or with a malformed one, decodes to. Trailing, after RawBytes.
Rollup *Rollup
// BindingNonce distinguishes immutable part instances with otherwise identical descriptors.
BindingNonce [16]byte
}
Manifest is the part descriptor: format version, row count, time range, granule size, and the per-column descriptors. It is serialized to the `{prefix}/manifest` object, CRC32C-checked, and written last to commit the part.
func DecodeManifest ¶
DecodeManifest parses a manifest object. It verifies the CRC and bounds-checks every field, returning an ErrCorrupt-wrapping error on any malformed input — it never panics, so it is safe to fuzz on arbitrary bytes.
func (Manifest) Encode ¶
Encode appends the binary manifest to dst and returns the extended slice. Layout:
[u32 magic][uvarint version][uvarint rowCount][varint minTime][varint maxTime]
[uvarint granuleSize][uvarint colCount]
per column: [uvarint nameLen][name][byte kind][byte codec][byte compress][byte flags]
[byte xflags if version ≥ 3]
[byte precisionBits if flagLossy][byte level if flagLevel]
[uvarint objectBytes if flagBytes]
[uvarint dictOff, dictLen, dictRaw, dictEntries if xTrailerDict]
[uvarint the seven ColumnSizing fields, in declaration order, if xSizing]
[numeric min/max per kind][const value per kind if flagConst]
[uvarint diskBytes][uvarint rawBytes]
[uvarint n][n × (varint before, uvarint interval, byte agg)] if Rollup != nil
[u32 CRC32C over all the above]
func (Manifest) RequiresSeriesIndex ¶ added in v0.56.0
RequiresSeriesIndex reports whether a primary series index supplies the part's series row ranges.
type Marks ¶
Marks is the sparse granule index for a part: granules of GranuleSize rows over the sort-key column (timestamp for the metrics vertical). It is serialized to the `{prefix}/marks` object.
func BuildMarks ¶
BuildMarks computes the sparse index over a sort-key column, chunked into granules of granuleSize rows. The min/max are computed by scanning each granule, so correctness does not depend on sortKey being sorted (though for the metrics vertical it is). granuleSize must be > 0.
func DecodeMarks ¶
DecodeMarks parses a marks object. It verifies the CRC and bounds-checks every field, returning an ErrCorrupt-wrapping error on malformed input; it never panics.
func (Marks) Encode ¶
Encode appends the binary marks index to dst. Layout:
[u32 magic][uvarint version][uvarint granuleSize][uvarint count] per granule: [uvarint firstRow][varint minKey-prevMinKey][varint maxKey-minKey] [u32 CRC32C]
Keys are delta-encoded across granules (sort key is non-decreasing) for compactness.
func (Marks) Overlapping ¶
Overlapping returns the granules whose [MinKey, MaxKey] range intersects the inclusive window [lo, hi]. It is the pruning primitive the fetcher (M3) uses to skip granules.
type PartOption ¶
type PartOption func(*partConfig)
PartOption configures a PartWriter or a StreamWriter.
func WithCompressBlockBytes ¶ added in v0.37.0
func WithCompressBlockBytes(n int) PartOption
WithCompressBlockBytes sets the minimum uncompressed bytes packed into one compression frame of a block-framed column (default [defaultCompressBlockBytes]). It decouples the compression unit from the decode granule (WithGranuleSize): a granule stays the smallest decodable slice, while a frame gathers enough consecutive granules to give the compressor real context. Decode-compatible either way — the directory records the packing.
func WithCompression ¶
func WithCompression(alg compress.Algorithm) PartOption
WithCompression sets the default block-compression algorithm for columns that do not set Column.Compress (default none — the chunk codecs already compress well).
func WithCompressionLevel ¶ added in v0.4.0
func WithCompressionLevel(level compress.Level) PartOption
WithCompressionLevel sets the compression level used by the block compressors (default compress.LevelDefault). It is decode-irrelevant — the reader reconstructs the decompressor from the per-column algorithm recorded in the manifest, regardless of the level data was written at — so a merge can rewrite cold parts at a higher ratio with no format change.
func WithCompressors ¶ added in v0.49.0
func WithCompressors(cs ...*compress.Compressor) PartOption
WithCompressors makes the writer compress through cs, where one matches a column's algorithm and the writer's level, instead of a compressor of its own — so writers open at once share one set of pooled encoders. A zstd encoder at the best level holds tens of MiB while its pool keeps it.
func WithFrameCompressors ¶ added in v0.49.0
func WithFrameCompressors(cs ...*compress.Compressor) PartOption
WithFrameCompressors makes a StreamWriter compress its columns' frames through cs, where one matches a column's algorithm and the writer's level; whole objects — a dictionary region, a column written unframed — still go through WithCompressors or the writer's own. A frame is bounded where those are not, so its encoder can be sized for it (NewFrameCompressor).
func WithGranuleSize ¶
func WithGranuleSize(n int) PartOption
WithGranuleSize sets the sparse-index granularity in rows (default 8192).
func WithIndependentGroups ¶ added in v0.52.0
func WithIndependentGroups() PartOption
WithIndependentGroups makes streaming numeric groups independently readable. Call StreamWriter.EndGroup between groups.
func WithPrimarySeriesIndex ¶ added in v0.56.0
func WithPrimarySeriesIndex() PartOption
WithPrimarySeriesIndex uses a manifest version that requires a separate series index.
func WithRawFloatGroupSelection ¶ added in v0.56.0
func WithRawFloatGroupSelection(rows int) PartOption
WithRawFloatGroupSelection uses raw encoded sizes for independent float groups up to rows. Each candidate still has to preserve the input float bits.
func WithRollup ¶ added in v0.49.0
func WithRollup(r Rollup) PartOption
WithRollup records r as the downsampling layout the part's rows were written under (Manifest.Rollup). Without it the manifest carries none and reads as unknown.
func WithSharedDictBytes ¶ added in v0.49.0
func WithSharedDictBytes(n int64) PartOption
WithSharedDictBytes caps the resident size of a bytes column's shared dictionary: its entries' bytes plus a fixed per-entry overhead (default 32 MiB). A granule whose new values would pass the cap self-encodes instead of joining. n is clamped to [0, 64 MiB], the format's ceiling.
func WithSharedRowGroups ¶ added in v0.56.0
func WithSharedRowGroups() PartOption
WithSharedRowGroups marks variable numeric chunks as covering multiple logical row groups.
func WithSizingStats ¶ added in v0.49.0
func WithSizingStats() PartOption
WithSizingStats records ColumnSizing for every column with an object, so a merge can bound its memory from the manifest alone. A part carrying it needs a manifest version-3 reader.
func WithSortKey ¶
func WithSortKey(name string) PartOption
WithSortKey names the int64 column that the marks index and time range are built over. If unset, the first int64 column is used.
type PartReader ¶
type PartReader struct {
// contains filtered or unexported fields
}
PartReader reads a part written by WritePart. It loads only the manifest up front; columns and marks are read lazily, so a query touches only the objects it references (DESIGN.md §7).
func OpenPart ¶
func OpenPart(ctx context.Context, b backend.Backend, prefix string, opts ...ReadOption) (*PartReader, error)
OpenPart reads a part's manifest from b under prefix and returns a reader. It returns an error (wrapping ErrCorrupt or backend.ErrNotExist) if the manifest is absent or malformed — an incompletely written part (no manifest) is therefore not readable.
func (*PartReader) AcquireReaders ¶ added in v0.54.0
func (r *PartReader) AcquireReaders()
AcquireReaders protects idle handles from ordinary LRU eviction during an operation.
func (*PartReader) Close ¶ added in v0.54.0
func (r *PartReader) Close() error
Close retires this part's retained file handles; active reads may finish first.
func (*PartReader) Column ¶
func (r *PartReader) Column(ctx context.Context, name string) (*ColumnReader, error)
Column returns a lazy reader for the named column. A constant column is synthesized from the manifest with no I/O; otherwise its object is read from the backend.
func (*PartReader) ColumnBlocks ¶ added in v0.37.0
ColumnBlocks returns a per-block decoder for the named column that reads only the block directory up front and fetches each compression frame by ranged read as blocks are decoded.
It is the read counterpart of the streaming writer: the whole-object PartReader.Column is right when a caller decodes the whole column, and this is right when it decodes a fraction of it — the query path, where the matched series' rows lie in a handful of granules. The returned decoder holds ctx for its frame reads, so it must not outlive the operation that opened it.
The column must be block-framed and not constant-collapsed; PartReader.Column handles those. A bytes column is read through Decoder.DecodeBytes, which takes its shared dictionary — Decoder.SharedEntries — from the object head this open already peeled.
func (*PartReader) ColumnDescByName ¶ added in v0.20.0
func (r *PartReader) ColumnDescByName(name string) (ColumnDesc, bool)
ColumnDescByName returns the named column's descriptor from the already-loaded manifest, without reading the column object — so a caller can check Const/Blocked/Codec before deciding whether to read and decode the column. ok is false for an unknown column.
func (*PartReader) ColumnInputSize ¶ added in v0.49.0
func (r *PartReader) ColumnInputSize(name string) (ColumnInputSize, error)
ColumnInputSize sizes the named column from the manifest. It reads nothing.
func (*PartReader) ColumnNames ¶
func (r *PartReader) ColumnNames() []string
ColumnNames returns the column names in part order.
func (*PartReader) ColumnScan ¶ added in v0.48.0
ColumnScan returns a decoder over the named column tuned for a forward walk: instead of one ranged read per compression frame it fetches whole frames up to window bytes at a time.
It is PartReader.ColumnBlocks' sequential counterpart, and the distinction is not a tuning knob. A query touches a handful of frames out of thousands, scattered, so reading ahead would fetch bytes it never decodes. A merge touches every frame exactly once in order, and a frame is [defaultCompressBlockBytes] *uncompressed* — so without coalescing a multi-source merge issues hundreds of thousands of serialized ranged reads that nothing caches.
window is the read side's memory budget for this column: the decoder holds one buffer that large. A column whose frames all fit inside it is fetched in a single request, which is PartReader.Column minus the cache write. A window at or below zero disables read-ahead.
A column the ranged path cannot serve is read whole, once: the legacy unframed layout, and any column object backend.RangesNatively denies, where every ranged read is itself a whole-object read and a windowed walk would repeat it per window.
func (*PartReader) Int64ScanBound ¶ added in v0.51.0
func (r *PartReader) Int64ScanBound(ctx context.Context, name string) (retained, transient int64, ok bool)
Int64ScanBound bounds retained and transient memory for Decoder.Int64Cursor, without reads.
func (*PartReader) Manifest ¶
func (r *PartReader) Manifest() Manifest
Manifest returns the part's decoded manifest.
func (*PartReader) ManifestDigest ¶ added in v0.55.0
func (r *PartReader) ManifestDigest() [32]byte
ManifestDigest returns the digest of the exact persisted manifest bytes.
func (*PartReader) Marks ¶
func (r *PartReader) Marks(ctx context.Context) (Marks, error)
Marks reads the legacy sparse index; variable numeric chunks return an empty index. Use Decoder.BlockTimeBounds for their inline bounds.
func (*PartReader) OpenColumnScan ¶ added in v0.53.1
func (r *PartReader) OpenColumnScan(ctx context.Context, name string, window int64) (*Decoder, error)
OpenColumnScan reuses a file handle and pooled read-ahead buffer. The caller must Close the decoder.
func (*PartReader) ReaderContext ¶ added in v0.54.0
func (r *PartReader) ReaderContext(ctx context.Context) context.Context
ReaderContext binds immutable object reads to this part's operation generation.
func (*PartReader) ReleaseReaders ¶ added in v0.54.0
func (r *PartReader) ReleaseReaders()
ReleaseReaders ends one [AcquireReaders] pin.
func (*PartReader) ResidentBytes ¶ added in v0.49.0
func (r *PartReader) ResidentBytes() int64
ResidentBytes bounds what the open reader holds: its decoded manifest — a descriptor, name, constant value and name-index slot per column — plus retained reader bookkeeping. Decoded columns remain the caller's responsibility.
func (*PartReader) RowCount ¶
func (r *PartReader) RowCount() int
RowCount returns the number of rows in the part.
func (*PartReader) ScanBound ¶ added in v0.49.0
func (r *PartReader) ScanBound(ctx context.Context, name string, window int64) (steady, open int64, ok bool)
ScanBound bounds, from the manifest alone, what Decoder.ResidentBytes reports for ColumnScan(ctx, name, window) — steady — and what opening it holds on top while it reads and parses the column's tail — open: the dictionary region and directory as read, and the dictionary decompressed into scratch before it is kept. A caller can reserve both before opening the column. ok is false for a column the manifest cannot size: one written without WithSizingStats, an unframed or leading-dictionary layout, a constant or unblocked column, or none by that name.
type PartSizes ¶ added in v0.47.0
type PartSizes struct {
Total int64
// Columns is keyed by manifest column index. A constant-collapsed column has no object, so no entry.
Columns map[int]int64
// Other is every non-column object (manifest, marks, and whatever indexes the engine writes
// alongside), keyed by its name under the part prefix.
Other map[string]int64
}
PartSizes is the on-backend size of a part's objects.
func PartObjectSizes ¶ added in v0.47.0
PartObjectSizes sizes every object under the part at prefix, using the backend.Sizer fast path when available. A nil backend has no objects.
type PartWriter ¶
type PartWriter struct {
// contains filtered or unexported fields
}
PartWriter accumulates columns and serializes them into a part's objects. Columns are added in order; their ordinal is their object key. The sort-key column (timestamp for metrics) drives the marks index and the manifest time range.
func NewPartWriter ¶
func NewPartWriter(opts ...PartOption) *PartWriter
NewPartWriter returns a PartWriter with the given options applied.
func (*PartWriter) AddColumn ¶
func (w *PartWriter) AddColumn(c Column) error
AddColumn appends a column. All columns in a part must have the same row count.
type ReadOption ¶ added in v0.49.0
type ReadOption func(*PartReader)
ReadOption configures a PartReader.
func NewReadCompressors ¶ added in v0.49.0
func NewReadCompressors() ReadOption
NewReadCompressors returns a WithReadCompressors over a fresh compressor for every algorithm a part may be written in, for an owner to hand every reader it opens.
func WithReadCompressors ¶ added in v0.49.0
func WithReadCompressors(cs ...*compress.Compressor) ReadOption
WithReadCompressors makes the reader decompress through cs, one per algorithm, instead of compressors of its own, so every reader of one owner shares its pooled decoders: a zstd decoder costs its buffers and tables anew in each pool it is built in, and a store holds thousands of parts.
type Rollup ¶ added in v0.49.0
type Rollup struct {
Tiers []RollupTier
}
Rollup is the downsampling layout a part was last written under. No tiers means none was applied: the rows are raw.
type RollupTier ¶ added in v0.49.0
RollupTier is one tier of a Rollup: rows older than Before reduced to one per Interval-wide bucket by Agg, an aggregation id this package does not interpret. Interval must be positive.
type StreamBuildScratch ¶ added in v0.55.0
type StreamBuildScratch struct {
// contains filtered or unexported fields
}
StreamBuildScratch reuses metadata encoding buffers across sequential part writes. Retained capacity above 4 MiB is released after a write. Raw Marks views are never pooled.
func (*StreamBuildScratch) SizeBytes ¶ added in v0.55.0
func (s *StreamBuildScratch) SizeBytes() int64
SizeBytes returns the buffer capacity retained by s.
type StreamWriter ¶ added in v0.37.0
type StreamWriter struct {
// contains filtered or unexported fields
}
StreamWriter builds a part incrementally: the schema is declared up front and each column encodes a granule as soon as one fills, so the working set is the encoded part rather than its uncompressed rows. See ARCH.md ("Two writers") for what that buys and what it costs.
Only encodings that restart per granule can stream: blocked KindInt64/KindFloat64/KindBytes, and KindInt128, whose RLE codec is fed runs. Output matches PartWriter's byte for byte except for an Column.AutoCodec column.
Constructed with NewStreamWriter it still accumulates the *encoded* part in memory, which caps the part at what the process can hold. NewStreamWriterTo removes that ceiling: sealed compression frames go to the backend as they seal, leaving only one frame per column resident.
func NewStreamWriter ¶ added in v0.37.0
func NewStreamWriter(opts ...PartOption) *StreamWriter
NewStreamWriter returns a StreamWriter with the given options applied. It takes the same options as NewPartWriter and lays a part out identically.
func NewStreamWriterTo ¶ added in v0.37.0
func NewStreamWriterTo(ctx context.Context, b backend.Backend, prefix string, opts ...PartOption) *StreamWriter
NewStreamWriterTo returns a StreamWriter that hands each column's compression frames to b under prefix as they seal, rather than holding the encoded part until the end. Resident memory becomes one unsealed frame per column plus the column directories (kilobytes per column, one entry per granule and frame) instead of the whole part, so the part's size stops being bounded by the process's memory.
The column objects it produces carry their directory as a footer (ColumnDesc.Footer) — with the directory leading, no byte of the object could be final until the last frame sealed. A column that turns out to be constant is written under neither layout: it collapses into the manifest, so it stays buffered until it is known non-constant (which for real data is the second row) or holds one frame of output, past which it streams and is discarded if it ends constant.
ctx spans the writer's whole life, appends included. Nothing is stored under prefix until the writer finishes; a writer that will not finish must be released with StreamWriter.Abort. WriteStreamPart must be called with the same b and prefix.
func (*StreamWriter) Abort ¶ added in v0.37.0
func (w *StreamWriter) Abort()
Abort releases every object a streaming writer has under way without publishing any of them. It is idempotent, and a no-op on a writer that finished or never streamed, so `defer w.Abort()` is the correct cleanup.
func (*StreamWriter) AddColumn ¶ added in v0.37.0
func (w *StreamWriter) AddColumn(c Column) error
AddColumn declares a column; only c's schema fields are read, since rows arrive through the Append methods. A column's ordinal — the index those methods take — is its object key.
An AutoCodec column streams under both candidate codecs and keeps the denser, so the choice is still made over the whole column rather than a prefix. It compares block-framed sizes where PartWriter compares whole-column ones, so the two can pick differently in a marginal case; both are lossless.
func (*StreamWriter) AppendBytes ¶ added in v0.49.0
func (w *StreamWriter) AppendBytes(i int, vals [][]byte) error
AppendBytes appends vals to the i-th column, copying each value it keeps.
func (*StreamWriter) AppendBytesBlob ¶ added in v0.49.0
func (w *StreamWriter) AppendBytesBlob(i int, blob []byte, offsets []int32) error
AppendBytesBlob appends the rows of a blob column — row k is blob[offsets[k]:offsets[k+1]] — to the i-th column, as Column.BytesBlob describes them.
func (*StreamWriter) AppendEncodedGranule ¶ added in v0.55.0
func (w *StreamWriter) AppendEncodedGranule(col int, g EncodedGranule, stats GranuleStats) error
AppendEncodedGranule copies a borrowed granule and recompresses its outer frame. End the current group before switching between sample and encoded appends.
func (*StreamWriter) AppendEncodedRun ¶ added in v0.55.0
func (w *StreamWriter) AppendEncodedRun(tsCol, valueCol int, ts, value EncodedGranule, stats GranuleStats) error
AppendEncodedRun copies aligned timestamp/value granules, coalescing regular cadence up to the row cap. EndGroup prevents joining granules from different logical series.
func (*StreamWriter) AppendFloat64 ¶ added in v0.37.0
func (w *StreamWriter) AppendFloat64(i int, vals []float64) error
AppendFloat64 appends vals to the i-th column, encoding every granule they complete.
func (*StreamWriter) AppendFloat64Group ¶ added in v0.52.0
func (w *StreamWriter) AppendFloat64Group(i int, vals []float64, begin bool) error
AppendFloat64Group appends rows, starting a logical group when begin is true.
func (*StreamWriter) AppendInt64 ¶ added in v0.37.0
func (w *StreamWriter) AppendInt64(i int, vals []int64) error
AppendInt64 appends vals to the i-th column, encoding every granule they complete.
func (*StreamWriter) AppendU128Run ¶ added in v0.37.0
AppendU128Run appends count copies of v to the i-th column as one run, which is how an id column streams without materializing its rows. A count ≤ 0 is a no-op.
func (*StreamWriter) AppendU128RunView ¶ added in v0.55.0
AppendU128RunView appends a run and returns read-only runs, valid until the next column mutation.
func (*StreamWriter) Binding ¶ added in v0.49.0
func (w *StreamWriter) Binding(i int) (*Binding, error)
Binding returns a new binding to the i-th column, which must be KindBytes.
func (*StreamWriter) EncodedBytes ¶ added in v0.37.0
func (w *StreamWriter) EncodedBytes() int64
EncodedBytes returns the compressed bytes accumulated so far, what a caller seals a part on when the target is a size on disk.
It is a lower bound: low by at most one unsealed frame per column plus the id column's RLE stream, tens of KiB against a cap in the hundreds of MiB.
func (*StreamWriter) EndGroup ¶ added in v0.52.0
func (w *StreamWriter) EndGroup() error
EndGroup completes one streaming row group without sharing its chunks with another group.
func (*StreamWriter) FinishBytes ¶ added in v0.49.0
func (w *StreamWriter) FinishBytes() int64
FinishBytes bounds what the writer allocates past StreamWriter.ResidentBytes while it seals a frame or builds the part. Columns finish one at a time, so it is the largest one column's work drops once done — its pending frame compressed, its dictionary region (the dictionary serialized, compressed and framed), a buffered dictionary column no granule joined decompressed back into one stream and recompressed, or the id column's runs encoded — plus every buffered column's region, which stays with the part until it is written.
func (*StreamWriter) Marks ¶ added in v0.51.0
func (w *StreamWriter) Marks() Marks
Marks returns legacy sort-key bounds after writing; independent groups return no granules. Returned granules remain valid after the writer is discarded.
func (*StreamWriter) OmitConstColumn ¶ added in v0.37.0
func (w *StreamWriter) OmitConstColumn(v float64) error
OmitConstColumn drops the last declared column from the part entirely if every row appended to it turned out to be v.
It covers a column the format leaves *absent* rather than constant — the sampling weight, which a reader defaults to 1. A present-but-constant column is not block-framed and would drop readers onto the whole-part decode path. Only the last column may be omitted; dropping an earlier one would renumber the object keys after it.
func (*StreamWriter) RequirePagedCoverage ¶ added in v0.56.0
func (w *StreamWriter) RequirePagedCoverage()
RequirePagedCoverage marks an indexed metric part whose coverage uses the paged format.
func (*StreamWriter) ReserveU128Runs ¶ added in v0.50.1
func (w *StreamWriter) ReserveU128Runs(i, n int) error
ReserveU128Runs reserves room for n runs in the i-th column without appending rows.
func (*StreamWriter) ResidentBytes ¶ added in v0.37.0
func (w *StreamWriter) ResidentBytes() int64
ResidentBytes returns what the writer is holding in RAM right now: per column, the frame still being filled, the block directory it is building, and — for a buffered writer, or a column not yet proven non-constant — the frames sealed so far.
It is what a caller seals a part on when the bound is memory rather than a size on disk. For a NewStreamWriterTo writer it settles at a few hundred KiB per column, plus a dictionary bytes column's dictionary (bounded by WithSharedDictBytes), and stops tracking the part; for a buffered one it tracks StreamWriter.EncodedBytes and grows without limit.
func (*StreamWriter) Rows ¶ added in v0.37.0
func (w *StreamWriter) Rows() int
Rows returns the row count appended to the first declared column, or 0 if none is declared.
Source Files
¶
- arena.go
- binding.go
- blockcolumn.go
- chunkgeometry.go
- chunkrows.go
- column.go
- columnscan.go
- compactdir.go
- decodelimit.go
- decoder_clone.go
- dictgen.go
- doc.go
- encodedgranule.go
- encodedrun.go
- floatgroups.go
- framemetadata.go
- frames.go
- inputsize.go
- int64stream.go
- manifest.go
- manifest_binding.go
- manifestext.go
- marks.go
- observer.go
- part.go
- partsize.go
- rangedcolumn.go
- scanreader.go
- shareddict.go
- shareddictwrite.go
- streambuild.go
- streambytes.go
- streamwriter.go