Files
milvus/internal/datacoord/import_util.go
T
e2787d3981 enhance: standardize error handling on merr + Sys/Input classification (#50221)
issue: #47420

## What this PR does

Project-wide migration of raw `fmt.Errorf` / `errors.New` in function
bodies onto
the `merr` framework, plus the Sys-vs-Input error classification and the
machinery it drives (retriability, fine-grained metrics, segcore
unification),
plus the convention docs and a linter that keeps it from regressing.

Scope: storage, proxy, coordinators (root/data/query), query node, data
node,
`pkg/util` & `internal/util`, expression parser, message queue,
streaming, and
misc packages. Bare raw-error usages went from ~3000 to a ~340 allowlist
(package-level sentinels / build-tag / test sites).

---

## How to review this PR

It is large but the vast majority is mechanical. Changes fall into three
tiers;
spend review budget on Part 2 and Part 3.

### Part 1 — Mechanical standardization (low risk, verify by rule)

Each converted call follows one of a small fixed set of rules. To
review, check
that each site obeys the matching rule rather than reading every line:

| Pattern | Rule |
|---|---|
| `fmt.Errorf("...")` originating a new error | →
`merr.WrapErrXxxMsg("...")` with a code matching the failure's meaning |
| Adding context to an existing typed error | → `merr.Wrap(err, "...")`
/ `merr.Wrapf(...)` — **preserves** the inner code (never `WrapErr*Err`,
which overwrites it) |
| Errors inside the streaming subsystem | → `status.New*` factories
(StreamingError), **not** merr — this is the component-internal dialect
(see `docs/dev/error_handling_guide.md`) |
| Low-level / control-flow signal caught by `errors.Is` | → kept as a
package-level `errors.New` sentinel (lowercase, same-package) |

Conventions are documented in `docs/dev/error_handling_guide.md`
(how-to) and
`docs/dev/error_sentinel_convention.md` (rules + audit). A
`gocritic`/`ruleguard`
rule (`rawmerrerror`, in `rules.go`) enforces "no raw `return
errors.New/fmt.Errorf`"
under `make verifiers`.

### Part 2 — Behavior changes (review these closely)

These are the sites where the wire contract or runtime behavior changes,
not just
the source text. Listed by category; representative locations given,
full set in
the diff.

**A. gRPC wire-code shifts: `UnexpectedError(1)/Code 65535` → typed
code.**
Where a handler previously returned a raw error (collapsed to
`Code=65535` on the
wire), it now returns a typed merr, so the client sees a real code. The
most
common shift is to `IllegalArgument(5)/Code 1100` (ParameterInvalid).
Touch
points include datanode task handlers (CreateTask/Query/Drop), proxy
Upsert,
querynode GetMetrics, datacoord CreateIndex, httpserver query-response
builder,
and typeutil schema validation. One code refinement: an index-param
validation
moved `1100` → `1101` (ParameterMissing). **Client/SDK assertions and
any code
that switched on `Code=65535` for these paths must be re-checked** (the
go_client
e2e assertions were already aligned in this PR).

**B. Prometheus `status` label contract change (externally visible).**
The proxy metric's coarse `fail` / `rejected` values are split into
`fail_input` / `fail_system` and `rejected_user` / `rejected_system` (in
`requestutil.ParseMetricLabel`; auth/privilege rejections count as
`rejected_user`), so dashboards can attribute a failure to caller vs
operator.
**Dashboards/alerts querying `status="fail"` must migrate to
`status=~"fail_.*"`, and `status="rejected"` to
`status=~"rejected_.*"`.** The
in-repo Grafana dashboard is already migrated; external dashboards built
on the
old values silently go empty after upgrade. This is the one change that
requires an ops-side migration.

**C. Retriability semantics.**
- C1: `merr.Status(err)` now forces `Retriable=false` when the error is
an
`InputError` — a malformed request can never succeed on blind retry, so
clients
never get the self-contradictory "your input is wrong but you may
retry".
- C2: `retry.Do` short-circuits an `InputError` (non-retriable) — **but
only when
  the caller did not pass a `RetryErr` predicate**. The check is an
`if c.isRetryErr != nil { ... } else if InputError { ... }` *mutually
exclusive*
branch (`pkg/util/retry/retry.go`): an explicit `RetryErr` takes
precedence and
bypasses the InputError abort. `retry.Handle` deliberately does **not**
apply
the InputError abort (its callers signal abort via `shouldRetry=false`).
Four
flusher startup callsites that must retry through transient "not ready"
errors
  were given explicit `RetryErr` escape hatches.

**D. segcore (C++→Go) error classification.**
A single shared Go-side table (`pkg/util/merr/segcore.go`) maps each
segcore code
to a merr sentinel + InputError/signal category, replacing scattered
hand-written
`if errorCode == ...` switches in the cgo wrappers. **Wire `Code` values
change
for every segcore pass-through error, not just the remapped ones.**
Named
sentinels remap (C++ `2003` → merr `2001`, `2033` → `2002`,
Folly/Knowhere codes
likewise); **all remaining pass-through codes (`2004`–`2043`, previously
surfaced to clients as raw C++ enum values) now serialize as `2000`**
(`ErrSegcore`), with the original C++ code preserved in the `Reason`
text
(`segcoreCode=...`); unknown/future codes collapse to `2000` as well
(pinned by
the `wire_code_projection` test). Transient segcore classes (object
storage /
file IO / OOM / mmap / FieldNotLoaded — 11 codes) now report
`Retriable=true`.
**Any client switching on raw segcore codes in the `2004`–`2043` range
must be
re-checked**; the in-Reason code remains available for diagnostics.
Signal
codes (PretendFinished / FollyCancel) are recognized centrally.
`errors.Is`-based
control flow on these (e.g. scheduler skip/retry) is preserved.

**E. InputError classification (25 sentinels + dynamic marks).**
25 sentinels in `errors.go` carry `WithErrorType(InputError)` (the
Collection /
ResourceGroup / Database families, `ErrIndexDuplicate`,
`ErrParameterInvalid`,
`ErrPrivilegeNotAuthenticated`, `ErrImportFailed`, `ErrQueryPlan`, ...),
plus dynamic
marks for the 8 segcore input codes (ExprInvalid, DimNotMatch,
MetricTypeInvalid, FieldIDInvalid, ...) and
`WrapErrAsInputError`. The widest blast radius is `ErrParameterInvalid`
(1100):
~2335 `WrapErrParameterInvalid*` callsites now classify as input /
non-retriable. Because of C1/C2 this changes retriability for
any path that returns these. **The audit to confirm no transient path
was
mis-marked is the single most important review item** (see Part 3). One
reverse
correction: storage field-stats parsing moved from `ErrParameterInvalid`
(input)
to `ErrDataIntegrity` — a corrupted stored stat is data corruption, not
user
input.

### Part 3 — Known risks & traps (called out proactively)

1. **`merr.Wrap` vs `WrapErr*Err` (code-masking).** `WrapErr*Err` builds
a
`wrappedMilvusError{sentinel: ErrServiceInternal}` whose `code()`
returns the
*outer* sentinel — it overwrites the inner typed code and hides the
`errors.Is`
chain. This is intentional (use it to *deliberately* downgrade), but it
was a
recurring conversion defect; the rule "add context with `merr.Wrap`,
downgrade
with `WrapErr*Err`" is enforced by convention and reviewed across the
diff.
2. **InputError × `retry.Do` blast radius.** Marking a sentinel
`InputError` makes
any `retry.Do(...)` without a `RetryErr` predicate stop retrying it.
Reviewers
should sanity-check that no transient use of the 19 newly-marked
sentinels
(especially `ErrParameterInvalid`) sits inside a retry loop that needed
to keep
   spinning. The known flusher cases were handled (see C2).
3. **The ~340 raw-error allowlist.** What remains as bare `errors.New`
is, by
design: package-level sentinels (caught by `errors.Is`), `//go:build
test`
sites, and out-of-band trees (`cmd/`, `tests/`, codegen, walimpls). The
linter
only bans the *direct-return* form; assignment-then-return escapes and
the full
no-exceptions ban are deferred to an AST-based linter (Tier 2,
documented).
4. **segcore C++ second step deferred.** This PR unifies classification
on the Go
side; splitting the dual-semantic C++ codes at the source is a
follow-up.

---

## Validation

- `make verifiers`: Go side clean (gofmt + static-check across modules,
including
  the new `rawmerrerror` rule with a 0-hit baseline repo-wide).
- `make test-go`: passing; the one real regression introduced (a
datanode
`invalid_task_type` assertion shifting `1` → `5` from a ParameterInvalid
  conversion) was fixed in-tree.
- go_client e2e CreateIndex assertions aligned to the new merr messages.

---------

Signed-off-by: zhenshan.cao <zhenshan.cao@zilliz.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-12 15:04:51 -07:00

926 lines
33 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"
"fmt"
"math"
"path"
"sort"
"sync"
"time"
"github.com/cockroachdb/errors"
"github.com/samber/lo"
"go.uber.org/zap"
"github.com/milvus-io/milvus-proto/go-api/v3/commonpb"
"github.com/milvus-io/milvus-proto/go-api/v3/msgpb"
"github.com/milvus-io/milvus/internal/datacoord/allocator"
"github.com/milvus-io/milvus/internal/datacoord/session"
"github.com/milvus-io/milvus/internal/storage"
"github.com/milvus-io/milvus/internal/util/importutilv2"
"github.com/milvus-io/milvus/pkg/v3/common"
"github.com/milvus-io/milvus/pkg/v3/log"
"github.com/milvus-io/milvus/pkg/v3/proto/datapb"
"github.com/milvus-io/milvus/pkg/v3/proto/internalpb"
"github.com/milvus-io/milvus/pkg/v3/taskcommon"
"github.com/milvus-io/milvus/pkg/v3/util/conc"
"github.com/milvus-io/milvus/pkg/v3/util/hardware"
"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/timerecord"
"github.com/milvus-io/milvus/pkg/v3/util/typeutil"
)
func WrapTaskLog(task ImportTask, fields ...zap.Field) []zap.Field {
res := []zap.Field{
zap.Int64("taskID", task.GetTaskID()),
zap.Int64("jobID", task.GetJobID()),
zap.Int64("collectionID", task.GetCollectionID()),
zap.String("type", task.GetType().String()),
zap.String("state", task.GetTaskState().String()),
zap.Int64("nodeID", task.GetNodeID()),
}
res = append(res, fields...)
return res
}
func NewPreImportTasks(fileGroups [][]*internalpb.ImportFile,
job ImportJob, alloc allocator.Allocator, importMeta ImportMeta,
) ([]ImportTask, error) {
idStart, _, err := alloc.AllocN(int64(len(fileGroups)))
if err != nil {
return nil, err
}
tasks := make([]ImportTask, 0, len(fileGroups))
for i, files := range fileGroups {
fileStats := lo.Map(files, func(f *internalpb.ImportFile, _ int) *datapb.ImportFileStats {
return &datapb.ImportFileStats{
ImportFile: f,
}
})
taskProto := &datapb.PreImportTask{
JobID: job.GetJobID(),
TaskID: idStart + int64(i),
CollectionID: job.GetCollectionID(),
State: datapb.ImportTaskStateV2_Pending,
FileStats: fileStats,
CreatedTime: time.Now().Format("2006-01-02T15:04:05Z07:00"),
}
task := &preImportTask{
importMeta: importMeta,
tr: timerecord.NewTimeRecorder("preimport task"),
times: taskcommon.NewTimes(),
}
task.task.Store(taskProto)
tasks = append(tasks, task)
}
return tasks, nil
}
func NewImportTasks(fileGroups [][]*datapb.ImportFileStats,
job ImportJob, alloc allocator.Allocator, meta *meta, importMeta ImportMeta, segmentMaxSize int,
) ([]ImportTask, error) {
idBegin, _, err := alloc.AllocN(int64(len(fileGroups)))
if err != nil {
return nil, err
}
tasks := make([]ImportTask, 0, len(fileGroups))
for i, group := range fileGroups {
taskProto := &datapb.ImportTaskV2{
JobID: job.GetJobID(),
TaskID: idBegin + int64(i),
CollectionID: job.GetCollectionID(),
NodeID: NullNodeID,
State: datapb.ImportTaskStateV2_Pending,
FileStats: group,
CreatedTime: time.Now().Format("2006-01-02T15:04:05Z07:00"),
}
task := &importTask{
alloc: alloc,
meta: meta,
importMeta: importMeta,
tr: timerecord.NewTimeRecorder("import task"),
times: taskcommon.NewTimes(),
}
task.task.Store(taskProto)
segments, err := AssignSegments(job, task, alloc, meta, int64(segmentMaxSize))
if err != nil {
return nil, err
}
taskProto.SegmentIDs = segments
if enableSortCompaction() {
sortedSegIDBegin, _, err := alloc.AllocN(int64(len(segments)))
if err != nil {
return nil, err
}
taskProto.SortedSegmentIDs = lo.RangeFrom(sortedSegIDBegin, len(segments))
log.Info("preallocate sorted segment ids", WrapTaskLog(task, zap.Int64s("segmentIDs", taskProto.SortedSegmentIDs))...)
}
tasks = append(tasks, task)
}
return tasks, nil
}
func GetSegmentMaxSize(job ImportJob, meta *meta) int {
if importutilv2.IsL0Import(job.GetOptions()) {
return paramtable.Get().DataNodeCfg.FlushDeleteBufferBytes.GetAsInt()
}
return int(getExpectedSegmentSize(meta, job.GetCollectionID(), job.GetSchema()))
}
func AssignSegments(job ImportJob, task ImportTask, alloc allocator.Allocator, meta *meta, segmentMaxSize int64) ([]int64, error) {
pkField, err := typeutil.GetPrimaryFieldSchema(job.GetSchema())
if err != nil {
return nil, err
}
// merge hashed sizes
hashedDataSize := make(map[string]map[int64]int64) // vchannel->(partitionID->size)
for _, fileStats := range task.GetFileStats() {
for vchannel, partStats := range fileStats.GetHashedStats() {
if hashedDataSize[vchannel] == nil {
hashedDataSize[vchannel] = make(map[int64]int64)
}
for partitionID, size := range partStats.GetPartitionDataSize() {
hashedDataSize[vchannel][partitionID] += size
}
}
}
isL0Import := importutilv2.IsL0Import(job.GetOptions())
segmentLevel := datapb.SegmentLevel_L1
if isL0Import {
segmentLevel = datapb.SegmentLevel_L0
}
storageVersion := storage.StorageV2
if paramtable.Get().CommonCfg.UseLoonFFI.GetAsBool() {
storageVersion = storage.StorageV3
}
// alloc new segments
segments := make([]int64, 0)
addSegment := func(vchannel string, partitionID int64, size int64) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
for size > 0 {
segmentInfo, err := AllocImportSegment(ctx, alloc, meta,
task.GetJobID(), task.GetTaskID(), task.GetCollectionID(),
partitionID, vchannel, job.GetDataTs(), segmentLevel, storageVersion)
if err != nil {
return err
}
segments = append(segments, segmentInfo.GetID())
size -= segmentMaxSize
}
return nil
}
for vchannel, partitionSizes := range hashedDataSize {
for partitionID, size := range partitionSizes {
if pkField.GetAutoID() && size == 0 {
// When autoID is enabled, the preimport task estimates row distribution by
// evenly dividing the total row count (numRows) across all vchannels:
// `estimatedCount = numRows / vchannelNum`.
//
// However, the actual import task hashes real auto-generated IDs to determine
// the target vchannel. This mismatch can lead to inaccurate row distribution estimation
// in such corner cases:
//
// - Importing 1 row into 2 vchannels:
// • Preimport: 1 / 2 = 0 → both v0 and v1 are estimated to have 0 rows
// • Import: real autoID (e.g., 457975852966809057) hashes to v1
// → actual result: v0 = 0, v1 = 1
//
// To avoid such inconsistencies, we ensure that at least one segment is
// allocated for each vchannel when autoID is enabled.
size = 1
}
err := addSegment(vchannel, partitionID, size)
if err != nil {
return nil, err
}
}
}
return segments, nil
}
func AllocImportSegment(ctx context.Context,
alloc allocator.Allocator,
meta *meta,
jobID int64, taskID int64,
collectionID UniqueID, partitionID UniqueID,
channelName string,
dataTimestamp uint64,
level datapb.SegmentLevel,
storageVersion int64,
) (*SegmentInfo, error) {
log := log.Ctx(ctx)
id, err := alloc.AllocID(ctx)
if err != nil {
log.Error("failed to alloc id for import segment", zap.Error(err))
return nil, err
}
if dataTimestamp == 0 {
_, err = alloc.AllocTimestamp(ctx)
if err != nil {
return nil, err
}
}
segmentInfo := &datapb.SegmentInfo{
ID: id,
CollectionID: collectionID,
PartitionID: partitionID,
InsertChannel: channelName,
NumOfRows: 0,
State: commonpb.SegmentState_Importing,
MaxRowNum: 0,
Level: level,
LastExpireTime: math.MaxUint64,
StorageVersion: storageVersion,
}
segmentInfo.IsImporting = true
segment := NewSegmentInfo(segmentInfo)
if err = meta.AddSegment(ctx, segment); err != nil {
log.Error("failed to add import segment", zap.Error(err))
return nil, err
}
log.Info("add import segment done",
zap.Int64("jobID", jobID),
zap.Int64("taskID", taskID),
zap.Int64("collectionID", segmentInfo.CollectionID),
zap.Int64("segmentID", segmentInfo.ID),
zap.String("channel", segmentInfo.InsertChannel),
zap.String("level", level.String()))
return segment, nil
}
func AssemblePreImportRequest(task ImportTask, job ImportJob) *datapb.PreImportRequest {
importFiles := lo.Map(task.(*preImportTask).GetFileStats(),
func(fileStats *datapb.ImportFileStats, _ int) *internalpb.ImportFile {
return fileStats.GetImportFile()
})
req := &datapb.PreImportRequest{
JobID: task.GetJobID(),
TaskID: task.GetTaskID(),
CollectionID: task.GetCollectionID(),
PartitionIDs: job.GetPartitionIDs(),
Vchannels: job.GetVchannels(),
Schema: job.GetSchema(),
ImportFiles: importFiles,
Options: job.GetOptions(),
TaskSlot: task.GetTaskSlot(),
StorageConfig: createStorageConfig(),
PluginContext: GetReadPluginContext(job.GetOptions()),
}
WrapPluginContext(task.GetCollectionID(), job.GetSchema().GetProperties(), req)
return req
}
func AssembleImportRequest(task ImportTask, job ImportJob, meta *meta, alloc allocator.Allocator) (*datapb.ImportRequest, error) {
requestSegments := make([]*datapb.ImportRequestSegment, 0)
for _, segmentID := range task.(*importTask).GetSegmentIDs() {
segment := meta.GetSegment(context.TODO(), segmentID)
if segment == nil {
return nil, merr.WrapErrSegmentNotFound(segmentID, "assemble import request failed")
}
requestSegments = append(requestSegments, &datapb.ImportRequestSegment{
SegmentID: segment.GetID(),
PartitionID: segment.GetPartitionID(),
Vchannel: segment.GetInsertChannel(),
})
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
ts := job.GetDataTs()
var err error
if ts == 0 {
ts, err = alloc.AllocTimestamp(ctx)
if err != nil {
return nil, err
}
}
totalRows := lo.SumBy(task.GetFileStats(), func(stat *datapb.ImportFileStats) int64 {
return stat.GetTotalRows()
})
// Pre-allocate IDs for autoIDs and logIDs.
fieldsNum := len(job.GetSchema().GetFields()) + 2 // userFields + tsField + rowIDField
binlogNum := fieldsNum + 2 // binlogs + statslog + BM25Statslog
expansionFactor := paramtable.Get().DataCoordCfg.ImportPreAllocIDExpansionFactor.GetAsInt64()
preAllocIDNum := (totalRows + 1) * int64(binlogNum) * expansionFactor
idBegin, idEnd, err := common.AllocAutoID(func(n uint32) (int64, int64, error) {
ids, ide, e := alloc.AllocN(int64(n))
return ids, ide, e
}, uint32(preAllocIDNum), Params.CommonCfg.ClusterID.GetAsUint64())
if err != nil {
return nil, err
}
log.Info("pre-allocate ids and ts for import task", WrapTaskLog(task,
zap.Int64("totalRows", totalRows),
zap.Int("fieldsNum", fieldsNum),
zap.Int64("idBegin", idBegin),
zap.Int64("idEnd", idEnd),
zap.Uint64("ts", ts))...,
)
importFiles := lo.Map(task.GetFileStats(), func(fileStat *datapb.ImportFileStats, _ int) *internalpb.ImportFile {
return fileStat.GetImportFile()
})
storageVersion := storage.StorageV2
if paramtable.Get().CommonCfg.UseLoonFFI.GetAsBool() {
storageVersion = storage.StorageV3
}
req := &datapb.ImportRequest{
ClusterID: Params.CommonCfg.ClusterPrefix.GetValue(),
JobID: task.GetJobID(),
TaskID: task.GetTaskID(),
CollectionID: task.GetCollectionID(),
PartitionIDs: job.GetPartitionIDs(),
Vchannels: job.GetVchannels(),
Schema: job.GetSchema(),
Files: importFiles,
Options: job.GetOptions(),
Ts: ts,
IDRange: &datapb.IDRange{Begin: idBegin, End: idEnd},
RequestSegments: requestSegments,
StorageConfig: createStorageConfig(),
TaskSlot: task.GetTaskSlot(),
StorageVersion: storageVersion,
PluginContext: GetReadPluginContext(job.GetOptions()),
UseLoonFfi: Params.CommonCfg.UseLoonFFI.GetAsBool(),
}
WrapPluginContext(task.GetCollectionID(), job.GetSchema().GetProperties(), req)
return req, nil
}
func RegroupImportFiles(job ImportJob, files []*datapb.ImportFileStats, segmentMaxSize int) [][]*datapb.ImportFileStats {
if len(files) == 0 {
return nil
}
threshold := paramtable.Get().DataCoordCfg.MaxSizeInMBPerImportTask.GetAsInt() * 1024 * 1024
maxSizePerFileGroup := segmentMaxSize * len(job.GetPartitionIDs()) * len(job.GetVchannels())
if maxSizePerFileGroup > threshold {
maxSizePerFileGroup = threshold
}
fileGroups := make([][]*datapb.ImportFileStats, 0)
currentGroup := make([]*datapb.ImportFileStats, 0)
currentSum := 0
sort.Slice(files, func(i, j int) bool {
return files[i].GetTotalMemorySize() < files[j].GetTotalMemorySize()
})
for _, file := range files {
size := int(file.GetTotalMemorySize())
if size > maxSizePerFileGroup {
fileGroups = append(fileGroups, []*datapb.ImportFileStats{file})
} else if currentSum+size <= maxSizePerFileGroup {
currentGroup = append(currentGroup, file)
currentSum += size
} else {
fileGroups = append(fileGroups, currentGroup)
currentGroup = []*datapb.ImportFileStats{file}
currentSum = size
}
}
if len(currentGroup) > 0 {
fileGroups = append(fileGroups, currentGroup)
}
return fileGroups
}
func CheckDiskQuota(ctx context.Context, job ImportJob, meta *meta, importMeta ImportMeta) (int64, error) {
if !Params.QuotaConfig.DiskProtectionEnabled.GetAsBool() {
return 0, nil
}
if importutilv2.SkipDiskQuotaCheck(job.GetOptions()) {
log.Info("skip disk quota check for import", zap.Int64("jobID", job.GetJobID()))
return 0, nil
}
var (
requestedTotal int64
requestedCollections = make(map[int64]int64)
)
for _, j := range importMeta.GetJobBy(ctx) {
requested := j.GetRequestedDiskSize()
requestedTotal += requested
requestedCollections[j.GetCollectionID()] += requested
}
err := merr.WrapErrServiceQuotaExceeded("disk quota exceeded, please allocate more resources")
quotaInfo := meta.GetQuotaInfo()
totalUsage, collectionsUsage := quotaInfo.TotalBinlogSize, quotaInfo.CollectionBinlogSize
tasks := importMeta.GetTaskBy(ctx, WithJob(job.GetJobID()), WithType(PreImportTaskType))
files := make([]*datapb.ImportFileStats, 0)
for _, task := range tasks {
files = append(files, task.GetFileStats()...)
}
requestSize := lo.SumBy(files, func(file *datapb.ImportFileStats) int64 {
return file.GetTotalMemorySize()
})
totalDiskQuota := Params.QuotaConfig.DiskQuota.GetAsFloat()
if float64(totalUsage+requestedTotal+requestSize) > totalDiskQuota {
log.Warn("global disk quota exceeded", zap.Int64("jobID", job.GetJobID()),
zap.Bool("enabled", Params.QuotaConfig.DiskProtectionEnabled.GetAsBool()),
zap.Int64("totalUsage", totalUsage),
zap.Int64("requestedTotal", requestedTotal),
zap.Int64("requestSize", requestSize),
zap.Float64("totalDiskQuota", totalDiskQuota))
return 0, err
}
collectionDiskQuota := Params.QuotaConfig.DiskQuotaPerCollection.GetAsFloat()
colID := job.GetCollectionID()
if float64(collectionsUsage[colID]+requestedCollections[colID]+requestSize) > collectionDiskQuota {
log.Warn("collection disk quota exceeded", zap.Int64("jobID", job.GetJobID()),
zap.Bool("enabled", Params.QuotaConfig.DiskProtectionEnabled.GetAsBool()),
zap.Int64("collectionsUsage", collectionsUsage[colID]),
zap.Int64("requestedCollection", requestedCollections[colID]),
zap.Int64("requestSize", requestSize),
zap.Float64("collectionDiskQuota", collectionDiskQuota))
return 0, err
}
return requestSize, nil
}
func getPendingProgress(ctx context.Context, jobID int64, importMeta ImportMeta) float32 {
tasks := importMeta.GetTaskBy(context.TODO(), WithJob(jobID), WithType(PreImportTaskType))
preImportingFiles := lo.SumBy(tasks, func(task ImportTask) int {
return len(task.GetFileStats())
})
totalFiles := len(importMeta.GetJob(ctx, jobID).GetFiles())
if totalFiles == 0 {
return 1
}
return float32(preImportingFiles) / float32(totalFiles)
}
func getPreImportingProgress(ctx context.Context, jobID int64, importMeta ImportMeta) float32 {
tasks := importMeta.GetTaskBy(ctx, WithJob(jobID), WithType(PreImportTaskType))
completedTasks := lo.Filter(tasks, func(task ImportTask, _ int) bool {
return task.GetState() == datapb.ImportTaskStateV2_Completed
})
if len(tasks) == 0 {
return 1
}
return float32(len(completedTasks)) / float32(len(tasks))
}
func getImportRowsInfo(ctx context.Context, jobID int64, importMeta ImportMeta, meta *meta) (importedRows, totalRows int64) {
tasks := importMeta.GetTaskBy(ctx, WithJob(jobID), WithType(ImportTaskType))
segmentIDs := make([]int64, 0)
for _, task := range tasks {
totalRows += lo.SumBy(task.GetFileStats(), func(file *datapb.ImportFileStats) int64 {
return file.GetTotalRows()
})
segmentIDs = append(segmentIDs, task.(*importTask).GetSegmentIDs()...)
}
importedRows = meta.GetSegmentsTotalNumRows(segmentIDs)
return
}
func getImportingProgress(ctx context.Context, jobID int64, importMeta ImportMeta, meta *meta) (float32, int64, int64) {
importedRows, totalRows := getImportRowsInfo(ctx, jobID, importMeta, meta)
if totalRows == 0 {
return 1, importedRows, totalRows
}
return float32(importedRows) / float32(totalRows), importedRows, totalRows
}
func getStatsProgress(ctx context.Context, jobID int64, importMeta ImportMeta, meta *meta) float32 {
if !enableSortCompaction() {
return 1
}
tasks := importMeta.GetTaskBy(ctx, WithJob(jobID), WithType(ImportTaskType))
targetSegmentIDs := lo.FlatMap(tasks, func(t ImportTask, _ int) []int64 {
return t.(*importTask).GetSortedSegmentIDs()
})
if len(targetSegmentIDs) == 0 {
return 1
}
doneCnt := 0
for _, segID := range targetSegmentIDs {
seg := meta.GetHealthySegment(ctx, segID)
if seg != nil {
doneCnt++
}
}
return float32(doneCnt) / float32(len(targetSegmentIDs))
}
func getIndexBuildingProgress(ctx context.Context, jobID int64, importMeta ImportMeta, meta *meta) float32 {
job := importMeta.GetJob(ctx, jobID)
if !Params.DataCoordCfg.WaitForIndex.GetAsBool() {
return 1
}
tasks := importMeta.GetTaskBy(ctx, WithJob(jobID), WithType(ImportTaskType))
originSegmentIDs := lo.FlatMap(tasks, func(t ImportTask, _ int) []int64 {
return t.(*importTask).GetSegmentIDs()
})
targetSegmentIDs := lo.FlatMap(tasks, func(t ImportTask, _ int) []int64 {
return t.(*importTask).GetSortedSegmentIDs()
})
if len(originSegmentIDs) == 0 {
return 1
}
if !enableSortCompaction() {
targetSegmentIDs = originSegmentIDs
}
unindexed := meta.indexMeta.GetUnindexedSegments(job.GetCollectionID(), targetSegmentIDs)
return float32(len(targetSegmentIDs)-len(unindexed)) / float32(len(targetSegmentIDs))
}
// GetJobProgress calculates the importing job progress.
// The weight of each status is as follows:
// 10%: Pending
// 30%: PreImporting
// 30%: Importing
// 10%: Stats
// 10%: IndexBuilding
// 10%: Completed
// TODO: Wrap a function to map status to user status.
// TODO: Save these progress to job instead of recalculating.
func GetJobProgress(ctx context.Context, jobID int64,
importMeta ImportMeta, meta *meta,
) (int64, internalpb.ImportJobState, int64, int64, string) {
job := importMeta.GetJob(ctx, jobID)
if job == nil {
return 0, internalpb.ImportJobState_Failed, 0, 0, fmt.Sprintf("import job does not exist, jobID=%d", jobID)
}
switch job.GetState() {
case internalpb.ImportJobState_Pending:
progress := getPendingProgress(ctx, jobID, importMeta)
return int64(progress * 10), internalpb.ImportJobState_Pending, 0, 0, ""
case internalpb.ImportJobState_PreImporting:
progress := getPreImportingProgress(ctx, jobID, importMeta)
return 10 + int64(progress*30), internalpb.ImportJobState_Importing, 0, 0, ""
case internalpb.ImportJobState_Importing:
progress, importedRows, totalRows := getImportingProgress(ctx, jobID, importMeta, meta)
return 10 + 30 + int64(progress*30), internalpb.ImportJobState_Importing, importedRows, totalRows, ""
case internalpb.ImportJobState_Sorting:
progress := getStatsProgress(ctx, jobID, importMeta, meta)
_, totalRows := getImportRowsInfo(ctx, jobID, importMeta, meta)
return 10 + 30 + 30 + int64(progress*10), internalpb.ImportJobState_Importing, totalRows, totalRows, ""
case internalpb.ImportJobState_IndexBuilding:
progress := getIndexBuildingProgress(ctx, jobID, importMeta, meta)
_, totalRows := getImportRowsInfo(ctx, jobID, importMeta, meta)
return 10 + 30 + 30 + 10 + int64(progress*10), internalpb.ImportJobState_Importing, totalRows, totalRows, ""
case internalpb.ImportJobState_Uncommitted:
_, totalRows := getImportRowsInfo(ctx, jobID, importMeta, meta)
if job.GetAutoCommit() {
return 99, internalpb.ImportJobState_Importing, totalRows, totalRows, ""
}
return 99, internalpb.ImportJobState_Uncommitted, totalRows, totalRows, ""
case internalpb.ImportJobState_Committing:
_, totalRows := getImportRowsInfo(ctx, jobID, importMeta, meta)
if job.GetAutoCommit() {
return 99, internalpb.ImportJobState_Importing, totalRows, totalRows, ""
}
return 99, internalpb.ImportJobState_Committing, totalRows, totalRows, ""
case internalpb.ImportJobState_Completed:
_, totalRows := getImportRowsInfo(ctx, jobID, importMeta, meta)
return 100, internalpb.ImportJobState_Completed, totalRows, totalRows, ""
case internalpb.ImportJobState_Failed:
return 0, internalpb.ImportJobState_Failed, 0, 0, job.GetReason()
}
return 0, internalpb.ImportJobState_None, 0, 0, "unknown import job state"
}
func GetTaskProgresses(ctx context.Context, jobID int64, importMeta ImportMeta, meta *meta) []*internalpb.ImportTaskProgress {
progresses := make([]*internalpb.ImportTaskProgress, 0)
tasks := importMeta.GetTaskBy(ctx, WithJob(jobID), WithType(ImportTaskType))
for _, task := range tasks {
totalRows := lo.SumBy(task.GetFileStats(), func(file *datapb.ImportFileStats) int64 {
return file.GetTotalRows()
})
importedRows := meta.GetSegmentsTotalNumRows(task.(*importTask).GetSegmentIDs())
progress := int64(100)
if totalRows != 0 {
progress = int64(float32(importedRows) / float32(totalRows) * 100)
}
for _, fileStat := range task.GetFileStats() {
progresses = append(progresses, &internalpb.ImportTaskProgress{
FileName: fmt.Sprintf("%v", fileStat.GetImportFile().GetPaths()),
FileSize: fileStat.GetFileSize(),
Reason: task.GetReason(),
Progress: progress,
CompleteTime: task.(*importTask).GetCompleteTime(),
State: task.GetState().String(),
ImportedRows: progress * fileStat.GetTotalRows() / 100,
TotalRows: fileStat.GetTotalRows(),
})
}
}
return progresses
}
func DropImportTask(task ImportTask, cluster session.Cluster, tm ImportMeta) error {
if task.GetNodeID() == NullNodeID {
return nil
}
err := cluster.DropImport(task.GetNodeID(), task.GetTaskID())
if err != nil && !errors.Is(err, merr.ErrNodeNotFound) {
return err
}
log.Info("drop import in datanode done", WrapTaskLog(task)...)
return tm.UpdateTask(context.TODO(), task.GetTaskID(), UpdateNodeID(NullNodeID))
}
func ListBinlogsAndGroupBySegment(ctx context.Context,
cm storage.ChunkManager, importFile *internalpb.ImportFile,
) ([]*internalpb.ImportFile, error) {
if len(importFile.GetPaths()) == 0 {
return nil, merr.WrapErrImportFailed("no insert binlogs to import")
}
if len(importFile.GetPaths()) > 2 {
return nil, merr.WrapErrImportFailedMsg("too many input paths for binlog import. "+
"Valid paths length should be one or two, but got paths:%s", importFile.GetPaths())
}
insertPrefix := importFile.GetPaths()[0]
segmentInsertPaths, _, err := storage.ListAllChunkWithPrefix(ctx, cm, insertPrefix, false)
if err != nil {
return nil, err
}
segmentImportFiles := lo.Map(segmentInsertPaths, func(segmentPath string, _ int) *internalpb.ImportFile {
return &internalpb.ImportFile{Paths: []string{segmentPath}}
})
if len(importFile.GetPaths()) < 2 {
return segmentImportFiles, nil
}
deltaPrefix := importFile.GetPaths()[1]
segmentDeltaPaths, _, err := storage.ListAllChunkWithPrefix(ctx, cm, deltaPrefix, false)
if err != nil {
return nil, err
}
if len(segmentDeltaPaths) == 0 {
return segmentImportFiles, nil
}
deltaSegmentIDs := lo.KeyBy(segmentDeltaPaths, path.Base)
for i := range segmentImportFiles {
segmentID := path.Base(segmentImportFiles[i].GetPaths()[0])
if deltaPrefix, ok := deltaSegmentIDs[segmentID]; ok {
segmentImportFiles[i].Paths = append(segmentImportFiles[i].Paths, deltaPrefix)
}
}
return segmentImportFiles, nil
}
func LogResultSegmentsInfo(jobID int64, meta *meta, segmentIDs []int64) {
type (
segments = []*SegmentInfo
segmentInfo struct {
ID int64
Rows int64
Size int64
}
)
segmentsByChannelAndPartition := make(map[string]map[int64]segments) // channel => [partition => segments]
for _, segmentInfo := range meta.GetSegmentInfos(segmentIDs) {
channel := segmentInfo.GetInsertChannel()
partition := segmentInfo.GetPartitionID()
if _, ok := segmentsByChannelAndPartition[channel]; !ok {
segmentsByChannelAndPartition[channel] = make(map[int64]segments)
}
segmentsByChannelAndPartition[channel][partition] = append(segmentsByChannelAndPartition[channel][partition], segmentInfo)
}
var (
totalRows int64
totalSize int64
)
for channel, partitionSegments := range segmentsByChannelAndPartition {
for partitionID, segments := range partitionSegments {
infos := lo.Map(segments, func(segment *SegmentInfo, _ int) *segmentInfo {
rows := segment.GetNumOfRows()
size := segment.getSegmentSize()
totalRows += rows
totalSize += size
return &segmentInfo{
ID: segment.GetID(),
Rows: rows,
Size: size,
}
})
log.Info("import segments info", zap.Int64("jobID", jobID),
zap.String("channel", channel), zap.Int64("partitionID", partitionID),
zap.Int("segmentsNum", len(segments)), zap.Any("segmentsInfo", infos),
)
}
}
log.Info("import result info", zap.Int64("jobID", jobID),
zap.Int64("totalRows", totalRows), zap.Int64("totalSize", totalSize))
}
// ValidateBinlogImportRequest validates the binlog import request.
func ValidateBinlogImportRequest(ctx context.Context, cm storage.ChunkManager,
reqFiles []*msgpb.ImportFile, options []*commonpb.KeyValuePair,
) error {
files := lo.Map(reqFiles, func(file *msgpb.ImportFile, _ int) *internalpb.ImportFile {
return &internalpb.ImportFile{Id: file.GetId(), Paths: file.GetPaths()}
})
_, err := ListBinlogImportRequestFiles(ctx, cm, files, options)
return err
}
// ListBinlogImportRequestFiles lists the binlog files from the request.
// TODO: dyh, remove listing binlog after backup-restore derectly passed the segments paths.
func ListBinlogImportRequestFiles(ctx context.Context, cm storage.ChunkManager,
reqFiles []*internalpb.ImportFile, options []*commonpb.KeyValuePair,
) ([]*internalpb.ImportFile, error) {
isBackup := importutilv2.IsBackup(options)
if !isBackup {
return reqFiles, nil
}
resFiles := make([]*internalpb.ImportFile, 0)
pool := conc.NewPool[struct{}](hardware.GetCPUNum() * 2)
defer pool.Release()
futures := make([]*conc.Future[struct{}], 0, len(reqFiles))
mu := &sync.Mutex{}
for _, importFile := range reqFiles {
importFile := importFile
futures = append(futures, pool.Submit(func() (struct{}, error) {
segmentPrefixes, err := ListBinlogsAndGroupBySegment(ctx, cm, importFile)
if err != nil {
return struct{}{}, err
}
mu.Lock()
defer mu.Unlock()
resFiles = append(resFiles, segmentPrefixes...)
return struct{}{}, nil
}))
}
err := conc.AwaitAll(futures...)
if err != nil {
return nil, merr.WrapErrServiceUnavailableMsg("list binlogs failed, err=%s", err)
}
resFiles = lo.Filter(resFiles, func(file *internalpb.ImportFile, _ int) bool {
return len(file.GetPaths()) > 0
})
if len(resFiles) == 0 {
return nil, merr.WrapErrImportFailedMsg("no binlog to import, input=%s", reqFiles)
}
if len(resFiles) > paramtable.Get().DataCoordCfg.MaxFilesPerImportReq.GetAsInt() {
return nil, merr.WrapErrImportFailedMsg("The max number of import files should not exceed %d, but got %d",
paramtable.Get().DataCoordCfg.MaxFilesPerImportReq.GetAsInt(), len(resFiles))
}
log.Info("list binlogs prefixes for import done", zap.Int("num", len(resFiles)), zap.Any("binlog_prefixes", resFiles))
return resFiles, nil
}
// ValidateMaxImportJobExceed checks if the number of import jobs exceeds the limit.
func ValidateMaxImportJobExceed(ctx context.Context, importMeta ImportMeta) error {
maxNum := paramtable.Get().DataCoordCfg.MaxImportJobNum.GetAsInt()
executingNum := importMeta.CountJobBy(ctx, WithoutJobStates(internalpb.ImportJobState_Completed, internalpb.ImportJobState_Failed))
if executingNum >= maxNum {
return merr.WrapErrImportSysFailed(
fmt.Sprintf("The number of jobs has reached the limit, please try again later. " +
"If your request is set to only import a single file, " +
"please consider importing multiple files in one request for better efficiency."))
}
return nil
}
// CalculateTaskSlot calculates the required resource slots for an import task based on CPU and memory constraints
// The function uses a dual-constraint approach:
// 1. CPU constraint: Based on the number of files to process in parallel
// 2. Memory constraint: Based on the total buffer size required for all virtual channels and partitions
// Returns the maximum of the two constraints to ensure sufficient resources
func CalculateTaskSlot(task ImportTask, importMeta ImportMeta) int {
job := importMeta.GetJob(context.TODO(), task.GetJobID())
// Calculate CPU-based slots
fileNumPerSlot := paramtable.Get().DataCoordCfg.ImportFileNumPerSlot.GetAsInt()
cpuBasedSlots := len(task.GetFileStats()) / fileNumPerSlot
if cpuBasedSlots < 1 {
cpuBasedSlots = 1
}
// Calculate memory-based slots
var taskBufferSize int
baseBufferSize := paramtable.Get().DataNodeCfg.ImportBaseBufferSize.GetAsInt()
if task.GetType() == ImportTaskType {
// ImportTask use dynamic buffer size calculated by vchannels and partitions
taskBufferSize = baseBufferSize * len(job.GetVchannels()) * len(job.GetPartitionIDs())
} else {
// PreImportTask use fixed buffer size
taskBufferSize = baseBufferSize
}
isL0Import := importutilv2.IsL0Import(job.GetOptions())
if isL0Import {
// L0 import use fixed buffer size
taskBufferSize = paramtable.Get().DataNodeCfg.ImportDeleteBufferSize.GetAsInt()
}
memoryLimitPerSlot := paramtable.Get().DataCoordCfg.ImportMemoryLimitPerSlot.GetAsInt()
memoryBasedSlots := taskBufferSize / memoryLimitPerSlot
// Return the larger value to ensure both CPU and memory constraints are satisfied
if cpuBasedSlots > memoryBasedSlots {
return cpuBasedSlots
}
return memoryBasedSlots
}
func createSortCompactionTask(ctx context.Context,
t ImportTask,
originSegment *SegmentInfo,
targetSegmentID int64,
meta *meta,
handler Handler,
alloc allocator.Allocator,
) (*datapb.CompactionTask, error) {
log := log.Ctx(ctx).With(WrapTaskLog(t)...)
if originSegment.GetNumOfRows() == 0 {
operator := UpdateStatusOperator(originSegment.GetID(), commonpb.SegmentState_Dropped)
err := meta.UpdateSegmentsInfo(ctx, operator)
if err != nil {
log.Warn("import zero num row segment, but mark it dropped failed", zap.Error(err))
return nil, err
}
return nil, nil
}
collection, err := handler.GetCollection(ctx, originSegment.GetCollectionID())
if err != nil {
log.Warn("Failed to create sort compaction task because get collection fail", zap.Error(err))
return nil, err
}
collectionTTL, err := common.GetCollectionTTLFromMap(collection.Properties)
if err != nil {
log.Warn("Failed to create sort compaction task because get collection ttl failed")
return nil, err
}
startID, _, err := alloc.AllocN(2)
if err != nil {
log.Warn("Failed to create sort compaction task because allocate id fail", zap.Error(err))
return nil, err
}
expectedSize := getExpectedSegmentSize(meta, collection.ID, collection.Schema)
task := &datapb.CompactionTask{
PlanID: startID + 1,
TriggerID: startID,
State: datapb.CompactionTaskState_pipelining,
StartTime: time.Now().Unix(),
CollectionTtl: collectionTTL.Nanoseconds(),
Type: datapb.CompactionType_SortCompaction,
CollectionID: originSegment.GetCollectionID(),
PartitionID: originSegment.GetPartitionID(),
Channel: originSegment.GetInsertChannel(),
Schema: collection.Schema,
InputSegments: []int64{originSegment.GetID()},
ResultSegments: []int64{},
TotalRows: originSegment.GetNumOfRows(),
LastStateStartTime: time.Now().Unix(),
MaxSize: expectedSize,
PreAllocatedSegmentIDs: &datapb.IDRange{
Begin: targetSegmentID,
End: targetSegmentID + 1,
},
}
log.Info("create sort compaction task success", zap.Int64("segmentID", originSegment.GetID()),
zap.Int64("targetSegmentID", targetSegmentID), zap.Int64("num rows", originSegment.GetNumOfRows()))
return task, nil
}