nativeice

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2026 License: Apache-2.0 Imports: 23 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package nativeice reads the ICE v3 segment and snapshot v3 manifest grammar defined by BDB-NIDX-SPEC-001 revision 0.2 sections 08 and 09, using only BanyanDB code. It is the bounded read-only container reader that the read-only production paths in pkg/index/native open committed index directories through, and it never depends on the retired index libraries.

The package is deliberately reachable only from pkg/index/native and its legacy adapter. Footer, offset, mapping, and section decoder types are private to it; the contract other packages observe is the behavior of the exported functions in pkg/index/native that call it.

Index

Constants

View Source
const DroppedDocumentNumber = math.MaxUint64

DroppedDocumentNumber marks an input physical document removed by its snapshot deletion mask or an external merge drop mask.

Variables

View Source
var ErrCorrupt = errors.New("nativeice: corrupt index")

ErrCorrupt is the sentinel that every structural rejection wraps: a footer, record framing, count, length, or section offset that violates the ICE v3 or snapshot v3 grammar, or that would require reading or allocating past a configured bound. Callers classify with errors.Is.

View Source
var ErrInvalidGeneration = errors.New("nativeice: invalid generation")

ErrInvalidGeneration is the sentinel reported when a caller asks Encode to write a generation the ICE v3 grammar has no representation for: a document carrying no identifier, or a field carrying no name. It is deliberately distinct from ErrCorrupt -- nothing on disk is damaged, and nothing on disk is touched, because the request is rejected before the first byte is written. Callers classify with errors.Is.

View Source
var ErrInvalidRepairPage = errors.New("nativeice: invalid repair page request")

ErrInvalidRepairPage reports a bounded repair page request that the native reader cannot serve.

View Source
var ErrInvalidSelection = errors.New("nativeice: invalid term selection")

ErrInvalidSelection is the sentinel reported when a caller asks for a term selection the reader will not serve: one that names no field, that carries more terms than the reader's configured term-count bound, or that carries a term longer than its configured term-length bound.

It is deliberately distinct from ErrCorrupt. Nothing on disk is damaged; the request itself lies outside the bounds BDB-NIDX-SPEC-001 revision 0.2 READ-002 requires the reader to hold, so no dictionary is opened and no posting is decoded. Callers classify with errors.Is.

View Source
var ErrNoSnapshot = errors.New("nativeice: no committed snapshot")

ErrNoSnapshot is the sentinel reported when a directory holds no committed generation at all: it is absent, empty, or was never flushed. It is distinct from ErrCorrupt because nothing is damaged -- there is simply nothing committed to read.

View Source
var ErrPublishConflict = errors.New("nativeice: publication conflict")

ErrPublishConflict reports a snapshot or segment identifier that is already published in the destination directory. A conflicting publication never replaces an existing immutable file.

View Source
var ErrReaderClosed = errors.New("nativeice: reader is closed")

ErrReaderClosed reports a read through a Reader, or a handle or iterator derived from it, after the Reader closed.

Functions

func DecodePrefixCodedInt64

func DecodePrefixCodedInt64(value []byte) (int64, error)

DecodePrefixCodedInt64 decodes the shift-zero prefix-coded signed integer used by the established date/time stored-field format. It intentionally accepts only shift-zero values: date/time fields are full-precision int64 nanoseconds, while shifted terms are query-analysis tokens rather than a stored timestamp value.

func Encode

func Encode(path string, generation Generation) error

Encode writes generation into the index directory at path as one committed ICE v3 generation -- a segment holding every document, and a snapshot manifest referencing that segment and carrying its deletion masks -- and leaves the directory's existing generations untouched. Open selects the written generation when its snapshot identifier is the directory's newest.

The generation is published by its snapshot manifest, so the segment is complete on disk before any manifest names it. A write interrupted before publication therefore leaves the directory's committed state exactly as it was: Open still selects the newest generation that was published, or reports ErrNoSnapshot when none ever was.

Every field a document marks Index contributes its value as a term to that field's dictionary, every field it marks Store contributes a stored value, and every field it marks Sort contributes a doc value; one field may do all three. Within a document, a walk yields the identifier's stored value first and the remaining names in ascending byte order, with the values of a repeated name consecutive and in the order the document lists them.

The snapshot manifest carries a calculated CRC32, because the pinned compatibility reader validates it: that reader's default configuration turns snapshot CRC validation on, and it rejects a manifest whose trailing four bytes are not the IEEE CRC32 of everything before them. The segment footer's CRC32 field is a different case and stays reserved -- no reader validates it, so Encode writes the field without calculating it.

A generation whose documents the ICE v3 grammar cannot represent is rejected with an error wrapping ErrInvalidGeneration before the directory is touched.

func EncodePrefixCodedInt64

func EncodePrefixCodedInt64(value int64) []byte

EncodePrefixCodedInt64 encodes a full-precision signed integer in the shift-zero format used by the established date/time stored-field format. The returned bytes are owned by the caller.

func EncodePrefixCodedInt64Shift

func EncodePrefixCodedInt64Shift(value int64, shift uint) []byte

EncodePrefixCodedInt64Shift encodes an int64 numeric term at the requested precision shift. It matches the legacy numeric/date term format, where each byte carries seven sortable bits and the header records the shift.

func EncodeSegment

func EncodeSegment(generation Generation) ([]byte, error)

EncodeSegment returns the native ICE segment bytes for generation without publishing a snapshot. Callers that own a segment lifecycle can persist these bytes through their own WriteTo seam and publish them separately.

func HasTime

func HasTime(timeMin, timeMax uint64) bool

HasTime reports whether a segment's recorded time bounds hold a timestamp: a segment whose documents carry none records 0 for both.

func NextPublicationIDs

func NextPublicationIDs(path string) (uint64, uint64, error)

NextPublicationIDs returns the first unused segment and snapshot identifiers in path. It considers both committed and orphaned files, so an interrupted publication cannot cause a later write to reuse an immutable filename. Empty or absent directories return zero for each identifier.

func PublishSnapshot

func PublishSnapshot(path string, snapshotID uint64, segments []SnapshotSegmentPayload) error

PublishSnapshot durably publishes one multi-segment ICE v3 snapshot. Every new segment is validated and linked before the snapshot manifest is linked, making the manifest the sole visibility point. Existing referenced segments are never rewritten. On a pre-manifest failure, segments linked by this call are removed while unrelated files and prior snapshots remain untouched. A write or sync failure is returned as *PublishError; when Published is true, the manifest link completed and the caller must reconcile or enter a terminal state without deleting the linked files.

The caller owns Payload and must not mutate it until this function returns. A nil Payload means that the named segment must already exist, which lets a new root retain disk-backed segments without copying their bytes.

func SplitSortableRange

func SplitSortableRange(lo, hi uint64, emit func(shift uint, first, last uint64))

SplitSortableRange covers the closed sortable interval [lo, hi] with the fewest possible trie buckets, calling emit once per run of consecutive buckets as (shift, first, last) in sortable units at that shift.

It is Lucene's NumericUtils.splitRange specialised to a 64-bit value and the prefix-coded precision step of 4 that the writer emits, and exists so a time range becomes a handful of _timestamp terms instead of a scan. Because the writer indexes every document under one term per level, and this cover partitions [lo, hi] into disjoint buckets, a document is in the union of the emitted runs' postings if and only if its timestamp is in [lo, hi].

The cover never exceeds sortableRangeMaxTerms terms, and for a realistic window it is a few dozen: a 15-minute window is about 12 buckets at shift 36 plus at most 15 at each finer level on either edge.

emit must not retain the shift or bucket values; they are only valid for the duration of the call.

Types

type DecodedDocument

type DecodedDocument struct {
	Fields []DecodedField
}

DecodedDocument is one physical document read from a native ICE segment.

func DecodeStoredSegment

func DecodeStoredSegment(payload []byte) ([]DecodedDocument, error)

DecodeStoredSegment decodes every physical stored document from one native ICE segment. It deliberately ignores snapshot deletion masks: those masks belong to the manifest, while a Segment contract represents physical docs.

type DecodedField

type DecodedField struct {
	Name  string
	Value []byte
}

DecodedField is one stored value read from a native ICE segment.

type Dictionary

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

Dictionary is a single-segment exact-term handle bound to one field's term dictionary. The parent Reader remains responsible for the dictionary's lifetime.

func (*Dictionary) Bound

func (d *Dictionary) Bound() bool

Bound reports whether this handle resolved an indexed field dictionary.

func (*Dictionary) Close

func (d *Dictionary) Close() error

Close releases no shared state; the parent Reader owns the dictionary FST.

func (*Dictionary) NewDictionaryTermIterator

func (d *Dictionary) NewDictionaryTermIterator(automaton DictionaryAutomaton, start, end []byte) (*DictionaryTermIterator, error)

NewDictionaryTermIterator opens an iterator using this dictionary handle's already-loaded FST, avoiding repeated field-cache lookups.

func (*Dictionary) TermExists

func (d *Dictionary) TermExists(term []byte) (bool, error)

TermExists reports whether an exact term is present in this dictionary.

func (*Dictionary) TermPosting

func (d *Dictionary) TermPosting(term []byte) (TermPosting, bool, error)

TermPosting resolves one exact term through this handle's reusable decoder.

type DictionaryAutomaton

type DictionaryAutomaton interface {
	Start() int
	IsMatch(int) bool
	CanMatch(int) bool
	WillAlwaysMatch(int) bool
	Accept(int, byte) int
}

DictionaryAutomaton is the byte automaton used to prune dictionary walks. Implementations are evaluated by the cached FST before a posting is read.

type DictionaryTermIterator

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

DictionaryTermIterator walks one field's terms in lexical order. Terms are selected by the FST before their posting bitmap is decoded; Count returns only that bitmap's cardinality and never decodes the frequency stream. Terms returned by Next are owned by the caller.

func (*DictionaryTermIterator) Close

func (i *DictionaryTermIterator) Close() error

Close stops the dictionary walk and releases its FST iterator.

func (*DictionaryTermIterator) Next

func (i *DictionaryTermIterator) Next() ([]byte, uint64, error)

Next returns the next matching term and its document count. A nil term and nil error indicate exhaustion. The empty term is valid and is distinguished from exhaustion by its non-zero posting value.

func (*DictionaryTermIterator) NextKey

func (i *DictionaryTermIterator) NextKey() ([]byte, bool, error)

NextKey advances to the next matching dictionary key without decoding its posting cardinality. The present flag distinguishes a valid empty key from exhaustion, so range scans do not pay a second posting decode.

func (*DictionaryTermIterator) NextString

func (i *DictionaryTermIterator) NextString() (string, uint64, error)

NextString returns the next matching term without the intermediate byte slice allocation used by Next. The returned string is owned by the caller.

func (*DictionaryTermIterator) NextTerm

func (i *DictionaryTermIterator) NextTerm() ([]byte, error)

NextTerm returns the next dictionary term without decoding its posting bitmap. A nil term and nil error indicate exhaustion.

type EncodeDocument

type EncodeDocument struct {
	// Fields are the document's values, in the order the document records them.
	Fields []EncodeField
	// Identifier is the document's identity. Encode records it as an indexed,
	// stored value under the reserved identifier field.
	Identifier []byte
	// Deleted marks the document as covered by the generation's deletion masks.
	// It still occupies a document number in the segment, and it is absent from
	// every count, walk, selection and repair page the generation serves.
	Deleted bool
}

EncodeDocument is one physical document of a generation.

type EncodeField

type EncodeField struct {
	// Name is the segment field name the value is recorded under.
	Name string
	// Value is the field's raw bytes.
	Value []byte
	// Terms, when non-nil, are the analyzed terms recorded for this value.
	// A nil slice retains the compatibility behavior of indexing Value as one
	// term; a non-nil empty slice deliberately records no terms.
	Terms []EncodeTerm
	// Index records Value as a term in Name's dictionary, so a selection on
	// Name and Value reaches the document.
	Index bool
	// Store records Value as a stored value, so a document walk yields it.
	Store bool
	// Sort records Value as a doc value, so a repair page may sort on Name.
	Sort bool
}

EncodeField is one value a document contributes to a generation. The same name may appear on several fields of one document; each contributes its own value, and Encode preserves them in the order the document lists them.

Value is an opaque byte sequence. Encode applies no analysis, no normalization and no numeric coding to it, so a term selects, sorts and reads back as exactly the bytes the caller supplied -- which is the same contract Reader.VisitSelectedDocuments resolves terms under.

type EncodeTerm

type EncodeTerm struct {
	Value     []byte
	Frequency uint64
}

EncodeTerm is one analyzed term and its occurrence frequency. Multi-hit postings retain the ICE frequency stream even when every frequency is one.

type Generation

type Generation struct {
	// Documents are the generation's physical documents, in the order they take
	// document numbers in the segment.
	Documents []EncodeDocument
	// SegmentID numbers the segment file the generation writes.
	SegmentID uint64
	// SnapshotID numbers the snapshot manifest that publishes the generation,
	// and is the identifier Reader.SnapshotID reports once it is opened.
	SnapshotID uint64
	// TimeMin and TimeMax are the segment's encoded timestamp bounds.
	TimeMin uint64
	TimeMax uint64
	// IdentifierDocValues additionally writes "_id" as a doc-value column, as
	// the previous release's writer does, so a rolled-back node can still
	// read document identity back from a segment this encoder wrote.
	IdentifierDocValues bool
}

Generation is one committed ICE v3 generation: the documents it holds and the identifiers its segment and snapshot manifest are numbered by.

type MergeInput

type MergeInput struct {
	Reader        *Reader
	Drop          *roaringpkg.Bitmap
	IndexedFields []string
}

MergeInput is one single-segment reader participating in a native merge. IndexedFields carries modality information that ICE deliberately does not encode when an indexed field has an empty term set; callers should provide those names from the segment owner. Reader deletion masks are always applied in addition to Drop.

type MergeResult

type MergeResult struct {
	Payload []byte
}

MergeResult contains an in-memory encoded merged segment. Input readers remain owned by the caller and are not closed.

func MergeSegments

func MergeSegments(ctx context.Context, inputs []MergeInput) (MergeResult, error)

MergeSegments merges native single-segment readers into an in-memory segment. It is the buffered form of MergeSegmentsTo and holds the whole output in memory, so it is meant for small merges and owners without a directory; MergeSegmentsToFile keeps merge memory independent of the merged segment's size.

type MergeStats

type MergeStats struct {
	// DocumentCount is the merged segment's physical document count: every
	// input document that neither its snapshot deletion mask nor its Drop
	// mask removed, numbered in input order.
	DocumentCount uint64
	// Size is the number of segment bytes written.
	Size uint64
	// TimeMin and TimeMax are the merged segment's exact time bounds, encoded
	// as uint64(int64) exactly as the footer stores them. They cover the
	// surviving documents that carry a timestamp; HasTime reports whether any
	// did. A merge of input whose own bounds are unknown still produces exact
	// bounds, because they are folded from the surviving documents rather than
	// combined from the inputs.
	TimeMin uint64
	TimeMax uint64
	HasTime bool
}

MergeStats describes a segment written by MergeSegmentsTo or MergeSegmentsToFile.

func MergeSegmentsTo

func MergeSegmentsTo(ctx context.Context, inputs []MergeInput, output io.Writer, spillPrefix string) (MergeStats, error)

MergeSegmentsTo merges native single-segment readers without involving a query engine and streams the merged segment to output in one forward pass. Stored repeated values, analyzed terms and frequencies, and repeated doc values are retained. Documents are emitted in input order, and context cancellation is checked between documents, chunks and terms.

The ICE v3 layout is strictly sequential, so every section is written as soon as it is complete: stored chunks as each fills, doc values one chunk at a time, and each field's postings in term order while the inputs' term dictionaries are k-way merged. Only sections whose length must precede them -- the per-document stored offset index and each field's term dictionary -- are staged, in buffers that spill to files named spillPrefix+".spill-N" once they outgrow a fixed bound. An empty spillPrefix keeps them in memory. Merge memory is therefore bounded by chunk buffers, one term's posting bitmap, the dictionary builder, and per-field and per-input metadata, not by the merged segment's size.

The output is byte-identical to encoding the merged documents with EncodeSegment. Input readers remain owned by the caller and are not closed.

func MergeSegmentsToFile

func MergeSegmentsToFile(ctx context.Context, inputs []MergeInput, path string) (stats MergeStats, err error)

MergeSegmentsToFile streams a merge of inputs into a new segment file at path, fsyncs it and closes it. Temporary spill files are created beside it under path's name with a ".spill-" suffix. On any failure, including a panic, the partial output and every spill file are removed, so a failed merge never leaves a file behind.

type Promotion

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

Promotion pairs an admitted, in-memory segment's Reader with the file PublishSnapshot writes from its payload, so the Reader that will serve the file can take over what the admitted one already built, and only from it.

func NewPromotion

func NewPromotion(source *Reader) *Promotion

NewPromotion starts following source, a Reader of one admitted segment, through the publication of its payload.

type PublishError

type PublishError struct {
	SnapshotID uint64
	Published  bool
	Err        error
}

PublishError describes a publication failure and whether its manifest was linked. Published is true only after the manifest link succeeds; a later directory-sync error therefore leaves an uncertain, already-visible generation and must not be cleaned up or blindly retried by the caller. Published is false for every failure before the manifest becomes visible.

func (*PublishError) Error

func (e *PublishError) Error() string

func (*PublishError) Unwrap

func (e *PublishError) Unwrap() error

Unwrap preserves the underlying filesystem or validation failure for errors.Is/errors.As callers.

type Reader

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

Reader is a bounded read-only handle on exactly one generation of an index directory. The generation is chosen at Open and fixed for the Reader's lifetime, so generations committed afterwards stay invisible to it.

func Open

func Open(path string) (*Reader, error)

Open selects the newest committed generation in the index directory at path, validates its snapshot manifest and every segment that manifest references against the grammar and the reader's configured bounds, and returns a Reader pinned to that generation.

Open takes no exclusive directory lock and creates, removes, or modifies no file, so a directory a live writer owns can be inspected while it is being written. Directory entries outside the grammar, the writer lock file among them, are ignored. Snapshot and segment identifiers are numbered independently, so the newest generation is chosen by decoding the manifest rather than by pairing file names.

A directory holding no committed generation reports an error wrapping ErrNoSnapshot. Open skips each generation whose manifest or referenced segments fail structural validation and pins the newest complete generation. It reports an error wrapping ErrCorrupt only when no committed generation validates.

func OpenPromotedSegment

func OpenPromotedSegment(path string, metadata SnapshotSegment, promotion *Promotion) (*Reader, error)

OpenPromotedSegment opens the file an admitted segment was persisted to, as OpenSnapshotSegment does, for an owner promoting the segment's handle to it. promotion is the one that followed the segment's payload through PublishSnapshot. When the file opened is the very file written there, the new Reader takes over the term filters and term sets the admitted Reader already built rather than rebuilding them from the file; otherwise it adopts nothing, and its filters are built as for any segment.

func OpenSegment

func OpenSegment(payload []byte) (*Reader, error)

OpenSegment validates and opens one immutable in-memory ICE segment. The payload is copied, so callers may reuse it after this returns.

func OpenSegmentBorrowed

func OpenSegmentBorrowed(payload []byte) (*Reader, error)

OpenSegmentBorrowed opens an immutable segment view without copying payload. The caller must keep payload unchanged and live until Reader.Close returns. It is intended for adapters whose segment data already has that lifetime; callers needing ownership should use OpenSegment.

func OpenSegmentFile

func OpenSegmentFile(path string) (*Reader, error)

OpenSegmentFile opens and validates one standalone immutable segment, read through its file like every persisted segment. It is used for external receives and merge outputs before they are introduced into a published snapshot.

func OpenSnapshotSegment

func OpenSnapshotSegment(path string, metadata SnapshotSegment) (*Reader, error)

OpenSnapshotSegment opens one immutable segment named by snapshot metadata. The returned Reader retains the segment file descriptor and validates its footer, field index, stored sections, and deletion-mask bounds without copying the segment payload. The caller owns the Reader and must Close it. DeletionBitmap is retained in the Reader's private record; callers that need to apply masks to another root should keep their own copy of the metadata.

func OpenStrict

func OpenStrict(path string) (*Reader, error)

OpenStrict opens only the newest committed snapshot in path. Unlike Open, it never falls back to an older generation when that newest manifest or one of its segments is damaged. Writers use this fail-closed mode at startup so an acknowledged generation cannot silently disappear after a restart.

func (*Reader) Close

func (r *Reader) Close() error

Close refuses new operations at once and never waits for one. If an operation admitted before Close is still running, Close returns nil at once and the last such operation releases the files when it ends; otherwise Close releases them itself before returning -- closing the descriptors and running the WhenReleased hooks -- and returns the error closing them reported. Close may therefore be called from any goroutine, a callback of the Reader's own operations or a release hook included, without deadlock. Operations started after Close, and handles and iterators used after it, report ErrReaderClosed; so do point reads (lookups, VisitDocument) racing the release. Close is idempotent: once the files are released, it returns the same error.

Because the release may happen after Close returns, a caller that must act once the files are closed -- deleting one, say -- does so through WhenReleased, which also delivers the release's error.

func (*Reader) Dictionary

func (r *Reader) Dictionary(field string) (*Dictionary, error)

Dictionary opens a field dictionary without retaining a reader lock or looking up field state on each exact-term operation.

func (*Reader) DictionaryValue

func (r *Reader) DictionaryValue(field string) (Dictionary, error)

DictionaryValue opens a field dictionary as an embeddable value. It avoids a second heap object when a segment adapter stores the handle in its own per-search dictionary wrapper.

func (*Reader) DocValues

func (r *Reader) DocValues(field string) ([]SegmentDocValues, error)

DocValues returns one segment's doc values in physical document order. It includes doc-value-only fields and copies every returned value.

func (*Reader) DocumentCount

func (r *Reader) DocumentCount() uint64

DocumentCount returns the number of physical documents in this reader's generation. It is useful to segment adapters that preserve physical document numbering while decoding individual documents lazily.

func (*Reader) DocumentValues

func (r *Reader) DocumentValues(field string, number uint64) ([][]byte, error)

DocumentValues returns one document's values for field. Returned bytes are owned by the caller.

func (*Reader) DocumentValuesContext

func (r *Reader) DocumentValuesContext(ctx context.Context, field string, number uint64) ([][]byte, error)

DocumentValuesContext reserves the selected doc-value chunk and owned copies.

func (*Reader) FieldStats

func (r *Reader) FieldStats(field string) (uint64, uint64, error)

FieldStats returns the encoded document count and total term frequency for field. The values are segment metadata, independent of posting score norms.

func (*Reader) Fields

func (r *Reader) Fields() ([]string, error)

Fields returns every field represented in the segment, including stored-only, indexed-only and doc-value-only fields.

func (*Reader) NewDictionaryTermIterator

func (r *Reader) NewDictionaryTermIterator(field string, automaton DictionaryAutomaton, start, end []byte) (*DictionaryTermIterator, error)

NewDictionaryTermIterator opens a bounded dictionary iterator over one segment. The end key is exclusive, and nil or empty bounds retain vellum's unbounded semantics. Close is safe to call more than once.

func (*Reader) NewDictionaryTermIterators

func (r *Reader) NewDictionaryTermIterators(ctx context.Context, field string) ([]*DictionaryTermIterator, error)

NewDictionaryTermIterators opens one bounded dictionary cursor per pinned segment. Callers own and must close every returned cursor.

func (*Reader) PrepareTermFilter

func (r *Reader) PrepareTermFilter(field string) error

PrepareTermFilter eagerly builds field's absent-term filter (the exact term set on a small segment, the bloom filter on a larger one) for this reader's one segment, so the first exact lookup against field after the segment is published does not pay to build it lazily. It is a no-op for a reader spanning more than one segment (a merged read view, not a single freshly constructed or reopened segment), since those callers build their own per-segment readers and warm each individually.

func (*Reader) RenameSegmentFile

func (r *Reader) RenameSegmentFile(newPath string) error

RenameSegmentFile renames the file a single-segment Reader was opened from to newPath, keeping the Reader serving it. It is how an owner publishes a staged segment under its final name without reopening it.

func (*Reader) RepairTuplePage

func (r *Reader) RepairTuplePage(ctx context.Context, request RepairPageRequest) ([]RepairTupleRow, error)

RepairTuplePage returns a bounded page from the Reader's pinned generation.

func (*Reader) SegmentCount

func (r *Reader) SegmentCount() int

SegmentCount returns the number of segments in the pinned snapshot.

func (*Reader) SnapshotID

func (r *Reader) SnapshotID() uint64

SnapshotID returns the identifier of the committed generation the Reader pins.

func (*Reader) SnapshotMetadata

func (r *Reader) SnapshotMetadata() SnapshotMetadata

SnapshotMetadata returns a copy of the pinned snapshot's manifest metadata. The returned deletion bitmaps are owned by the caller and may be retained until the Reader closes.

func (*Reader) TermDocumentCounts

func (r *Reader) TermDocumentCounts(field string, terms [][]byte) ([]uint64, error)

TermDocumentCounts returns posting cardinalities aligned with terms.

func (*Reader) TermDocuments

func (r *Reader) TermDocuments(field string, term []byte) ([]SegmentTermDocuments, error)

TermDocuments returns document membership for one exact indexed term.

func (*Reader) TermDocumentsBatch

func (r *Reader) TermDocumentsBatch(field string, terms [][]byte) ([][]uint64, error)

TermDocumentsBatch returns local document membership aligned with terms, resolving all terms through one cached field dictionary.

func (*Reader) TermExists

func (r *Reader) TermExists(field string, term []byte) (bool, error)

TermExists reports whether an exact term is present in one segment's field dictionary without decoding its posting list.

func (*Reader) TermFrequencies

func (r *Reader) TermFrequencies(field string, term []byte) ([]SegmentTermFrequencies, error)

TermFrequencies returns per-document frequencies, defaulting to one for legacy postings without a frequency stream.

func (*Reader) TermPosting

func (r *Reader) TermPosting(field string, term []byte) (TermPosting, bool, error)

TermPosting resolves one exact term without enumerating the field dictionary. Compact one-hit postings remain scalar; general postings retain the validated slices used by VisitTermPostings.

func (*Reader) TermPostingBitmap

func (r *Reader) TermPostingBitmap(field string, term []byte) (*roaringpkg.Bitmap, bool, error)

TermPostingBitmap resolves one exact term to a caller-owned document bitmap. Unlike TermPosting it neither decodes the posting's frequency stream nor materializes a document slice, which is all a membership test needs.

func (*Reader) TermPostingBitmapContext

func (r *Reader) TermPostingBitmapContext(ctx context.Context, field string, term []byte) (*roaringpkg.Bitmap, bool, error)

TermPostingBitmapContext reserves only the selected posting before reading and decoding it.

func (*Reader) Terms

func (r *Reader) Terms(field string) ([][]byte, error)

Terms returns all exact dictionary terms for field in lexical order.

func (*Reader) TimeBounds

func (r *Reader) TimeBounds() (int64, int64)

TimeBounds returns the timestamp bounds recorded by the segment footer.

func (*Reader) VisibleDocCount

func (r *Reader) VisibleDocCount() (int64, error)

VisibleDocCount returns the number of live documents in the pinned generation: the document counts the manifest records for the segments it references, less the documents those segments' deletion masks mark.

func (*Reader) VisitDocument

func (r *Reader) VisitDocument(number uint64, visit func(StoredDocument) error) error

VisitDocument visits one physical stored document without decoding the surrounding generation.

Like a point lookup it is not an admitted operation (see check): it does not hold the files open, so if a Close releases them while it reads it reports ErrReaderClosed. Its callback may close the Reader.

func (*Reader) VisitDocumentCalls

func (r *Reader) VisitDocumentCalls() int64

VisitDocumentCalls returns how many times VisitDocument has been called on this Reader. It is test instrumentation: production code never reads it.

func (*Reader) VisitDocumentContext

func (r *Reader) VisitDocumentContext(ctx context.Context, number uint64, visit func(StoredDocument) error) error

VisitDocumentContext reserves the selected stored chunk before decoding or borrowing it.

func (*Reader) VisitFieldDocumentValues

func (r *Reader) VisitFieldDocumentValues(field string, visit func(uint64, [][]byte) error) error

VisitFieldDocumentValues streams one segment's values in physical document order. Values are borrowed until visit returns; callers retaining them must copy each value. A document with no values is still visited with an empty slice.

func (*Reader) VisitLiveDocuments

func (r *Reader) VisitLiveDocuments(ctx context.Context, visit func(StoredDocument) error) error

VisitLiveDocuments streams the pinned generation's live documents to visit, one at a time, in ascending segment and local document order. Documents the pinned snapshot's deletion masks cover are skipped, so a deleted document is never handed to visit.

The StoredDocument handed to visit is borrowed: it, and every name and value it yields, stay valid only until visit returns. At most one document plus the reader's configured decode buffers are resident at a time, so the walk's memory does not grow with the generation's size.

The walk stops and returns ctx.Err() when ctx is canceled between two documents or two stored chunks, and stops and returns visit's error when visit fails. A stored section whose chunk table, offsets, lengths, varints or field identifiers violate the ICE v3 grammar, or that would require decoding past a configured bound, stops the walk with an error wrapping ErrCorrupt.

func (*Reader) VisitPhysicalDocuments

func (r *Reader) VisitPhysicalDocuments(ctx context.Context, visit func(StoredDocument, bool) error) error

VisitPhysicalDocuments streams every physical document in the pinned generation. The deleted argument reports the snapshot deletion mask for the document; unlike VisitLiveDocuments this method does not hide deleted documents. Documents are visited in ascending segment and local document order and are borrowed for the callback duration.

func (*Reader) VisitSelectedDocuments

func (r *Reader) VisitSelectedDocuments(ctx context.Context, field string, terms [][]byte, visit func(StoredDocument) error) error

VisitSelectedDocuments streams the pinned generation's live documents whose field records any of terms to visit, one at a time, in ascending segment and local document order.

Terms are resolved exactly against the field's term dictionary: they are compared as raw bytes, with no analysis, no normalization and no range, prefix or wildcard expansion. A term the dictionary does not hold selects nothing rather than failing. The documents the terms' postings select are unioned, the pinned snapshot's deletion masks are removed from that union, and each surviving document is handed to visit exactly once however many of the terms selected it. An empty term set selects no document and is not an error.

Selection precedes stored-field decoding: a document the selection does not hold has its stored bytes left unread, so a generation holding a damaged document still serves a selection that excludes it.

The StoredDocument handed to visit is borrowed exactly as in VisitLiveDocuments: it, and every name and value it yields, stay valid only until visit returns. At most one document plus the reader's configured decode buffers, the selected field's dictionary and the unioned postings are resident at a time.

A selection that names no field, or whose term count or term length exceeds the reader's configured bounds, is rejected with an error wrapping ErrInvalidSelection before any document is visited. The walk stops and returns ctx.Err() when ctx is canceled while postings are decoded or unioned, or between two documents. It stops and returns visit's error when visit fails. A dictionary, posting record or stored record that violates the ICE v3 grammar, or that would require decoding past a configured bound, stops the walk with an error wrapping ErrCorrupt.

func (*Reader) VisitTermPostings

func (r *Reader) VisitTermPostings(field string, terms [][]byte, visit func([]byte, []uint64, []TermFrequency) error) error

VisitTermPostings resolves all terms in one segment while retaining a single dictionary decoder. A nil terms argument enumerates the dictionary. The callback receives local document numbers and frequencies one term at a time.

func (*Reader) VisitTerms

func (r *Reader) VisitTerms(ctx context.Context, field string, visit func([]byte) bool) error

VisitTerms walks one field's exact dictionary terms in each pinned segment. Terms are copied before the callback and are not globally ordered across segments. No posting bitmap or frequency stream is decoded. Returning false stops the walk without error.

func (*Reader) WhenReleased

func (r *Reader) WhenReleased(fn func(error))

WhenReleased runs fn with the release's error once the Reader's files are closed: at once, on the caller, if they already are, otherwise right after the release on the goroutine performing it. A panicking hook is recovered and does not keep the others from running.

type RepairCursor

type RepairCursor struct {
	SortValues     [][]byte
	SegmentID      uint64
	DocumentNumber uint64
}

RepairCursor identifies a row in the pinned generation, including tuple ties.

type RepairPageRequest

type RepairPageRequest struct {
	After        *RepairCursor
	SortFields   [repairSortFieldCount]string
	ProjectField string
	PageSize     int
}

RepairPageRequest describes one bounded repair page.

type RepairTupleRow

type RepairTupleRow struct {
	SortValues [][]byte
	Value      []byte
	Cursor     RepairCursor
}

RepairTupleRow is one bounded repair row returned by Reader.RepairTuplePage.

type SegmentDocValues

type SegmentDocValues struct {
	Values  [][][]byte
	Segment uint64
}

SegmentDocValues contains one field's values in physical document order. Missing values are represented by nil entries.

type SegmentTermDocuments

type SegmentTermDocuments struct {
	DocumentNumber []uint64
	Segment        uint64
}

SegmentTermDocuments identifies the physical documents containing a term.

type SegmentTermFrequencies

type SegmentTermFrequencies struct {
	Values  []TermFrequency
	Segment uint64
}

SegmentTermFrequencies identifies term frequencies in one segment.

type SnapshotMetadata

type SnapshotMetadata struct {
	ID       uint64
	Segments []SnapshotSegment
}

SnapshotMetadata describes the committed generation pinned by a Reader. It contains manifest metadata only; segment payloads remain file-backed by the Reader and are not materialized by this method.

func ReadStrictSnapshotMetadata

func ReadStrictSnapshotMetadata(path string, held func(segmentID uint64) *Reader) (SnapshotMetadata, error)

ReadStrictSnapshotMetadata returns the manifest metadata of the newest committed snapshot in path after validating it as a restart would -- OpenStrict, then OpenSnapshotSegment per segment -- for callers that need only the metadata: garbage collection scanning for live segment IDs, for example. It keeps no file open and shares nothing with serving readers. Every segment must be a regular file, named without following a symbolic link (Lstat). For a segment held returns an open Reader of -- one the caller already serves from a validated file -- the path must still name that very file (os.SameFile against the descriptor's fstat at open) with its size, which is checked without opening it. Every other segment is opened, checked to be the very file Lstat described, and validated, without page-cache advice.

func (SnapshotMetadata) TimeBounds

func (m SnapshotMetadata) TimeBounds() (lo, hi int64, ok bool)

TimeBounds returns the smallest and largest timestamp the segments of m record. A segment recording no timestamp, or bounds folded across a sign change (min above max), is skipped; ok is false when no segment is left.

type SnapshotSegment

type SnapshotSegment struct {
	ID             uint64
	Size           uint64
	DocumentCount  uint64
	TimeMin        uint64
	TimeMax        uint64
	DeletionBitmap []byte
}

SnapshotSegment is the immutable metadata a snapshot manifest records for one segment. DeletionBitmap is copied when metadata is exported and must be treated as read-only by callers.

type SnapshotSegmentPayload

type SnapshotSegmentPayload struct {
	SnapshotSegment
	Payload []byte
	// SourcePath is a validated standalone segment file to copy as a new
	// immutable segment. It is mutually exclusive with Payload.
	SourcePath string
	// Source is an open single-segment Reader to copy as a new immutable
	// segment, read through the Reader itself rather than by path, so the
	// copy never depends on the name its file has at the time. The caller
	// keeps it open until PublishSnapshot returns. It is mutually exclusive
	// with Payload and SourcePath.
	Source *Reader
	// TrustedExisting skips reparsing an existing segment's dictionaries. It
	// is valid only for a nil Payload after the caller has opened the same
	// immutable directory with OpenStrict and still holds the owner lease.
	// The publication path still checks regular-file kind and size; the owner
	// lease, not those checks, is what guarantees the already-validated file
	// identity remains immutable.
	TrustedExisting bool
	// Promotion, set with Payload, follows the admitted segment whose
	// payload Payload is through this publication: once the snapshot is
	// published it records the identity of the file written, for
	// OpenPromotedSegment. Payload must be that segment's own payload.
	Promotion *Promotion
}

SnapshotSegmentPayload is one immutable segment reference in a new snapshot. A non-nil Payload is written as a new segment; a nil Payload references an already-published segment with the metadata in SnapshotSegment. Payload is consumed synchronously and is not retained by this package.

type StoredDocument

type StoredDocument interface {
	// VisitStoredFields calls visit once for every stored value the document
	// records, passing the field's name and its raw value bytes. A field the
	// document records more than once is visited once per recorded value, in
	// the order the document records them. Visiting stops early when visit
	// returns false.
	//
	// The name and value handed to visit are borrowed from the reader's decode
	// buffers and stay valid only until visit returns; a caller that keeps
	// either beyond that copies it.
	VisitStoredFields(visit func(name string, value []byte) bool) error
}

StoredDocument is one live document of the pinned generation, borrowed for the duration of a single walk callback.

type TermFrequency

type TermFrequency struct {
	DocumentNumber uint64
	Frequency      uint64
}

TermFrequency is one document's stored occurrence frequency for a term.

type TermPosting

type TermPosting struct {
	OneHit bool
	// Bitmap is the caller-owned multi-document posting bitmap. It is exposed
	// so query engines that support bitmap optimization can combine postings
	// without materializing a document slice first.
	Bitmap         *roaringpkg.Bitmap
	Documents      []uint64
	Frequencies    []TermFrequency
	DocumentNumber uint64
}

TermPosting is the exact posting for one dictionary term. OneHit is set for the compact single-document encoding, allowing callers to consume it without allocating document and frequency slices.

type TimestampCover

type TimestampCover struct {
	// Start is the first dictionary key in the run, inclusive.
	Start []byte
	// End is the exclusive dictionary key one past the run. It is nil only
	// where the run reaches the top shift, where no larger key exists at this
	// level.
	End []byte
}

TimestampCover runs covers the closed sortable interval [lo, hi] with dictionary term ranges instead of bucket indices, so a caller can iterate a segment's _timestamp dictionary directly.

func TimestampCoverKeys

func TimestampCoverKeys(lo, hi uint64) []TimestampCover

TimestampCoverKeys runs SplitSortableRange over [lo, hi] and turns each emitted bucket run into the dictionary bounds that select it. Keys are in sortable units, so a caller passes sortableInt64 of its own range.

The end key is the encoding of the bucket after the run, because dictionary iterators take an exclusive bound. Where the run reaches the largest bucket at its level there is no such key, so the end becomes the first key of the next shift level: the shift byte leads each key, so every key of this level sorts below it. Above the top shift the end is nil, which an iterator reads as unbounded.

Jump to

Keyboard shortcuts

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