compaction_trigger_test.go 46.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// 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.

S
sunby 已提交
17 18 19
package datacoord

import (
20
	"fmt"
S
sunby 已提交
21 22 23 24
	"sort"
	"testing"
	"time"

J
jaime 已提交
25 26 27 28
	"github.com/milvus-io/milvus/internal/common"

	"github.com/milvus-io/milvus/internal/util/tsoutil"

S
SimFG 已提交
29 30
	"github.com/milvus-io/milvus-proto/go-api/commonpb"
	"github.com/milvus-io/milvus-proto/go-api/schemapb"
S
sunby 已提交
31 32 33 34 35 36 37 38 39
	"github.com/milvus-io/milvus/internal/proto/datapb"
	"github.com/stretchr/testify/assert"
)

type spyCompactionHandler struct {
	spyChan chan *datapb.CompactionPlan
}

// execCompactionPlan start to execute plan and return immediately
40
func (h *spyCompactionHandler) execCompactionPlan(signal *compactionSignal, plan *datapb.CompactionPlan) error {
41
	fmt.Println("plan ", plan.SegmentBinlogs)
S
sunby 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
	h.spyChan <- plan
	return nil
}

// completeCompaction record the result of a compaction
func (h *spyCompactionHandler) completeCompaction(result *datapb.CompactionResult) error {
	return nil
}

// getCompaction return compaction task. If planId does not exist, return nil.
func (h *spyCompactionHandler) getCompaction(planID int64) *compactionTask {
	panic("not implemented") // TODO: Implement
}

// expireCompaction set the compaction state to expired
57
func (h *spyCompactionHandler) updateCompaction(ts Timestamp) error {
S
sunby 已提交
58 59 60 61 62 63 64 65
	panic("not implemented") // TODO: Implement
}

// isFull return true if the task pool is full
func (h *spyCompactionHandler) isFull() bool {
	return false
}

66 67
// get compaction tasks by signal id
func (h *spyCompactionHandler) getCompactionTasksBySignalID(signalID int64) []*compactionTask {
S
sunby 已提交
68 69 70 71 72 73 74 75 76
	panic("not implemented") // TODO: Implement
}

func (h *spyCompactionHandler) start() {}

func (h *spyCompactionHandler) stop() {}

var _ compactionPlanContext = (*spyCompactionHandler)(nil)

77
func Test_compactionTrigger_force(t *testing.T) {
S
sunby 已提交
78
	type fields struct {
79 80 81 82 83
		meta              *meta
		allocator         allocator
		signals           chan *compactionSignal
		compactionHandler compactionPlanContext
		globalTrigger     *time.Ticker
84
		segRefer          *SegmentReferenceManager
S
sunby 已提交
85
	}
J
jaime 已提交
86

87
	Params.Init()
J
jaime 已提交
88 89 90 91 92 93
	Params.CommonCfg.RetentionDuration = 200

	pts, _ := tsoutil.ParseTS(0)
	ttRetention := pts.Add(-time.Duration(Params.CommonCfg.RetentionDuration) * time.Second)
	timeTravel := tsoutil.ComposeTS(ttRetention.UnixNano()/int64(time.Millisecond), 0)

94
	vecFieldID := int64(201)
S
sunby 已提交
95
	tests := []struct {
J
jaime 已提交
96 97 98 99 100
		name         string
		fields       fields
		collectionID UniqueID
		wantErr      bool
		wantPlans    []*datapb.CompactionPlan
S
sunby 已提交
101 102
	}{
		{
103
			"test force compaction",
S
sunby 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
			fields{
				&meta{
					segments: &SegmentsInfo{
						map[int64]*SegmentInfo{
							1: {
								SegmentInfo: &datapb.SegmentInfo{
									ID:             1,
									CollectionID:   2,
									PartitionID:    1,
									LastExpireTime: 100,
									NumOfRows:      100,
									MaxRowNum:      300,
									InsertChannel:  "ch1",
									State:          commonpb.SegmentState_Flushed,
									Binlogs: []*datapb.FieldBinlog{
119 120 121 122 123
										{
											Binlogs: []*datapb.Binlog{
												{EntriesNum: 5, LogPath: "log1"},
											},
										},
S
sunby 已提交
124
									},
125 126 127 128 129 130
									Deltalogs: []*datapb.FieldBinlog{
										{
											Binlogs: []*datapb.Binlog{
												{EntriesNum: 5, LogPath: "deltalog1"},
											},
										},
S
sunby 已提交
131 132 133 134 135 136 137 138 139 140 141 142 143 144
									},
								},
							},
							2: {
								SegmentInfo: &datapb.SegmentInfo{
									ID:             2,
									CollectionID:   2,
									PartitionID:    1,
									LastExpireTime: 100,
									NumOfRows:      100,
									MaxRowNum:      300,
									InsertChannel:  "ch1",
									State:          commonpb.SegmentState_Flushed,
									Binlogs: []*datapb.FieldBinlog{
145 146 147 148 149
										{
											Binlogs: []*datapb.Binlog{
												{EntriesNum: 5, LogPath: "log2"},
											},
										},
S
sunby 已提交
150
									},
151 152 153 154 155 156
									Deltalogs: []*datapb.FieldBinlog{
										{
											Binlogs: []*datapb.Binlog{
												{EntriesNum: 5, LogPath: "deltalog2"},
											},
										},
S
sunby 已提交
157 158 159
									},
								},
							},
J
jaime 已提交
160 161 162 163 164 165 166 167 168 169 170 171
							3: {
								SegmentInfo: &datapb.SegmentInfo{
									ID:             3,
									CollectionID:   1111,
									PartitionID:    1,
									LastExpireTime: 100,
									NumOfRows:      100,
									MaxRowNum:      300,
									InsertChannel:  "ch1",
									State:          commonpb.SegmentState_Flushed,
								},
							},
S
sunby 已提交
172 173
						},
					},
J
jaime 已提交
174
					collections: map[int64]*collectionInfo{
175 176 177 178 179 180 181
						2: {
							ID: 2,
							Schema: &schemapb.CollectionSchema{
								Fields: []*schemapb.FieldSchema{
									{
										FieldID:  vecFieldID,
										DataType: schemapb.DataType_FloatVector,
182 183 184 185 186 187
										TypeParams: []*commonpb.KeyValuePair{
											{
												Key:   "dim",
												Value: "128",
											},
										},
188 189 190
									},
								},
							},
J
jaime 已提交
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
							Properties: map[string]string{
								common.CollectionTTLConfigKey: "0",
							},
						},
						1111: {
							ID: 1111,
							Schema: &schemapb.CollectionSchema{
								Fields: []*schemapb.FieldSchema{
									{
										FieldID:  vecFieldID,
										DataType: schemapb.DataType_FloatVector,
										TypeParams: []*commonpb.KeyValuePair{
											{
												Key:   "dim",
												Value: "128",
											},
										},
									},
								},
							},
							Properties: map[string]string{
								common.CollectionTTLConfigKey: "error",
							},
214
						},
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
						1000: {
							ID: 1000,
							Schema: &schemapb.CollectionSchema{
								Fields: []*schemapb.FieldSchema{
									{
										FieldID:  vecFieldID,
										DataType: schemapb.DataType_FloatVector,
										TypeParams: []*commonpb.KeyValuePair{
											{
												Key:   "dim",
												Value: "128",
											},
										},
									},
								},
							},
						},
						// error (has no vector field)
						2000: {
							ID: 2000,
							Schema: &schemapb.CollectionSchema{
								Fields: []*schemapb.FieldSchema{
									{
										FieldID:  vecFieldID,
										DataType: schemapb.DataType_Int16,
									},
								},
							},
						},
						// error (has no dim)
						3000: {
							ID: 3000,
							Schema: &schemapb.CollectionSchema{
								Fields: []*schemapb.FieldSchema{
									{
										FieldID:  vecFieldID,
										DataType: schemapb.DataType_FloatVector,
										TypeParams: []*commonpb.KeyValuePair{
											{},
										},
									},
								},
							},
						},
						// error (dim parse fail)
						4000: {
							ID: 4000,
							Schema: &schemapb.CollectionSchema{
								Fields: []*schemapb.FieldSchema{
									{
										FieldID:  vecFieldID,
										DataType: schemapb.DataType_FloatVector,
										TypeParams: []*commonpb.KeyValuePair{
											{
												Key:   "dim",
												Value: "128error",
											},
										},
									},
								},
							},
						},
						10000: {
							ID: 10000,
							Schema: &schemapb.CollectionSchema{
								Fields: []*schemapb.FieldSchema{
									{
										FieldID:  vecFieldID,
										DataType: schemapb.DataType_FloatVector,
284 285 286 287 288 289
										TypeParams: []*commonpb.KeyValuePair{
											{
												Key:   "dim",
												Value: "128",
											},
										},
290 291 292 293
									},
								},
							},
						},
294
					},
S
sunby 已提交
295
				},
J
jaime 已提交
296
				&MockAllocator0{},
S
sunby 已提交
297 298 299
				nil,
				&spyCompactionHandler{spyChan: make(chan *datapb.CompactionPlan, 1)},
				nil,
300
				&SegmentReferenceManager{segmentsLock: map[UniqueID]map[UniqueID]*datapb.SegmentReferenceLock{}},
S
sunby 已提交
301
			},
J
jaime 已提交
302
			2,
S
sunby 已提交
303 304 305
			false,
			[]*datapb.CompactionPlan{
				{
J
jaime 已提交
306
					PlanID: 0,
S
sunby 已提交
307 308 309 310
					SegmentBinlogs: []*datapb.CompactionSegmentBinlogs{
						{
							SegmentID: 1,
							FieldBinlogs: []*datapb.FieldBinlog{
311 312 313 314 315
								{
									Binlogs: []*datapb.Binlog{
										{EntriesNum: 5, LogPath: "log1"},
									},
								},
S
sunby 已提交
316 317
							},
							Field2StatslogPaths: nil,
318 319 320 321 322 323
							Deltalogs: []*datapb.FieldBinlog{
								{
									Binlogs: []*datapb.Binlog{
										{EntriesNum: 5, LogPath: "deltalog1"},
									},
								},
S
sunby 已提交
324 325 326 327 328
							},
						},
						{
							SegmentID: 2,
							FieldBinlogs: []*datapb.FieldBinlog{
329 330 331 332 333
								{
									Binlogs: []*datapb.Binlog{
										{EntriesNum: 5, LogPath: "log2"},
									},
								},
S
sunby 已提交
334 335
							},
							Field2StatslogPaths: nil,
336 337 338 339 340 341
							Deltalogs: []*datapb.FieldBinlog{
								{
									Binlogs: []*datapb.Binlog{
										{EntriesNum: 5, LogPath: "deltalog2"},
									},
								},
S
sunby 已提交
342 343 344
							},
						},
					},
345
					StartTime:        0,
346
					TimeoutInSeconds: Params.DataCoordCfg.CompactionTimeoutInSeconds,
347
					Type:             datapb.CompactionType_MixCompaction,
J
jaime 已提交
348
					Timetravel:       timeTravel,
S
sunby 已提交
349 350 351 352
					Channel:          "ch1",
				},
			},
		},
353 354 355
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
356
			indexCoord := newMockIndexCoord()
357

358
			tr := &compactionTrigger{
359 360 361 362 363 364 365 366 367 368 369
				meta:                         tt.fields.meta,
				handler:                      newMockHandlerWithMeta(tt.fields.meta),
				allocator:                    tt.fields.allocator,
				signals:                      tt.fields.signals,
				compactionHandler:            tt.fields.compactionHandler,
				globalTrigger:                tt.fields.globalTrigger,
				segRefer:                     tt.fields.segRefer,
				indexCoord:                   indexCoord,
				estimateDiskSegmentPolicy:    calBySchemaPolicyWithDiskIndex,
				estimateNonDiskSegmentPolicy: calBySchemaPolicy,
				testingOnly:                  true,
370
			}
J
jaime 已提交
371
			_, err := tr.forceTriggerCompaction(tt.collectionID)
372 373 374 375 376 377
			assert.Equal(t, tt.wantErr, err != nil)
			spy := (tt.fields.compactionHandler).(*spyCompactionHandler)
			plan := <-spy.spyChan
			sortPlanCompactionBinlogs(plan)
			assert.EqualValues(t, tt.wantPlans[0], plan)
		})
378 379 380 381 382 383 384 385 386 387

		t.Run(tt.name+" with DiskANN index", func(t *testing.T) {
			indexCood := newMockIndexCoord()
			segmentIDs := make([]int64, 0)
			for _, segment := range tt.fields.meta.segments.GetSegments() {
				segmentIDs = append(segmentIDs, segment.GetID())
				// Collection 1000 means it has DiskANN index
				segment.CollectionID = 1000
			}
			tr := &compactionTrigger{
388 389 390 391 392 393 394 395 396 397 398
				meta:                         tt.fields.meta,
				handler:                      newMockHandlerWithMeta(tt.fields.meta),
				allocator:                    tt.fields.allocator,
				signals:                      tt.fields.signals,
				compactionHandler:            tt.fields.compactionHandler,
				globalTrigger:                tt.fields.globalTrigger,
				segRefer:                     tt.fields.segRefer,
				indexCoord:                   indexCood,
				estimateDiskSegmentPolicy:    calBySchemaPolicyWithDiskIndex,
				estimateNonDiskSegmentPolicy: calBySchemaPolicy,
				testingOnly:                  true,
399
			}
J
jaime 已提交
400 401
			tt.collectionID = 1000
			_, err := tr.forceTriggerCompaction(tt.collectionID)
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
			assert.Equal(t, tt.wantErr, err != nil)
			// expect max row num =  2048*1024*1024/(128*4) = 4194304
			assert.EqualValues(t, 4194304, tt.fields.meta.segments.GetSegments()[0].MaxRowNum)
			spy := (tt.fields.compactionHandler).(*spyCompactionHandler)
			<-spy.spyChan
		})

		t.Run(tt.name+" with no filtered segments", func(t *testing.T) {
			indexCood := newMockIndexCoord()
			segmentIDs := make([]int64, 0)
			for _, segment := range tt.fields.meta.segments.GetSegments() {
				segmentIDs = append(segmentIDs, segment.GetID())
				// Collection 2000 means has no vector field
				segment.CollectionID = 2000
			}
			tr := &compactionTrigger{
418 419 420 421 422 423 424 425 426 427 428
				meta:                         tt.fields.meta,
				handler:                      newMockHandlerWithMeta(tt.fields.meta),
				allocator:                    tt.fields.allocator,
				signals:                      tt.fields.signals,
				compactionHandler:            tt.fields.compactionHandler,
				globalTrigger:                tt.fields.globalTrigger,
				segRefer:                     tt.fields.segRefer,
				indexCoord:                   indexCood,
				estimateDiskSegmentPolicy:    calBySchemaPolicyWithDiskIndex,
				estimateNonDiskSegmentPolicy: calBySchemaPolicy,
				testingOnly:                  true,
429
			}
J
jaime 已提交
430 431
			tt.collectionID = 2000
			_, err := tr.forceTriggerCompaction(tt.collectionID)
432 433 434 435 436 437 438 439 440
			assert.Equal(t, tt.wantErr, err != nil)
			spy := (tt.fields.compactionHandler).(*spyCompactionHandler)
			hasPlan := true
			select {
			case <-spy.spyChan:
				hasPlan = true
			case <-time.After(2 * time.Second):
				hasPlan = false
			}
441
			assert.Equal(t, true, hasPlan)
442 443 444 445 446 447 448 449 450 451 452
		})

		t.Run(tt.name+" with meta error", func(t *testing.T) {
			indexCood := newMockIndexCoord()
			segmentIDs := make([]int64, 0)
			for _, segment := range tt.fields.meta.segments.GetSegments() {
				segmentIDs = append(segmentIDs, segment.GetID())
				// Collection 3000 means field has no dim info
				segment.CollectionID = 3000
			}
			tr := &compactionTrigger{
453 454 455 456 457 458 459 460 461 462 463
				meta:                         tt.fields.meta,
				handler:                      newMockHandlerWithMeta(tt.fields.meta),
				allocator:                    tt.fields.allocator,
				signals:                      tt.fields.signals,
				compactionHandler:            tt.fields.compactionHandler,
				globalTrigger:                tt.fields.globalTrigger,
				segRefer:                     tt.fields.segRefer,
				indexCoord:                   indexCood,
				estimateDiskSegmentPolicy:    calBySchemaPolicyWithDiskIndex,
				estimateNonDiskSegmentPolicy: calBySchemaPolicy,
				testingOnly:                  true,
464
			}
J
jaime 已提交
465 466
			tt.collectionID = 3000
			_, err := tr.forceTriggerCompaction(tt.collectionID)
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
			assert.Equal(t, tt.wantErr, err != nil)
			spy := (tt.fields.compactionHandler).(*spyCompactionHandler)
			hasPlan := true
			select {
			case <-spy.spyChan:
				hasPlan = true
			case <-time.After(2 * time.Second):
				hasPlan = false
			}
			assert.Equal(t, false, hasPlan)
		})

		t.Run(tt.name+" with meta error", func(t *testing.T) {
			indexCood := newMockIndexCoord()
			segmentIDs := make([]int64, 0)
			for _, segment := range tt.fields.meta.segments.GetSegments() {
				segmentIDs = append(segmentIDs, segment.GetID())
				// Collection 4000 means field has dim mistake
				segment.CollectionID = 4000
			}
			tr := &compactionTrigger{
488 489 490 491 492 493 494 495 496 497 498
				meta:                         tt.fields.meta,
				handler:                      newMockHandlerWithMeta(tt.fields.meta),
				allocator:                    tt.fields.allocator,
				signals:                      tt.fields.signals,
				compactionHandler:            tt.fields.compactionHandler,
				globalTrigger:                tt.fields.globalTrigger,
				segRefer:                     tt.fields.segRefer,
				indexCoord:                   indexCood,
				estimateDiskSegmentPolicy:    calBySchemaPolicyWithDiskIndex,
				estimateNonDiskSegmentPolicy: calBySchemaPolicy,
				testingOnly:                  true,
499
			}
J
jaime 已提交
500 501
			tt.collectionID = 4000
			_, err := tr.forceTriggerCompaction(tt.collectionID)
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
			assert.Equal(t, tt.wantErr, err != nil)
			spy := (tt.fields.compactionHandler).(*spyCompactionHandler)
			hasPlan := true
			select {
			case <-spy.spyChan:
				hasPlan = true
			case <-time.After(2 * time.Second):
				hasPlan = false
			}
			assert.Equal(t, false, hasPlan)
		})

		t.Run(tt.name+" with index info error", func(t *testing.T) {
			indexCood := newMockIndexCoord()
			segmentIDs := make([]int64, 0)
			for _, segment := range tt.fields.meta.segments.GetSegments() {
				segmentIDs = append(segmentIDs, segment.GetID())
				// Collection 10000 means it has DescribeIndexInfo error
				segment.CollectionID = 10000
			}
			tr := &compactionTrigger{
				meta:              tt.fields.meta,
524
				handler:           newMockHandlerWithMeta(tt.fields.meta),
525 526 527 528 529 530
				allocator:         tt.fields.allocator,
				signals:           tt.fields.signals,
				compactionHandler: tt.fields.compactionHandler,
				globalTrigger:     tt.fields.globalTrigger,
				segRefer:          tt.fields.segRefer,
				indexCoord:        indexCood,
531
				testingOnly:       true,
532
			}
J
jaime 已提交
533 534
			tt.collectionID = 10000
			_, err := tr.forceTriggerCompaction(tt.collectionID)
535 536 537 538 539 540 541 542 543 544 545 546 547
			assert.Equal(t, tt.wantErr, err != nil)
			spy := (tt.fields.compactionHandler).(*spyCompactionHandler)
			hasPlan := true
			select {
			case <-spy.spyChan:
				hasPlan = true
			case <-time.After(2 * time.Second):
				hasPlan = false
			}

			assert.Equal(t, false, hasPlan)

		})
J
jaime 已提交
548 549 550
		t.Run(tt.name+" with allocate ts error", func(t *testing.T) {
			indexCood := newMockIndexCoord()
			tr := &compactionTrigger{
551 552 553 554 555 556 557 558 559 560 561
				meta:                         tt.fields.meta,
				handler:                      newMockHandlerWithMeta(tt.fields.meta),
				allocator:                    &FailsAllocator{allocIDSucceed: true},
				signals:                      tt.fields.signals,
				compactionHandler:            tt.fields.compactionHandler,
				globalTrigger:                tt.fields.globalTrigger,
				segRefer:                     tt.fields.segRefer,
				indexCoord:                   indexCood,
				estimateDiskSegmentPolicy:    calBySchemaPolicyWithDiskIndex,
				estimateNonDiskSegmentPolicy: calBySchemaPolicy,
				testingOnly:                  true,
J
jaime 已提交
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
			}

			{
				// test alloc ts fail for handle global signal
				signal := &compactionSignal{
					id:           0,
					isForce:      true,
					isGlobal:     true,
					collectionID: tt.collectionID,
				}
				tr.handleGlobalSignal(signal)

				spy := (tt.fields.compactionHandler).(*spyCompactionHandler)
				hasPlan := true
				select {
				case <-spy.spyChan:
					hasPlan = true
				case <-time.After(2 * time.Second):
					hasPlan = false
				}
				assert.Equal(t, false, hasPlan)
			}

			{
				// test alloc ts fail for handle signal
				signal := &compactionSignal{
					id:           0,
					isForce:      true,
					collectionID: tt.collectionID,
					segmentID:    3,
				}
				tr.handleSignal(signal)

				spy := (tt.fields.compactionHandler).(*spyCompactionHandler)
				hasPlan := true
				select {
				case <-spy.spyChan:
					hasPlan = true
				case <-time.After(2 * time.Second):
					hasPlan = false
				}
				assert.Equal(t, false, hasPlan)
			}
		})

		t.Run(tt.name+" with getCompact error", func(t *testing.T) {
			indexCood := newMockIndexCoord()
			for _, segment := range tt.fields.meta.segments.GetSegments() {
				segment.CollectionID = 1111
			}
			tr := &compactionTrigger{
613 614 615 616 617 618 619 620 621 622 623
				meta:                         tt.fields.meta,
				handler:                      newMockHandlerWithMeta(tt.fields.meta),
				allocator:                    tt.fields.allocator,
				signals:                      tt.fields.signals,
				compactionHandler:            tt.fields.compactionHandler,
				globalTrigger:                tt.fields.globalTrigger,
				segRefer:                     tt.fields.segRefer,
				indexCoord:                   indexCood,
				estimateDiskSegmentPolicy:    calBySchemaPolicyWithDiskIndex,
				estimateNonDiskSegmentPolicy: calBySchemaPolicy,
				testingOnly:                  true,
J
jaime 已提交
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
			}

			{
				// test getCompactTime fail for handle global signal
				signal := &compactionSignal{
					id:           0,
					isForce:      true,
					isGlobal:     true,
					collectionID: 1111,
				}
				tr.handleGlobalSignal(signal)

				spy := (tt.fields.compactionHandler).(*spyCompactionHandler)
				hasPlan := true
				select {
				case <-spy.spyChan:
					hasPlan = true
				case <-time.After(2 * time.Second):
					hasPlan = false
				}
				assert.Equal(t, false, hasPlan)
			}

			{
				// test getCompactTime fail for handle signal
				signal := &compactionSignal{
					id:           0,
					isForce:      true,
					collectionID: 1111,
					segmentID:    3,
				}
				tr.handleSignal(signal)

				spy := (tt.fields.compactionHandler).(*spyCompactionHandler)
				hasPlan := true
				select {
				case <-spy.spyChan:
					hasPlan = true
				case <-time.After(2 * time.Second):
					hasPlan = false
				}
				assert.Equal(t, false, hasPlan)
			}
		})
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
	}
}

// test force compaction with too many Segment
func Test_compactionTrigger_force_maxSegmentLimit(t *testing.T) {
	type fields struct {
		meta              *meta
		allocator         allocator
		signals           chan *compactionSignal
		compactionHandler compactionPlanContext
		globalTrigger     *time.Ticker
	}
	type args struct {
		collectionID int64
		compactTime  *compactTime
	}
	Params.Init()
685
	vecFieldID := int64(201)
686 687 688 689 690 691 692 693 694 695 696
	segmentInfos := &SegmentsInfo{
		segments: make(map[UniqueID]*SegmentInfo),
	}
	for i := UniqueID(0); i < 50; i++ {
		info := &SegmentInfo{
			SegmentInfo: &datapb.SegmentInfo{
				ID:             i,
				CollectionID:   2,
				PartitionID:    1,
				LastExpireTime: 100,
				NumOfRows:      100,
697
				MaxRowNum:      300000,
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
				InsertChannel:  "ch1",
				State:          commonpb.SegmentState_Flushed,
				Binlogs: []*datapb.FieldBinlog{
					{
						Binlogs: []*datapb.Binlog{
							{EntriesNum: 5, LogPath: "log1"},
						},
					},
				},
				Deltalogs: []*datapb.FieldBinlog{
					{
						Binlogs: []*datapb.Binlog{
							{EntriesNum: 5, LogPath: "deltalog1"},
						},
					},
				},
			},
		}
		segmentInfos.segments[i] = info
	}

	tests := []struct {
		name      string
		fields    fields
		args      args
		wantErr   bool
		wantPlans []*datapb.CompactionPlan
	}{
S
sunby 已提交
726
		{
727
			"test many segments",
S
sunby 已提交
728 729
			fields{
				&meta{
730
					segments: segmentInfos,
J
jaime 已提交
731
					collections: map[int64]*collectionInfo{
732 733 734 735 736 737 738
						2: {
							ID: 2,
							Schema: &schemapb.CollectionSchema{
								Fields: []*schemapb.FieldSchema{
									{
										FieldID:  vecFieldID,
										DataType: schemapb.DataType_FloatVector,
739 740 741 742 743 744
										TypeParams: []*commonpb.KeyValuePair{
											{
												Key:   "dim",
												Value: "128",
											},
										},
745 746 747 748 749
									},
								},
							},
						},
					},
S
sunby 已提交
750 751 752
				},
				newMockAllocator(),
				nil,
753
				&spyCompactionHandler{spyChan: make(chan *datapb.CompactionPlan, 2)},
S
sunby 已提交
754 755 756 757
				nil,
			},
			args{
				2,
758
				&compactTime{travelTime: 200, expireTime: 0},
S
sunby 已提交
759 760 761 762 763 764 765 766 767
			},
			false,
			[]*datapb.CompactionPlan{
				{
					PlanID: 2,
					SegmentBinlogs: []*datapb.CompactionSegmentBinlogs{
						{
							SegmentID: 1,
							FieldBinlogs: []*datapb.FieldBinlog{
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
								{
									Binlogs: []*datapb.Binlog{
										{EntriesNum: 5, LogPath: "log1"},
									},
								},
							},
							Field2StatslogPaths: nil,
							Deltalogs: []*datapb.FieldBinlog{
								{
									Binlogs: []*datapb.Binlog{
										{EntriesNum: 5, LogPath: "deltalog1"},
									},
								},
							},
						},
						{
							SegmentID: 2,
							FieldBinlogs: []*datapb.FieldBinlog{
								{
									Binlogs: []*datapb.Binlog{
										{EntriesNum: 5, LogPath: "log2"},
									},
								},
S
sunby 已提交
791 792
							},
							Field2StatslogPaths: nil,
793 794 795
							Deltalogs: []*datapb.FieldBinlog{
								{
									Binlogs: []*datapb.Binlog{
796
										{EntriesNum: 5, LogPath: "deltalog2"},
797 798
									},
								},
S
sunby 已提交
799 800 801
							},
						},
					},
802
					StartTime:        3,
803
					TimeoutInSeconds: Params.DataCoordCfg.CompactionTimeoutInSeconds,
804
					Type:             datapb.CompactionType_MixCompaction,
S
sunby 已提交
805 806 807 808 809 810 811 812
					Timetravel:       200,
					Channel:          "ch1",
				},
			},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
813
			indexCoord := newMockIndexCoord()
814

S
sunby 已提交
815
			tr := &compactionTrigger{
816 817 818 819 820 821 822 823 824 825 826
				meta:                         tt.fields.meta,
				handler:                      newMockHandlerWithMeta(tt.fields.meta),
				allocator:                    tt.fields.allocator,
				signals:                      tt.fields.signals,
				compactionHandler:            tt.fields.compactionHandler,
				globalTrigger:                tt.fields.globalTrigger,
				segRefer:                     &SegmentReferenceManager{segmentsLock: map[UniqueID]map[UniqueID]*datapb.SegmentReferenceLock{}},
				indexCoord:                   indexCoord,
				estimateDiskSegmentPolicy:    calBySchemaPolicyWithDiskIndex,
				estimateNonDiskSegmentPolicy: calBySchemaPolicy,
				testingOnly:                  true,
S
sunby 已提交
827
			}
J
jaime 已提交
828
			_, err := tr.forceTriggerCompaction(tt.args.collectionID)
S
sunby 已提交
829 830
			assert.Equal(t, tt.wantErr, err != nil)
			spy := (tt.fields.compactionHandler).(*spyCompactionHandler)
831 832

			// should be split into two plans
S
sunby 已提交
833
			plan := <-spy.spyChan
834 835 836 837
			assert.Equal(t, len(plan.SegmentBinlogs), 30)

			plan = <-spy.spyChan
			assert.Equal(t, len(plan.SegmentBinlogs), 20)
S
sunby 已提交
838 839 840 841 842 843 844 845 846 847
		})
	}
}

func sortPlanCompactionBinlogs(plan *datapb.CompactionPlan) {
	sort.Slice(plan.SegmentBinlogs, func(i, j int) bool {
		return plan.SegmentBinlogs[i].SegmentID < plan.SegmentBinlogs[j].SegmentID
	})
}

848 849
// Test no compaction selection
func Test_compactionTrigger_noplan(t *testing.T) {
S
sunby 已提交
850
	type fields struct {
851 852 853 854 855
		meta              *meta
		allocator         allocator
		signals           chan *compactionSignal
		compactionHandler compactionPlanContext
		globalTrigger     *time.Ticker
S
sunby 已提交
856 857
	}
	type args struct {
858 859
		collectionID int64
		compactTime  *compactTime
S
sunby 已提交
860
	}
861
	Params.Init()
862
	Params.DataCoordCfg.MinSegmentToMerge = 4
863
	vecFieldID := int64(201)
S
sunby 已提交
864 865 866 867 868 869 870 871
	tests := []struct {
		name      string
		fields    fields
		args      args
		wantErr   bool
		wantPlans []*datapb.CompactionPlan
	}{
		{
872
			"test no plan",
S
sunby 已提交
873 874
			fields{
				&meta{
875
					// 4 segment
S
sunby 已提交
876 877 878 879 880
					segments: &SegmentsInfo{
						map[int64]*SegmentInfo{
							1: {
								SegmentInfo: &datapb.SegmentInfo{
									ID:             1,
881
									CollectionID:   2,
S
sunby 已提交
882 883
									PartitionID:    1,
									LastExpireTime: 100,
884
									NumOfRows:      1,
885
									MaxRowNum:      300,
S
sunby 已提交
886 887 888
									InsertChannel:  "ch1",
									State:          commonpb.SegmentState_Flushed,
									Binlogs: []*datapb.FieldBinlog{
889 890 891 892 893
										{
											Binlogs: []*datapb.Binlog{
												{EntriesNum: 5, LogPath: "log1", LogSize: 100},
											},
										},
S
sunby 已提交
894 895
									},
								},
896
								lastFlushTime: time.Now(),
S
sunby 已提交
897 898 899 900 901 902 903
							},
							2: {
								SegmentInfo: &datapb.SegmentInfo{
									ID:             2,
									CollectionID:   2,
									PartitionID:    1,
									LastExpireTime: 100,
904
									NumOfRows:      200,
905 906
									MaxRowNum:      300,
									InsertChannel:  "ch1",
S
sunby 已提交
907 908
									State:          commonpb.SegmentState_Flushed,
									Binlogs: []*datapb.FieldBinlog{
909 910 911 912 913
										{
											Binlogs: []*datapb.Binlog{
												{EntriesNum: 5, LogPath: "log2", LogSize: int64(Params.DataCoordCfg.SegmentMaxSize)*1024*1024 - 1},
											},
										},
S
sunby 已提交
914
									},
915 916 917 918 919 920
									Deltalogs: []*datapb.FieldBinlog{
										{
											Binlogs: []*datapb.Binlog{
												{EntriesNum: 5, LogPath: "deltalog2"},
											},
										},
S
sunby 已提交
921 922
									},
								},
923
								lastFlushTime: time.Now(),
S
sunby 已提交
924 925 926 927 928 929 930
							},
							3: {
								SegmentInfo: &datapb.SegmentInfo{
									ID:             3,
									CollectionID:   2,
									PartitionID:    1,
									LastExpireTime: 100,
931
									NumOfRows:      2,
932 933 934 935 936 937 938 939 940 941 942
									MaxRowNum:      300,
									InsertChannel:  "ch1",
									State:          commonpb.SegmentState_Flushed,
									Binlogs: []*datapb.FieldBinlog{
										{
											Binlogs: []*datapb.Binlog{
												{EntriesNum: 5, LogPath: "log1", LogSize: 100},
											},
										},
									},
								},
943
								lastFlushTime: time.Now(),
944 945 946 947 948 949 950
							},
							4: {
								SegmentInfo: &datapb.SegmentInfo{
									ID:             4,
									CollectionID:   2,
									PartitionID:    1,
									LastExpireTime: 100,
951
									NumOfRows:      3,
952 953
									MaxRowNum:      300,
									InsertChannel:  "ch1",
S
sunby 已提交
954 955
									State:          commonpb.SegmentState_Flushed,
									Binlogs: []*datapb.FieldBinlog{
956 957 958 959 960
										{
											Binlogs: []*datapb.Binlog{
												{EntriesNum: 5, LogPath: "log1", LogSize: 100},
											},
										},
S
sunby 已提交
961 962
									},
								},
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
								lastFlushTime: time.Now(),
							},
							5: {
								SegmentInfo: &datapb.SegmentInfo{
									ID:             4,
									CollectionID:   2,
									PartitionID:    1,
									LastExpireTime: 100,
									NumOfRows:      3,
									MaxRowNum:      300,
									InsertChannel:  "ch1",
									State:          commonpb.SegmentState_Flushed,
									Binlogs: []*datapb.FieldBinlog{
										{
											Binlogs: []*datapb.Binlog{
												{EntriesNum: 5, LogPath: "log1", LogSize: 100},
											},
										},
									},
								},
								lastFlushTime: time.Unix(0, 0),
S
sunby 已提交
984 985 986
							},
						},
					},
J
jaime 已提交
987
					collections: map[int64]*collectionInfo{
988 989 990 991 992 993 994 995 996 997 998 999
						2: {
							ID: 2,
							Schema: &schemapb.CollectionSchema{
								Fields: []*schemapb.FieldSchema{
									{
										FieldID:  vecFieldID,
										DataType: schemapb.DataType_FloatVector,
									},
								},
							},
						},
					},
S
sunby 已提交
1000 1001 1002
				},
				newMockAllocator(),
				make(chan *compactionSignal, 1),
1003 1004
				&spyCompactionHandler{spyChan: make(chan *datapb.CompactionPlan, 1)},
				nil,
S
sunby 已提交
1005 1006
			},
			args{
1007 1008
				2,
				&compactTime{travelTime: 200, expireTime: 0},
S
sunby 已提交
1009 1010
			},
			false,
1011
			nil,
S
sunby 已提交
1012
		},
1013 1014 1015
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
1016 1017
			indexCoord := newMockIndexCoord()

1018
			tr := &compactionTrigger{
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
				meta:                         tt.fields.meta,
				handler:                      newMockHandlerWithMeta(tt.fields.meta),
				allocator:                    tt.fields.allocator,
				signals:                      tt.fields.signals,
				compactionHandler:            tt.fields.compactionHandler,
				globalTrigger:                tt.fields.globalTrigger,
				segRefer:                     &SegmentReferenceManager{segmentsLock: map[UniqueID]map[UniqueID]*datapb.SegmentReferenceLock{}},
				indexCoord:                   indexCoord,
				estimateDiskSegmentPolicy:    calBySchemaPolicyWithDiskIndex,
				estimateNonDiskSegmentPolicy: calBySchemaPolicy,
				testingOnly:                  true,
1030 1031 1032
			}
			tr.start()
			defer tr.stop()
J
jaime 已提交
1033
			err := tr.triggerCompaction()
1034 1035
			assert.Equal(t, tt.wantErr, err != nil)
			spy := (tt.fields.compactionHandler).(*spyCompactionHandler)
1036 1037
			plan := <-spy.spyChan
			assert.Equal(t, len(plan.SegmentBinlogs), 4)
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
		})
	}
}

// Test compaction with small files
func Test_compactionTrigger_smallfiles(t *testing.T) {
	type fields struct {
		meta              *meta
		allocator         allocator
		signals           chan *compactionSignal
		compactionHandler compactionPlanContext
		globalTrigger     *time.Ticker
	}
	type args struct {
		collectionID int64
		compactTime  *compactTime
	}
	Params.Init()
1056
	vecFieldID := int64(201)
1057 1058 1059 1060 1061 1062 1063
	tests := []struct {
		name      string
		fields    fields
		args      args
		wantErr   bool
		wantPlans []*datapb.CompactionPlan
	}{
1064
		{
1065
			"test small segment",
1066 1067
			fields{
				&meta{
1068
					// 4 small segments
1069 1070 1071 1072 1073
					segments: &SegmentsInfo{
						map[int64]*SegmentInfo{
							1: {
								SegmentInfo: &datapb.SegmentInfo{
									ID:             1,
1074
									CollectionID:   2,
1075 1076
									PartitionID:    1,
									LastExpireTime: 100,
1077
									NumOfRows:      50,
1078
									MaxRowNum:      300,
1079 1080 1081
									InsertChannel:  "ch1",
									State:          commonpb.SegmentState_Flushed,
									Binlogs: []*datapb.FieldBinlog{
1082 1083 1084 1085 1086
										{
											Binlogs: []*datapb.Binlog{
												{EntriesNum: 5, LogPath: "log1", LogSize: 100},
											},
										},
1087
									},
1088 1089 1090 1091 1092 1093
									Deltalogs: []*datapb.FieldBinlog{
										{
											Binlogs: []*datapb.Binlog{
												{EntriesNum: 5, LogPath: "deltalog1"},
											},
										},
1094 1095
									},
								},
1096
								lastFlushTime: time.Now().Add(-100 * time.Minute),
1097 1098 1099 1100 1101 1102 1103
							},
							2: {
								SegmentInfo: &datapb.SegmentInfo{
									ID:             2,
									CollectionID:   2,
									PartitionID:    1,
									LastExpireTime: 100,
1104
									NumOfRows:      50,
1105 1106 1107 1108 1109 1110 1111 1112 1113
									MaxRowNum:      300,
									InsertChannel:  "ch1",
									State:          commonpb.SegmentState_Flushed,
									Binlogs: []*datapb.FieldBinlog{
										{
											Binlogs: []*datapb.Binlog{
												{EntriesNum: 5, LogPath: "log2", LogSize: 800},
											},
										},
1114
									},
1115 1116 1117 1118 1119 1120
									Deltalogs: []*datapb.FieldBinlog{
										{
											Binlogs: []*datapb.Binlog{
												{EntriesNum: 5, LogPath: "deltalog2"},
											},
										},
1121 1122
									},
								},
1123
								lastFlushTime: time.Now(),
1124 1125 1126 1127 1128 1129 1130
							},
							3: {
								SegmentInfo: &datapb.SegmentInfo{
									ID:             3,
									CollectionID:   2,
									PartitionID:    1,
									LastExpireTime: 100,
1131
									NumOfRows:      50,
1132 1133
									MaxRowNum:      300,
									InsertChannel:  "ch1",
1134 1135
									State:          commonpb.SegmentState_Flushed,
									Binlogs: []*datapb.FieldBinlog{
1136 1137 1138 1139 1140
										{
											Binlogs: []*datapb.Binlog{
												{EntriesNum: 5, LogPath: "log1", LogSize: 100},
											},
										},
1141
									},
1142 1143 1144 1145 1146 1147
									Deltalogs: []*datapb.FieldBinlog{
										{
											Binlogs: []*datapb.Binlog{
												{EntriesNum: 5, LogPath: "deltalog1"},
											},
										},
1148 1149
									},
								},
1150
								lastFlushTime: time.Now(),
1151
							},
1152
							4: {
1153
								SegmentInfo: &datapb.SegmentInfo{
1154
									ID:             4,
1155 1156 1157
									CollectionID:   2,
									PartitionID:    1,
									LastExpireTime: 100,
1158
									NumOfRows:      50,
1159 1160 1161
									MaxRowNum:      300,
									InsertChannel:  "ch1",
									State:          commonpb.SegmentState_Flushed,
1162
									Binlogs: []*datapb.FieldBinlog{
1163 1164
										{
											Binlogs: []*datapb.Binlog{
1165
												{EntriesNum: 5, LogPath: "log1", LogSize: 100},
1166 1167
											},
										},
1168
									},
1169 1170 1171
									Deltalogs: []*datapb.FieldBinlog{
										{
											Binlogs: []*datapb.Binlog{
1172
												{EntriesNum: 5, LogPath: "deltalog1"},
1173 1174
											},
										},
1175 1176
									},
								},
1177
								lastFlushTime: time.Now(),
1178 1179 1180
							},
						},
					},
J
jaime 已提交
1181
					collections: map[int64]*collectionInfo{
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
						2: {
							ID: 2,
							Schema: &schemapb.CollectionSchema{
								Fields: []*schemapb.FieldSchema{
									{
										FieldID:  vecFieldID,
										DataType: schemapb.DataType_FloatVector,
									},
								},
							},
						},
					},
1194 1195 1196
				},
				newMockAllocator(),
				make(chan *compactionSignal, 1),
1197 1198
				&spyCompactionHandler{spyChan: make(chan *datapb.CompactionPlan, 1)},
				nil,
1199 1200
			},
			args{
1201 1202
				2,
				&compactTime{travelTime: 200, expireTime: 0},
1203 1204
			},
			false,
1205
			nil,
1206
		},
S
sunby 已提交
1207 1208 1209
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
1210 1211
			indexCoord := newMockIndexCoord()

S
sunby 已提交
1212
			tr := &compactionTrigger{
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
				meta:                         tt.fields.meta,
				handler:                      newMockHandlerWithMeta(tt.fields.meta),
				allocator:                    tt.fields.allocator,
				signals:                      tt.fields.signals,
				compactionHandler:            tt.fields.compactionHandler,
				globalTrigger:                tt.fields.globalTrigger,
				segRefer:                     &SegmentReferenceManager{segmentsLock: map[UniqueID]map[UniqueID]*datapb.SegmentReferenceLock{}},
				indexCoord:                   indexCoord,
				estimateDiskSegmentPolicy:    calBySchemaPolicyWithDiskIndex,
				estimateNonDiskSegmentPolicy: calBySchemaPolicy,
				testingOnly:                  true,
S
sunby 已提交
1224 1225 1226
			}
			tr.start()
			defer tr.stop()
J
jaime 已提交
1227
			err := tr.triggerCompaction()
S
sunby 已提交
1228
			assert.Equal(t, tt.wantErr, err != nil)
1229 1230 1231 1232 1233 1234 1235 1236 1237
			spy := (tt.fields.compactionHandler).(*spyCompactionHandler)
			select {
			case val := <-spy.spyChan:
				// 4 segments in the final pick list
				assert.Equal(t, len(val.SegmentBinlogs), 4)
				return
			case <-time.After(3 * time.Second):
				assert.Fail(t, "failed to get plan")
				return
1238
			}
S
sunby 已提交
1239 1240 1241 1242
		})
	}
}

1243 1244
// Test segment compaction target size
func Test_compactionTrigger_noplan_random_size(t *testing.T) {
S
sunby 已提交
1245
	type fields struct {
1246 1247 1248 1249 1250
		meta              *meta
		allocator         allocator
		signals           chan *compactionSignal
		compactionHandler compactionPlanContext
		globalTrigger     *time.Ticker
S
sunby 已提交
1251 1252 1253
	}
	type args struct {
		collectionID int64
1254
		compactTime  *compactTime
S
sunby 已提交
1255
	}
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
	Params.Init()

	segmentInfos := &SegmentsInfo{
		segments: make(map[UniqueID]*SegmentInfo),
	}

	size := []int64{
		510, 500, 480, 300, 250, 200, 128, 128, 128, 127,
		40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
		20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
		10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
		10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
	}

1270
	vecFieldID := int64(201)
1271 1272 1273 1274 1275 1276 1277
	for i := UniqueID(0); i < 50; i++ {
		info := &SegmentInfo{
			SegmentInfo: &datapb.SegmentInfo{
				ID:             i,
				CollectionID:   2,
				PartitionID:    1,
				LastExpireTime: 100,
1278 1279
				NumOfRows:      size[i],
				MaxRowNum:      512,
1280 1281 1282 1283 1284 1285
				InsertChannel:  "ch1",
				State:          commonpb.SegmentState_Flushed,
				Binlogs: []*datapb.FieldBinlog{
					{
						Binlogs: []*datapb.Binlog{
							{EntriesNum: 5, LogPath: "log1", LogSize: size[i] * 1024 * 1024},
S
sunby 已提交
1286 1287 1288 1289
						},
					},
				},
			},
1290
			lastFlushTime: time.Now(),
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
		}
		segmentInfos.segments[i] = info
	}

	tests := []struct {
		name      string
		fields    fields
		args      args
		wantErr   bool
		wantPlans []*datapb.CompactionPlan
	}{
1302
		{
1303 1304 1305 1306
			"test rand size segment",
			fields{
				&meta{
					segments: segmentInfos,
J
jaime 已提交
1307
					collections: map[int64]*collectionInfo{
1308 1309 1310 1311 1312 1313 1314
						2: {
							ID: 2,
							Schema: &schemapb.CollectionSchema{
								Fields: []*schemapb.FieldSchema{
									{
										FieldID:  vecFieldID,
										DataType: schemapb.DataType_FloatVector,
1315 1316 1317 1318 1319 1320
										TypeParams: []*commonpb.KeyValuePair{
											{
												Key:   "dim",
												Value: "128",
											},
										},
1321 1322 1323 1324 1325
									},
								},
							},
						},
					},
1326
				},
1327 1328 1329 1330
				newMockAllocator(),
				make(chan *compactionSignal, 1),
				&spyCompactionHandler{spyChan: make(chan *datapb.CompactionPlan, 10)},
				nil,
1331
			},
1332 1333 1334
			args{
				2,
				&compactTime{travelTime: 200, expireTime: 0},
1335
			},
1336 1337
			false,
			nil,
1338
		},
S
sunby 已提交
1339 1340 1341
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
1342 1343
			indexCoord := newMockIndexCoord()

S
sunby 已提交
1344
			tr := &compactionTrigger{
1345
				meta:              tt.fields.meta,
1346
				handler:           newMockHandlerWithMeta(tt.fields.meta),
1347 1348 1349 1350
				allocator:         tt.fields.allocator,
				signals:           tt.fields.signals,
				compactionHandler: tt.fields.compactionHandler,
				globalTrigger:     tt.fields.globalTrigger,
1351
				segRefer:          &SegmentReferenceManager{segmentsLock: map[UniqueID]map[UniqueID]*datapb.SegmentReferenceLock{}},
1352
				indexCoord:        indexCoord,
1353
				testingOnly:       true,
S
sunby 已提交
1354 1355 1356
			}
			tr.start()
			defer tr.stop()
J
jaime 已提交
1357
			err := tr.triggerCompaction()
S
sunby 已提交
1358 1359
			assert.Equal(t, tt.wantErr, err != nil)
			spy := (tt.fields.compactionHandler).(*spyCompactionHandler)
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369

			// should be split into two plans
			var plans []*datapb.CompactionPlan
		WAIT:
			for {
				select {
				case val := <-spy.spyChan:
					plans = append(plans, val)
				case <-time.After(1 * time.Second):
					break WAIT
S
sunby 已提交
1370
				}
1371 1372 1373 1374 1375 1376 1377
			}

			for _, plan := range plans {

				size := int64(0)
				for _, log := range plan.SegmentBinlogs {
					size += log.FieldBinlogs[0].GetBinlogs()[0].LogSize
S
sunby 已提交
1378
				}
1379
				fmt.Println("target ", len(plan.SegmentBinlogs))
S
sunby 已提交
1380
			}
1381 1382 1383 1384 1385 1386 1387
			assert.Equal(t, len(plans), 3)
			// plan 1: 250 + 20 * 10 + 3 * 20
			// plan 2: 200 + 7 * 20 + 4 * 40
			// plan 3  128 + 6 * 40 + 127
			assert.Equal(t, len(plans[0].SegmentBinlogs), 24)
			assert.Equal(t, len(plans[1].SegmentBinlogs), 12)
			assert.Equal(t, len(plans[2].SegmentBinlogs), 8)
S
sunby 已提交
1388 1389 1390 1391
		})
	}
}

1392 1393 1394 1395
// Test shouldDoSingleCompaction
func Test_compactionTrigger_shouldDoSingleCompaction(t *testing.T) {
	Params.Init()

1396
	indexCoord := newMockIndexCoord()
1397
	trigger := newCompactionTrigger(&meta{}, &compactionPlanHandler{}, newMockAllocator(),
1398
		&SegmentReferenceManager{segmentsLock: map[UniqueID]map[UniqueID]*datapb.SegmentReferenceLock{}}, indexCoord, newMockHandler())
1399

1400
	// Test too many deltalogs.
1401
	var binlogs []*datapb.FieldBinlog
1402
	for i := UniqueID(0); i < 1000; i++ {
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
		binlogs = append(binlogs, &datapb.FieldBinlog{
			Binlogs: []*datapb.Binlog{
				{EntriesNum: 5, LogPath: "log1", LogSize: 100},
			},
		})
	}
	info := &SegmentInfo{
		SegmentInfo: &datapb.SegmentInfo{
			ID:             1,
			CollectionID:   2,
			PartitionID:    1,
			LastExpireTime: 100,
			NumOfRows:      100,
			MaxRowNum:      300,
			InsertChannel:  "ch1",
			State:          commonpb.SegmentState_Flushed,
1419
			Deltalogs:      binlogs,
1420 1421 1422
		},
	}

1423
	couldDo := trigger.ShouldDoSingleCompaction(info, false, &compactTime{travelTime: 200, expireTime: 0})
1424 1425
	assert.True(t, couldDo)

1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
	//Test too many stats log
	info = &SegmentInfo{
		SegmentInfo: &datapb.SegmentInfo{
			ID:             1,
			CollectionID:   2,
			PartitionID:    1,
			LastExpireTime: 100,
			NumOfRows:      100,
			MaxRowNum:      300,
			InsertChannel:  "ch1",
			State:          commonpb.SegmentState_Flushed,
			Statslogs:      binlogs,
		},
	}

	couldDo = trigger.ShouldDoSingleCompaction(info, false, &compactTime{travelTime: 200, expireTime: 0})
	assert.True(t, couldDo)

	couldDo = trigger.ShouldDoSingleCompaction(info, true, &compactTime{travelTime: 200, expireTime: 0})
	assert.True(t, couldDo)

	// if only 10 bin logs, then disk index won't trigger compaction
	info.Statslogs = binlogs[0:20]
	couldDo = trigger.ShouldDoSingleCompaction(info, false, &compactTime{travelTime: 200, expireTime: 0})
	assert.True(t, couldDo)

	couldDo = trigger.ShouldDoSingleCompaction(info, true, &compactTime{travelTime: 200, expireTime: 0})
	assert.False(t, couldDo)
	//Test too many stats log but compacted
	info.CompactionFrom = []int64{0, 1}
	couldDo = trigger.ShouldDoSingleCompaction(info, false, &compactTime{travelTime: 200, expireTime: 0})
	assert.False(t, couldDo)

	//Test expire triggered compaction
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
	var binlogs2 []*datapb.FieldBinlog
	for i := UniqueID(0); i < 100; i++ {
		binlogs2 = append(binlogs2, &datapb.FieldBinlog{
			Binlogs: []*datapb.Binlog{
				{EntriesNum: 5, LogPath: "log1", LogSize: 100000, TimestampFrom: 300, TimestampTo: 500},
			},
		})
	}

	for i := UniqueID(0); i < 100; i++ {
		binlogs2 = append(binlogs2, &datapb.FieldBinlog{
			Binlogs: []*datapb.Binlog{
				{EntriesNum: 5, LogPath: "log1", LogSize: 1000000, TimestampFrom: 300, TimestampTo: 1000},
			},
		})
	}
	info2 := &SegmentInfo{
		SegmentInfo: &datapb.SegmentInfo{
			ID:             1,
			CollectionID:   2,
			PartitionID:    1,
			LastExpireTime: 600,
1482
			NumOfRows:      10000,
1483 1484 1485 1486 1487 1488 1489 1490
			MaxRowNum:      300,
			InsertChannel:  "ch1",
			State:          commonpb.SegmentState_Flushed,
			Binlogs:        binlogs2,
		},
	}

	// expire time < Timestamp To
1491
	couldDo = trigger.ShouldDoSingleCompaction(info2, false, &compactTime{travelTime: 200, expireTime: 300})
1492 1493 1494
	assert.False(t, couldDo)

	// didn't reach single compaction size 10 * 1024 * 1024
1495
	couldDo = trigger.ShouldDoSingleCompaction(info2, false, &compactTime{travelTime: 200, expireTime: 600})
1496 1497 1498
	assert.False(t, couldDo)

	// expire time < Timestamp False
1499
	couldDo = trigger.ShouldDoSingleCompaction(info2, false, &compactTime{travelTime: 200, expireTime: 1200})
1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
	assert.True(t, couldDo)

	// Test Delete triggered compaction
	var binlogs3 []*datapb.FieldBinlog
	for i := UniqueID(0); i < 100; i++ {
		binlogs3 = append(binlogs2, &datapb.FieldBinlog{
			Binlogs: []*datapb.Binlog{
				{EntriesNum: 5, LogPath: "log1", LogSize: 100000, TimestampFrom: 300, TimestampTo: 500},
			},
		})
	}

	info3 := &SegmentInfo{
		SegmentInfo: &datapb.SegmentInfo{
			ID:             1,
			CollectionID:   2,
			PartitionID:    1,
			LastExpireTime: 700,
			NumOfRows:      100,
			MaxRowNum:      300,
			InsertChannel:  "ch1",
			State:          commonpb.SegmentState_Flushed,
			Binlogs:        binlogs3,
			Deltalogs: []*datapb.FieldBinlog{
				{
					Binlogs: []*datapb.Binlog{
						{EntriesNum: 200, LogPath: "deltalog1"},
					},
				},
			},
		},
	}

	// expire time < Timestamp To
1534
	couldDo = trigger.ShouldDoSingleCompaction(info3, false, &compactTime{travelTime: 600, expireTime: 0})
1535 1536 1537
	assert.False(t, couldDo)

	// deltalog is large enough, should do compaction
1538
	couldDo = trigger.ShouldDoSingleCompaction(info3, false, &compactTime{travelTime: 800, expireTime: 0})
1539 1540 1541
	assert.True(t, couldDo)
}

S
sunby 已提交
1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
func Test_newCompactionTrigger(t *testing.T) {
	type args struct {
		meta              *meta
		compactionHandler compactionPlanContext
		allocator         allocator
	}
	tests := []struct {
		name string
		args args
	}{
		{
			"test new trigger",
			args{
				&meta{},
				&compactionPlanHandler{},
				newMockAllocator(),
			},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
1563
			indexCoord := newMockIndexCoord()
1564
			got := newCompactionTrigger(tt.args.meta, tt.args.compactionHandler, tt.args.allocator,
1565
				&SegmentReferenceManager{segmentsLock: map[UniqueID]map[UniqueID]*datapb.SegmentReferenceLock{}}, indexCoord, newMockHandler())
S
sunby 已提交
1566 1567 1568 1569 1570 1571
			assert.Equal(t, tt.args.meta, got.meta)
			assert.Equal(t, tt.args.compactionHandler, got.compactionHandler)
			assert.Equal(t, tt.args.allocator, got.allocator)
		})
	}
}
1572 1573 1574

func Test_handleSignal(t *testing.T) {

1575
	indexCoord := newMockIndexCoord()
1576
	got := newCompactionTrigger(&meta{segments: NewSegmentsInfo()}, &compactionPlanHandler{}, newMockAllocator(),
1577
		&SegmentReferenceManager{segmentsLock: map[UniqueID]map[UniqueID]*datapb.SegmentReferenceLock{}}, indexCoord, newMockHandler())
1578 1579 1580 1581 1582 1583 1584
	signal := &compactionSignal{
		segmentID: 1,
	}
	assert.NotPanics(t, func() {
		got.handleSignal(signal)
	})
}
J
jaime 已提交
1585 1586 1587

func Test_allocTs(t *testing.T) {
	got := newCompactionTrigger(&meta{segments: NewSegmentsInfo()}, &compactionPlanHandler{}, newMockAllocator(),
1588
		&SegmentReferenceManager{segmentsLock: map[UniqueID]map[UniqueID]*datapb.SegmentReferenceLock{}}, nil, newMockHandler())
J
jaime 已提交
1589 1590 1591 1592 1593
	ts, err := got.allocTs()
	assert.NoError(t, err)
	assert.True(t, ts > 0)

	got = newCompactionTrigger(&meta{segments: NewSegmentsInfo()}, &compactionPlanHandler{}, &FailsAllocator{},
1594
		&SegmentReferenceManager{segmentsLock: map[UniqueID]map[UniqueID]*datapb.SegmentReferenceLock{}}, nil, newMockHandler())
J
jaime 已提交
1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621
	ts, err = got.allocTs()
	assert.Error(t, err)
	assert.Equal(t, uint64(0), ts)
}

func Test_getCompactTime(t *testing.T) {
	collections := map[UniqueID]*collectionInfo{
		1: {
			ID:         1,
			Schema:     newTestSchema(),
			Partitions: []UniqueID{1},
			Properties: map[string]string{
				common.CollectionTTLConfigKey: "10",
			},
		},
		2: {
			ID:         2,
			Schema:     newTestSchema(),
			Partitions: []UniqueID{1},
			Properties: map[string]string{
				common.CollectionTTLConfigKey: "error",
			},
		},
	}

	m := &meta{segments: NewSegmentsInfo(), collections: collections}
	got := newCompactionTrigger(m, &compactionPlanHandler{}, newMockAllocator(),
1622 1623 1624 1625 1626
		&SegmentReferenceManager{segmentsLock: map[UniqueID]map[UniqueID]*datapb.SegmentReferenceLock{}}, nil, &ServerHandler{
			&Server{
				meta: m,
			},
		})
J
jaime 已提交
1627 1628 1629 1630 1631 1632

	now := tsoutil.GetCurrentTime()
	ct, err := got.getCompactTime(now, 1)
	assert.NoError(t, err)
	assert.NotNil(t, ct)
}