stream

package
v0.11.2 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: Apache-2.0 Imports: 81 Imported by: 1 module, 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 stream implements a time-series-based storage which is consists of a sequence of element. Each element drops in a arbitrary interval. They are immutable, can not be updated or overwritten.

Index

Constants

View Source
const PartTypeCore = "core"

PartTypeCore is the type of the core part.

Variables

View Source
var ErrQueryMemoryBudgetExceeded = errors.New("stream: vectorized query memory budget exceeded")

ErrQueryMemoryBudgetExceeded is returned by the vec scan when a block would be decoded past the per-query QueryMemoryMiB soft budget (after the first-block exception). The scan fails loud rather than silently dropping the block, so the vec path preserves parity with the row path (which errors under memory pressure via the protector) — a partial result would break vec==row equivalence.

View Source
var (

	// ErrStreamNotExist denotes a stream doesn't exist in the metadata repo.
	ErrStreamNotExist = errors.New("stream doesn't exist")
)

Functions

func BuildElementsFromBatches added in v0.11.0

func BuildElementsFromBatches(batches []*vectorized.RecordBatch,
	projectionTags []model.TagProjection,
) ([]*streamv1.Element, error)

BuildElementsFromBatches materializes []*streamv1.Element from an already-drained slice of columnar batches (the M4 pipeline output). It is the egress used by the data-node standalone path — the batches hold the merged/deduped/limited result in memory rather than a live scan source. It delegates to the shared vec egress (vstream) so the columnar→proto conversion is identical to the liaison side.

func BuildElementsFromVecBatches added in v0.11.0

func BuildElementsFromVecBatches(ctx context.Context, source vecScanSource,
	projectionTags []model.TagProjection,
) (elements []*streamv1.Element, err error)

BuildElementsFromVecBatches drains a columnar scan source and materializes []*streamv1.Element from the batch columns. The Element shape is byte-for-byte identical to BuildElementsFromStreamResult: hex-encoded elementID, timestamppb timestamp, and tag families/tags in projection order (with NullTagValue for a missing projected tag).

This is the standalone (§5.6b) in-process egress used by M6's local path. It does NOT apply cross-source dedup/order/limit — those are M4 operators applied upstream; this function preserves whatever order/dedup the batches already carry, matching the row egress' per-result behavior.

func CountBlugeDocs added in v0.11.0

func CountBlugeDocs(path string) (uint64, error)

CountBlugeDocs opens the bluge index at path read-only and returns the total document count. Used by verify to spot-check idx/ and sidx/.

func CreatePartFileReaderFromPath added in v0.9.0

func CreatePartFileReaderFromPath(partPath string, lfs fs.FileSystem) ([]queue.FileInfo, func())

CreatePartFileReaderFromPath opens all files in a part directory and returns their FileInfo and a cleanup function.

func FastPathHits added in v0.11.0

func FastPathHits() int64

FastPathHits returns the number of source parts that took the fast (byte-copy) path.

func ParsePartMetadata added in v0.9.0

func ParsePartMetadata(fileSystem fs.FileSystem, partPath string) (queue.StreamingPartData, error)

ParsePartMetadata parses the part metadata from the metadata.json file.

func SlowPathHits added in v0.11.0

func SlowPathHits() int64

SlowPathHits returns the number of source parts that went through the slow path.

func SlowPathRows added in v0.11.0

func SlowPathRows() int64

SlowPathRows returns the total source-row count across slow-path parts.

func SumGroupSourceRows added in v0.11.0

func SumGroupSourceRows(srcRoots []string, fileSystem fs.FileSystem) (uint64, int, error)

SumGroupSourceRows walks every <root>/seg-*/shard-*/<partID>/ across the given source roots, opens each part read-only, and returns the total row count plus the part count.

func VerifyShardParts added in v0.11.0

func VerifyShardParts(shardDir string, fileSystem fs.FileSystem) (uint64, int, error)

VerifyShardParts reads the newest .snp under shardDir, confirms every listed partID has an on-disk directory, opens each part, and returns the sum of partMetadata.TotalCount plus the part count.

func VisitStreamsInTimeRange added in v0.9.0

func VisitStreamsInTimeRange(tsdbRootPath string, timeRange timestamp.TimeRange, visitor Visitor, segmentInterval storage.IntervalRule) ([]string, error)

VisitStreamsInTimeRange traverses stream segments within the specified time range and calls the visitor methods for series index, parts, and element indexes. This function works directly with the filesystem without requiring a database instance. Returns a list of segment suffixes that were visited.

Types

type AnalyzeDiffResult added in v0.11.0

type AnalyzeDiffResult struct {
	Missing     []AnalyzeMissingRow
	Extra       []AnalyzeExtraRow
	SourceRows  uint64
	TargetRows  uint64
	MissingRows uint64
	MissingKeys int
	ExtraRows   uint64
	ExtraKeys   int
}

AnalyzeDiffResult is the source-vs-target multiset diff for stream. Stream never deduplicates, so the diff should always be zero in a correct migration. Any non-zero MissingRows or ExtraRows indicates a true bug.

func AnalyzeGroupDiffWithTarget added in v0.11.0

func AnalyzeGroupDiffWithTarget(
	srcRoots []string,
	targetGroupRoot string,
	fileSystem fs.FileSystem,
	sampleCap int,
) (AnalyzeDiffResult, error)

AnalyzeGroupDiffWithTarget builds a (seriesID, ts, elementID) multiset for source and target, then computes the set diff. For a correct stream migration the diff is always zero. Any missing row is a true bug.

type AnalyzeExtraRow added in v0.11.0

type AnalyzeExtraRow struct {
	PartPath  string
	SeriesID  common.SeriesID
	Timestamp int64
	ElementID uint64
}

AnalyzeExtraRow names one (seriesID, ts, elementID) tuple that appears in target more times than in source — indicating a duplicate incorrectly introduced by the copy.

type AnalyzeGroupResult added in v0.11.0

type AnalyzeGroupResult struct {
	PartsScanned uint64
	TotalRows    uint64
	UniqueKeys   uint64
}

AnalyzeGroupResult is the per-group output of AnalyzeGroupRows, which walks every source part under srcRoots and decodes only block metadata + timestamps + elementIDs (NOT tag bodies — cheap scan). For stream, TotalRows == UniqueKeys always (no dedup); any MissingRows in a src-vs-tgt diff is a real bug.

func AnalyzeGroupRows added in v0.11.0

func AnalyzeGroupRows(srcRoots []string, fileSystem fs.FileSystem) (AnalyzeGroupResult, error)

AnalyzeGroupRows scans all source parts and counts rows.

type AnalyzeMissingRow added in v0.11.0

type AnalyzeMissingRow struct {
	PartPath  string
	SeriesID  common.SeriesID
	Timestamp int64
	ElementID uint64
}

AnalyzeMissingRow names one (seriesID, ts, elementID) tuple that exists in source but not in target after a migration copy.

type DumpRow added in v0.11.0

type DumpRow struct {
	Entity    string
	Tags      []DumpTag
	SeriesID  common.SeriesID
	Timestamp int64
	ElementID uint64
}

DumpRow is one stream element for BuildPartForDump. When Entity is set the SeriesID is derived as hash(Entity) and (optionally) written to smeta.bin.

func BuildEntityPartWithSeriesMeta added in v0.11.0

func BuildEntityPartWithSeriesMeta(tmpPath string, fileSystem fs.FileSystem, partID uint64, entities []string) (string, []DumpRow, func())

BuildEntityPartWithSeriesMeta builds an entity-keyed stream part (via EntityDumpRows) and writes a matching smeta.bin so the dump tool can resolve each row's EntityValues.

func BuildPartForDump added in v0.11.0

func BuildPartForDump(tmpPath string, fileSystem fs.FileSystem, partID uint64, rows []DumpRow) (string, []DumpRow, func())

BuildPartForDump writes rows into a stream part at root/<partID>, returning the part directory, the rows (with resolved SeriesID) for verification and a cleanup func. When writeSeriesMeta is true a matching smeta.bin is written for every row that carries an Entity.

func EntityDumpRows added in v0.11.0

func EntityDumpRows(entities []string) []DumpRow

EntityDumpRows returns one element per entity whose SeriesID is hash(entity), each carrying a single meta.name string tag. Pair with writeSeriesMeta=true to also emit smeta.bin.

func StandardDumpRows added in v0.11.0

func StandardDumpRows() []DumpRow

StandardDumpRows returns the canonical stream fixture: three elements exercising string / int64 / string-array / int64-array tags across two tag families, with one element carrying no tags.

type DumpTag added in v0.11.0

type DumpTag struct {
	Value  any
	Family string
	Name   string
}

DumpTag describes one tag of a stream row for the dump test builder. Value is a Go-native value (string, int64, []string, []int64 or []byte) encoded through the production encodeTagValue path.

type EntryGroupReport added in v0.11.0

type EntryGroupReport struct {
	Group       string
	EntryStage  string
	EntryTarget string
	TargetGroup string
	EntryNodes  []string
	SrcRoots    []string
	TargetSegs  []SegmentReport
	SrcRows     uint64
	SrcParts    int
}

EntryGroupReport aggregates source row count + target per-seg report for one (entry, group) pair. Both source and target are read-only.

type Filter added in v0.10.0

type Filter interface {
	MightContain(item []byte) bool
}

Filter interface provides a unified interface for both BloomFilter and DictionaryFilter.

type MigrationExecutor added in v0.11.0

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

MigrationExecutor is the stream implementation of migration.CatalogExecutor: it copies / verifies stream groups one (entry, group) at a time under the shared orchestrator.

func NewMigrationExecutor added in v0.11.0

func NewMigrationExecutor() *MigrationExecutor

NewMigrationExecutor returns the stream catalog executor.

func (*MigrationExecutor) Catalog added in v0.11.0

func (e *MigrationExecutor) Catalog() commonv1.Catalog

Catalog reports CATALOG_STREAM.

func (*MigrationExecutor) CopyEntryGroup added in v0.11.0

CopyEntryGroup migrates one (entry, group): discovers source parts, rewrites them onto the target grid and finalizes the element index.

func (*MigrationExecutor) LogPrefix added in v0.11.0

func (e *MigrationExecutor) LogPrefix() string

LogPrefix tags this executor's progress lines.

func (*MigrationExecutor) Prepare added in v0.11.0

func (e *MigrationExecutor) Prepare(_ context.Context, schemaRoot string, groups []string) error

Prepare loads the stream schemas and per-stream index locators of the given groups from the schema-property catalog.

func (*MigrationExecutor) VerifyEntryGroup added in v0.11.0

func (e *MigrationExecutor) VerifyEntryGroup(_ context.Context, in migration.EntryGroupInput, onReport func(report any)) error

VerifyEntryGroup re-reads one (entry, group) read-only: it sums source rows, enumerates target segments (including per-shard idx/ doc counts), and emits a EntryGroupReport.

Core invariant: stream never deduplicates, so srcRows == tgtRows strictly.

type NodeSelector added in v0.9.0

type NodeSelector interface {
	Locate(group, name string, shardID, replicaID uint32) (string, error)
	fmt.Stringer
}

NodeSelector provides functionality to locate nodes for data distribution.

type Query

type Query interface {
	LoadGroup(name string) (schema.Group, bool)
	Stream(stream *commonv1.Metadata) (Stream, error)
	GetRemovalSegmentsTimeRange(group string) *timestamp.TimeRange
}

Query allow to retrieve elements in a series of streams.

type SchemaService added in v0.5.0

type SchemaService interface {
	Query
	Close()
}

SchemaService allows querying schema information.

type SegmentReport added in v0.11.0

type SegmentReport struct {
	StartTime    time.Time
	EndTime      time.Time
	Seg          string
	Shards       []ShardReport
	Rows         uint64
	SidxDocCount uint64
	Parts        int
	Aligned      bool
	SidxOpened   bool
}

SegmentReport summarizes one seg-* directory under a stream group root. Populated by EnumerateGroupTarget for the migration verify CLI.

Aligned is true only when ALL of the following hold:

  • the dir name parses cleanly into a start time;
  • start = IntervalRule.Standard(start) (start is on the grid);
  • <seg>/metadata exists, is well-formed JSON, and carries a non-empty endTime;
  • end = IntervalRule.NextTime(start) (segment spans exactly one bucket);
  • the inclusive last instant (end - 1ns) standardizes back to start.

func EnumerateGroupTarget added in v0.11.0

func EnumerateGroupTarget(groupRoot string, intervalRule storage.IntervalRule, fileSystem fs.FileSystem) ([]SegmentReport, error)

EnumerateGroupTarget walks <groupRoot>/seg-* and reports per-segment row total + sidx doc count + per-shard idx doc count + whether the segment's start time aligns to the supplied IntervalRule's standard grid. A missing groupRoot returns (nil, nil).

type Service

type Service interface {
	run.PreRunner
	run.Config
	run.Service
	Query
	CollectDataInfo(context.Context, string) (*databasev1.DataInfo, error)
	CollectLiaisonInfo(context.Context, string) (*databasev1.LiaisonInfo, error)
	VectorizedConfig() vstream.VectorizedConfig
}

Service allows inspecting the stream elements.

func NewLiaison added in v0.9.0

func NewLiaison(metadata metadata.Repo, pipeline queue.Server, omr observability.MetricsRegistry, pm protector.Memory,
	dataNodeSelector node.Selector, tire2Client queue.Client,
) (Service, error)

NewLiaison creates a new stream liaison service with the given dependencies.

func NewReadonlyService added in v0.8.0

func NewReadonlyService(metadata metadata.Repo, omr observability.MetricsRegistry, pm protector.Memory) (Service, error)

NewReadonlyService returns a new readonly service.

func NewService

func NewService(
	metadata metadata.Repo,
	pipeline queue.Server,
	omr observability.MetricsRegistry,
	pm protector.Memory,
	internalWritePipeline queue.Server,
) (Service, error)

NewService returns a new service.

type ShardReport added in v0.11.0

type ShardReport struct {
	Shard       string
	IdxDocCount uint64
	Rows        uint64
	Parts       int
	IdxOpened   bool
}

ShardReport summarizes one shard-N directory inside a segment, including the element index (idx/) bluge doc count (stream-only).

type Stream

type Stream interface {
	GetSchema() *databasev1.Stream
	GetIndexRules() []*databasev1.IndexRule
	Query(ctx context.Context, opts model.StreamQueryOptions) (model.StreamQueryResult, error)
	QueryVectorized(ctx context.Context, opts model.StreamQueryOptions) (executor.StreamVecScanSource, error)
	VectorizedConfig() vstream.VectorizedConfig
}

Stream allows inspecting elements' details.

type Visitor added in v0.9.0

type Visitor interface {
	// VisitSeries visits the series index directory for a segment.
	VisitSeries(segmentTR *timestamp.TimeRange, seriesIndexPath string, shardIDs []common.ShardID) error
	// VisitPart visits a part directory within a shard.
	VisitPart(segmentTR *timestamp.TimeRange, shardID common.ShardID, partPath string) error
	// VisitElementIndex visits the element index directory within a shard.
	VisitElementIndex(segmentTR *timestamp.TimeRange, shardID common.ShardID, indexPath string) error
}

Visitor defines the interface for visiting stream components.

Jump to

Keyboard shortcuts

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