mirror of
https://github.com/milvus-io/milvus.git
synced 2026-10-11 22:49:53 +00:00
issue: #53051, #53052, #53152 ## Summary Align local storage around one path contract: a key is a complete absolute filesystem path, and the local loon/Arrow filesystem is rooted at `/`. Previously, some writers used `minio.rootPath` while others supplied complete local paths to an already-prefixed filesystem, placing files in different physical locations from those expected by readers and GC. Remote keys remain complete bucket-relative object keys; their filesystem-root convention is unchanged. ## Changes - Unify Go/C++ local filesystem roots and StorageV3 manifest-base construction across writers. Preserve the existing base/version pair when continuing a growing-source manifest. - Fix local JSON/TEXT stats reads, rejected-stats cleanup, and explore temporary paths. Exercise resolved V3 stats paths through the actual `LocalChunkManager.MultiRead` interface. - Resolve legacy local manifest bases in loaded metadata and locally referenced snapshots, without eager catalog or manifest-file writes. Preserve manifest CAS compatibility and pathless V3 summaries; copy/restore writes use the target storage root. - Require an absolute, nonempty `localStorage.path` at initialization, including on remote deployments where it is a cache directory. Freeze forbidden parameters against configuration-source refresh while retaining explicit runtime/test overrides, and derive mmap, pprof, and disk-capacity defaults from the same canonical startup value. - Make segment deletion prefixes segment-boundary aware, retain root/identity and snapshot checks, and add BM25 orphan scanning. These shared GC changes also apply to remote storage; this PR does not claim every remote code path is untouched. - Remove the local test-only root override and unused local-only property initialization chain; use the production storage-config initialization path. ## Automatic local upgrade Let `R = localStorage.path` and `M = minio.rootPath`. Before standalone components start, local deployments check the known legacy locations: | Existing data | Upgrade handling | | --- | --- | | Canonical files under `R/<layout>` | Leave in place. | | Double-root files under `R/<R-without-leading-slash>/<layout>` | Move into `R/<layout>` for `insert_log`, `text_log`, `json_stats`, `index_files`, and `index_v1`. | | Recognized late-2.6 unified packed indexes under the process CWD | Move into the corresponding directory under `R`, if visible to the new process. | | Legacy manifest base `M/insert_log/<c>/<p>/<s>`, with files under `R/M/insert_log/<c>/<p>/<s>` | **Do not move the files.** Resolve the loaded manifest base to that existing absolute location. New segment layouts use the canonical root; updates to an existing legacy manifest can retain its base. | Migration prefers directory/subtree rename and recursively merges overlapping directories. Cross-filesystem moves fall back to copy-then-remove. Existing same-name files cause a conflict rather than content comparison or overwrite, except a published copy recognized as this migration's own interrupted work. The copy path synchronizes the file and target directory chain before deleting the source. Remaining sources are rediscovered on retry; empty legacy directories are pruned. Once migrated, restarts probe the known old locations without rescanning canonical data. The initial pass walks legacy file metadata but does not hash file contents. There is no configured migration timeout. SIGTERM/SIGINT cancels the migration and prevents etcd or components from starting; directory walks and cross-filesystem copies observe cancellation between filesystem reads. A canceled partial copy is never published and is recopied from the intact source on the next start. No user migration script, offline command, reverse migration, journal, or backup is provided. Successfully moved sources are removed. ## Compatibility and limits - Preserve the absolute local root, data mounts, and legacy `minio.rootPath` when upgrading. Canonical 2.6 data stays in place; misplaced late-2.6 indexes and affected 3.0.0/3.0.1 layouts are handled as above. Relative roots from older versions are unsupported. - Automatic migration is standalone/local-only. If old CWD indexes disappeared with an old container, they cannot be discovered: preserve/make those files visible or rebuild the derived indexes. Cross-filesystem copy has no configured timeout and can extend the first startup, but a shutdown signal cancels it and the next start resumes from the remaining source. - Downgrade to the affected old layout is unsupported after migration. Symlink layouts require manual resolution. - Known legacy LOB/orphan GC gaps under `R/M/insert_log`, pending old external-refresh paths, and rare interrupted-copy publication residue remain outside scope. This is not a claim that every historical file is recovered or reclaimable. ## Validation At head `898dba4b41`, `ci-v2/build-ut-cov` passed Build, Code Check, Integration UT, Go UT, and C++ UT (9,145/9,145). Diff coverage was 100% for C++ and 81.2% for Go; total patch coverage was 82.8%. Focused local tests for canonical/frozen `localStorage.path` derivation and migration cancellation/deadline/copy recovery passed with `-tags dynamic,test -gcflags='all=-N -l' -count=1`, and `git diff --check` passed before publication. Full paramtable execution remains locally blocked by tests attempting to create `/var/lib/milvus/data`; roles/native-dependent Go tests remain build-blocked by local C++ header/library mismatches. A real 3.0.0/3.0.1 version-to-version upgrade was not executed locally. `ci-v2/e2e-default` and `ci-v2/go-sdk` are still pending for this head. Signed-off-by: xiaofanluan <[email protected]> Co-authored-by: xiaofanluan <[email protected]>
439 lines
20 KiB
Go
439 lines
20 KiB
Go
// Licensed to the LF AI & Data foundation 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 datacoord
|
|
|
|
import (
|
|
"context"
|
|
"io"
|
|
"io/fs"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/apache/arrow/go/v17/arrow"
|
|
"github.com/apache/arrow/go/v17/arrow/array"
|
|
"github.com/apache/arrow/go/v17/arrow/memory"
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/mock"
|
|
"github.com/stretchr/testify/require"
|
|
"google.golang.org/protobuf/proto"
|
|
|
|
"github.com/milvus-io/milvus-proto/go-api/v3/commonpb"
|
|
"github.com/milvus-io/milvus-proto/go-api/v3/schemapb"
|
|
"github.com/milvus-io/milvus/internal/metastore"
|
|
catalogmocks "github.com/milvus-io/milvus/internal/metastore/mocks"
|
|
"github.com/milvus-io/milvus/internal/storage"
|
|
"github.com/milvus-io/milvus/internal/storage/localmigrate"
|
|
"github.com/milvus-io/milvus/internal/storagev2/packed"
|
|
"github.com/milvus-io/milvus/pkg/v3/objectstorage"
|
|
"github.com/milvus-io/milvus/pkg/v3/proto/datapb"
|
|
"github.com/milvus-io/milvus/pkg/v3/proto/indexpb"
|
|
"github.com/milvus-io/milvus/pkg/v3/util/conc"
|
|
"github.com/milvus-io/milvus/pkg/v3/util/merr"
|
|
"github.com/milvus-io/milvus/pkg/v3/util/paramtable"
|
|
"github.com/milvus-io/milvus/pkg/v3/util/typeutil"
|
|
)
|
|
|
|
type legacyLocalPackedFixture struct {
|
|
root string
|
|
legacyRoot string
|
|
physicalManifest string
|
|
segment *datapb.SegmentInfo
|
|
cm *storage.LocalChunkManager
|
|
cfg *indexpb.StorageConfig
|
|
pks []int64
|
|
texts []string
|
|
}
|
|
|
|
// Write a real manifest at the physical location used by the old rooted
|
|
// filesystem. Its writer-generated internal references are serialized relative
|
|
// to the segment/partition, while the catalog retains the old relative base.
|
|
// Compatibility must resolve that base to this original location without copying.
|
|
// This does not fabricate a parquet, manifest, stats blob, or LOB marker file.
|
|
func newLegacyLocalPackedFixture(t *testing.T) *legacyLocalPackedFixture {
|
|
t.Helper()
|
|
return newLocalPackedFixture(t, false)
|
|
}
|
|
|
|
// The displaced variant models complete keys passed to the old double-rooted
|
|
// filesystem. Both variants use real writers and unchanged relative manifest
|
|
// references; only the physical namespace and catalog base differ.
|
|
func newLocalPackedFixture(t *testing.T, displaced bool) *legacyLocalPackedFixture {
|
|
t.Helper()
|
|
setLocalManifestLegacyPrefix(t, "files")
|
|
root := t.TempDir()
|
|
params := paramtable.Get()
|
|
for _, setting := range []struct{ key, value, original string }{
|
|
{params.CommonCfg.StorageType.Key, "local", params.CommonCfg.StorageType.GetValue()},
|
|
{params.LocalStorageCfg.Path.Key, root, params.LocalStorageCfg.Path.GetValue()},
|
|
} {
|
|
require.NoError(t, params.Save(setting.key, setting.value))
|
|
t.Cleanup(func() { require.NoError(t, params.Save(setting.key, setting.original)) })
|
|
}
|
|
cfg := &indexpb.StorageConfig{StorageType: "local", RootPath: root}
|
|
legacyRoot := filepath.Join(root, "files")
|
|
catalogBase := "files/insert_log/1/2/3"
|
|
if displaced {
|
|
legacyRoot = filepath.Join(root, strings.TrimPrefix(root, string(filepath.Separator)))
|
|
catalogBase = filepath.Join(root, "insert_log/1/2/3")
|
|
}
|
|
base := filepath.Join(legacyRoot, "insert_log/1/2/3")
|
|
pks := []int64{11, 22, 33}
|
|
texts := []string{strings.Repeat("first lob ", 32), strings.Repeat("second lob ", 32), strings.Repeat("third lob ", 32)}
|
|
schema := arrow.NewSchema([]arrow.Field{
|
|
{Name: "100", Type: arrow.PrimitiveTypes.Int64, Metadata: arrow.NewMetadata([]string{packed.ArrowFieldIdMetadataKey}, []string{"100"})},
|
|
{Name: "101", Type: arrow.BinaryTypes.String, Metadata: arrow.NewMetadata([]string{packed.ArrowFieldIdMetadataKey}, []string{"101"})},
|
|
}, nil)
|
|
builder := array.NewRecordBuilder(memory.DefaultAllocator, schema)
|
|
defer builder.Release()
|
|
builder.Field(0).(*array.Int64Builder).AppendValues(pks, nil)
|
|
builder.Field(1).(*array.StringBuilder).AppendValues(texts, nil)
|
|
record := builder.NewRecord()
|
|
defer record.Release()
|
|
writer, err := packed.NewFFISegmentWriter(schema, &packed.SegmentWriterConfig{
|
|
SegmentPath: base,
|
|
WriterFormat: "parquet",
|
|
TextColumns: []packed.TextColumnConfig{{
|
|
FieldID: 101, LobBasePath: filepath.Join(legacyRoot, "insert_log/1/2/lobs/101"),
|
|
InlineThreshold: 1, MaxLobFileBytes: 1 << 20, FlushThresholdBytes: 1 << 20,
|
|
}},
|
|
}, cfg)
|
|
require.NoError(t, err)
|
|
closed := false
|
|
t.Cleanup(func() {
|
|
if !closed {
|
|
out, closeErr := writer.Close()
|
|
if out != nil {
|
|
out.Destroy()
|
|
}
|
|
require.NoError(t, closeErr)
|
|
}
|
|
})
|
|
require.NoError(t, writer.Write(record))
|
|
output, err := writer.Close()
|
|
closed = true
|
|
require.NoError(t, err)
|
|
defer output.Destroy()
|
|
statsWriter := &storage.StatsWriter{}
|
|
require.NoError(t, statsWriter.GenerateByData(100, schemapb.DataType_Int64, &storage.Int64FieldData{Data: pks}))
|
|
statsPath := filepath.Join(base, "_stats/bloom_filter.100/42")
|
|
require.NoError(t, packed.WriteFile(cfg, statsPath, statsWriter.GetBuffer()))
|
|
physicalManifest, err := packed.CommitManifestUpdates(base, packed.ManifestEarliest, cfg, &packed.ManifestUpdates{
|
|
NewFiles: output,
|
|
Stats: []packed.StatEntry{{Key: "bloom_filter.100", Files: []string{statsPath}, Metadata: map[string]string{"memory_size": "24"}}},
|
|
})
|
|
require.NoError(t, err)
|
|
_, version, err := packed.UnmarshalManifestPath(physicalManifest)
|
|
require.NoError(t, err)
|
|
return &legacyLocalPackedFixture{
|
|
root: root, legacyRoot: legacyRoot, physicalManifest: physicalManifest,
|
|
segment: &datapb.SegmentInfo{
|
|
ID: 3, CollectionID: 1, PartitionID: 2, State: commonpb.SegmentState_Flushed,
|
|
StorageVersion: storage.StorageV3, NumOfRows: int64(len(pks)),
|
|
ManifestPath: packed.MarshalManifestPath(catalogBase, version),
|
|
},
|
|
cm: storage.NewLocalChunkManager(objectstorage.RootPath(root)), cfg: cfg, pks: pks, texts: texts,
|
|
}
|
|
}
|
|
|
|
func (f *legacyLocalPackedFixture) assertNoCanonicalLayout(t *testing.T) {
|
|
t.Helper()
|
|
_, err := os.Stat(filepath.Join(f.root, "insert_log"))
|
|
require.ErrorIs(t, err, os.ErrNotExist, "legacy V3 compatibility must not create a canonical insert_log tree")
|
|
}
|
|
|
|
// Read the old segment's real data, stats and LOB payload in place. This does
|
|
// not exercise compaction between the legacy and canonical storage namespaces.
|
|
func (f *legacyLocalPackedFixture) assertReadable(t *testing.T, manifest, expectedRoot string) {
|
|
t.Helper()
|
|
base, _, err := packed.UnmarshalManifestPath(manifest)
|
|
require.NoError(t, err)
|
|
fragments, err := packed.ReadFragmentsFromManifest(manifest, f.cfg, []string{"100"})
|
|
require.NoError(t, err)
|
|
require.NotEmpty(t, fragments)
|
|
for _, fragment := range fragments {
|
|
require.True(t, strings.HasPrefix(fragment.FilePath, filepath.Join(base, "_data")+"/"), fragment.FilePath)
|
|
}
|
|
pkSchema := arrow.NewSchema([]arrow.Field{{Name: "100", Type: arrow.PrimitiveTypes.Int64}}, nil)
|
|
reader, err := packed.NewFFIPackedReader(manifest, pkSchema, []string{"100"}, 1<<20, f.cfg, nil, packed.ExternalReaderContext{})
|
|
require.NoError(t, err)
|
|
defer func() { require.NoError(t, reader.Close()) }()
|
|
var gotPKs []int64
|
|
for {
|
|
record, readErr := reader.ReadNext()
|
|
if readErr == io.EOF {
|
|
break
|
|
}
|
|
require.NoError(t, readErr)
|
|
gotPKs = append(gotPKs, record.Column(0).(*array.Int64).Int64Values()...)
|
|
}
|
|
require.Equal(t, f.pks, gotPKs)
|
|
|
|
statsPaths, err := packed.NewStatsResolver(manifest, f.cfg).BloomFilterPaths(100)
|
|
require.NoError(t, err)
|
|
require.Equal(t, []string{filepath.Join(base, "_stats/bloom_filter.100/42")}, statsPaths)
|
|
statsBytes, err := f.cm.Read(context.Background(), statsPaths[0])
|
|
require.NoError(t, err)
|
|
statsReader := &storage.StatsReader{}
|
|
statsReader.SetBuffer(statsBytes)
|
|
stats, err := statsReader.GetPrimaryKeyStats()
|
|
require.NoError(t, err)
|
|
assert.Equal(t, int64(100), stats.FieldID)
|
|
assert.True(t, stats.MinPk.EQ(storage.NewInt64PrimaryKey(f.pks[0])))
|
|
assert.True(t, stats.MaxPk.EQ(storage.NewInt64PrimaryKey(f.pks[len(f.pks)-1])))
|
|
|
|
lobs, err := packed.GetManifestLobFiles(manifest, f.cfg)
|
|
require.NoError(t, err)
|
|
require.Len(t, lobs, 1, "the TEXT values must be stored out of line in a real Vortex file")
|
|
lob := lobs[0]
|
|
require.True(t, strings.HasPrefix(lob.Path, filepath.Join(expectedRoot, "insert_log/1/2/lobs/101/_data")+"/"), lob.Path)
|
|
require.Equal(t, int64(101), lob.FieldID)
|
|
require.Equal(t, int64(len(f.texts)), lob.TotalRows)
|
|
lobSchema := arrow.NewSchema([]arrow.Field{{Name: "text_data", Type: arrow.BinaryTypes.String}}, nil)
|
|
lobReader, err := packed.NewFFIPackedReaderWithFragments([]string{"text_data"}, "vortex", []packed.Fragment{{
|
|
FilePath: lob.Path, StartRow: 0, EndRow: lob.TotalRows, RowCount: lob.TotalRows,
|
|
}}, lobSchema, []string{"text_data"}, 1<<20, f.cfg, nil, packed.ExternalReaderContext{})
|
|
require.NoError(t, err)
|
|
defer func() { require.NoError(t, lobReader.Close()) }()
|
|
var gotTexts []string
|
|
for {
|
|
record, readErr := lobReader.ReadNext()
|
|
if readErr == io.EOF {
|
|
break
|
|
}
|
|
require.NoError(t, readErr)
|
|
column := record.Column(0).(*array.String)
|
|
for i := 0; i < column.Len(); i++ {
|
|
// ReadNext releases the preceding Arrow batch. Copy strings while
|
|
// its backing buffer is still alive, including before the EOF read.
|
|
gotTexts = append(gotTexts, strings.Clone(column.Value(i)))
|
|
}
|
|
}
|
|
require.Equal(t, f.texts, gotTexts)
|
|
}
|
|
|
|
// Keep every fixture read beneath an opened root. The names returned by
|
|
// WalkDir are root-relative; they are never reopened as unchecked absolute
|
|
// filesystem paths.
|
|
func readLocalPackedFixtureFiles(t *testing.T, directory string) map[string][]byte {
|
|
t.Helper()
|
|
root, err := os.OpenRoot(directory)
|
|
require.NoError(t, err)
|
|
defer func() { require.NoError(t, root.Close()) }()
|
|
rootFS := root.FS()
|
|
files := make(map[string][]byte)
|
|
require.NoError(t, fs.WalkDir(rootFS, ".", func(name string, entry fs.DirEntry, walkErr error) error {
|
|
if walkErr != nil {
|
|
return walkErr
|
|
}
|
|
if entry.IsDir() {
|
|
return nil
|
|
}
|
|
contents, err := fs.ReadFile(rootFS, name)
|
|
if err == nil {
|
|
files[name] = contents
|
|
}
|
|
return err
|
|
}))
|
|
return files
|
|
}
|
|
|
|
func TestReloadLocalManifestPreservesPackedReferences(t *testing.T) {
|
|
f := newLegacyLocalPackedFixture(t)
|
|
t.Chdir(f.root)
|
|
f.assertReadable(t, f.physicalManifest, f.legacyRoot)
|
|
f.assertNoCanonicalLayout(t)
|
|
originalFiles := readLocalPackedFixtureFiles(t, f.legacyRoot)
|
|
catalog := catalogmocks.NewDataCoordCatalog(t)
|
|
catalog.EXPECT().ListSegments(mock.Anything, int64(1)).Return([]*datapb.SegmentInfo{f.segment}, nil).Twice()
|
|
catalog.EXPECT().ListChannelCheckpoint(mock.Anything).Return(nil, nil).Twice()
|
|
mt := newLocalManifestTestMeta(catalog, f.cm)
|
|
originalSegment := proto.Clone(f.segment)
|
|
for i := 0; i < 2; i++ {
|
|
// The R/M namespace remains live compatibility data, not a rename source
|
|
// candidate, even when startup also checks for the double-root layout.
|
|
report, err := localmigrate.Migrate(t.Context(), f.root, localmigrate.Options{LegacyPrefix: "files"})
|
|
require.NoError(t, err)
|
|
require.Zero(t, report.Renamed)
|
|
require.NoError(t, mt.reloadFromKV(context.Background(), []int64{1}))
|
|
loaded := mt.segments.GetSegment(3)
|
|
require.Equal(t, f.physicalManifest, loaded.GetManifestPath())
|
|
f.assertReadable(t, loaded.GetManifestPath(), f.legacyRoot)
|
|
require.True(t, proto.Equal(originalSegment, f.segment))
|
|
assertLocalManifestCatalogReadOnly(t, catalog)
|
|
f.assertNoCanonicalLayout(t)
|
|
}
|
|
// Neither metadata reload nor real reads rewrite the original manifest,
|
|
// data, stats or partition-level LOB files under root/minio.rootPath.
|
|
require.Equal(t, originalFiles, readLocalPackedFixtureFiles(t, f.legacyRoot))
|
|
f.assertReadable(t, f.physicalManifest, f.legacyRoot)
|
|
}
|
|
|
|
func TestMigrateDoubleRootPackedReferencesAndGCRetry(t *testing.T) {
|
|
f := newLocalPackedFixture(t, true)
|
|
t.Chdir(f.root)
|
|
f.assertNoCanonicalLayout(t)
|
|
f.assertReadable(t, f.physicalManifest, f.legacyRoot)
|
|
sources := readLocalPackedFixtureFiles(t, f.legacyRoot)
|
|
// CWD is the canonical root, leaving only the double-root rename source.
|
|
opts := localmigrate.Options{LegacyPrefix: "files"}
|
|
report, err := localmigrate.Migrate(t.Context(), f.root, opts)
|
|
require.NoError(t, err)
|
|
// The displaced insert_log directory is moved atomically as one unit; no
|
|
// file copy or backup tree is created.
|
|
require.Equal(t, 1, report.Renamed)
|
|
f.assertReadable(t, f.segment.GetManifestPath(), f.root)
|
|
canonicalRoot, err := os.OpenRoot(f.root)
|
|
require.NoError(t, err)
|
|
defer func() { require.NoError(t, canonicalRoot.Close()) }()
|
|
for name, original := range sources {
|
|
require.NoFileExists(t, filepath.Join(f.legacyRoot, name))
|
|
contents, err := fs.ReadFile(canonicalRoot.FS(), name)
|
|
require.NoError(t, err)
|
|
require.Equal(t, original, contents, name)
|
|
}
|
|
|
|
catalog := catalogmocks.NewDataCoordCatalog(t)
|
|
catalog.EXPECT().ListSegments(mock.Anything, int64(1)).Return([]*datapb.SegmentInfo{f.segment}, nil).Twice()
|
|
catalog.EXPECT().ListChannelCheckpoint(mock.Anything).Return(nil, nil).Twice()
|
|
mt := newLocalManifestTestMeta(catalog, f.cm)
|
|
for range 2 {
|
|
report, err = localmigrate.Migrate(t.Context(), f.root, opts)
|
|
require.NoError(t, err)
|
|
require.Zero(t, report.Renamed)
|
|
require.NoError(t, mt.reloadFromKV(context.Background(), []int64{1}))
|
|
require.Equal(t, f.segment.GetManifestPath(), mt.segments.GetSegment(3).GetManifestPath())
|
|
assertLocalManifestCatalogReadOnly(t, catalog)
|
|
f.assertReadable(t, mt.segments.GetSegment(3).GetManifestPath(), f.root)
|
|
}
|
|
|
|
// Segment GC and partition-level LOB GC may reclaim the canonical files.
|
|
removePool := conc.NewPool[struct{}](1)
|
|
t.Cleanup(removePool.Release)
|
|
gc := &garbageCollector{option: GcOption{cli: f.cm, removeObjectPool: removePool}}
|
|
dropped := proto.Clone(f.segment).(*datapb.SegmentInfo)
|
|
dropped.State = commonpb.SegmentState_Dropped
|
|
for range 2 {
|
|
require.NoError(t, gc.removeDroppedSegmentFiles(context.Background(), &SegmentInfo{SegmentInfo: dropped}, nil))
|
|
}
|
|
canonicalBase, _, err := packed.UnmarshalManifestPath(f.segment.GetManifestPath())
|
|
require.NoError(t, err)
|
|
require.NoFileExists(t, filepath.Join(canonicalBase, "_stats/bloom_filter.100/42"))
|
|
params := paramtable.Get()
|
|
safetyWindow := params.DataCoordCfg.GCLOBSafetyWindow.GetValue()
|
|
require.NoError(t, params.Save(params.DataCoordCfg.GCLOBSafetyWindow.Key, "0"))
|
|
t.Cleanup(func() { require.NoError(t, params.Save(params.DataCoordCfg.GCLOBSafetyWindow.Key, safetyWindow)) })
|
|
lobGC := newLOBGCContext(gc)
|
|
orphans := lobGC.scanOrphanLOBFiles(t.Context(), typeutil.NewSet[string]())
|
|
require.Len(t, orphans, 1, "the canonical orphan LOB is offered to the deletion callback")
|
|
require.True(t, strings.HasPrefix(orphans[0].FilePath, filepath.Join(f.root, "insert_log/1/2/lobs")+"/"))
|
|
lobGC.removeOrphanLOBFiles(t.Context(), orphans)
|
|
require.Empty(t, lobGC.scanOrphanLOBFiles(t.Context(), typeutil.NewSet[string]()))
|
|
// A fresh startup never treats completed renames as sources. GC must not be
|
|
// undone by restoring old immutable manifests, stats, data or LOB files.
|
|
for range 2 {
|
|
report, err = localmigrate.Migrate(t.Context(), f.root, opts)
|
|
require.NoError(t, err)
|
|
require.Zero(t, report.Renamed)
|
|
for name := range sources {
|
|
_, err := canonicalRoot.Stat(name)
|
|
require.ErrorIs(t, err, fs.ErrNotExist, name)
|
|
require.NoFileExists(t, filepath.Join(f.legacyRoot, name))
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestReloadLocalManifestCommitSegmentManifestCAS(t *testing.T) {
|
|
for _, mutationType := range []ManifestMutationType{ManifestMutationNoop, ManifestMutationCommitUpdates} {
|
|
name := "noop CAS"
|
|
if mutationType == ManifestMutationCommitUpdates {
|
|
name = "structured mutation"
|
|
}
|
|
t.Run(name, func(t *testing.T) {
|
|
f := newLegacyLocalPackedFixture(t)
|
|
f.assertNoCanonicalLayout(t)
|
|
stored := proto.Clone(f.segment).(*datapb.SegmentInfo)
|
|
catalog := catalogmocks.NewDataCoordCatalog(t)
|
|
catalog.EXPECT().ListSegments(mock.Anything, int64(1)).RunAndReturn(func(context.Context, int64) ([]*datapb.SegmentInfo, error) {
|
|
return []*datapb.SegmentInfo{stored}, nil
|
|
}).Twice()
|
|
catalog.EXPECT().ListChannelCheckpoint(mock.Anything).Return(nil, nil).Twice()
|
|
mt := newLocalManifestTestMeta(catalog, f.cm)
|
|
ctx := context.Background()
|
|
require.NoError(t, mt.reloadFromKV(ctx, []int64{1}))
|
|
assertLocalManifestCatalogReadOnly(t, catalog)
|
|
base, version, err := packed.UnmarshalManifestPath(f.physicalManifest)
|
|
require.NoError(t, err)
|
|
prepared := packed.MarshalManifestPath(base, version+1)
|
|
// CAS compares the authoritative normalized in-memory pointer, not the
|
|
// still-relative catalog value. Old workers and old versions are stale.
|
|
for _, expected := range []string{f.segment.GetManifestPath(), packed.MarshalManifestPath(base, version-1)} {
|
|
err := mt.CommitSegmentManifest(ctx, SegmentManifestCommit{
|
|
SegmentID: 3, ExpectedManifest: expected,
|
|
Mutation: ManifestMutation{Type: ManifestMutationNoop, ManifestPath: prepared},
|
|
})
|
|
require.ErrorIs(t, err, errSegmentManifestStale)
|
|
require.ErrorIs(t, err, merr.ErrServiceUnavailable)
|
|
}
|
|
catalog.AssertNotCalled(t, "Update", mock.Anything, mock.Anything)
|
|
require.Equal(t, f.segment.GetManifestPath(), stored.GetManifestPath())
|
|
updates := &packed.ManifestUpdates{Stats: []packed.StatEntry{{
|
|
Key: "bloom_filter.100", Files: []string{filepath.Join(base, "_stats/bloom_filter.100/42")},
|
|
Metadata: map[string]string{"memory_size": "48"},
|
|
}}}
|
|
commit := SegmentManifestCommit{
|
|
SegmentID: 3, StorageConfig: f.cfg,
|
|
Mutation: ManifestMutation{Type: mutationType, Updates: updates},
|
|
}
|
|
if mutationType == ManifestMutationNoop {
|
|
actualPrepared, err := packed.CommitManifestUpdates(base, version, f.cfg, updates)
|
|
require.NoError(t, err)
|
|
require.Equal(t, prepared, actualPrepared)
|
|
commit.ExpectedManifest = f.physicalManifest
|
|
commit.Mutation.ManifestPath = actualPrepared
|
|
}
|
|
catalog.EXPECT().Update(mock.Anything, mock.Anything).RunAndReturn(func(_ context.Context, actions ...metastore.UpdateAction) error {
|
|
require.Equal(t, f.segment.GetManifestPath(), stored.GetManifestPath(), "no startup write may precede the ordinary commit")
|
|
require.Equal(t, f.physicalManifest, mt.segments.GetSegment(3).GetManifestPath(), "publish memory only after catalog success")
|
|
require.Len(t, actions, 1)
|
|
entry, ok := actions[0].Entry.(metastore.SegmentEntry)
|
|
require.True(t, ok)
|
|
require.Equal(t, prepared, entry.Segment.GetManifestPath())
|
|
stored = proto.Clone(entry.Segment).(*datapb.SegmentInfo)
|
|
return nil
|
|
}).Once()
|
|
require.NoError(t, mt.CommitSegmentManifest(ctx, commit))
|
|
require.Equal(t, prepared, mt.segments.GetSegment(3).GetManifestPath())
|
|
f.assertReadable(t, prepared, f.legacyRoot)
|
|
f.assertNoCanonicalLayout(t)
|
|
// A result prepared on the previously normalized pointer must not be
|
|
// accepted after this publication, even with a higher prepared version.
|
|
err = mt.CommitSegmentManifest(ctx, SegmentManifestCommit{
|
|
SegmentID: 3, ExpectedManifest: f.physicalManifest,
|
|
Mutation: ManifestMutation{Type: ManifestMutationNoop, ManifestPath: packed.MarshalManifestPath(base, version+2)},
|
|
})
|
|
require.ErrorIs(t, err, errSegmentManifestStale)
|
|
require.Equal(t, prepared, stored.GetManifestPath())
|
|
catalog.AssertNumberOfCalls(t, "Update", 1)
|
|
require.NoError(t, mt.reloadFromKV(ctx, []int64{1}))
|
|
require.Equal(t, prepared, mt.segments.GetSegment(3).GetManifestPath())
|
|
f.assertNoCanonicalLayout(t)
|
|
})
|
|
}
|
|
}
|