native

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: 25 Imported by: ? 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 native provides bounded, committed-generation read-only operations.

Index

Constants

View Source
const (
	// RepairSortFieldCount is the fixed number of Property repair tuple fields.
	RepairSortFieldCount = 4
	// MaxRepairPageSize bounds one repair page.
	MaxRepairPageSize = 1 << 16
	// MaxRepairSortValueLength bounds one encoded repair tuple component.
	MaxRepairSortValueLength = 64 << 10
)
View Source
const (
	// MaxSQLPatternBytes bounds the UTF-8 bytes in one LIKE or ILIKE pattern.
	MaxSQLPatternBytes = 1024
	// MaxSQLPatterns bounds LIKE and ILIKE conjuncts in one native request.
	MaxSQLPatterns = 16
)
View Source
const LadderFieldSuffix = "#t"

LadderFieldSuffix is appended to the name of a sort field to name its companion ladder field. The companion holds, for every document that carries a scalar ladder key, the prefix-coded terms of that key at each precision level (shift 0 to 60 in steps of 4), the same numeric trie the engine keeps for _timestamp. It is a separate field because a sort field may be an opaque keyword whose dictionary range queries must not see prefix-coded terms.

Variables

View Source
var (
	// ErrOwnerClosed reports a mutation or acquire after owner shutdown.
	ErrOwnerClosed = errors.New("native: owner is closed")
	// ErrViewClosed reports a read through a released pinned view.
	ErrViewClosed = errors.New("native: view is closed")
	// ErrInvalidDocument reports a mutation that cannot be admitted.
	ErrInvalidDocument = errors.New("native: invalid document")
	// ErrLeaseUnavailable reports a missing or invalid database ownership lease.
	ErrLeaseUnavailable = errors.New("native: root lease unavailable")
	// ErrStaleCompaction reports a compaction built from a root superseded by
	// another admission. Its output is discarded rather than resurrecting late
	// deletes or updates.
	ErrStaleCompaction = errors.New("native: stale compaction root")
	// ErrPersistenceConfiguration reports mutually exclusive test and durable
	// persistence configurations.
	ErrPersistenceConfiguration = errors.New("native: invalid persistence configuration")
	// ErrPersistenceBusy reports garbage collection while persistence work or
	// an active immutable view still retains files.
	ErrPersistenceBusy = errors.New("native: persistence or view references remain")
	// ErrPersistenceFailed reports an owner that encountered an uncertain
	// durability result. The in-memory root remains readable, but new writes
	// are rejected until the owner is reopened and the on-disk snapshot is
	// validated again.
	ErrPersistenceFailed = errors.New("native: persistence failed")
)
View Source
var ErrCorrupt = nativeice.ErrCorrupt

ErrCorrupt reports malformed committed-generation bytes.

View Source
var ErrExternalSegmentState = errors.New("native: invalid external segment state")

ErrExternalSegmentState reports an invalid receiver lifecycle transition.

View Source
var ErrInvalidQuery = errors.New("native: invalid query")

ErrInvalidQuery reports a query mode or shape that cannot be executed by the native primitives without changing its meaning.

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

ErrInvalidRepairPage identifies an invalid page size or continuation cursor.

View Source
var ErrInvalidSelection = nativeice.ErrInvalidSelection

ErrInvalidSelection reports that a TermSelection names no field, or that its term count or one of its term lengths exceeds the bound the read-only reader serves. It is distinct from ErrCorrupt: nothing on disk is damaged, the request itself is outside the reader's bounds, so no dictionary is opened and no posting is decoded.

View Source
var ErrNoSnapshot = nativeice.ErrNoSnapshot

ErrNoSnapshot reports an index directory with no committed generation.

View Source
var ErrQueryLimit = errors.New("native: query budget exceeded")

ErrQueryLimit reports a caller-supplied term or candidate budget that was exceeded. Native execution never silently turns an unbounded dictionary expansion into an all-documents scan.

Functions

func DecodeTimestamp

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

DecodeTimestamp decodes one series/property document's stored "_timestamp" field value, in the same prefix-coded int64 layout the owner's encoder writes (newMemorySegment) and ProjectHit already decodes internally. It is exported for offline tools that walk stored documents directly (via VisitLiveDocuments/StoredFields) instead of going through ProjectHit, so they never need their own encoding of this reserved field.

func NewestGenerationFiles

func NewestGenerationFiles(dir string) ([]string, error)

NewestGenerationFiles returns the file names ReferencedFiles would return for the generation OpenReadOnlyGenerationStrict opens in dir, after the same strict validation, but without page-cache advice and with no file left open: for a caller that needs only the names.

func ReadOnlyDocCount

func ReadOnlyDocCount(path string) (int64, error)

ReadOnlyDocCount opens the index directory at path read-only and returns the number of indexed (live, non-deleted) documents. Unlike a writable owner it never acquires exclusive directory ownership, so it can inspect a closed (or even concurrently open) index without reopening its writer. A missing or unflushed index (no usable committed generation) returns a count of 0 together with the open error, which callers may treat as an empty index.

func ReadOnlySelectDocuments

func ReadOnlySelectDocuments(ctx context.Context, path string, selection TermSelection, visit func(doc StoredDocument) error) error

ReadOnlySelectDocuments opens the index directory at path read-only, pins its newest structurally complete committed generation and calls visit once for every live document of that generation the selection holds, streaming one document at a time. See ReadOnlyGeneration.VisitSelectedDocuments for the selection semantics, and ReadOnlyWalkDocuments for the open/error contract.

func ReadOnlyWalkDocuments

func ReadOnlyWalkDocuments(ctx context.Context, path string, visit func(doc StoredDocument) error) error

ReadOnlyWalkDocuments opens the index directory at path read-only, pins its newest structurally complete committed generation and calls visit once for every live document that generation holds, streaming one document at a time. Documents the pinned generation's deletion masks cover are skipped.

It never acquires exclusive directory ownership and writes no bytes, so a directory a live owner holds can be walked while it is being written, and the walk leaves file contents, modification times and directory entries unchanged.

A directory holding no committed generation reports an error wrapping ErrNoSnapshot, which callers that treat a cold or unflushed index as empty match on. Committed bytes that violate the on-disk grammar report an error wrapping ErrCorrupt. Canceling ctx stops the walk between two documents and returns ctx.Err(); an error from visit stops the walk and is returned as-is.

func TimestampSortValue

func TimestampSortValue(timestamp int64) []byte

TimestampSortValue returns the sort value a document with the given timestamp carries in its sorted "_timestamp" doc value, so a caller that already holds QueryHit.Timestamp can order or merge hits by time without reading the doc value again. The returned bytes are owned by the caller.

func TopFieldCandidateBuilds

func TopFieldCandidateBuilds() int64

TopFieldCandidateBuilds returns how many per-segment candidate sets TopFieldHits and TopFieldPlan have built so far. It exists for tests only.

func ValidateWildcardPattern

func ValidateWildcardPattern(pattern WildcardPattern) error

ValidateWildcardPattern checks syntax without compiling or opening storage.

Types

type Batch

type Batch struct {
	Documents []Document
	Deletes   [][]byte
	// Mode selects upsert, insert-only, or insert-if-absent admission for
	// Documents. The default zero value is BatchUpsert.
	Mode               BatchMode
	PersistentCallback func(error)
}

Batch is one serialized admission operation. Deletes are applied before Documents, so an update cannot leave two live physical documents.

type BatchMode

type BatchMode uint8

BatchMode selects how Batch treats a document whose identifier may already be live elsewhere in the owner.

const (
	// BatchUpsert replaces any live document sharing an identifier. This is
	// the default (zero value) and Batch's original, only behavior.
	BatchUpsert BatchMode = iota
	// BatchInsertOnly preserves every physical document, including duplicate
	// identifiers, admitting them as new physical documents rather than
	// replacing an earlier live one.
	BatchInsertOnly
	// BatchInsertIfAbsent skips a document when some segment already has a
	// live posting for its identifier and that segment's field-name set
	// contains every field name the document carries; otherwise it upserts
	// exactly like BatchUpsert. The check runs under the owner lock against
	// the admission root, so it is serialized with every other admission.
	BatchInsertIfAbsent
)

type Document

type Document struct {
	Identifier []byte
	Fields     []Field
	Timestamp  int64
}

Document is one physical document admitted to a native segment.

type ExternalDedupMode

type ExternalDedupMode uint8

ExternalDedupMode controls how introducing an external segment (EnableExternalSegments) treats an identifier the incoming segment shares with one already live elsewhere in the owner.

const (
	// ExternalDedupNone introduces every incoming document unconditionally.
	// Neither copy is masked, so a shared identifier ends up live in more than
	// one segment. This is the default and preserves the legacy native
	// receiver's append-only semantics.
	ExternalDedupNone ExternalDedupMode = iota
	// ExternalDedupPreferIncoming masks the existing live copy of every
	// identifier the incoming segment also carries, so the incoming document
	// wins. This is today's DeduplicateExternal=true behavior.
	ExternalDedupPreferIncoming
	// ExternalDedupKeepExisting masks an incoming document whose identifier is
	// already live elsewhere, in the incoming segment's own deletion bitmap,
	// leaving every existing segment untouched, so the existing document wins.
	ExternalDedupKeepExisting
)

type ExternalSegmentStreamer

type ExternalSegmentStreamer interface {
	StartSegment() error
	WriteChunk([]byte) error
	CompleteSegment() error
	Status() string
	BytesReceived() uint64
}

ExternalSegmentStreamer receives one complete immutable native ICE segment. Chunks are staged in a temporary file until CompleteSegment validates and atomically introduces the segment into the owner's next publication root.

type Field

type Field struct {
	Name      string
	Value     []byte
	Terms     []Term
	LadderKey int64
	Store     bool
	Index     bool
	Sort      bool
	Ladder    bool
}

Field is an opaque native field. Product schema and analyzer types stay outside this package; callers provide encoded names, values, and terms.

A Field with Ladder, Index and Sort set also writes a companion ladder field named Name+LadderFieldSuffix that holds the prefix-coded terms of LadderKey at every precision level, which lets ReadView.TopFieldHits and SortCursor find the first documents in sort order without reading every candidate. LadderKey must be order-preserving: a smaller key must belong to a value that sorts before the value of a larger key. Only scalar values may set Ladder.

type FieldRequest

type FieldRequest struct {
	Field         string
	Scope         QueryScope
	MaxTerms      uint64
	MaxCandidates uint64
}

FieldRequest selects documents having an actual indexed posting for Field. Stored-only values and indexed fields with no terms are absent. MaxTerms is required because field presence is implemented by bounded dictionary expansion rather than by decoding every stored document.

type FileRootLease

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

FileRootLease adapts the database-owned root lock to the neutral native owner capability. The caller retains ownership and closes the lock only after the native owner has closed.

func NewFileRootLease

func NewFileRootLease(lock fs.File, root string) (*FileRootLease, error)

NewFileRootLease validates that lock is the root/lock capability protecting root and returns a lease suitable for OwnerOptions. No directory is created and the lock is never acquired by this constructor.

func (*FileRootLease) Revoke

func (l *FileRootLease) Revoke() error

Revoke invalidates this capability before its database-owned lock is released. The lock file may remain on disk, so checking its path alone is not sufficient to prove that this lease is still live.

func (*FileRootLease) Revoked

func (l *FileRootLease) Revoked() bool

Revoked reports whether this lease can no longer authorize access, without the lock-file stat Validate performs.

func (*FileRootLease) Validate

func (l *FileRootLease) Validate() error

Validate verifies that the capability has not been revoked and that its lock pathname still exists. The constructor is intentionally restricted to storage-owned callers holding the lock; native code does not acquire or infer lock ownership from a pathname.

func (*FileRootLease) ValidatePath

func (l *FileRootLease) ValidatePath(path string) error

ValidatePath verifies that a native index directory remains inside the leased root. It does not create or scan the directory.

type MatchRequest

type MatchRequest struct {
	Field       string
	Term        []byte
	SeriesField string
	SeriesID    []byte
	TimeRange   *TimeRange
	// contains filtered or unexported fields
}

MatchRequest describes an exact indexed term plus optional series/time constraints. Names and terms are already encoded by the caller.

type MatchResult

type MatchResult struct {
	Identifiers [][]byte
	Timestamps  []int64
}

MatchResult returns copied external identifiers and timestamps. Physical segment ordinals are an implementation detail and never escape this API.

type MergeDocument

type MergeDocument struct {
	SegmentID      uint64
	DocumentNumber uint64
	StoredFields   func(func(name string, value []byte) bool) error
}

MergeDocument describes one visible physical document while a root is being compacted. StoredFields is borrowed for the duration of the callback; a callback must copy values it retains. Returning true adds the document to the private merge drop set. Existing root deletion masks are applied before this callback is invoked.

type Owner

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

Owner serializes mutation admission and publishes immutable roots. A root is a shallow copy-on-write list of immutable segments; acquiring a view is O(1) and does not clone documents. Deletes clone only affected segment masks. Persistence runs after publication, so a durability failure reports an error without rolling back the already-visible in-memory root.

func NewOwner

func NewOwner(options OwnerOptions) (*Owner, error)

NewOwner creates or recovers a native publication root. A valid database lease is required even for an empty owner, making ownership an executable invariant.

func (*Owner) Acquire

func (o *Owner) Acquire(ctx context.Context) (*ReadView, error)

Acquire pins the currently published root without copying its documents.

func (*Owner) Activity

func (o *Owner) Activity() (admittedDocuments, acquiredViews uint64)

Activity returns the owner's monotonic activity counters: documents admitted by Batch and read views pinned by Acquire.

func (*Owner) Batch

func (o *Owner) Batch(ctx context.Context, batch Batch) error

Batch admits one operation and publishes the resulting root before starting asynchronous persistence. The callback is invoked exactly once, with the persistence result; admission errors are reported synchronously and do not publish a root.

func (*Owner) Close

func (o *Owner) Close() error

Close stops new admissions and waits for owner-started persistence calls. Existing views remain valid until their own Close.

Close takes no context parameter by design: its final persistence flush must run to completion regardless of any caller's own cancellation, the same way draining activeOps and the maintenance goroutine already do, so it uses context.Background() rather than one.

func (*Owner) Collect

func (o *Owner) Collect(ctx context.Context) error

Collect is the concise alias for CollectGarbage.

func (*Owner) CollectGarbage

func (o *Owner) CollectGarbage(ctx context.Context) error

CollectGarbage removes obsolete owner-created manifests and segments after validating the newest committed snapshot. It never removes unknown files, newer uncertain snapshots, the current root, or a root with active readers.

func (*Owner) Compact

func (o *Owner) Compact(ctx context.Context) error

Compact plans and executes at most one bounded merge task outside the admission lock, then publishes the result only if every segment the task merged is still present, unchanged, in the current root. A stale build is discarded, leaving all old segment files and references untouched for readers and prior manifests.

Unlike a design that always merges every live segment into one, Compact delegates to planMerges (see mergeplan.go) so that routine calls only combine a bounded batch of comparably small segments, and a segment is retired from further merging once it crosses a size ceiling. That keeps a single merge's cost proportional to its own tier instead of to the whole index, which is what lets compaction keep pace with a long, continuous burst of small writes (for example OAP's schema-registry preload) instead of every cycle re-merging an ever-growing backlog. Compact is a no-op (nil, nil) once the root is already within the tiered budget; see forceMergeAll for unconditionally sweeping every segment, for example to guarantee a product's PrepareMergeCallback reclaims a tombstone sitting alone in a not-yet-tiered segment.

func (*Owner) DurableGeneration

func (o *Owner) DurableGeneration() uint64

DurableGeneration returns the newest generation whose persistence completed successfully. It is monotonic and does not imply caller-visible query state.

func (*Owner) EnableExternalSegments

func (o *Owner) EnableExternalSegments() (ExternalSegmentStreamer, error)

EnableExternalSegments creates a native segment receiver. It does not publish a root until CompleteSegment succeeds.

func (*Owner) Reset

func (o *Owner) Reset() error

Reset publishes an empty root. Existing pinned views remain readable until they close; the reset itself is persisted through the same background worker as normal writes.

func (*Owner) ResetPresenceCache

func (o *Owner) ResetPresenceCache()

ResetPresenceCache drops every memoized InsertIfAbsent presence entry. It never touches admitted data; the next InsertIfAbsent batch simply recomputes presence from the admission root. It is a no-op when OwnerOptions.PresenceCacheBytes was not positive.

func (*Owner) Stats

func (o *Owner) Stats() (dataCount int64, dataSizeBytes int64)

Stats returns the current live document count and immutable segment bytes. It observes the current in-memory root and does not reopen a cold directory.

func (*Owner) TakeFileSnapshot

func (o *Owner) TakeFileSnapshot(destination string) error

TakeFileSnapshot publishes a copy of the current pinned root. Unlike a committed-directory copy, this includes admitted NRT segments even when their asynchronous persistence has not completed. The destination manifest is installed last by nativeice.PublishSnapshot.

type OwnerOptions

type OwnerOptions struct {
	Lease                RootLease
	Persist              PersistFunc
	PrepareMergeCallback PrepareMergeCallback
	// Path enables the built-in ICE snapshot publisher. An empty path keeps the
	// owner in memory-only mode unless Persist is supplied for a test seam.
	Path string
	// CompactionThreshold schedules one serialized background compaction after
	// this many immutable segments are published. Zero uses a conservative
	// default; a negative value disables scheduling for maintenance tests.
	CompactionThreshold int
	// ExternalDedup controls whether external segment introduction masks
	// existing or incoming identifiers. It defaults to ExternalDedupNone to
	// preserve legacy receiver semantics; callers that need deduplication opt
	// into one of the other modes explicitly.
	ExternalDedup ExternalDedupMode
	// PersistInterval is the minimum time between two background persists.
	// Zero persists as soon as an admission wakes the worker. A positive
	// interval lets compaction merge a write burst's small segments in memory
	// before they are written, like the legacy engine's persister nap, so
	// callers that wait on PersistentCallback should leave it zero. Close
	// persists everything admitted regardless.
	PersistInterval time.Duration
	// PresenceCacheBytes bounds the memory an InsertIfAbsent presence cache
	// may use to remember "identifier present with this field set" per root
	// generation. Zero or negative disables the cache; every InsertIfAbsent
	// admission then recomputes presence from the admission root.
	PresenceCacheBytes int
	// IdentifierDocValues makes the encoder and merger write "_id" as a
	// doc-value column in addition to its term, matching the layout the
	// previous release's writer produces so a rolled-back node can still read
	// document identity back from a segment this owner wrote.
	IdentifierDocValues bool
	// TimeMetrics receives time-range pruning classification and savings
	// counts from every query this owner serves. Nil, the default, drops
	// every count.
	TimeMetrics TimeMetrics
}

OwnerOptions supplies database ownership and asynchronous persistence.

type PathRootLease

type PathRootLease interface {
	RootLease
	ValidatePath(string) error
}

PathRootLease binds a lease to the directory whose immutable files the owner publishes. Disk-backed owners refuse an unbound lease so a caller cannot accidentally publish outside the database-owned root.

type PersistFunc

type PersistFunc func(context.Context, *ReadView) error

PersistFunc receives a pinned immutable view after in-memory publication. It must persist only the new immutable segments and publication metadata; it must not mutate the view. The owner releases the view after the callback.

type PostingFilter

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

PostingFilter is a boolean tree over term sets and ranges that a search evaluates on the postings of one segment, before it decodes any document. Every leaf is evaluated against the whole segment and then combined, so a selective filter costs the postings it touches and not a document per candidate. A negation subtracts from the candidates the filter is applied to, the way a hit-level subtraction of the same condition would.

A leaf keeps the bitmap it evaluated for each segment, so a search that evaluates the filter again (a chunk that grows, a fallback) expands a wildcard pattern or a range once, not once per evaluation. That makes a filter valid for the segments of one view only: build one filter per search and do not use it with another view.

func AllOf

func AllOf(children ...*PostingFilter) *PostingFilter

AllOf matches the documents every child matches. No child matches everything. A nested AllOf is spliced into this one, and the single-term ranges of one field are folded into one range, so the order the conditions were joined in does not decide whether two bounds of a field meet.

func AnyOf

func AnyOf(children ...*PostingFilter) *PostingFilter

AnyOf matches the documents at least one child matches. No child matches nothing.

func FilterRanges

func FilterRanges(request RangeRequest) *PostingFilter

FilterRanges matches the documents whose field falls in a range, as FilterRange does: a document matches when any of its terms falls in the range.

func FilterSingleTermRanges

func FilterSingleTermRanges(request RangeRequest) *PostingFilter

FilterSingleTermRanges is FilterRanges over a field that holds exactly one term per document. Two such ranges of one field inside an AllOf fold into one range with the tightest bounds, so only the dictionary terms between the bounds are expanded. A field that can hold several terms (an analyzed text, an array) must not use it: a document with the terms "apple" and "zebra" matches "x >= m" and "x <= c" taken one at a time, and matches no term of the folded range [m, c].

func FilterTerms

func FilterTerms(request TermSetRequest) *PostingFilter

FilterTerms matches the documents a term set selects, as FilterTermsSet does. A request with no terms and no pattern matches nothing. The request carries no time range.

func MatchAll

func MatchAll() *PostingFilter

MatchAll matches every candidate.

func MatchNone

func MatchNone() *PostingFilter

MatchNone matches no candidate.

func NotOf

func NotOf(child *PostingFilter) *PostingFilter

NotOf matches the candidates the child does not match.

type PrepareMergeCallback

type PrepareMergeCallback func(context.Context, MergeDocument) (drop bool, err error)

PrepareMergeCallback supplies product-specific expiry/tombstone policy without exposing ICE readers or allowing a callback to mutate a published root. It runs synchronously while Compact owns a pinned immutable root.

type ProjectedHit

type ProjectedHit struct {
	QueryHit
	Fields map[string][][]byte
}

ProjectedHit contains one candidate's owned stored fields and coordinates. Segment and DocumentNumber remain available for stable physical identity.

type QueryHit

type QueryHit struct {
	Identifier     []byte
	SeriesID       []byte
	Timestamp      int64
	Segment        uint64
	DocumentNumber uint64
}

QueryHit is an owned candidate projection. Segment and DocumentNumber are internal tie-break coordinates retained only while SortHits is called.

type QueryScope

type QueryScope struct {
	SeriesField string
	SeriesID    []byte
	SeriesIDs   [][]byte
	TimeRange   *TimeRange
}

QueryScope carries the optional series and timestamp constraints shared by native membership operations. SeriesID is matched against SeriesField as an exact encoded term. A timestamp range excludes documents without a stored native timestamp.

type RangeRequest

type RangeRequest struct {
	Field         string
	Lower         []byte
	Upper         []byte
	IncludesLower bool
	IncludesUpper bool
	Scope         QueryScope
	MaxTerms      uint64
	MaxCandidates uint64
}

RangeRequest selects terms in encoded byte order. Numeric callers provide the native prefix-coded endpoint bytes; no numeric library or analyzer is used here. A nil endpoint is unbounded, while a non-nil empty endpoint is a valid empty term bound.

type ReadOnlyGeneration

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

ReadOnlyGeneration owns one immutable native ICE generation. The selected snapshot is fixed when it is opened; later files published in the directory are invisible until another generation is opened.

func OpenReadOnlyGeneration

func OpenReadOnlyGeneration(path string) (*ReadOnlyGeneration, error)

OpenReadOnlyGeneration opens the newest structurally complete committed generation without creating or modifying files. ErrNoSnapshot is returned when the directory has no committed generation, and ErrCorrupt is returned when committed candidates are malformed.

func OpenReadOnlyGenerationStrict

func OpenReadOnlyGenerationStrict(path string) (*ReadOnlyGeneration, error)

OpenReadOnlyGenerationStrict opens only the newest committed snapshot in path, like a writer reopening the directory at startup, and never falls back to an older generation when that newest manifest or one of its segments is damaged: it returns ErrCorrupt (or another decode error) instead. Use this -- instead of the lenient OpenReadOnlyGeneration, which deliberately recovers the newest structurally complete generation for best-effort offline tools -- wherever a silent rollback to stale data would be a correctness bug, for example reading a closed segment's acknowledged generation for a backup or a doc-count report: a corrupt newest manifest must fail loudly there rather than make the backup (or the live owner, which already opens strict) disagree about which generation is current.

func (*ReadOnlyGeneration) Close

func (g *ReadOnlyGeneration) Close() error

Close releases the pinned generation. It is idempotent and must not be called concurrently with another operation on the same generation.

func (*ReadOnlyGeneration) NewSeriesIterator

func (g *ReadOnlyGeneration) NewSeriesIterator(ctx context.Context) (*SeriesIterator, error)

NewSeriesIterator creates a bounded k-way dictionary merge over the pinned generation. Deleted terms remain visible because this is metadata access.

func (*ReadOnlyGeneration) ReferencedFiles

func (g *ReadOnlyGeneration) ReferencedFiles() []string

ReferencedFiles returns the on-disk file names (relative to the index directory, not full paths) the pinned generation's manifest references: its own snapshot manifest file and every segment file it lists, in the same "%012x.snp" / "%012x.seg" naming Encode and the owner's persister write. A caller that must copy or hard-link only the current generation -- for example snapshotting a closed (cold) index directory -- uses this to exclude superseded snapshots and segments a live owner has not yet garbage collected, instead of copying the whole directory.

func (*ReadOnlyGeneration) RepairTuplePage

func (g *ReadOnlyGeneration) RepairTuplePage(ctx context.Context, request RepairPageRequest) ([]RepairRow, error)

RepairTuplePage returns one bounded page ordered by Property's fixed repair tuple: group, name, entity ID, and timestamp. The generation remains pinned across pages, so a publication after the first page is invisible.

func (*ReadOnlyGeneration) SnapshotID

func (g *ReadOnlyGeneration) SnapshotID() uint64

SnapshotID returns the identifier of the generation pinned at open time.

func (*ReadOnlyGeneration) StoredFields

func (g *ReadOnlyGeneration) StoredFields(ctx context.Context, docID []byte, projection ...string) (map[string][][]byte, error)

StoredFields returns the first live physical document whose identifier is docID. Stored values are copied before the borrowed native document is released. Internal bookkeeping fields are always omitted; projection names are applied to the remaining fields. A missing identifier returns nil, nil.

func (*ReadOnlyGeneration) TimeBounds

func (g *ReadOnlyGeneration) TimeBounds() (lo, hi int64, ok bool)

TimeBounds returns the smallest and largest "_timestamp" the pinned generation's segments record in their footers, without reading any document. The footers count deleted documents too, so the range may be wider than the live documents. 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.

func (*ReadOnlyGeneration) VisibleDocCount

func (g *ReadOnlyGeneration) VisibleDocCount() (int64, error)

VisibleDocCount returns the number of live (non-deleted) documents the pinned generation holds. It is the read-only counterpart to Owner.Stats for a closed/cold index directory: callers that need a document count without reopening a writable owner (for example, reporting a segment's series-index size while it is idle-closed) open a ReadOnlyGeneration and call this instead of reopening the owner.

func (*ReadOnlyGeneration) VisitIdentifiers

func (g *ReadOnlyGeneration) VisitIdentifiers(ctx context.Context, visit func([]byte) bool) error

VisitIdentifiers visits each identifier term in committed segment order. Terms from deleted documents are intentionally included because this seam is metadata enumeration rather than a live query hit walk. The identifier passed to visit is copied and remains valid after the callback. Returning false stops the walk without error; global lexical ordering across segments is not promised.

func (*ReadOnlyGeneration) VisitLiveDocuments

func (g *ReadOnlyGeneration) VisitLiveDocuments(ctx context.Context, visit func(doc StoredDocument) error) error

VisitLiveDocuments calls visit once for every live document the pinned generation holds, streaming one document at a time. Documents the generation's deletion masks cover are skipped. Canceling ctx stops the walk between two documents and returns ctx.Err(); an error visit returns stops the walk and is returned as-is.

This is the read-only counterpart to a writable owner's full contents that offline tools use instead of opening one: the union-sidx builder and the index-mode Measure copy both need to re-emit every live series document through EncodeSeriesDocument without acquiring the exclusive directory ownership a native.Owner requires.

func (*ReadOnlyGeneration) VisitSelectedDocuments

func (g *ReadOnlyGeneration) VisitSelectedDocuments(ctx context.Context, selection TermSelection, visit func(doc StoredDocument) error) error

VisitSelectedDocuments calls visit once for every live document of the pinned generation the selection holds, streaming one document at a time.

The selection resolves exact terms against one field's dictionary, unions their postings and removes the pinned generation's deletion masks, so a deleted document is never handed to visit however many terms selected it, and a document several terms select is handed to visit once. A term the dictionary does not hold, and an empty term set, select nothing rather than failing. Selection precedes stored-field decoding, so a document the selection excludes has its stored bytes left unread.

A selection naming no field, or exceeding the reader's term-count or term-length bounds, reports an error wrapping ErrInvalidSelection before any document is visited. Canceling ctx stops posting decode, posting union or the read between two documents and returns ctx.Err(); an error from visit stops the read and is returned as-is.

type ReadOnlyIndexStats

type ReadOnlyIndexStats struct {
	// DocCount is the number of live, non-deleted documents.
	DocCount int64
	// MinTimestamp and MaxTimestamp are the bounds ReadOnlyGeneration.TimeBounds returns;
	// both are 0 when HasTime is false.
	MinTimestamp int64
	MaxTimestamp int64
	HasTime      bool
}

ReadOnlyIndexStats describes the committed generation of an index directory.

func ReadOnlyStats

func ReadOnlyStats(path string) (ReadOnlyIndexStats, error)

ReadOnlyStats opens the index directory at path read-only, as ReadOnlyDocCount does, and returns its document count and time bounds; the errors are those of ReadOnlyDocCount.

type ReadView

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

ReadView pins one immutable published root. It must be closed by its caller; closing is idempotent and releases exactly one root reference. The caller must not close a view concurrently with an operation on that same view; independent views may be used concurrently.

func (*ReadView) Close

func (v *ReadView) Close() error

Close releases the pinned root reference exactly once.

func (*ReadView) FilterRange

func (v *ReadView) FilterRange(ctx context.Context, hits []QueryHit, request RangeRequest) ([]QueryHit, error)

FilterRange keeps the hits, taken from this view, whose documents also fall in request's range, without decoding any stored document. request must not set Scope.TimeRange.

func (*ReadView) FilterTermsSet

func (v *ReadView) FilterTermsSet(ctx context.Context, hits []QueryHit, request TermSetRequest) ([]QueryHit, error)

FilterTermsSet keeps the hits, taken from this view, whose documents also match request. It tests posting membership only, so no stored document is decoded. request must not set Scope.TimeRange.

func (*ReadView) Generation

func (v *ReadView) Generation() uint64

Generation returns the immutable generation number pinned by the view.

func (*ReadView) Lookup

func (v *ReadView) Lookup(ctx context.Context, identifier []byte) (Document, bool, error)

Lookup returns a copied live document by external identifier.

func (*ReadView) MatchAllTermSets

func (v *ReadView) MatchAllTermSets(ctx context.Context, requests []TermSetRequest) ([]QueryHit, error)

MatchAllTermSets intersects several exact term sets at posting level and projects only the documents every set matches, so a selective conjunct bounds stored-document decoding no matter how broad the others are. The first request's Scope.TimeRange applies to projection; later requests must not set one.

func (*ReadView) MatchField

func (v *ReadView) MatchField(ctx context.Context, request FieldRequest) ([]QueryHit, error)

MatchField selects indexed-present documents using bounded dictionary expansion. It deliberately does not substitute schema or stored-field presence for posting membership.

func (*ReadView) MatchRange

func (v *ReadView) MatchRange(ctx context.Context, request RangeRequest) ([]QueryHit, error)

MatchRange selects encoded dictionary terms between the requested bounds. The dictionary remains bounded by MaxTerms and postings are combined before candidate-only identifier/timestamp projection.

func (*ReadView) MatchTerms

func (v *ReadView) MatchTerms(ctx context.Context, request MatchRequest) (MatchResult, error)

MatchTerms performs exact membership against the pinned immutable root. Segment-local adapters can replace the in-memory matcher with dictionary and posting cursors without changing this read-view contract.

func (*ReadView) MatchTermsSet

func (v *ReadView) MatchTermsSet(ctx context.Context, request TermSetRequest) ([]QueryHit, error)

MatchTermsSet performs exact any/all term matching over one pinned root. Deletion masks and QueryScope are applied before hits escape the view.

func (*ReadView) MatchTermsSetPrefixFiltered

func (v *ReadView) MatchTermsSetPrefixFiltered(ctx context.Context, request TermSetRequest, filter *PostingFilter, limit int,
) (hits []QueryHit, truncated bool, err error)

MatchTermsSetPrefixFiltered is MatchTermsSet over the candidates that the filter also matches, listing at most limit of them: it takes the first documents of each segment in document order and decodes only those, so a caller that needs a few of the candidates neither reads nor charges the rest. The filter is evaluated on postings, before any document is decoded, so a selective filter lists and charges only the documents it keeps instead of every candidate. truncated reports that candidates were left out, so the caller can ask for more. A nil filter keeps every candidate, and a non-positive limit lists every candidate and never truncates.

func (*ReadView) NewSortCursor

func (v *ReadView) NewSortCursor(ctx context.Context, request SortCursorRequest) (*SortCursor, error)

NewSortCursor creates a keyset-paginated ordered cursor over one pinned root. A positive MaxCandidates is enforced globally across segments.

func (*ReadView) NewTopFieldPlan

func (v *ReadView) NewTopFieldPlan(ctx context.Context, request TopFieldRequest) (*TopFieldPlan, error)

NewTopFieldPlan builds the candidates of request in every segment once. request.Limit is ignored; Top takes the limit.

func (*ReadView) ProjectHit

func (v *ReadView) ProjectHit(ctx context.Context, hit QueryHit, fields ...string) (ProjectedHit, error)

ProjectHit reads one physical candidate from the pinned root without an identifier posting lookup. All returned bytes are owned by the caller.

func (*ReadView) ProjectSortValue

func (v *ReadView) ProjectSortValue(ctx context.Context, hit QueryHit, field string) ([]byte, bool, error)

ProjectSortValue returns the smallest copied doc value for one candidate.

func (*ReadView) SortHits

func (v *ReadView) SortHits(ctx context.Context, hits []QueryHit, request SortRequest) ([]QueryHit, error)

SortHits orders only the supplied candidates. It reads one candidate's doc values at a time and retains at most Offset+Limit items when a positive limit is requested; ICE doc values are not assumed to be sorted streams.

func (*ReadView) TopFieldHits

func (v *ReadView) TopFieldHits(ctx context.Context, request TopFieldRequest) ([]QueryHit, error)

TopFieldHits returns at most Limit candidates in the order SortHits gives Field: the smallest doc value first (the largest with Desc), a document without the field last in both directions, ties by identifier, segment and document. A segment whose ladder for Field is complete is not read in full: the descent selects the buckets that can rank inside the first Limit, and only those documents are decoded and ranked. Any other segment, and any segment whose descent cannot prove the result, ranks all its candidates, so the result never depends on whether a ladder exists.

func (*ReadView) TopTimeHits

func (v *ReadView) TopTimeHits(ctx context.Context, request TopTimeRequest) ([]QueryHit, error)

TopTimeHits returns at most Limit candidates in timestamp order (newest first with Desc), ties by identifier, segment and document, the order SortHits gives the _timestamp field. It does not read every candidate: per segment it walks the _timestamp trie from the coarsest useful level, takes the buckets that rank inside the first Limit whole, refines only the bucket that holds the Limit-th document, and decodes the few documents that remain. A segment whose trie or time bounds cannot be trusted, or whose candidates are few, is read in full instead.

func (*ReadView) VisitIdentifiers

func (v *ReadView) VisitIdentifiers(ctx context.Context, visit func([]byte) bool) error

VisitIdentifiers enumerates physical identifiers in snapshot order, including deleted metadata entries. Returning false stops without error.

type RepairCursor

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

RepairCursor is an opaque continuation position belonging to one generation.

type RepairPageRequest

type RepairPageRequest struct {
	// After must be a cursor returned by this generation; nil starts the scan.
	After *RepairCursor
	// PageSize must be positive and no greater than MaxRepairPageSize.
	PageSize int
}

RepairPageRequest selects one bounded ascending repair page.

type RepairRow

type RepairRow struct {
	Cursor     *RepairCursor
	SortValues [][]byte
	Value      []byte
}

RepairRow contains the fixed tuple values and projected stored value.

type RootLease

type RootLease interface {
	Validate() error
}

RootLease is supplied by the database owner. Native indexing never creates or manages an index-local lock; it only verifies this capability before admitting writes.

type SeriesIterator

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

SeriesIterator enumerates distinct _id terms from one pinned generation in lexical order. Values returned by Next are owned by the caller.

func (*SeriesIterator) Close

func (i *SeriesIterator) Close() error

Close releases all dictionary cursors. It is safe to call repeatedly.

func (*SeriesIterator) Next

func (i *SeriesIterator) Next() ([]byte, error)

Next returns the next distinct identifier. A nil identifier with nil error indicates exhaustion. Cancellation and malformed dictionary data are returned unchanged (or wrapped by nativeice as corruption).

type SortCursor

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

SortCursor retains per-segment candidate bitmaps and one page-sized frontier per call. It never materializes the complete hit list. The caller keeps the ReadView pinned until Close and must not use the view concurrently with its own Close.

func (*SortCursor) Close

func (c *SortCursor) Close() error

Close releases cursor scratch and is idempotent. The caller still owns the pinned ReadView and must close it separately.

func (*SortCursor) NextPage

func (c *SortCursor) NextPage(ctx context.Context) ([]SortedHit, error)

NextPage returns the next ordered page and advances its keyset position. Cancellation is checked between candidates and leaves the cursor closeable.

type SortCursorRequest

type SortCursorRequest struct {
	Selection TermSetRequest
	Range     *RangeRequest
	SortField string
	Desc      bool
	PageSize  int
}

SortCursorRequest describes one pinned-view candidate selection and one bounded ordered page. Selection terms are exact encoded bytes; analyzer and numeric conversion remain caller responsibilities.

type SortKey

type SortKey struct {
	Value          []byte
	Missing        bool
	Identifier     []byte
	Segment        uint64
	DocumentNumber uint64
}

SortKey is a complete keyset cursor position. Segment and document coordinates make equal repeated values and duplicate identifiers stable. Callers should treat the byte slices as immutable and owned by the cursor.

type SortRequest

type SortRequest struct {
	Field  string
	Desc   bool
	Offset int
	Limit  int
}

SortRequest orders candidate-only results by the smallest encoded repeated doc value. Missing values sort last in either direction. Limit zero means return all candidates; positive limits use a bounded top-K frontier.

type SortedHit

type SortedHit struct {
	QueryHit
	SortValue []byte
	Missing   bool
}

SortedHit is a candidate-only projection with the selected sort value. Repeated values use the smallest encoded value and missing values sort last in both directions.

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, in the
	// order the document recorded them. The name and value handed to visit
	// are borrowed and stay valid only until visit returns.
	VisitStoredFields(visit func(name string, value []byte) bool) error
}

StoredDocument is one live physical document of a committed generation, borrowed for the duration of a single VisitLiveDocuments callback. It mirrors nativeice.StoredDocument's shape without exposing that internal package to callers outside pkg/index.

type Term

type Term struct {
	Value     []byte
	Frequency uint64
}

Term is one already encoded exact indexed term.

type TermSelection

type TermSelection struct {
	// Field is the name of the indexed field whose term dictionary the
	// selection resolves against.
	Field string
	// Terms are the literal term byte sequences to select. The documents
	// selected are the union of these terms' postings; an empty Terms selects
	// no document.
	Terms [][]byte
}

TermSelection is the one bounded document filter a read-only walk accepts: the documents whose Field records any of the literal byte sequences in Terms.

It is deliberately not a query language. There is exactly one field, the terms are matched as raw bytes with no analysis or normalization, and they are unioned. There is no range, prefix, wildcard, negation, conjunction, existence test, scoring, projection or ordering, and the term dictionary and postings that resolve a selection stay private to the reader.

type TermSetMode

type TermSetMode uint8

TermSetMode controls whether a term-set selection uses union or intersection semantics.

const (
	// MatchAnyTerm selects a document containing at least one requested term.
	MatchAnyTerm TermSetMode = iota
	// MatchAllTerms selects a document containing every requested term.
	MatchAllTerms
)

type TermSetRequest

type TermSetRequest struct {
	Field string
	Terms [][]byte
	// Prefix selects every dictionary term in the half-open byte range
	// [p, successor(p)) for each p.
	Prefix [][]byte
	// Wildcard selects every dictionary term a `*`/`?` pattern matches. `*`
	// matches zero or more Unicode scalars and `?` matches one, excluding
	// newline. Every other character, including `|` and `\`, is literal.
	Wildcard [][]byte
	// WildcardPatterns extends Wildcard with syntax, escape and case options.
	WildcardPatterns []WildcardPattern
	// PatternBudget shares wildcard pattern limits across the worker execution. A nil
	// budget selects the bounded defaults for this native call.
	PatternBudget *WildcardBudget
	Mode          TermSetMode
	Scope         QueryScope
	MaxTerms      uint64
	MaxCandidates uint64
}

TermSetRequest selects exact encoded terms from one field, ORed with every term the dictionary expansion of Prefix and Wildcard matches. The caller owns term analysis and encoding; native execution only performs byte-exact dictionary membership and, for Prefix/Wildcard, dictionary-bounded pattern matching. Field combination (Any/All, via Mode) treats Terms, each Prefix expansion, and each Wildcard expansion as one operand apiece. MaxTerms bounds the number of dictionary terms Prefix and Wildcard may expand to and is required when either is non-empty, like MatchRange. WildcardPatterns select syntax and case handling for the same native wildcard compiler and search.

type TimeMetrics

type TimeMetrics interface {
	// IncTimeSegments records one segment's time-range classification:
	// "disjoint", "contained", "overlap_trie", or "overlap_fallback".
	IncTimeSegments(class string)
	// AddTimeCandidatesPruned adds delta candidates removed from a segment's
	// candidate set by intersecting it with the _timestamp trie's coverage.
	AddTimeCandidatesPruned(delta uint64)
}

TimeMetrics receives the outcome of a native query's time-range pruning decisions (native-index-time-pruning design, §6). Implementations must be safe for concurrent use: a query records inline, under no owner-wide lock. A nil TimeMetrics is valid everywhere one is read and simply drops every count, so OwnerOptions.TimeMetrics is optional.

type TimeRange

type TimeRange struct {
	Lower         int64
	Upper         int64
	IncludesLower bool
	IncludesUpper bool
}

TimeRange is an inclusive/exclusive timestamp interval.

type TopFieldPlan

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

TopFieldPlan holds the candidates of a TopFieldRequest, narrowed per segment, so that the first limit documents can be asked for several times (a search that grows its chunk until enough survive a filter) without building the candidates again. The plan reads the view's segments: it must not be used after the view it came from is closed, and its bitmaps are never modified after they are built.

func (*TopFieldPlan) Candidates

func (p *TopFieldPlan) Candidates() uint64

Candidates returns how many documents the plan ranks among, over all segments.

func (*TopFieldPlan) Hits

func (p *TopFieldPlan) Hits(ctx context.Context) ([]QueryHit, error)

Hits returns every candidate of the plan, in segment then document order, without ranking them: the universe a caller ranks itself when the plan's chunks would read most of it anyway.

func (*TopFieldPlan) Top

func (p *TopFieldPlan) Top(ctx context.Context, limit int) ([]QueryHit, error)

Top returns at most limit candidates in the order SortHits gives the plan's field, exactly as TopFieldHits does.

type TopFieldRequest

type TopFieldRequest struct {
	Candidates TermSetRequest
	// Filter, when set, narrows the candidates at posting level, before any document is decoded, so a selective filter
	// ranks only the documents it keeps.
	Filter *PostingFilter
	Field  string
	Limit  int
	Desc   bool
}

TopFieldRequest asks for the first Limit documents, ordered by the sort doc value of Field, among the candidates of one term-set request. Candidates.Scope.TimeRange is optional.

type TopTimeRequest

type TopTimeRequest struct {
	// Filter, when set, narrows the candidates at posting level, before any document is decoded, so a selective filter
	// ranks only the documents it keeps.
	Filter     *PostingFilter
	Candidates TermSetRequest
	Limit      int
	Desc       bool
}

TopTimeRequest asks for the first Limit documents, in timestamp order, among the candidates of one term-set request. The request's Scope.TimeRange is required: documents without a timestamp never match a time range, which is what makes the _timestamp trie a complete index of the candidates.

type WildcardBudget

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

WildcardBudget is shared by all native scans in one query execution. Parsed programs are cached only with an explicit memory owner; mutable automaton states remain local to one native call.

func NewWildcardBudget

func NewWildcardBudget(limits WildcardLimits) *WildcardBudget

NewWildcardBudget constructs a concurrency-safe, query-owned budget.

func NewWildcardBudgetWithMemory

func NewWildcardBudgetWithMemory(limits WildcardLimits, reserve func(int64) error, release func(int64)) *WildcardBudget

NewWildcardBudgetWithMemory retains immutable programs against an execution memory owner. Both callbacks must be supplied to enable caching. Close must run after all native searches finish, including error and cancellation exits.

func (*WildcardBudget) Close

func (b *WildcardBudget) Close() error

Close drops cached programs before releasing their execution-owned charge. It is idempotent and must not overlap native searches using this budget.

func (*WildcardBudget) Stats

func (b *WildcardBudget) Stats() WildcardStats

Stats returns counters, which never exceed their configured limits.

type WildcardLimits

type WildcardLimits struct{ MaxWork, MaxTerms, MaxBytes uint64 }

WildcardLimits bounds work, expanded terms and cumulative allocation across one worker request. Zero fields select the bounded server defaults.

type WildcardPattern

type WildcardPattern struct {
	Pattern    string
	Escape     string
	IgnoreCase bool
	Syntax     WildcardSyntax
}

WildcardPattern describes a whole-value pattern. Escape is empty to disable escaping, or one Unicode scalar. The zero syntax retains native glob semantics; SQL callers select WildcardSyntaxSQL and supply their SQL escape character.

type WildcardStats

type WildcardStats struct{ Work, Terms, Bytes uint64 }

WildcardStats reports cumulative work, matching terms and reserved bytes.

type WildcardSyntax

type WildcardSyntax uint8

WildcardSyntax selects the operators and newline semantics of a pattern.

const (
	// WildcardSyntaxGlob recognizes '*' and '?'. Wildcards exclude newline,
	// matching the existing native wildcard contract.
	WildcardSyntaxGlob WildcardSyntax = iota
	// WildcardSyntaxSQL recognizes '%' and '_', including newline.
	WildcardSyntaxSQL
)

Directories

Path Synopsis
Package criteria translates modelv1.Criteria into pkg/index/native engine calls over a candidate set of native.QueryHit.
Package criteria translates modelv1.Criteria into pkg/index/native engine calls over a candidate set of native.QueryHit.

Jump to

Keyboard shortcuts

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