You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@skywalking.apache.org by ha...@apache.org on 2026/09/17 05:39:46 UTC
(skywalking-banyandb) branch main updated: feat(index): encode Property documents as native ICE v3 segment bytes (#1345)
This is an automated email from the ASF dual-hosted git repository.
hanahmily pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/skywalking-banyandb.git
The following commit(s) were added to refs/heads/main by this push:
new 6d6e40858 feat(index): encode Property documents as native ICE v3 segment bytes (#1345)
6d6e40858 is described below
commit 6d6e4085858d4afbab9beb24bb35fb8e7bfcd708
Author: Gao Hongtao <ha...@gmail.com>
AuthorDate: Thu Sep 17 13:39:41 2026 +0800
feat(index): encode Property documents as native ICE v3 segment bytes (#1345)
---
CHANGES.md | 2 +
pkg/index/inverted/internal/nativeice/encode.go | 592 +++++++++++++++++++++
.../internal/nativeice/encode_contract_test.go | 493 +++++++++++++++++
.../inverted/internal/nativeice/encode_test.go | 351 ++++++++++++
pkg/index/inverted/native_fixture_nidx02a_test.go | 393 ++++++++++++++
pkg/index/inverted/native_nidx01b_boundary_test.go | 15 +-
.../inverted/native_nidx01e_tuple_page_test.go | 13 +-
pkg/index/inverted/native_nidx02a_encode_test.go | 407 ++++++++++++++
.../inverted/testdata/nidx02a/provenance.json | 103 ++++
.../testdata/nidx02a/shard-0/000000000002.seg | Bin 0 -> 3057 bytes
.../testdata/nidx02a/shard-0/000000000003.snp | Bin 0 -> 68 bytes
11 files changed, 2366 insertions(+), 3 deletions(-)
diff --git a/CHANGES.md b/CHANGES.md
index 2931458e4..70761914e 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -6,6 +6,8 @@ Release Notes.
### Features
+- Add a native ICE v3 encoder that writes committed index generations compatible with existing readers.
+
- Add logging related flags to the FODC proxy and agent. Every BanyanDB binary now shares the same logging flags and the matching `BYDB_LOGGING_*` environment variables.
- [Breaking Change] Remove the row-based query execution path from the Stream, Measure and Trace query engines. Measure TopN pre-aggregation is unchanged and still executes row-based. The `--stream-vectorized-enabled`, `--trace-vectorized-enabled` and `--measure-vectorized-enabled` flags stay registered but no longer select an engine; `=false` now fails fast at startup on standalone, data and liaison nodes. A query shape the vectorized engine cannot plan now returns an error instead of f [...]
- Push the criteria tag filter ahead of the vectorized stream merge, so a filtered index-order query bounds its merge at limit+offset. For such a query, where several rows share an ElementID, the criteria is now evaluated first and the element is represented by its first matching row in the requested sort order. Filtered timestamp-order queries are unchanged.
diff --git a/pkg/index/inverted/internal/nativeice/encode.go b/pkg/index/inverted/internal/nativeice/encode.go
new file mode 100644
index 000000000..276a41fae
--- /dev/null
+++ b/pkg/index/inverted/internal/nativeice/encode.go
@@ -0,0 +1,592 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with this work for
+// additional information regarding copyright ownership. The ASF licenses this
+// file to you under the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations
+// under the License.
+
+package nativeice
+
+import (
+ "bytes"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "hash/crc32"
+ "io"
+ "math"
+ "os"
+ "path/filepath"
+ "sort"
+
+ roaringpkg "github.com/RoaringBitmap/roaring"
+ "github.com/blevesearch/vellum"
+ "github.com/klauspost/compress/s2"
+)
+
+// identifierField is the name ICE v3 reserves for the document identifier, the
+// field every segment records first. Encode writes each document's Identifier
+// under this name, so a walk yields it ahead of the document's other stored
+// values and a selection resolves it like any other exact term.
+const identifierField = "_id"
+
+// 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.
+var ErrInvalidGeneration = errors.New("nativeice: invalid generation")
+
+// 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 EncodeField struct {
+ // Name is the segment field name the value is recorded under.
+ Name string
+ // Value is the field's raw bytes.
+ Value []byte
+ // 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
+}
+
+// EncodeDocument is one physical document of a generation.
+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
+}
+
+// Generation is one committed ICE v3 generation: the documents it holds and the
+// identifiers its segment and snapshot manifest are numbered by.
+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
+}
+
+// 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 Encode(path string, generation Generation) error {
+ if validationErr := validateGeneration(generation); validationErr != nil {
+ return validationErr
+ }
+ segmentPayload, deletionBitmap, segmentErr := encodeNativeSegment(generation)
+ if segmentErr != nil {
+ return segmentErr
+ }
+ if directoryErr := os.MkdirAll(path, 0o755); directoryErr != nil {
+ return fmt.Errorf("create index directory %q: %w", path, directoryErr)
+ }
+ segmentName := nativeICEFileName(generation.SegmentID, ".seg")
+ if publishErr := publishNativeICEFile(path, segmentName, segmentPayload); publishErr != nil {
+ return fmt.Errorf("publish segment %q: %w", segmentName, publishErr)
+ }
+ manifestPayload := encodeNativeSnapshot(generation, uint64(len(segmentPayload)), deletionBitmap)
+ manifestName := nativeICEFileName(generation.SnapshotID, ".snp")
+ if publishErr := publishNativeICEFile(path, manifestName, manifestPayload); publishErr != nil {
+ return fmt.Errorf("publish snapshot %q: %w", manifestName, publishErr)
+ }
+ return nil
+}
+
+func validateGeneration(generation Generation) error {
+ for documentIndex, document := range generation.Documents {
+ if len(document.Identifier) == 0 {
+ return fmt.Errorf("document %d has no identifier: %w", documentIndex, ErrInvalidGeneration)
+ }
+ for fieldIndex, field := range document.Fields {
+ if field.Name == "" {
+ return fmt.Errorf("document %d field %d has no name: %w", documentIndex, fieldIndex, ErrInvalidGeneration)
+ }
+ }
+ }
+ return nil
+}
+
+const nativeICEOneHitNorm uint64 = 1
+
+type nativeICEField struct {
+ documentNumbers map[uint64]struct{}
+ sortValues map[uint64][][]byte
+ termDocuments map[string][]uint64
+ name string
+ documentCount uint64
+ frequency uint64
+}
+
+func encodeNativeSegment(generation Generation) ([]byte, []byte, error) {
+ fields := nativeICEFields(generation)
+ fieldIDs := make(map[string]uint64, len(fields))
+ for fieldIndex, field := range fields {
+ fieldIDs[field.name] = uint64(fieldIndex)
+ }
+ storedData, documentOffsets := encodeStoredDocuments(generation, fieldIDs)
+ segment := make([]byte, 0, len(storedData)+len(documentOffsets)*storedDocumentOffsetByteWidth+segmentFooterLength)
+ segment = append(segment, storedData...)
+ storedIndexOffset := uint64(len(segment))
+ for _, documentOffset := range documentOffsets {
+ segment = appendNativeUint64(segment, documentOffset)
+ }
+ docValueStarts := make([]uint64, len(fields))
+ docValueEnds := make([]uint64, len(fields))
+ hasDocValues := false
+ for fieldIndex, field := range fields {
+ if len(field.sortValues) == 0 {
+ docValueStarts[fieldIndex] = math.MaxUint64
+ docValueEnds[fieldIndex] = math.MaxUint64
+ continue
+ }
+ hasDocValues = true
+ docValueStarts[fieldIndex] = uint64(len(segment))
+ segment = append(segment, encodeNativeICEDocValues(uint64(len(generation.Documents)), field.sortValues)...)
+ docValueEnds[fieldIndex] = uint64(len(segment))
+ }
+ fieldOffsets := make([]uint64, len(fields))
+ for fieldIndex, field := range fields {
+ var dictionaryOffset uint64
+ var termsErr error
+ segment, dictionaryOffset, termsErr = appendNativeICETerms(segment, field)
+ if termsErr != nil {
+ return nil, nil, termsErr
+ }
+ fieldOffsets[fieldIndex] = uint64(len(segment))
+ segment = appendNativeUvarint(segment, dictionaryOffset)
+ segment = appendNativeUvarint(segment, uint64(len(field.name)))
+ segment = append(segment, field.name...)
+ segment = appendNativeUvarint(segment, field.documentCount)
+ segment = appendNativeUvarint(segment, field.frequency)
+ }
+ var docValueOffset uint64 = math.MaxUint64
+ if hasDocValues {
+ docValueOffset = uint64(len(segment))
+ for fieldIndex := range fields {
+ segment = appendNativeUvarint(segment, docValueStarts[fieldIndex])
+ segment = appendNativeUvarint(segment, docValueEnds[fieldIndex])
+ }
+ }
+ fieldsIndexOffset := uint64(len(segment))
+ for _, fieldOffset := range fieldOffsets {
+ segment = appendNativeUint64(segment, fieldOffset)
+ }
+ footer := make([]byte, segmentFooterLength)
+ binary.BigEndian.PutUint64(footer[0:8], uint64(len(generation.Documents)))
+ binary.BigEndian.PutUint64(footer[8:16], storedIndexOffset)
+ binary.BigEndian.PutUint64(footer[16:24], fieldsIndexOffset)
+ binary.BigEndian.PutUint64(footer[24:32], docValueOffset)
+ binary.BigEndian.PutUint32(footer[32:36], 1)
+ binary.BigEndian.PutUint32(footer[52:56], segmentVersion)
+ segment = append(segment, footer...)
+ deletionBitmap, deletionErr := encodeDeletionBitmap(generation.Documents)
+ if deletionErr != nil {
+ return nil, nil, deletionErr
+ }
+ return segment, deletionBitmap, nil
+}
+
+func encodeNativeICEDocValues(documentCount uint64, sortValues map[uint64][][]byte) []byte {
+ chunkCount := (documentCount + docValueDocumentsPerChunk - 1) / docValueDocumentsPerChunk
+ chunkOffsets := make([]uint64, chunkCount)
+ encoded := make([]byte, 0)
+ for chunkIndex := uint64(0); chunkIndex < chunkCount; chunkIndex++ {
+ encoded = append(encoded, encodeNativeICEDocValueChunk(chunkIndex, documentCount, sortValues)...)
+ chunkOffsets[chunkIndex] = uint64(len(encoded))
+ }
+ chunkTable := make([]byte, 0, len(chunkOffsets)*binary.MaxVarintLen64)
+ for _, chunkOffset := range chunkOffsets {
+ chunkTable = appendNativeUvarint(chunkTable, chunkOffset)
+ }
+ encoded = append(encoded, chunkTable...)
+ encoded = appendNativeUint64(encoded, uint64(len(chunkTable)))
+ return appendNativeUint64(encoded, chunkCount)
+}
+
+func encodeNativeICEDocValueChunk(chunkIndex, documentCount uint64, sortValues map[uint64][][]byte) []byte {
+ firstDocument := chunkIndex * docValueDocumentsPerChunk
+ lastDocument := firstDocument + docValueDocumentsPerChunk
+ if lastDocument > documentCount {
+ lastDocument = documentCount
+ }
+ type documentValues struct {
+ documentNumber uint64
+ valueEnd uint64
+ }
+ values := make([]byte, 0)
+ header := make([]documentValues, 0)
+ for documentNumber := firstDocument; documentNumber < lastDocument; documentNumber++ {
+ documentTerms, found := sortValues[documentNumber]
+ if !found {
+ continue
+ }
+ for _, value := range documentTerms {
+ values = appendNativeICEDocValueTerm(values, value)
+ }
+ header = append(header, documentValues{documentNumber: documentNumber, valueEnd: uint64(len(values))})
+ }
+ if len(header) == 0 {
+ return nil
+ }
+ encoded := make([]byte, 0, len(header)*2*binary.MaxVarintLen64+len(values))
+ encoded = appendNativeUvarint(encoded, uint64(len(header)))
+ var previousDocument, previousValueEnd uint64
+ for _, value := range header {
+ encoded = appendNativeUvarint(encoded, value.documentNumber-previousDocument)
+ encoded = appendNativeUvarint(encoded, value.valueEnd-previousValueEnd)
+ previousDocument = value.documentNumber
+ previousValueEnd = value.valueEnd
+ }
+ return append(encoded, s2.Encode(nil, values)...)
+}
+
+func appendNativeICEDocValueTerm(destination, value []byte) []byte {
+ for _, valueByte := range value {
+ if valueByte == 0xff || valueByte == 0x5c {
+ destination = append(destination, 0x5c)
+ }
+ destination = append(destination, valueByte)
+ }
+ return append(destination, 0xff)
+}
+
+func nativeICEFields(generation Generation) []nativeICEField {
+ fieldsByName := make(map[string]*nativeICEField)
+ identifier := nativeICEFieldFor(fieldsByName, identifierField)
+ for documentIndex, document := range generation.Documents {
+ documentNumber := uint64(documentIndex)
+ registerNativeICETerm(identifier, document.Identifier, documentNumber)
+ for _, field := range document.Fields {
+ if !field.Store && !field.Index && !field.Sort {
+ continue
+ }
+ nativeField := nativeICEFieldFor(fieldsByName, field.Name)
+ if field.Index {
+ registerNativeICETerm(nativeField, field.Value, documentNumber)
+ }
+ if field.Sort {
+ nativeField.sortValues[documentNumber] = append(nativeField.sortValues[documentNumber], field.Value)
+ }
+ }
+ }
+ fieldNames := make([]string, 0, len(fieldsByName))
+ for fieldName := range fieldsByName {
+ fieldNames = append(fieldNames, fieldName)
+ }
+ sort.Strings(fieldNames)
+ fields := make([]nativeICEField, 0, len(fieldNames))
+ for _, fieldName := range fieldNames {
+ nativeField := fieldsByName[fieldName]
+ nativeField.documentCount = uint64(len(nativeField.documentNumbers))
+ fields = append(fields, *nativeField)
+ }
+ return fields
+}
+
+func nativeICEFieldFor(fieldsByName map[string]*nativeICEField, name string) *nativeICEField {
+ if field, found := fieldsByName[name]; found {
+ return field
+ }
+ field := &nativeICEField{
+ name: name,
+ documentNumbers: make(map[uint64]struct{}),
+ sortValues: make(map[uint64][][]byte),
+ termDocuments: make(map[string][]uint64),
+ }
+ fieldsByName[name] = field
+ return field
+}
+
+func registerNativeICETerm(field *nativeICEField, value []byte, documentNumber uint64) {
+ term := string(value)
+ documents := field.termDocuments[term]
+ if len(documents) == 0 || documents[len(documents)-1] != documentNumber {
+ field.termDocuments[term] = append(documents, documentNumber)
+ }
+ field.documentNumbers[documentNumber] = struct{}{}
+ field.frequency++
+}
+
+func appendNativeICETerms(segment []byte, field nativeICEField) ([]byte, uint64, error) {
+ if len(field.termDocuments) == 0 {
+ return segment, 0, nil
+ }
+ terms := make([]string, 0, len(field.termDocuments))
+ for term := range field.termDocuments {
+ terms = append(terms, term)
+ }
+ sort.Strings(terms)
+ values := make(map[string]uint64, len(terms))
+ for _, term := range terms {
+ documents := field.termDocuments[term]
+ if len(documents) == 1 && documents[0] <= fstValueDocumentMask {
+ values[term] = fstValueEncodingOneHit | (nativeICEOneHitNorm << 31) | documents[0]
+ continue
+ }
+ postingsOffset := uint64(len(segment))
+ var postingsErr error
+ segment, postingsErr = appendNativeICEPosting(segment, documents)
+ if postingsErr != nil {
+ return nil, 0, postingsErr
+ }
+ values[term] = postingsOffset
+ }
+ dictionaryOffset := uint64(len(segment))
+ var dictionary bytes.Buffer
+ builder, builderErr := vellum.New(&dictionary, nil)
+ if builderErr != nil {
+ return nil, 0, fmt.Errorf("create term dictionary for field %q: %w", field.name, builderErr)
+ }
+ for _, term := range terms {
+ if insertErr := builder.Insert([]byte(term), values[term]); insertErr != nil {
+ return nil, 0, errors.Join(fmt.Errorf("insert term into dictionary for field %q: %w", field.name, insertErr), builder.Close())
+ }
+ }
+ if closeErr := builder.Close(); closeErr != nil {
+ return nil, 0, fmt.Errorf("close term dictionary for field %q: %w", field.name, closeErr)
+ }
+ segment = appendNativeUvarint(segment, uint64(dictionary.Len()))
+ segment = append(segment, dictionary.Bytes()...)
+ return segment, dictionaryOffset, nil
+}
+
+func appendNativeICEPosting(segment []byte, documents []uint64) ([]byte, error) {
+ postings := roaringpkg.New()
+ for _, documentNumber := range documents {
+ if documentNumber > math.MaxUint32 {
+ return nil, fmt.Errorf("document %d exceeds the posting range: %w", documentNumber, ErrInvalidGeneration)
+ }
+ postings.Add(uint32(documentNumber))
+ }
+ payload, marshalErr := postings.MarshalBinary()
+ if marshalErr != nil {
+ return nil, fmt.Errorf("encode posting bitmap: %w", marshalErr)
+ }
+ segment = appendNativeUvarint(segment, 0)
+ segment = appendNativeUvarint(segment, 0)
+ segment = appendNativeUvarint(segment, uint64(len(payload)))
+ return append(segment, payload...), nil
+}
+
+func encodeStoredDocuments(generation Generation, fieldIDs map[string]uint64) ([]byte, []uint64) {
+ documentOffsets := make([]uint64, len(generation.Documents))
+ chunkOffsets := []uint64{0}
+ encoded := make([]byte, 0)
+ for firstDocument := 0; firstDocument < len(generation.Documents); firstDocument += storedDocumentsPerChunk {
+ lastDocument := firstDocument + storedDocumentsPerChunk
+ if lastDocument > len(generation.Documents) {
+ lastDocument = len(generation.Documents)
+ }
+ decodedChunk := make([]byte, 0)
+ for documentIndex := firstDocument; documentIndex < lastDocument; documentIndex++ {
+ documentOffsets[documentIndex] = uint64(len(decodedChunk))
+ decodedChunk = append(decodedChunk, encodeStoredDocument(generation.Documents[documentIndex], fieldIDs)...)
+ }
+ encoded = append(encoded, s2.Encode(nil, decodedChunk)...)
+ chunkOffsets = append(chunkOffsets, uint64(len(encoded)))
+ }
+ chunkTable := make([]byte, 0, len(chunkOffsets)*binary.MaxVarintLen64)
+ for _, chunkOffset := range chunkOffsets {
+ chunkTable = appendNativeUvarint(chunkTable, chunkOffset)
+ }
+ encoded = append(encoded, chunkTable...)
+ encoded = appendNativeUint32(encoded, uint32(len(chunkTable)))
+ return appendNativeUint32(encoded, uint32(len(chunkOffsets))), documentOffsets
+}
+
+func encodeStoredDocument(document EncodeDocument, fieldIDs map[string]uint64) []byte {
+ type storedValue struct {
+ name string
+ value []byte
+ }
+ values := []storedValue{{name: identifierField, value: document.Identifier}}
+ for _, field := range document.Fields {
+ if field.Store {
+ values = append(values, storedValue{name: field.Name, value: field.Value})
+ }
+ }
+ sort.SliceStable(values[1:], func(leftIndex, rightIndex int) bool {
+ return values[leftIndex+1].name < values[rightIndex+1].name
+ })
+ meta := make([]byte, 0, len(values)*3)
+ data := make([]byte, 0)
+ for _, value := range values {
+ meta = appendNativeUvarint(meta, fieldIDs[value.name])
+ meta = appendNativeUvarint(meta, uint64(len(data)))
+ meta = appendNativeUvarint(meta, uint64(len(value.value)))
+ data = append(data, value.value...)
+ }
+ encoded := make([]byte, 0, len(meta)+len(data)+2*binary.MaxVarintLen64)
+ encoded = appendNativeUvarint(encoded, uint64(len(meta)))
+ encoded = appendNativeUvarint(encoded, uint64(len(data)))
+ encoded = append(encoded, meta...)
+ return append(encoded, data...)
+}
+
+func encodeDeletionBitmap(documents []EncodeDocument) ([]byte, error) {
+ deleted := roaringpkg.New()
+ hasDeletedDocument := false
+ for documentIndex, document := range documents {
+ if !document.Deleted {
+ continue
+ }
+ if uint64(documentIndex) > math.MaxUint32 {
+ return nil, fmt.Errorf("document %d exceeds the deletion-mask range: %w", documentIndex, ErrInvalidGeneration)
+ }
+ deleted.Add(uint32(documentIndex))
+ hasDeletedDocument = true
+ }
+ if !hasDeletedDocument {
+ return nil, nil
+ }
+ payload, marshalErr := deleted.MarshalBinary()
+ if marshalErr != nil {
+ return nil, fmt.Errorf("encode deletion bitmap: %w", marshalErr)
+ }
+ return payload, nil
+}
+
+func encodeNativeSnapshot(generation Generation, segmentSize uint64, deletionBitmap []byte) []byte {
+ manifest := make([]byte, 0, 64+len(deletionBitmap))
+ manifest = appendNativeUvarint(manifest, snapshotVersion)
+ manifest = appendNativeUvarint(manifest, 1)
+ manifest = appendNativeUvarint(manifest, uint64(len("ice")))
+ manifest = append(manifest, "ice"...)
+ manifest = appendNativeUint32(manifest, segmentVersion)
+ manifest = appendNativeUvarint(manifest, generation.SegmentID)
+ manifest = appendNativeUint64(manifest, segmentSize)
+ manifest = appendNativeUint64(manifest, uint64(len(generation.Documents)))
+ manifest = appendNativeUint64(manifest, 0)
+ manifest = appendNativeUint64(manifest, 0)
+ manifest = appendNativeUvarint(manifest, uint64(len(deletionBitmap)))
+ manifest = append(manifest, deletionBitmap...)
+ return appendNativeUint32(manifest, crc32.ChecksumIEEE(manifest))
+}
+
+func appendNativeUvarint(destination []byte, value uint64) []byte {
+ var encoded [binary.MaxVarintLen64]byte
+ encodedLength := binary.PutUvarint(encoded[:], value)
+ return append(destination, encoded[:encodedLength]...)
+}
+
+func appendNativeUint32(destination []byte, value uint32) []byte {
+ var encoded [4]byte
+ binary.BigEndian.PutUint32(encoded[:], value)
+ return append(destination, encoded[:]...)
+}
+
+func appendNativeUint64(destination []byte, value uint64) []byte {
+ var encoded [8]byte
+ binary.BigEndian.PutUint64(encoded[:], value)
+ return append(destination, encoded[:]...)
+}
+
+func nativeICEFileName(identifier uint64, extension string) string {
+ return fmt.Sprintf("%012x%s", identifier, extension)
+}
+
+func publishNativeICEFile(directory, name string, payload []byte) error {
+ temporaryFile, createErr := os.CreateTemp(directory, ".nativeice-")
+ if createErr != nil {
+ return fmt.Errorf("create temporary file: %w", createErr)
+ }
+ temporaryPath := temporaryFile.Name()
+ if writeErr := writeNativeICEFile(temporaryFile, payload); writeErr != nil {
+ return errors.Join(fmt.Errorf("write temporary file: %w", writeErr), closeAndRemoveNativeICEFile(temporaryFile, temporaryPath))
+ }
+ if syncErr := temporaryFile.Sync(); syncErr != nil {
+ return errors.Join(fmt.Errorf("sync temporary file: %w", syncErr), closeAndRemoveNativeICEFile(temporaryFile, temporaryPath))
+ }
+ if closeErr := temporaryFile.Close(); closeErr != nil {
+ return errors.Join(fmt.Errorf("close temporary file: %w", closeErr), os.Remove(temporaryPath))
+ }
+ finalPath := filepath.Join(directory, name)
+ if linkErr := os.Link(temporaryPath, finalPath); linkErr != nil {
+ return errors.Join(fmt.Errorf("link temporary file as %q: %w", finalPath, linkErr), os.Remove(temporaryPath))
+ }
+ if removeErr := os.Remove(temporaryPath); removeErr != nil {
+ return fmt.Errorf("remove temporary file %q: %w", temporaryPath, removeErr)
+ }
+ return syncNativeICEDirectory(directory)
+}
+
+func writeNativeICEFile(file *os.File, payload []byte) error {
+ for len(payload) > 0 {
+ written, writeErr := file.Write(payload)
+ if writeErr != nil {
+ return writeErr
+ }
+ if written == 0 {
+ return io.ErrShortWrite
+ }
+ payload = payload[written:]
+ }
+ return nil
+}
+
+func closeAndRemoveNativeICEFile(file *os.File, path string) error {
+ return errors.Join(file.Close(), os.Remove(path))
+}
+
+func syncNativeICEDirectory(path string) error {
+ directory, openErr := os.Open(path)
+ if openErr != nil {
+ return fmt.Errorf("open directory %q: %w", path, openErr)
+ }
+ syncErr := directory.Sync()
+ closeErr := directory.Close()
+ return errors.Join(syncErr, closeErr)
+}
diff --git a/pkg/index/inverted/internal/nativeice/encode_contract_test.go b/pkg/index/inverted/internal/nativeice/encode_contract_test.go
new file mode 100644
index 000000000..ae7ed2f6a
--- /dev/null
+++ b/pkg/index/inverted/internal/nativeice/encode_contract_test.go
@@ -0,0 +1,493 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with this work for
+// additional information regarding copyright ownership. The ASF licenses this
+// file to you under the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations
+// under the License.
+
+package nativeice
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "reflect"
+ "sort"
+ "strings"
+ "testing"
+)
+
+// The corpus below is declared here rather than derived from anything the
+// encoder produces. Every expected count, walk, selection and page in this file
+// is read off this table by hand; nothing in it is computed the way Encode
+// computes it, so an assertion can disagree with the implementation.
+//
+// It is shaped like one Property shard generation: three entities across two
+// groups, one of them holding two revisions, with the group, name, entity and
+// revision indexed and sorted, the payload and repair SHA stored, and the
+// revision stored as well.
+const (
+ encodeGroupField = "_group"
+ encodeNameField = "_im_name"
+ encodeEntityField = "_entity_id"
+ encodeTimestampField = "_timestamp"
+ encodeSourceField = "_source"
+ encodeSHAField = "_sha_value"
+
+ // encodeSegmentID and encodeSnapshotID number the generation the corpus is
+ // written as. They are the caller's choice, and Reader.SnapshotID must
+ // report the snapshot identifier back.
+ encodeSegmentID = uint64(2)
+ encodeSnapshotID = uint64(5)
+
+ // encodeVisibleDocCount is how many of the corpus's four documents survive
+ // its deletion masks: every document except the deleted revision of e-1.
+ encodeVisibleDocCount = int64(3)
+
+ // encodePageSize is the page size the repair order is measured at. The
+ // deleted revision sorts second of the four rows, so a page built without
+ // the deletion masks returns it inside this first page rather than at the
+ // end of the order.
+ encodePageSize = 2
+)
+
+// encodeRow is one physical document of the corpus.
+type encodeRow struct {
+ identifier string
+ group string
+ name string
+ entity string
+ sha string
+ sources []string
+ timestamp []byte
+ deleted bool
+}
+
+// encodeRows is the corpus, in the order its documents take document numbers.
+//
+// Ascending by (_group, _im_name, _entity_id, _timestamp) the rows order as
+// d-1, d-2, d-3, d-4, which is also insertion order; d-2 is the row the
+// generation's deletion masks hide.
+//
+// Row d-1 records two _source values, so an encoder that collapsed repeated
+// stored values into one is caught by the walk. The revision bytes are opaque
+// literals rather than encoded numbers: Encode applies no numeric coding, so a
+// term sorts and reads back as exactly the bytes declared here.
+var encodeRows = []encodeRow{
+ {
+ identifier: "d-1", group: "g-a", name: "n-a", entity: "e-1",
+ timestamp: []byte{0x20, 0x01, 0xa0}, sources: []string{"s-1a", "s-1b"}, sha: "sha-1",
+ },
+ {
+ identifier: "d-2", group: "g-a", name: "n-a", entity: "e-1",
+ timestamp: []byte{0x20, 0x01, 0xb0}, sources: []string{"s-2"}, sha: "sha-2", deleted: true,
+ },
+ {
+ identifier: "d-3", group: "g-a", name: "n-b", entity: "e-2",
+ timestamp: []byte{0x20, 0x01, 0xc0}, sources: []string{"s-3"}, sha: "sha-3",
+ },
+ {
+ identifier: "d-4", group: "g-b", name: "n-a", entity: "e-3",
+ timestamp: []byte{0x20, 0x01, 0xd0}, sources: []string{"s-4"}, sha: "sha-4",
+ },
+}
+
+// TestNativeEncodeRoundTripsThroughTheMergedReader is the contract's entry
+// point: a generation the encoder writes is a generation the merged reader
+// opens.
+//
+// Requirement proved here:
+//
+// R1 -- Encode writes one committed ICE v3 generation that Open selects. The
+// opened generation reports the snapshot identifier the caller asked
+// for and the number of documents its deletion masks leave visible, and
+// its stored-document walk yields every live document's stored values:
+// the identifier first, the remaining names in ascending byte order, a
+// repeated name's values consecutive and in the order the document
+// lists them, and no deleted document at all.
+func TestNativeEncodeRoundTripsThroughTheMergedReader(t *testing.T) {
+ directory := encodeCorpus(t)
+
+ reader := openEncoded(t, directory)
+ if reader.SnapshotID() != encodeSnapshotID {
+ t.Fatalf("SnapshotID() = %d, want %d", reader.SnapshotID(), encodeSnapshotID)
+ }
+ count, countErr := reader.VisibleDocCount()
+ if countErr != nil {
+ t.Fatal(countErr)
+ }
+ if count != encodeVisibleDocCount {
+ t.Fatalf("VisibleDocCount() = %d, want %d", count, encodeVisibleDocCount)
+ }
+
+ walked := walkDocuments(t, reader)
+ want := [][]string{
+ {
+ "_id=" + hexOf("d-1"), "_sha_value=" + hexOf("sha-1"),
+ "_source=" + hexOf("s-1a"), "_source=" + hexOf("s-1b"), "_timestamp=2001a0",
+ },
+ {"_id=" + hexOf("d-3"), "_sha_value=" + hexOf("sha-3"), "_source=" + hexOf("s-3"), "_timestamp=2001c0"},
+ {"_id=" + hexOf("d-4"), "_sha_value=" + hexOf("sha-4"), "_source=" + hexOf("s-4"), "_timestamp=2001d0"},
+ }
+ if !reflect.DeepEqual(want, walked) {
+ t.Fatalf("VisitLiveDocuments() =\n%v\nwant\n%v", walked, want)
+ }
+}
+
+// TestNativeEncodeSelectsLiveDocumentsByExactTerm asks the encoder's generation
+// for the documents one field's exact terms select.
+//
+// Requirement proved here:
+//
+// R2 -- every field a document marks indexed contributes its value to that
+// field's term dictionary, so a selection on the field and the literal
+// value reaches exactly the live documents that recorded it. A term no
+// document recorded selects nothing rather than failing, a document
+// several terms select is visited once, and a document the deletion
+// masks hide is never visited however many terms selected it.
+func TestNativeEncodeSelectsLiveDocumentsByExactTerm(t *testing.T) {
+ reader := openEncoded(t, encodeCorpus(t))
+
+ for _, testCase := range []struct {
+ field string
+ want []string
+ terms []string
+ }{
+ // "g-a" was recorded by d-1, d-2 and d-3; d-2 is masked.
+ {field: encodeGroupField, terms: []string{"g-a"}, want: []string{"d-1", "d-3"}},
+ // "g-z" was recorded by no document and must not fail the selection.
+ {field: encodeGroupField, terms: []string{"g-b", "g-z"}, want: []string{"d-4"}},
+ // Both terms select d-1, which must still be visited exactly once.
+ {field: encodeGroupField, terms: []string{"g-a", "g-a"}, want: []string{"d-1", "d-3"}},
+ // "e-1" was recorded by d-1 and the masked d-2.
+ {field: encodeEntityField, terms: []string{"e-1"}, want: []string{"d-1"}},
+ {field: encodeEntityField, terms: []string{"e-9"}, want: nil},
+ } {
+ terms := make([][]byte, 0, len(testCase.terms))
+ for _, term := range testCase.terms {
+ terms = append(terms, []byte(term))
+ }
+ var selected []string
+ selectErr := reader.VisitSelectedDocuments(context.Background(), testCase.field, terms,
+ func(document StoredDocument) error {
+ return document.VisitStoredFields(func(name string, value []byte) bool {
+ if name == identifierField {
+ selected = append(selected, string(value))
+ }
+ return true
+ })
+ })
+ if selectErr != nil {
+ t.Fatalf("VisitSelectedDocuments(%q, %v) failed: %v", testCase.field, testCase.terms, selectErr)
+ }
+ if !reflect.DeepEqual(testCase.want, selected) {
+ t.Fatalf("VisitSelectedDocuments(%q, %v) = %v, want %v",
+ testCase.field, testCase.terms, selected, testCase.want)
+ }
+ }
+}
+
+// TestNativeEncodePagesRepairTuplesInAscendingOrder pages the encoder's
+// generation in the ascending Property repair order.
+//
+// Requirement proved here:
+//
+// R3 -- every field a document marks sortable contributes a doc value, so the
+// generation serves the bounded repair page: live rows ascend by all
+// four sort components, a page resumes strictly after the cursor the
+// previous page ended on, and the deleted row -- which sorts second of
+// the four and would therefore land inside the first page -- never
+// appears.
+func TestNativeEncodePagesRepairTuplesInAscendingOrder(t *testing.T) {
+ reader := openEncoded(t, encodeCorpus(t))
+ request := RepairPageRequest{
+ SortFields: [repairSortFieldCount]string{encodeGroupField, encodeNameField, encodeEntityField, encodeTimestampField},
+ ProjectField: encodeSHAField,
+ PageSize: encodePageSize,
+ }
+
+ first, firstErr := reader.RepairTuplePage(context.Background(), request)
+ if firstErr != nil {
+ t.Fatal(firstErr)
+ }
+ wantFirst := []string{
+ repairRow("g-a", "n-a", "e-1", "2001a0", "sha-1"),
+ repairRow("g-a", "n-b", "e-2", "2001c0", "sha-3"),
+ }
+ if got := renderRepairRows(first); !reflect.DeepEqual(wantFirst, got) {
+ t.Fatalf("first page = %v, want %v", got, wantFirst)
+ }
+
+ request.After = &first[len(first)-1].Cursor
+ second, secondErr := reader.RepairTuplePage(context.Background(), request)
+ if secondErr != nil {
+ t.Fatal(secondErr)
+ }
+ wantSecond := []string{repairRow("g-b", "n-a", "e-3", "2001d0", "sha-4")}
+ if got := renderRepairRows(second); !reflect.DeepEqual(wantSecond, got) {
+ t.Fatalf("second page = %v, want %v", got, wantSecond)
+ }
+
+ request.After = &second[len(second)-1].Cursor
+ third, thirdErr := reader.RepairTuplePage(context.Background(), request)
+ if thirdErr != nil {
+ t.Fatal(thirdErr)
+ }
+ if len(third) != 0 {
+ t.Fatalf("third page = %v, want the order to be exhausted", renderRepairRows(third))
+ }
+}
+
+// TestNativeEncodeLeavesNoPartiallyVisibleGeneration interrupts a write between
+// its two durable steps -- the segment is on disk, the snapshot manifest that
+// publishes it is not -- and asks what the directory then holds.
+//
+// Requirement proved here:
+//
+// R4 -- a generation becomes visible only when its snapshot manifest is
+// published, so an interruption before publication leaves no partially
+// visible generation. A directory that already held a complete
+// generation opens at that prior generation, with its identifier and
+// visible count unchanged; a directory that never published one reports
+// ErrNoSnapshot rather than the unpublished segment.
+func TestNativeEncodeLeavesNoPartiallyVisibleGeneration(t *testing.T) {
+ directory := encodeCorpus(t)
+ later := Generation{
+ SegmentID: encodeSegmentID + 2,
+ SnapshotID: encodeSnapshotID + 2,
+ Documents: []EncodeDocument{encodeDocumentOf(encodeRows[0])},
+ }
+ if encodeErr := Encode(directory, later); encodeErr != nil {
+ t.Fatal(encodeErr)
+ }
+ if published := openEncoded(t, directory); published.SnapshotID() != later.SnapshotID {
+ t.Fatalf("SnapshotID() = %d, want the later generation %d", published.SnapshotID(), later.SnapshotID)
+ }
+
+ interruptPublication(t, directory)
+
+ reader := openEncoded(t, directory)
+ if reader.SnapshotID() != encodeSnapshotID {
+ t.Fatalf("SnapshotID() = %d, want the prior complete generation %d", reader.SnapshotID(), encodeSnapshotID)
+ }
+ count, countErr := reader.VisibleDocCount()
+ if countErr != nil {
+ t.Fatal(countErr)
+ }
+ if count != encodeVisibleDocCount {
+ t.Fatalf("VisibleDocCount() = %d, want the prior generation's %d", count, encodeVisibleDocCount)
+ }
+
+ fresh := t.TempDir()
+ if encodeErr := Encode(fresh, encodeGeneration()); encodeErr != nil {
+ t.Fatal(encodeErr)
+ }
+ interruptPublication(t, fresh)
+ if _, openErr := Open(fresh); !errors.Is(openErr, ErrNoSnapshot) {
+ t.Fatalf("Open() error = %v, want an error wrapping ErrNoSnapshot", openErr)
+ }
+}
+
+// TestNativeEncodeRejectsAnUnencodableGeneration hands the encoder a generation
+// the ICE v3 grammar has no representation for.
+//
+// Requirement proved here:
+//
+// R5 -- a generation carrying a document with no identifier, or a field with
+// no name, is rejected with ErrInvalidGeneration, and the rejection
+// leaves the directory's committed state exactly as it was: the
+// generation already published there still opens, at the same
+// identifier and the same visible count.
+func TestNativeEncodeRejectsAnUnencodableGeneration(t *testing.T) {
+ directory := encodeCorpus(t)
+
+ for name, generation := range map[string]Generation{
+ "document without an identifier": {
+ SegmentID: encodeSegmentID + 2,
+ SnapshotID: encodeSnapshotID + 2,
+ Documents: []EncodeDocument{{
+ Fields: []EncodeField{{Name: encodeGroupField, Value: []byte("g-a"), Index: true}},
+ }},
+ },
+ "field without a name": {
+ SegmentID: encodeSegmentID + 2,
+ SnapshotID: encodeSnapshotID + 2,
+ Documents: []EncodeDocument{{
+ Identifier: []byte("d-9"),
+ Fields: []EncodeField{{Value: []byte("g-a"), Index: true}},
+ }},
+ },
+ } {
+ if encodeErr := Encode(directory, generation); !errors.Is(encodeErr, ErrInvalidGeneration) {
+ t.Fatalf("Encode(%s) error = %v, want an error wrapping ErrInvalidGeneration", name, encodeErr)
+ }
+ reader := openEncoded(t, directory)
+ if reader.SnapshotID() != encodeSnapshotID {
+ t.Fatalf("after rejecting a %s, SnapshotID() = %d, want %d", name, reader.SnapshotID(), encodeSnapshotID)
+ }
+ count, countErr := reader.VisibleDocCount()
+ if countErr != nil {
+ t.Fatal(countErr)
+ }
+ if count != encodeVisibleDocCount {
+ t.Fatalf("after rejecting a %s, VisibleDocCount() = %d, want %d", name, count, encodeVisibleDocCount)
+ }
+ }
+}
+
+// encodeGeneration renders the declared corpus as the generation Encode is
+// asked to write.
+func encodeGeneration() Generation {
+ documents := make([]EncodeDocument, 0, len(encodeRows))
+ for _, row := range encodeRows {
+ documents = append(documents, encodeDocumentOf(row))
+ }
+ return Generation{SegmentID: encodeSegmentID, SnapshotID: encodeSnapshotID, Documents: documents}
+}
+
+// encodeDocumentOf renders one declared row as the document Encode is handed:
+// the group, name, entity and revision indexed and sorted, the revision also
+// stored, and the payloads and repair SHA stored only.
+func encodeDocumentOf(row encodeRow) EncodeDocument {
+ fields := []EncodeField{
+ {Name: encodeEntityField, Value: []byte(row.entity), Index: true, Sort: true},
+ {Name: encodeGroupField, Value: []byte(row.group), Index: true, Sort: true},
+ {Name: encodeNameField, Value: []byte(row.name), Index: true, Sort: true},
+ }
+ for _, source := range row.sources {
+ fields = append(fields, EncodeField{Name: encodeSourceField, Value: []byte(source), Store: true})
+ }
+ fields = append(fields,
+ EncodeField{Name: encodeSHAField, Value: []byte(row.sha), Store: true},
+ EncodeField{Name: encodeTimestampField, Value: row.timestamp, Index: true, Store: true, Sort: true},
+ )
+ return EncodeDocument{Identifier: []byte(row.identifier), Fields: fields, Deleted: row.deleted}
+}
+
+// encodeCorpus writes the declared corpus into a fresh directory and returns it.
+func encodeCorpus(t *testing.T) string {
+ t.Helper()
+ directory := t.TempDir()
+ if encodeErr := Encode(directory, encodeGeneration()); encodeErr != nil {
+ t.Fatalf("Encode() failed: %v", encodeErr)
+ }
+ return directory
+}
+
+// openEncoded pins a directory's newest committed generation for the duration
+// of the test.
+func openEncoded(t *testing.T, directory string) *Reader {
+ t.Helper()
+ reader, openErr := Open(directory)
+ if openErr != nil {
+ t.Fatalf("Open(%q) failed: %v", directory, openErr)
+ }
+ t.Cleanup(func() {
+ if closeErr := reader.Close(); closeErr != nil {
+ t.Error(closeErr)
+ }
+ })
+ return reader
+}
+
+// interruptPublication models a write that stopped between its two durable
+// steps: it removes the newest snapshot manifest and leaves every segment in
+// place, which is the state a directory is in when a writer died after the
+// segment reached disk and before the manifest naming it did.
+func interruptPublication(t *testing.T, directory string) {
+ t.Helper()
+ entries, readErr := os.ReadDir(directory)
+ if readErr != nil {
+ t.Fatal(readErr)
+ }
+ manifests, segments := []string{}, 0
+ for _, entry := range entries {
+ switch filepath.Ext(entry.Name()) {
+ case ".snp":
+ manifests = append(manifests, entry.Name())
+ case ".seg":
+ segments++
+ }
+ }
+ if len(manifests) == 0 || segments == 0 {
+ t.Fatalf("directory %q holds %d manifests and %d segments; "+
+ "a generation must be published by a manifest naming a segment", directory, len(manifests), segments)
+ }
+ sort.Strings(manifests)
+ newest := manifests[len(manifests)-1]
+ if removeErr := os.Remove(filepath.Join(directory, newest)); removeErr != nil {
+ t.Fatal(removeErr)
+ }
+ remaining, remainingErr := os.ReadDir(directory)
+ if remainingErr != nil {
+ t.Fatal(remainingErr)
+ }
+ unpublished := 0
+ for _, entry := range remaining {
+ if filepath.Ext(entry.Name()) == ".seg" {
+ unpublished++
+ }
+ }
+ if unpublished != segments {
+ t.Fatalf("removing manifest %q removed segments too: %d of %d remain", newest, unpublished, segments)
+ }
+}
+
+// walkDocuments renders every live document's stored values, one slice per
+// document, in the order the walk yields them.
+func walkDocuments(t *testing.T, reader *Reader) [][]string {
+ t.Helper()
+ var documents [][]string
+ walkErr := reader.VisitLiveDocuments(context.Background(), func(document StoredDocument) error {
+ var values []string
+ if visitErr := document.VisitStoredFields(func(name string, value []byte) bool {
+ values = append(values, fmt.Sprintf("%s=%x", name, value))
+ return true
+ }); visitErr != nil {
+ return visitErr
+ }
+ documents = append(documents, values)
+ return nil
+ })
+ if walkErr != nil {
+ t.Fatalf("VisitLiveDocuments() failed: %v", walkErr)
+ }
+ return documents
+}
+
+// renderRepairRows renders a repair page as one readable string per row: the
+// four ascending sort components followed by the projected value.
+func renderRepairRows(rows []RepairTupleRow) []string {
+ rendered := make([]string, 0, len(rows))
+ for _, row := range rows {
+ components := make([]string, 0, len(row.SortValues)+1)
+ for _, value := range row.SortValues {
+ components = append(components, fmt.Sprintf("%x", value))
+ }
+ components = append(components, fmt.Sprintf("%x", row.Value))
+ rendered = append(rendered, strings.Join(components, "|"))
+ }
+ return rendered
+}
+
+// hexOf renders a declared literal the way the assertions print values.
+func hexOf(value string) string {
+ return fmt.Sprintf("%x", value)
+}
+
+// repairRow renders one expected repair row: the group, name and entity as the
+// literal bytes their doc values hold, the revision as the literal hexadecimal
+// the corpus declares, and the projected repair SHA.
+func repairRow(group, name, entity, timestampHex, sha string) string {
+ return strings.Join([]string{hexOf(group), hexOf(name), hexOf(entity), timestampHex, hexOf(sha)}, "|")
+}
diff --git a/pkg/index/inverted/internal/nativeice/encode_test.go b/pkg/index/inverted/internal/nativeice/encode_test.go
new file mode 100644
index 000000000..8472ec8ab
--- /dev/null
+++ b/pkg/index/inverted/internal/nativeice/encode_test.go
@@ -0,0 +1,351 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with this work for
+// additional information regarding copyright ownership. The ASF licenses this
+// file to you under the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations
+// under the License.
+
+package nativeice
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestEncodeRejectsInvalidGenerationBeforeWriting(t *testing.T) {
+ target := filepath.Join(t.TempDir(), "generation")
+ generation := Generation{
+ Documents: []EncodeDocument{{
+ Fields: []EncodeField{{Name: "field", Value: []byte("value"), Store: true}},
+ }},
+ }
+
+ encodeErr := Encode(target, generation)
+ if !errors.Is(encodeErr, ErrInvalidGeneration) {
+ t.Fatalf("Encode() error = %v, want an error wrapping ErrInvalidGeneration", encodeErr)
+ }
+ if _, statErr := os.Stat(target); !errors.Is(statErr, os.ErrNotExist) {
+ t.Fatalf("target state after rejected generation = %v, want no directory", statErr)
+ }
+}
+
+func TestEncodePublishesReadableGeneration(t *testing.T) {
+ directory := t.TempDir()
+ generation := Generation{
+ SegmentID: 2,
+ SnapshotID: 3,
+ Documents: []EncodeDocument{{
+ Identifier: []byte("doc-1"),
+ Fields: []EncodeField{{Name: "title", Value: []byte("one"), Store: true}},
+ }},
+ }
+
+ if encodeErr := Encode(directory, generation); encodeErr != nil {
+ t.Fatal(encodeErr)
+ }
+ reader, openErr := Open(directory)
+ if openErr != nil {
+ t.Fatal(openErr)
+ }
+ t.Cleanup(func() {
+ if closeErr := reader.Close(); closeErr != nil {
+ t.Error(closeErr)
+ }
+ })
+ if reader.SnapshotID() != generation.SnapshotID {
+ t.Fatalf("SnapshotID() = %d, want %d", reader.SnapshotID(), generation.SnapshotID)
+ }
+ count, countErr := reader.VisibleDocCount()
+ if countErr != nil {
+ t.Fatal(countErr)
+ }
+ if count != 1 {
+ t.Fatalf("VisibleDocCount() = %d, want 1", count)
+ }
+ var stored []string
+ walkErr := reader.VisitLiveDocuments(context.Background(), func(document StoredDocument) error {
+ return document.VisitStoredFields(func(name string, value []byte) bool {
+ stored = append(stored, name+"="+string(value))
+ return true
+ })
+ })
+ if walkErr != nil {
+ t.Fatal(walkErr)
+ }
+ want := []string{"_id=doc-1", "title=one"}
+ if len(stored) != len(want) {
+ t.Fatalf("stored values = %v, want %v", stored, want)
+ }
+ for index := range want {
+ if stored[index] != want[index] {
+ t.Fatalf("stored values = %v, want %v", stored, want)
+ }
+ }
+}
+
+func TestEncodeSelectsIndexedDocuments(t *testing.T) {
+ directory := t.TempDir()
+ generation := Generation{
+ SegmentID: 2,
+ SnapshotID: 3,
+ Documents: []EncodeDocument{
+ {Identifier: []byte("doc-1"), Fields: []EncodeField{{Name: "tag", Value: []byte("red"), Index: true}}},
+ {Identifier: []byte("doc-2"), Fields: []EncodeField{{Name: "tag", Value: []byte("blue"), Index: true}}},
+ },
+ }
+ if encodeErr := Encode(directory, generation); encodeErr != nil {
+ t.Fatal(encodeErr)
+ }
+ reader, openErr := Open(directory)
+ if openErr != nil {
+ t.Fatal(openErr)
+ }
+ t.Cleanup(func() {
+ if closeErr := reader.Close(); closeErr != nil {
+ t.Error(closeErr)
+ }
+ })
+ var selected []string
+ selectionErr := reader.VisitSelectedDocuments(context.Background(), "tag", [][]byte{[]byte("red")}, func(document StoredDocument) error {
+ return document.VisitStoredFields(func(name string, value []byte) bool {
+ if name == identifierField {
+ selected = append(selected, string(value))
+ }
+ return true
+ })
+ })
+ if selectionErr != nil {
+ t.Fatal(selectionErr)
+ }
+ if len(selected) != 1 || selected[0] != "doc-1" {
+ t.Fatalf("selected documents = %v, want [doc-1]", selected)
+ }
+}
+
+func TestEncodeServesSortableDocument(t *testing.T) {
+ directory := t.TempDir()
+ generation := Generation{
+ SegmentID: 2,
+ SnapshotID: 3,
+ Documents: []EncodeDocument{{
+ Identifier: []byte("doc-1"),
+ Fields: []EncodeField{
+ {Name: "group", Value: []byte("g-a"), Sort: true},
+ {Name: "name", Value: []byte("n-a"), Sort: true},
+ {Name: "entity", Value: []byte("e-1"), Sort: true},
+ {Name: "timestamp", Value: []byte{0x20, 0x01}, Sort: true},
+ {Name: "sha", Value: []byte("sha-1"), Store: true},
+ },
+ }},
+ }
+ if encodeErr := Encode(directory, generation); encodeErr != nil {
+ t.Fatal(encodeErr)
+ }
+ reader, openErr := Open(directory)
+ if openErr != nil {
+ t.Fatal(openErr)
+ }
+ t.Cleanup(func() {
+ if closeErr := reader.Close(); closeErr != nil {
+ t.Error(closeErr)
+ }
+ })
+ page, pageErr := reader.RepairTuplePage(context.Background(), RepairPageRequest{
+ SortFields: [repairSortFieldCount]string{"group", "name", "entity", "timestamp"},
+ ProjectField: "sha",
+ PageSize: 1,
+ })
+ if pageErr != nil {
+ t.Fatal(pageErr)
+ }
+ if len(page) != 1 {
+ t.Fatalf("page length = %d, want 1", len(page))
+ }
+ if string(page[0].Value) != "sha-1" {
+ t.Fatalf("projected value = %q, want sha-1", page[0].Value)
+ }
+ wantSortValues := []string{"g-a", "n-a", "e-1", string([]byte{0x20, 0x01})}
+ for valueIndex, want := range wantSortValues {
+ if string(page[0].SortValues[valueIndex]) != want {
+ t.Fatalf("sort value %d = %x, want %x", valueIndex, page[0].SortValues[valueIndex], want)
+ }
+ }
+}
+
+func TestNativeEncodePreservesEscapedSortValue(t *testing.T) {
+ directory := t.TempDir()
+ sortValue := []byte{0x01, 0xff, 0x5c, 0x7f, 0x5c}
+ generation := Generation{
+ SegmentID: 2,
+ SnapshotID: 3,
+ Documents: []EncodeDocument{{
+ Identifier: []byte("doc-1"),
+ Fields: []EncodeField{
+ {Name: "group", Value: sortValue, Sort: true},
+ {Name: "name", Value: []byte("n-a"), Sort: true},
+ {Name: "entity", Value: []byte("e-1"), Sort: true},
+ {Name: "timestamp", Value: []byte("t-1"), Sort: true},
+ {Name: "sha", Value: []byte("sha-1"), Store: true},
+ },
+ }},
+ }
+
+ if encodeErr := Encode(directory, generation); encodeErr != nil {
+ t.Fatal(encodeErr)
+ }
+ reader, openErr := Open(directory)
+ if openErr != nil {
+ t.Fatal(openErr)
+ }
+ t.Cleanup(func() {
+ if closeErr := reader.Close(); closeErr != nil {
+ t.Error(closeErr)
+ }
+ })
+ page, pageErr := reader.RepairTuplePage(context.Background(), RepairPageRequest{
+ SortFields: [repairSortFieldCount]string{"group", "name", "entity", "timestamp"},
+ ProjectField: "sha",
+ PageSize: 1,
+ })
+ if pageErr != nil {
+ t.Fatal(pageErr)
+ }
+ if len(page) != 1 {
+ t.Fatalf("page length = %d, want 1", len(page))
+ }
+ if len(page[0].SortValues) != repairSortFieldCount {
+ t.Fatalf("sort value count = %d, want %d", len(page[0].SortValues), repairSortFieldCount)
+ }
+ if !bytes.Equal(page[0].SortValues[0], sortValue) {
+ t.Fatalf("escaped sort value = %x, want %x", page[0].SortValues[0], sortValue)
+ }
+}
+
+func TestNativeEncodeRoundTripsMultipleStoredAndDocValueChunks(t *testing.T) {
+ const (
+ documentCount = 2100
+ selectedDocument = 1024
+ pageSize = 173
+ )
+ documents := make([]EncodeDocument, 0, documentCount)
+ for documentIndex := 0; documentIndex < documentCount; documentIndex++ {
+ tagValue := []byte("other")
+ if documentIndex == selectedDocument {
+ tagValue = []byte("needle")
+ }
+ documents = append(documents, EncodeDocument{
+ Identifier: []byte(fmt.Sprintf("doc-%04d", documentIndex)),
+ Fields: []EncodeField{
+ {Name: "payload", Value: []byte(fmt.Sprintf("payload-%04d", documentIndex)), Store: true},
+ {Name: "tag", Value: tagValue, Index: true},
+ {Name: "group", Value: []byte("g"), Sort: true},
+ {Name: "name", Value: []byte(fmt.Sprintf("n-%04d", documentIndex)), Sort: true},
+ {Name: "entity", Value: []byte("e"), Sort: true},
+ {Name: "timestamp", Value: []byte("t"), Sort: true},
+ },
+ })
+ }
+
+ directory := t.TempDir()
+ generation := Generation{SegmentID: 2, SnapshotID: 3, Documents: documents}
+ if encodeErr := Encode(directory, generation); encodeErr != nil {
+ t.Fatal(encodeErr)
+ }
+ reader, openErr := Open(directory)
+ if openErr != nil {
+ t.Fatal(openErr)
+ }
+ t.Cleanup(func() {
+ if closeErr := reader.Close(); closeErr != nil {
+ t.Error(closeErr)
+ }
+ })
+
+ var storedFields []string
+ walkErr := reader.VisitLiveDocuments(context.Background(), func(document StoredDocument) error {
+ return document.VisitStoredFields(func(name string, value []byte) bool {
+ storedFields = append(storedFields, name+"="+string(value))
+ return true
+ })
+ })
+ if walkErr != nil {
+ t.Fatal(walkErr)
+ }
+ if len(storedFields) != documentCount*2 {
+ t.Fatalf("stored field count = %d, want %d", len(storedFields), documentCount*2)
+ }
+ for documentIndex := 0; documentIndex < documentCount; documentIndex++ {
+ wantIdentifier := fmt.Sprintf("_id=doc-%04d", documentIndex)
+ if storedFields[documentIndex*2] != wantIdentifier {
+ t.Fatalf("stored identifier at document %d = %q, want %q", documentIndex, storedFields[documentIndex*2], wantIdentifier)
+ }
+ wantPayload := fmt.Sprintf("payload=payload-%04d", documentIndex)
+ if storedFields[documentIndex*2+1] != wantPayload {
+ t.Fatalf("stored payload at document %d = %q, want %q", documentIndex, storedFields[documentIndex*2+1], wantPayload)
+ }
+ }
+
+ var selected []string
+ selectionErr := reader.VisitSelectedDocuments(context.Background(), "tag", [][]byte{[]byte("needle")}, func(document StoredDocument) error {
+ return document.VisitStoredFields(func(name string, value []byte) bool {
+ if name == identifierField {
+ selected = append(selected, string(value))
+ }
+ return true
+ })
+ })
+ if selectionErr != nil {
+ t.Fatal(selectionErr)
+ }
+ wantSelected := fmt.Sprintf("doc-%04d", selectedDocument)
+ if len(selected) != 1 || selected[0] != wantSelected {
+ t.Fatalf("selected documents = %v, want [%s]", selected, wantSelected)
+ }
+
+ var after *RepairCursor
+ repaired := make([]string, 0, documentCount)
+ for {
+ page, pageErr := reader.RepairTuplePage(context.Background(), RepairPageRequest{
+ After: after,
+ SortFields: [repairSortFieldCount]string{"group", "name", "entity", "timestamp"},
+ ProjectField: "payload",
+ PageSize: pageSize,
+ })
+ if pageErr != nil {
+ t.Fatal(pageErr)
+ }
+ if len(page) == 0 {
+ break
+ }
+ for _, row := range page {
+ repaired = append(repaired, string(row.Value))
+ }
+ if len(repaired) > documentCount {
+ t.Fatalf("repair returned %d rows, want at most %d", len(repaired), documentCount)
+ }
+ nextCursor := page[len(page)-1].Cursor
+ after = &nextCursor
+ }
+ if len(repaired) != documentCount {
+ t.Fatalf("repair row count = %d, want %d", len(repaired), documentCount)
+ }
+ for documentIndex, payload := range repaired {
+ wantPayload := fmt.Sprintf("payload-%04d", documentIndex)
+ if payload != wantPayload {
+ t.Fatalf("repair payload at row %d = %q, want %q", documentIndex, payload, wantPayload)
+ }
+ }
+}
diff --git a/pkg/index/inverted/native_fixture_nidx02a_test.go b/pkg/index/inverted/native_fixture_nidx02a_test.go
new file mode 100644
index 000000000..0fccc2594
--- /dev/null
+++ b/pkg/index/inverted/native_fixture_nidx02a_test.go
@@ -0,0 +1,393 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package inverted
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/apache/skywalking-banyandb/pkg/convert"
+ "github.com/apache/skywalking-banyandb/pkg/index"
+)
+
+// The NIDX-02A corpus is one Property shard generation written by BanyanDB's
+// compatibility writer through the pkg/index/inverted store boundary. It is the
+// oracle the native encoder is measured against: the encoder is handed the same
+// declared rows, and the generation it produces must yield the same visible
+// count, stored walk, exact-term selection and repair page order as these
+// checked-in bytes.
+//
+// The corpus is deliberately not a re-encoding of anything the encoder emits.
+// Its bytes come from the compatibility writer, pinned by the content hash of
+// the dependency set it ran with, and production code never generates them; the
+// generator lives in this test file behind nidx02aGenerateEnv so an ordinary
+// run reads the committed bytes instead of producing fresh ones.
+const (
+ nidx02aRoot = "testdata/nidx02a"
+ nidx02aShardDir = nidx02aRoot + "/shard-0"
+ nidx02aManifest = nidx02aRoot + "/provenance.json"
+
+ // nidx02aGenerateEnv gates regeneration so an ordinary test run can never
+ // overwrite the checked-in bytes the contract is pinned to.
+ nidx02aGenerateEnv = "GENERATE_NIDX02A_FIXTURE"
+ nidx02aGenerateCmd = "GENERATE_NIDX02A_FIXTURE=1 go test ./pkg/index/inverted/ -run TestGenerateNIDX02AFixture -count=1"
+
+ // The field names below are the Property shard's own, pinned here as
+ // literals rather than imported: pkg/index/inverted sits underneath
+ // banyand/property/db, so the corpus declares the names it was written with
+ // instead of borrowing the constants the consumer happens to hold.
+ nidx02aIDField = "_id"
+ nidx02aEntityField = "_entity_id"
+ nidx02aGroupField = "_group"
+ nidx02aNameField = index.IndexModeName
+ nidx02aSourceField = "_source"
+ nidx02aTimestampField = "_timestamp"
+ nidx02aDeletedField = "_deleted"
+ nidx02aSHAField = "_sha_value"
+
+ // nidx02aTagKey is the Property tag the corpus carries. The Property write
+ // path names a tag field by the hash of its key rather than by the key, so
+ // the corpus records both: the key a reader recognizes and the field name
+ // the bytes actually hold.
+ nidx02aTagKey = "color"
+
+ // nidx02aSnapshotID is the identifier of the committed generation the
+ // corpus's newest snapshot manifest names. It is a property of the
+ // checked-in bytes, recorded when they were produced.
+ nidx02aSnapshotID = uint64(3)
+
+ // nidx02aPhysicalRowCount and nidx02aVisibleRowCount are how many rows the
+ // pinned generation holds and how many survive its deletion masks.
+ nidx02aPhysicalRowCount = int64(6)
+ nidx02aVisibleRowCount = int64(4)
+)
+
+// nidx02aRow is one physical document of the corpus: the four ascending sort
+// components the repair order is built from, the stored SHA a repair leaf
+// carries, the stored payloads, the indexed tag, whether the row carries a
+// deletion marker as a stored field, and whether the generation's deletion
+// masks hide it.
+//
+// sources is a slice rather than a single value because one declared row
+// records the same stored field name twice. An encoder that collapsed repeated
+// stored values would still produce the right count and the right selection and
+// would be caught only here.
+type nidx02aRow struct {
+ group string
+ name string
+ entityID string
+ sha string
+ tag string
+ sources []string
+ timestamp int64
+ deletedAt int64
+ masked bool
+}
+
+// nidx02aRows is the corpus, in insertion order.
+//
+// Ascending by (_group, _im_name, _entity_id, _timestamp) the six rows order as
+// e-1@10, e-1@15, e-1@20, e-2@5, e-3@7, e-4@30. Two of them are masked: e-1@15
+// sorts between the first two visible rows, so a page built without the
+// deletion masks is caught inside the very first page; e-4@30 sorts last, so a
+// mask dropped only at the tail is caught too.
+//
+// Row e-1@10 records two _source values, and row e-2@5 carries the Property
+// deletion marker as a stored field while staying visible -- a row marked
+// deleted by the Property write path is still a live document of the
+// generation, which is a different thing from a masked row.
+var nidx02aRows = []nidx02aRow{
+ {group: "g-a", name: "n-a", entityID: "e-1", timestamp: 10, sha: "sha-a", sources: []string{"source-a1", "source-a2"}, tag: "red"},
+ {group: "g-a", name: "n-a", entityID: "e-1", timestamp: 15, sha: "sha-x", sources: []string{"source-x"}, tag: "red", masked: true},
+ {group: "g-a", name: "n-a", entityID: "e-1", timestamp: 20, sha: "sha-b", sources: []string{"source-b"}, tag: "blue"},
+ {group: "g-a", name: "n-b", entityID: "e-2", timestamp: 5, sha: "sha-c", sources: []string{"source-c"}, tag: "red", deletedAt: 99},
+ {group: "g-b", name: "n-a", entityID: "e-3", timestamp: 7, sha: "sha-d", sources: []string{"source-d"}, tag: "blue"},
+ {group: "g-b", name: "n-b", entityID: "e-4", timestamp: 30, sha: "sha-e", sources: []string{"source-e"}, tag: "red", masked: true},
+}
+
+// nidx02aEncodedTimestamps are the exact doc values and stored values the
+// corpus records for each declared revision. They are literals lifted from the
+// checked-in generation, not a re-encoding: an eleven-byte historical
+// prefix-coded signed int64 whose leading byte is the shift and whose sign bit
+// is inverted so byte order matches numeric order.
+var nidx02aEncodedTimestamps = map[int64][]byte{
+ 5: {0x20, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05},
+ 7: {0x20, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07},
+ 10: {0x20, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a},
+ 15: {0x20, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f},
+ 20: {0x20, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14},
+ 30: {0x20, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1e},
+}
+
+// nidx02aProvenance is the manifest checked in beside the corpus bytes. It
+// records which oracle produced them, how to re-derive them, what every row
+// declares, which rows the generation masks, which generation the bytes commit,
+// and what every file hashes to.
+type nidx02aProvenance struct {
+ Oracle map[string]string `json:"oracle"`
+ FileSHA256 map[string]string `json:"file_sha256"`
+ GeneratorCommand string `json:"generator_command"`
+ Notes string `json:"notes"`
+ TagFieldName string `json:"tag_field_name_hex"`
+ Rows []nidx02aProvenanceRow `json:"rows"`
+ PhysicalRowCount int64 `json:"physical_row_count"`
+ SnapshotID uint64 `json:"snapshot_id"`
+ VisibleRowCount int64 `json:"visible_row_count"`
+}
+
+// nidx02aProvenanceRow records one physical document of the corpus so a
+// reviewer can compare it against the milestone's declaration without decoding
+// a segment.
+type nidx02aProvenanceRow struct {
+ Group string `json:"group"`
+ Name string `json:"name"`
+ EntityID string `json:"entity_id"`
+ SHA string `json:"sha_value"`
+ DocID string `json:"doc_id"`
+ Tag string `json:"tag"`
+ Sources []string `json:"sources"`
+ Timestamp int64 `json:"timestamp"`
+ DeletedAt int64 `json:"deleted_at"`
+ Masked bool `json:"masked"`
+}
+
+// TestGenerateNIDX02AFixture rebuilds the checked-in NIDX-02A corpus and its
+// provenance manifest with BanyanDB's compatibility writer. It runs only when
+// nidx02aGenerateEnv is set, so a normal test run reads the committed bytes
+// instead of producing fresh ones.
+//
+// The corpus is written as one commit followed by one deletion, which is how a
+// Property shard reaches a generation carrying both live and masked rows for
+// the same entity. Every row keeps its own document identifier -- the Property
+// writer keys a document by entity and revision -- so the three revisions of
+// e-1 are three physical rows rather than one replacing the others.
+func TestGenerateNIDX02AFixture(t *testing.T) {
+ if os.Getenv(nidx02aGenerateEnv) != "1" {
+ t.Skipf("set %s=1 to regenerate the NIDX-02A corpus", nidx02aGenerateEnv)
+ }
+ tester := require.New(t)
+
+ staging := t.TempDir()
+ store, err := NewStore(StoreOpts{Path: staging})
+ tester.NoError(err)
+ tester.NoError(store.UpdateSeriesBatch(index.Batch{Documents: nidx02aBatch()}))
+ masked := make([][]byte, 0, len(nidx02aRows))
+ for _, row := range nidx02aRows {
+ if row.masked {
+ masked = append(masked, []byte(nidx02aDocID(row)))
+ }
+ }
+ tester.NoError(store.Delete(masked))
+ tester.NoError(store.Close())
+
+ tester.NoError(os.RemoveAll(nidx02aRoot))
+ tester.NoError(os.MkdirAll(nidx02aShardDir, 0o755))
+ entries, err := os.ReadDir(staging)
+ tester.NoError(err)
+ segments, snapshots := 0, uint64(0)
+ for _, entry := range entries {
+ extension := filepath.Ext(entry.Name())
+ if extension != segExt && extension != snpExt {
+ continue
+ }
+ if extension == segExt {
+ segments++
+ } else if identifier, parsed := parseFixtureIdentifier(entry.Name(), snpExt); parsed && identifier > snapshots {
+ snapshots = identifier
+ }
+ payload, readErr := os.ReadFile(filepath.Join(staging, entry.Name()))
+ tester.NoError(readErr)
+ tester.NoError(os.WriteFile(filepath.Join(nidx02aShardDir, entry.Name()), payload, 0o600))
+ }
+ tester.NotZero(segments, "the corpus must hold at least one sealed segment")
+
+ // The corpus is only evidence if its own declaration holds on the bytes
+ // just written, so the two facts every later assertion rests on -- which
+ // generation is newest, and that exactly the declared rows survive its
+ // deletion masks -- are checked here with operations already merged.
+ tester.Equal(nidx02aSnapshotID, snapshots, "regenerating moved the corpus's newest generation; update nidx02aSnapshotID")
+ visible, err := ReadOnlyDocCount(nidx02aShardDir)
+ tester.NoError(err)
+ tester.Equal(nidx02aVisibleRowCount, visible, "the corpus must leave exactly the declared visible rows undeleted")
+
+ tester.NoError(os.WriteFile(nidx02aManifest, nidx02aProvenanceBytes(t), 0o600))
+}
+
+// nidx02aBatch turns the declared rows into one commit shaped like the Property
+// shard's own writes: the entity identifier, the group, the name and the tag as
+// indexed sortable fields, the payloads and the repair SHA as stored fields, the
+// Property deletion marker as a stored field where the row declares one, and
+// the property's modification revision as the document timestamp.
+func nidx02aBatch() index.Documents {
+ documents := make(index.Documents, 0, len(nidx02aRows))
+ for _, row := range nidx02aRows {
+ fields := []index.Field{
+ nidx02aSortableField(index.FieldKey{TagName: nidx02aEntityField}, []byte(row.entityID)),
+ nidx02aSortableField(index.FieldKey{TagName: nidx02aGroupField}, []byte(row.group)),
+ nidx02aSortableField(index.FieldKey{TagName: nidx02aNameField}, []byte(row.name)),
+ nidx02aSortableField(nidx02aTagFieldKey(), []byte(row.tag)),
+ }
+ for _, source := range row.sources {
+ fields = append(fields, nidx02aStoredField(nidx02aSourceField, []byte(source)))
+ }
+ if row.deletedAt > 0 {
+ fields = append(fields, nidx02aStoredField(nidx02aDeletedField, convert.Int64ToBytes(row.deletedAt)))
+ }
+ fields = append(fields, nidx02aStoredField(nidx02aSHAField, []byte(row.sha)))
+ documents = append(documents, index.Document{
+ EntityValues: []byte(nidx02aDocID(row)),
+ Timestamp: row.timestamp,
+ Fields: fields,
+ })
+ }
+ return documents
+}
+
+// nidx02aTagFieldKey is the field key the Property write path gives the
+// corpus's tag: the hash of the tag key rather than the key itself.
+func nidx02aTagFieldKey() index.FieldKey {
+ return index.FieldKey{IndexRuleID: uint32(convert.HashStr(nidx02aTagKey))}
+}
+
+// nidx02aTagFieldName renders the segment field name the corpus's tag is
+// recorded under.
+func nidx02aTagFieldName() string {
+ return nidx02aTagFieldKey().Marshal()
+}
+
+// nidx02aDocID renders the document identifier the Property writer gives a
+// revision: the entity it belongs to followed by that revision.
+func nidx02aDocID(row nidx02aRow) string {
+ return row.group + "/" + row.name + "/" + row.entityID + "/" + strconv.FormatInt(row.timestamp, 10)
+}
+
+// nidx02aSortableField builds a field the segment indexes and records a doc
+// value for.
+func nidx02aSortableField(key index.FieldKey, value []byte) index.Field {
+ field := index.NewBytesField(key, value)
+ field.Index = true
+ return field
+}
+
+// nidx02aStoredField builds a field the segment stores but neither indexes nor
+// records a doc value for.
+func nidx02aStoredField(name string, value []byte) index.Field {
+ field := index.NewBytesField(index.FieldKey{TagName: name}, value)
+ field.Store = true
+ field.NoSort = true
+ return field
+}
+
+// nidx02aVisibleRows lists the corpus's rows that survive its deletion masks,
+// in the ascending order the four declared sort components put them in.
+func nidx02aVisibleRows() []nidx02aRow {
+ visible := make([]nidx02aRow, 0, len(nidx02aRows))
+ for _, row := range nidx02aRows {
+ if !row.masked {
+ visible = append(visible, row)
+ }
+ }
+ return visible
+}
+
+// nidx02aProvenanceBytes renders the manifest checked in beside the corpus.
+func nidx02aProvenanceBytes(t *testing.T) []byte {
+ t.Helper()
+ described := make([]nidx02aProvenanceRow, 0, len(nidx02aRows))
+ for _, row := range nidx02aRows {
+ described = append(described, nidx02aDescribeRow(row))
+ }
+ manifest := nidx02aProvenance{
+ Oracle: map[string]string{
+ "writer": "pkg/index/inverted.NewStore",
+ "go_mod_sha256": nidx02aGoModSHA256(t),
+ },
+ GeneratorCommand: nidx02aGenerateCmd,
+ FileSHA256: nidx02aFileHashes(t),
+ TagFieldName: hex.EncodeToString([]byte(nidx02aTagFieldName())),
+ Rows: described,
+ PhysicalRowCount: nidx02aPhysicalRowCount,
+ SnapshotID: nidx02aSnapshotID,
+ VisibleRowCount: nidx02aVisibleRowCount,
+ Notes: "One Property shard generation holding six physical rows of four entities. " +
+ "Ascending by (_group, _im_name, _entity_id, _timestamp) the rows order as " +
+ "e-1@10, e-1@15, e-1@20, e-2@5, e-3@7, e-4@30. Rows e-1@15 and e-4@30 are masked by the " +
+ "generation's deletion masks: the first sorts between the two leading visible rows so a page " +
+ "built without the masks is caught inside the first page, and the second sorts last so a mask " +
+ "dropped only at the tail is caught too. Row e-1@10 records two _source stored values, so an " +
+ "encoder that collapsed repeated stored values is caught. Row e-2@5 carries the Property " +
+ "_deleted marker as a stored field while staying a live document of the generation. Every row " +
+ "also carries one indexed, sortable Property tag recorded under the hash of its key.",
+ }
+ encoded, err := json.MarshalIndent(manifest, "", " ")
+ require.NoError(t, err)
+ return append(encoded, '\n')
+}
+
+func nidx02aDescribeRow(row nidx02aRow) nidx02aProvenanceRow {
+ return nidx02aProvenanceRow{
+ Group: row.group,
+ Name: row.name,
+ EntityID: row.entityID,
+ Timestamp: row.timestamp,
+ SHA: row.sha,
+ Sources: row.sources,
+ Tag: row.tag,
+ DocID: nidx02aDocID(row),
+ DeletedAt: row.deletedAt,
+ Masked: row.masked,
+ }
+}
+
+// nidx02aGoModSHA256 pins the dependency set the oracle ran with, so the corpus
+// is identified by an immutable content hash rather than by a module name.
+func nidx02aGoModSHA256(t *testing.T) string {
+ t.Helper()
+ raw, err := os.ReadFile(filepath.Join("..", "..", "..", "go.mod"))
+ require.NoError(t, err)
+ sum := sha256.Sum256(raw)
+ return hex.EncodeToString(sum[:])
+}
+
+// nidx02aFileHashes hashes every checked-in corpus file.
+func nidx02aFileHashes(t *testing.T) map[string]string {
+ t.Helper()
+ entries, err := os.ReadDir(nidx02aShardDir)
+ require.NoError(t, err)
+ names := make([]string, 0, len(entries))
+ for _, entry := range entries {
+ names = append(names, entry.Name())
+ }
+ sort.Strings(names)
+ hashes := make(map[string]string, len(names))
+ for _, name := range names {
+ payload, readErr := os.ReadFile(filepath.Join(nidx02aShardDir, name))
+ require.NoError(t, readErr)
+ sum := sha256.Sum256(payload)
+ hashes["shard-0/"+name] = hex.EncodeToString(sum[:])
+ }
+ return hashes
+}
diff --git a/pkg/index/inverted/native_nidx01b_boundary_test.go b/pkg/index/inverted/native_nidx01b_boundary_test.go
index 01fdeb477..81e861047 100644
--- a/pkg/index/inverted/native_nidx01b_boundary_test.go
+++ b/pkg/index/inverted/native_nidx01b_boundary_test.go
@@ -60,13 +60,24 @@ var nidx01bBoundary committedGenerationCounter = ReadOnlyDocCount
// issue #14011 added exact-term selection; and issue #14012 adds the bounded
// repair tuple page. Term dictionaries and postings are what those operations
// are built from, so they stay private: ranges, prefix and wildcard expansion,
-// analyzers, writers and merge remain outside the milestone, and an entry here
-// for any of them is the milestone growing surface it was explicitly denied.
+// analyzers and merge remain outside the milestone, and an entry here for any
+// of them is the milestone growing surface it was explicitly denied.
+//
+// Issue #14073 adds the one exception the list now carries: a single generation
+// encoder and the three types its input is expressed in. Encoding is the
+// milestone's whole point rather than a convenience, and it is bounded to
+// writing one committed generation -- there is deliberately no entry for a
+// merger, a segment implementation, a plugin adapter or a lifecycle hook.
var nativeReaderSurface = []string{
+ "Encode",
+ "EncodeDocument",
+ "EncodeField",
"ErrCorrupt",
+ "ErrInvalidGeneration",
"ErrInvalidRepairPage",
"ErrInvalidSelection",
"ErrNoSnapshot",
+ "Generation",
"Open",
"Reader",
"Reader.Close",
diff --git a/pkg/index/inverted/native_nidx01e_tuple_page_test.go b/pkg/index/inverted/native_nidx01e_tuple_page_test.go
index f1b75633f..e4e0a5455 100644
--- a/pkg/index/inverted/native_nidx01e_tuple_page_test.go
+++ b/pkg/index/inverted/native_nidx01e_tuple_page_test.go
@@ -71,14 +71,25 @@ var nidx01eEncodedTimestamps = map[int64][]byte{
//
// Nothing else may appear. An entry for a collector, a sort expression, a
// comparator, a heap, a doc-value reader, a chunk decoder, a range, a prefix,
-// a wildcard, an analyzer or any writer is the milestone growing the surface
+// a wildcard or an analyzer is the milestone growing the surface
// BDB-NIDX-SPEC-001 revision 0.2 NIDX-01 explicitly denied it, however
// convenient the entry is.
+//
+// Issue #14073 lifts the ceiling by exactly one operation: the generation
+// encoder and the three types its input is expressed in. NIDX-01 denied the
+// reader a writer because a writer was nobody's milestone then; NIDX-02A makes
+// encoding one committed generation the deliverable, and the entries below are
+// bounded to that -- no merger, no segment implementation, no plugin adapter.
var nidx01ePermittedReaderSurface = map[string]struct{}{
+ "Encode": {},
+ "EncodeDocument": {},
+ "EncodeField": {},
"ErrCorrupt": {},
+ "ErrInvalidGeneration": {},
"ErrInvalidRepairPage": {},
"ErrInvalidSelection": {},
"ErrNoSnapshot": {},
+ "Generation": {},
"Open": {},
"Reader": {},
"Reader.Close": {},
diff --git a/pkg/index/inverted/native_nidx02a_encode_test.go b/pkg/index/inverted/native_nidx02a_encode_test.go
new file mode 100644
index 000000000..d4205d965
--- /dev/null
+++ b/pkg/index/inverted/native_nidx02a_encode_test.go
@@ -0,0 +1,407 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package inverted
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/apache/skywalking-banyandb/pkg/convert"
+ "github.com/apache/skywalking-banyandb/pkg/index"
+ "github.com/apache/skywalking-banyandb/pkg/index/inverted/internal/nativeice"
+)
+
+const (
+ // nidx02aEncodedSegmentID and nidx02aEncodedSnapshotID number the generation
+ // the native encoder is asked to write. They match the identifiers the
+ // compatibility writer gave the checked-in corpus, so the two generations
+ // are comparable as generations and not merely as document sets.
+ nidx02aEncodedSegmentID = uint64(2)
+ nidx02aEncodedSnapshotID = nidx02aSnapshotID
+
+ // nidx02aEncodedPageSize is the page size both generations are paged at.
+ // Two of the corpus's four visible rows fit in a page, so the resume cursor
+ // is exercised and the masked row that sorts between the first two visible
+ // rows would surface inside the first page.
+ nidx02aEncodedPageSize = 2
+
+ // nidx02aLaterSegmentID and nidx02aLaterSnapshotID number the generation the
+ // encoder appends beside the compatibility writer's in the mixed-provenance
+ // directory. Both are above the corpus's own, so the appended generation is
+ // the directory's newest.
+ nidx02aLaterSegmentID = uint64(8)
+ nidx02aLaterSnapshotID = uint64(9)
+)
+
+// TestNativeEncodedGenerationMatchesCompatibilityFixture is the milestone's
+// end-to-end case: the native encoder is handed the documents the checked-in
+// corpus was written from, and everything a Property shard reads out of the
+// generation it produces must match, row for row, what the same reads return
+// from the corpus the compatibility writer produced.
+//
+// The corpus is the oracle. Its bytes came from pkg/index/inverted.NewStore at
+// the dependency set testdata/nidx02a/provenance.json pins by content hash, and
+// no reader or writer under test produced them, so an encoder that is
+// self-consistently wrong disagrees here.
+//
+// Requirement proved here:
+//
+// R6 -- a generation the native encoder writes from the corpus's input
+// documents serves the same pinned snapshot identifier, the same
+// visible document count, the same stored-document walk, the same
+// exact-term selections and the same ascending repair pages as the
+// checked-in generation the compatibility writer produced.
+func TestNativeEncodedGenerationMatchesCompatibilityFixture(t *testing.T) {
+ tester := require.New(t)
+ encoded := nidx02aEncodeCorpus(t)
+
+ expectedCount, countErr := ReadOnlyDocCount(nidx02aShardDir)
+ tester.NoError(countErr)
+ actualCount, actualCountErr := ReadOnlyDocCount(encoded)
+ tester.NoError(actualCountErr)
+ tester.Equal(expectedCount, actualCount, "the encoded generation must leave the same rows visible")
+ tester.Equal(nidx02aVisibleRowCount, actualCount)
+
+ tester.Equal(nidx02aWalk(t, nidx02aShardDir), nidx02aWalk(t, encoded),
+ "the encoded generation must yield the corpus's stored-document walk, repeated values included")
+
+ for _, selection := range nidx02aSelections() {
+ tester.Equal(nidx02aSelect(t, nidx02aShardDir, selection), nidx02aSelect(t, encoded, selection),
+ "the encoded generation must serve the corpus's selection on field %x", selection.Field)
+ }
+
+ tester.Equal(nidx02aPages(t, nidx02aShardDir), nidx02aPages(t, encoded),
+ "the encoded generation must serve the corpus's ascending repair pages")
+
+ expected := nidx02aOpen(t, nidx02aShardDir)
+ actual := nidx02aOpen(t, encoded)
+ tester.Equal(expected.SnapshotID(), actual.SnapshotID())
+ tester.Equal(nidx02aEncodedSnapshotID, actual.SnapshotID())
+}
+
+// TestNativeEncodedGenerationOpensInTheCompatibilityReader hands the encoder's
+// output to the reader a rollback would run.
+//
+// A native generation that only the new reader can open is a generation no
+// operator can roll back from, so this is the milestone's compatibility
+// requirement rather than a convenience: the bytes must be acceptable to the
+// pinned reader both on a first open and across a restart, which is what a
+// mixed-version cluster does to them.
+//
+// Requirement proved here:
+//
+// R7 -- the pinned compatibility reader opens a directory the native encoder
+// wrote, resolves a query against it, and resolves the same query again
+// after the store is closed and reopened. A row the generation's
+// deletion masks hide is absent from both.
+func TestNativeEncodedGenerationOpensInTheCompatibilityReader(t *testing.T) {
+ tester := require.New(t)
+ encoded := nidx02aEncodeCorpus(t)
+
+ visible := nidx02aVisibleRows()[0]
+ masked := nidx02aRows[1]
+ tester.True(masked.masked, "the corpus's second row must be the masked one this case queries for")
+
+ for _, attempt := range []string{"first open", "restart"} {
+ store, openErr := NewStore(StoreOpts{Path: encoded})
+ tester.NoError(openErr, "the compatibility reader must open the encoded generation on %s", attempt)
+
+ found := nidx02aCompatibilitySearch(t, store, nidx02aDocID(visible))
+ tester.Len(found, 1, "the compatibility reader must resolve a live row on %s", attempt)
+ tester.Equal(visible.sha, string(found[0].Fields[nidx02aSHAField]),
+ "the compatibility reader must read the live row's stored SHA on %s", attempt)
+
+ tester.Empty(nidx02aCompatibilitySearch(t, store, nidx02aDocID(masked)),
+ "the compatibility reader must not resolve a masked row on %s", attempt)
+
+ tester.NoError(store.Close())
+ }
+}
+
+// TestNativeEncodedGenerationJoinsACompatibilityWrittenDirectory appends an
+// encoder generation to a directory whose existing generation came from the
+// compatibility writer.
+//
+// This is the shape of a shard mid-rollout: older generations on disk were
+// written by the retired writer and the newest by the native encoder, and both
+// have to stay readable through one reader. It also covers the rollback
+// direction -- when the newest generation is lost, the retired writer's bytes
+// must still open exactly as they did before.
+//
+// Requirement proved here:
+//
+// R8 -- encoding into a directory that already holds a committed generation
+// leaves that generation's bytes intact and publishes the new one as the
+// directory's newest. Losing the newer generation's manifest returns the
+// directory to the older generation, whose visible count and
+// stored-document walk are unchanged.
+func TestNativeEncodedGenerationJoinsACompatibilityWrittenDirectory(t *testing.T) {
+ tester := require.New(t)
+ directory := filepath.Join(t.TempDir(), "shard-0")
+ nidx02aCopyDir(t, nidx02aShardDir, directory)
+
+ priorWalk := nidx02aWalk(t, directory)
+ priorCount, priorCountErr := ReadOnlyDocCount(directory)
+ tester.NoError(priorCountErr)
+ tester.Equal(nidx02aVisibleRowCount, priorCount)
+
+ later := nativeice.Generation{
+ SegmentID: nidx02aLaterSegmentID,
+ SnapshotID: nidx02aLaterSnapshotID,
+ Documents: []nativeice.EncodeDocument{nidx02aEncodeDocumentOf(nidx02aRows[4])},
+ }
+ tester.NoError(nativeice.Encode(directory, later))
+
+ appended := nidx02aOpen(t, directory)
+ tester.Equal(nidx02aLaterSnapshotID, appended.SnapshotID(), "the appended generation must be the directory's newest")
+ appendedCount, appendedCountErr := ReadOnlyDocCount(directory)
+ tester.NoError(appendedCountErr)
+ tester.Equal(int64(1), appendedCount, "the appended generation holds exactly the one document it was given")
+
+ nidx02aRemoveNewestManifest(t, directory)
+
+ rolledBack := nidx02aOpen(t, directory)
+ tester.Equal(nidx02aSnapshotID, rolledBack.SnapshotID(),
+ "losing the newer manifest must return the directory to the compatibility writer's generation")
+ rolledBackCount, rolledBackCountErr := ReadOnlyDocCount(directory)
+ tester.NoError(rolledBackCountErr)
+ tester.Equal(priorCount, rolledBackCount)
+ tester.Equal(priorWalk, nidx02aWalk(t, directory),
+ "the compatibility writer's bytes must read exactly as they did before the encoder wrote beside them")
+}
+
+// TestNativeEncoderSurfaceStaysWithinNIDX02A guards the boundary itself rather
+// than any behavior behind it.
+//
+// Requirement proved here:
+//
+// R9 -- the milestone adds one encoder and the types its input is expressed
+// in, and nothing else: no plugin adapter, no merger, no segment
+// implementation, no lifecycle hook. The sentinel a rejected generation
+// is classified with stays distinct from the four the package already
+// publishes, and the native reader package's third-party dependency set
+// is unchanged, so the encoder reaches no retired index library.
+func TestNativeEncoderSurfaceStaysWithinNIDX02A(t *testing.T) {
+ tester := require.New(t)
+
+ tester.ErrorIs(nativeice.ErrInvalidGeneration, nativeice.ErrInvalidGeneration)
+ tester.NotErrorIs(nativeice.ErrInvalidGeneration, ErrCorruptIndex)
+ tester.NotErrorIs(nativeice.ErrInvalidGeneration, ErrNoCommittedIndex)
+ tester.NotErrorIs(nativeice.ErrInvalidGeneration, ErrInvalidSelection)
+ tester.NotErrorIs(nativeice.ErrInvalidGeneration, ErrInvalidRepairPage)
+
+ tester.Equal(nativeReaderSurface, exportedSurfaceOf(t),
+ "the native reader package's exported surface changed; NIDX-02A admits one encoder and its input types")
+ assertNativeReaderImportsAreAllowed(t)
+}
+
+// nidx02aEncodeCorpus writes the corpus's declared input documents into a fresh
+// directory with the native encoder and returns it.
+func nidx02aEncodeCorpus(t *testing.T) string {
+ t.Helper()
+ directory := filepath.Join(t.TempDir(), "shard-0")
+ require.NoError(t, os.MkdirAll(directory, 0o755))
+ documents := make([]nativeice.EncodeDocument, 0, len(nidx02aRows))
+ for _, row := range nidx02aRows {
+ documents = append(documents, nidx02aEncodeDocumentOf(row))
+ }
+ require.NoError(t, nativeice.Encode(directory, nativeice.Generation{
+ SegmentID: nidx02aEncodedSegmentID,
+ SnapshotID: nidx02aEncodedSnapshotID,
+ Documents: documents,
+ }))
+ return directory
+}
+
+// nidx02aEncodeDocumentOf renders one declared row as the document the native
+// encoder is handed. It is an independent second mapping of the same corpus:
+// nidx02aBatch renders the row for the compatibility writer, this renders it
+// for the encoder, and the end-to-end case asserts the two generations read
+// alike.
+//
+// The revision is supplied as the literal encoded value the corpus declares
+// rather than as a number, because the encoder applies no numeric coding: a
+// term sorts and reads back as exactly the bytes it was handed.
+func nidx02aEncodeDocumentOf(row nidx02aRow) nativeice.EncodeDocument {
+ fields := []nativeice.EncodeField{
+ {Name: nidx02aEntityField, Value: []byte(row.entityID), Index: true, Sort: true},
+ {Name: nidx02aGroupField, Value: []byte(row.group), Index: true, Sort: true},
+ {Name: nidx02aNameField, Value: []byte(row.name), Index: true, Sort: true},
+ {Name: nidx02aTagFieldName(), Value: []byte(row.tag), Index: true, Sort: true},
+ }
+ for _, source := range row.sources {
+ fields = append(fields, nativeice.EncodeField{Name: nidx02aSourceField, Value: []byte(source), Store: true})
+ }
+ if row.deletedAt > 0 {
+ fields = append(fields, nativeice.EncodeField{
+ Name: nidx02aDeletedField, Value: convert.Int64ToBytes(row.deletedAt), Store: true,
+ })
+ }
+ fields = append(fields,
+ nativeice.EncodeField{Name: nidx02aSHAField, Value: []byte(row.sha), Store: true},
+ nativeice.EncodeField{
+ Name: nidx02aTimestampField, Value: nidx02aEncodedTimestamps[row.timestamp],
+ Index: true, Store: true, Sort: true,
+ },
+ )
+ return nativeice.EncodeDocument{Identifier: []byte(nidx02aDocID(row)), Fields: fields, Deleted: row.masked}
+}
+
+// nidx02aSelections are the exact-term selections both generations are asked
+// for: a group two visible rows and one masked row recorded, a group one
+// visible row recorded, a Property tag under its hashed field name, and a term
+// no row recorded.
+func nidx02aSelections() []TermSelection {
+ return []TermSelection{
+ {Field: nidx02aGroupField, Terms: [][]byte{[]byte("g-a")}},
+ {Field: nidx02aGroupField, Terms: [][]byte{[]byte("g-b")}},
+ {Field: nidx02aGroupField, Terms: [][]byte{[]byte("g-a"), []byte("g-b")}},
+ {Field: nidx02aTagFieldName(), Terms: [][]byte{[]byte("red")}},
+ {Field: nidx02aTagFieldName(), Terms: [][]byte{[]byte("green")}},
+ {Field: nidx02aEntityField, Terms: [][]byte{[]byte("e-1")}},
+ }
+}
+
+// nidx02aWalk renders every live document of a directory's newest committed
+// generation as its stored values, in the order the walk yields them.
+func nidx02aWalk(t *testing.T, directory string) []string {
+ t.Helper()
+ var documents []string
+ require.NoError(t, ReadOnlyWalkDocuments(context.Background(), directory, func(document StoredDocument) error {
+ documents = append(documents, nidx02aRenderDocument(document))
+ return nil
+ }))
+ return documents
+}
+
+// nidx02aSelect renders the live documents one selection holds.
+func nidx02aSelect(t *testing.T, directory string, selection TermSelection) []string {
+ t.Helper()
+ var documents []string
+ require.NoError(t, ReadOnlySelectDocuments(context.Background(), directory, selection,
+ func(document StoredDocument) error {
+ documents = append(documents, nidx02aRenderDocument(document))
+ return nil
+ }))
+ return documents
+}
+
+// nidx02aPages renders every ascending repair page of a directory's newest
+// committed generation, paged to exhaustion.
+func nidx02aPages(t *testing.T, directory string) [][]string {
+ t.Helper()
+ generation := nidx02aOpen(t, directory)
+ var pages [][]string
+ request := RepairPageRequest{PageSize: nidx02aEncodedPageSize}
+ for {
+ rows, pageErr := generation.RepairTuplePage(context.Background(), request)
+ require.NoError(t, pageErr)
+ if len(rows) == 0 {
+ return pages
+ }
+ rendered := make([]string, 0, len(rows))
+ for _, row := range rows {
+ components := make([]string, 0, len(row.SortValues)+1)
+ for _, value := range row.SortValues {
+ components = append(components, fmt.Sprintf("%x", value))
+ }
+ rendered = append(rendered, strings.Join(components, "|")+"=>"+fmt.Sprintf("%x", row.Value))
+ }
+ pages = append(pages, rendered)
+ request.After = rows[len(rows)-1].Cursor
+ }
+}
+
+// nidx02aRenderDocument renders one document's stored values as a single
+// comparable string, keeping the walk's own order so a collapsed repeated value
+// or a reordered field is visible in the difference.
+func nidx02aRenderDocument(document StoredDocument) string {
+ var values []string
+ _ = document.VisitStoredFields(func(name string, value []byte) bool {
+ values = append(values, fmt.Sprintf("%x=%x", name, value))
+ return true
+ })
+ return strings.Join(values, " ")
+}
+
+// nidx02aOpen pins a directory's newest committed generation for the duration
+// of the test.
+func nidx02aOpen(t *testing.T, directory string) *ReadOnlyGeneration {
+ t.Helper()
+ generation, openErr := OpenReadOnlyGeneration(directory)
+ require.NoError(t, openErr)
+ require.NotNil(t, generation)
+ t.Cleanup(func() {
+ require.NoError(t, generation.Close())
+ })
+ return generation
+}
+
+// nidx02aCompatibilitySearch resolves one document identifier through the
+// pinned compatibility reader.
+func nidx02aCompatibilitySearch(t *testing.T, store index.SeriesStore, documentID string) []index.SeriesDocument {
+ t.Helper()
+ query, queryErr := store.BuildQuery([]index.SeriesMatcher{
+ {Match: []byte(documentID), Type: index.SeriesMatcherTypeExact},
+ }, nil, nil)
+ require.NoError(t, queryErr)
+ found, searchErr := store.Search(context.Background(), []index.FieldKey{
+ {TagName: nidx02aIDField}, {TagName: nidx02aSHAField}, {TagName: nidx02aSourceField},
+ }, query, len(nidx02aRows))
+ require.NoError(t, searchErr)
+ return found
+}
+
+// nidx02aCopyDir copies a checked-in corpus into a writable directory, so a
+// case that appends a generation never touches the bytes under testdata.
+func nidx02aCopyDir(t *testing.T, source, destination string) {
+ t.Helper()
+ require.NoError(t, os.MkdirAll(destination, 0o755))
+ entries, readErr := os.ReadDir(source)
+ require.NoError(t, readErr)
+ for _, entry := range entries {
+ payload, fileErr := os.ReadFile(filepath.Join(source, entry.Name()))
+ require.NoError(t, fileErr)
+ require.NoError(t, os.WriteFile(filepath.Join(destination, entry.Name()), payload, 0o600))
+ }
+}
+
+// nidx02aRemoveNewestManifest models the loss of the newest generation's
+// publication while every segment stays on disk, which is the state a rollback
+// or an interrupted write leaves a directory in.
+func nidx02aRemoveNewestManifest(t *testing.T, directory string) {
+ t.Helper()
+ entries, readErr := os.ReadDir(directory)
+ require.NoError(t, readErr)
+ var manifests []string
+ for _, entry := range entries {
+ if filepath.Ext(entry.Name()) == snpExt {
+ manifests = append(manifests, entry.Name())
+ }
+ }
+ require.NotEmpty(t, manifests, "the directory must hold a published generation to lose")
+ sort.Strings(manifests)
+ require.NoError(t, os.Remove(filepath.Join(directory, manifests[len(manifests)-1])))
+}
diff --git a/pkg/index/inverted/testdata/nidx02a/provenance.json b/pkg/index/inverted/testdata/nidx02a/provenance.json
new file mode 100644
index 000000000..2937c4b9e
--- /dev/null
+++ b/pkg/index/inverted/testdata/nidx02a/provenance.json
@@ -0,0 +1,103 @@
+{
+ "oracle": {
+ "go_mod_sha256": "23076127a0a072d3a06b157fc063c483fe0d8293e0e77bea7fed76658423c28d",
+ "writer": "pkg/index/inverted.NewStore"
+ },
+ "file_sha256": {
+ "shard-0/000000000002.seg": "50264f9dba9ab2e1c7a4d83a19b6549385273de2bf2c51c3f8dd865bf3c118ff",
+ "shard-0/000000000003.snp": "e248cd0fda8c0b84bcbd7a119f60b91ec9af617394114390c3637dec2d7ff1e7"
+ },
+ "generator_command": "GENERATE_NIDX02A_FIXTURE=1 go test ./pkg/index/inverted/ -run TestGenerateNIDX02AFixture -count=1",
+ "notes": "One Property shard generation holding six physical rows of four entities. Ascending by (_group, _im_name, _entity_id, _timestamp) the rows order as e-1@10, e-1@15, e-1@20, e-2@5, e-3@7, e-4@30. Rows e-1@15 and e-4@30 are masked by the generation's deletion masks: the first sorts between the two leading visible rows so a page built without the masks is caught inside the first page, and the second sorts last so a mask dropped only at the tail is caught too. Row e-1@10 records t [...]
+ "tag_field_name_hex": "1e1e9004",
+ "rows": [
+ {
+ "group": "g-a",
+ "name": "n-a",
+ "entity_id": "e-1",
+ "sha_value": "sha-a",
+ "doc_id": "g-a/n-a/e-1/10",
+ "tag": "red",
+ "sources": [
+ "source-a1",
+ "source-a2"
+ ],
+ "timestamp": 10,
+ "deleted_at": 0,
+ "masked": false
+ },
+ {
+ "group": "g-a",
+ "name": "n-a",
+ "entity_id": "e-1",
+ "sha_value": "sha-x",
+ "doc_id": "g-a/n-a/e-1/15",
+ "tag": "red",
+ "sources": [
+ "source-x"
+ ],
+ "timestamp": 15,
+ "deleted_at": 0,
+ "masked": true
+ },
+ {
+ "group": "g-a",
+ "name": "n-a",
+ "entity_id": "e-1",
+ "sha_value": "sha-b",
+ "doc_id": "g-a/n-a/e-1/20",
+ "tag": "blue",
+ "sources": [
+ "source-b"
+ ],
+ "timestamp": 20,
+ "deleted_at": 0,
+ "masked": false
+ },
+ {
+ "group": "g-a",
+ "name": "n-b",
+ "entity_id": "e-2",
+ "sha_value": "sha-c",
+ "doc_id": "g-a/n-b/e-2/5",
+ "tag": "red",
+ "sources": [
+ "source-c"
+ ],
+ "timestamp": 5,
+ "deleted_at": 99,
+ "masked": false
+ },
+ {
+ "group": "g-b",
+ "name": "n-a",
+ "entity_id": "e-3",
+ "sha_value": "sha-d",
+ "doc_id": "g-b/n-a/e-3/7",
+ "tag": "blue",
+ "sources": [
+ "source-d"
+ ],
+ "timestamp": 7,
+ "deleted_at": 0,
+ "masked": false
+ },
+ {
+ "group": "g-b",
+ "name": "n-b",
+ "entity_id": "e-4",
+ "sha_value": "sha-e",
+ "doc_id": "g-b/n-b/e-4/30",
+ "tag": "red",
+ "sources": [
+ "source-e"
+ ],
+ "timestamp": 30,
+ "deleted_at": 0,
+ "masked": true
+ }
+ ],
+ "physical_row_count": 6,
+ "snapshot_id": 3,
+ "visible_row_count": 4
+}
diff --git a/pkg/index/inverted/testdata/nidx02a/shard-0/000000000002.seg b/pkg/index/inverted/testdata/nidx02a/shard-0/000000000002.seg
new file mode 100644
index 000000000..30c57c70b
Binary files /dev/null and b/pkg/index/inverted/testdata/nidx02a/shard-0/000000000002.seg differ
diff --git a/pkg/index/inverted/testdata/nidx02a/shard-0/000000000003.snp b/pkg/index/inverted/testdata/nidx02a/shard-0/000000000003.snp
new file mode 100644
index 000000000..3c6d220b3
Binary files /dev/null and b/pkg/index/inverted/testdata/nidx02a/shard-0/000000000003.snp differ