From 5093185c0f87b318680730f282aeac8b59dd437f Mon Sep 17 00:00:00 2001 From: Alex Le Date: Thu, 26 Nov 2026 21:13:34 +0000 Subject: [PATCH 1/5] Compactor: let an in-flight compaction finish on shutdown Add -compactor.compaction-drain-timeout. When set, shutdown no longer cancels a compaction that is already running. Compactions run under a context detached from the service context, cancelled once the drain timeout has passed after shutdown is requested. The compactor stops picking up further tenants as soon as shutdown is requested. Thanos's BucketCompactor keeps taking groups off its queue and repeats whole compaction passes until no work is left, and only sees cancellation through the calls it makes. A detached context alone would therefore keep compacting the tenant's backlog until the timeout cut it mid-merge. Two gates stop that. The planner returns an empty plan for every group not yet planned when shutdown is requested, which thanos treats as a group with nothing to do. The grouper returns no groups on later passes. Under the partitioning strategy, building a group writes a visit marker claiming its partition, so without the grouper gate a draining compactor would claim partitions it never compacts and other compactors would skip them until the marker timed out. Defaults to 0, which keeps the current behaviour of cancelling the running compaction immediately. Signed-off-by: Alex Le --- CHANGELOG.md | 1 + docs/blocks-storage/compactor.md | 11 + docs/configuration/config-file-reference.md | 10 + pkg/compactor/compactor.go | 90 ++++++- pkg/compactor/compactor_paritioning_test.go | 6 +- pkg/compactor/compactor_test.go | 281 +++++++++++++++++++- schemas/cortex-config-schema.json | 7 + 7 files changed, 388 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f32e39e4efe..ac7748a89dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ * [FEATURE] Distributor: Add experimental OTLP metrics ingestion over gRPC (`opentelemetry.proto.collector.metrics.v1.MetricsService/Export`) on the gRPC server port. Enable it with `-distributor.otlp.grpc-enabled`. The tenant is read from the `X-Scope-OrgID` gRPC metadata, and the request size is limited by `-server.grpc-max-recv-msg-size-bytes`. #7873 * [FEATURE] Storage: Add support for Alibaba Cloud OSS as a backend for blocks, ruler, and alertmanager storage. Configured via `-.oss.*` flags with `backend: oss`. #7907 * [ENHANCEMENT] Compactor: Add `-compactor.block-ranges-compaction-delay` to configure the compaction group graceful period per `-compactor.block-ranges` entry, matched by position. A larger block range can now be held back until its sub-ranges have settled, instead of every range sharing one period derived from `-compactor.cleanup-interval`. Leaving it empty, and any range without an entry, keeps the current behaviour of twice `-compactor.cleanup-interval`. The delay is a lower bound: groups only become eligible on a compaction run, so the effective wait can be up to `-compactor.compaction-interval` longer. Only used by the partitioning compaction strategy. #7916 +* [ENHANCEMENT] Compactor: Add `-compactor.compaction-drain-timeout`. When set, a compaction that is already running when shutdown is requested is allowed to finish, for up to this duration, instead of being cancelled. The compactor stops planning new compaction groups and stops picking up further tenants as soon as shutdown is requested. Defaults to 0, which cancels the running compaction immediately and discards the work it has done so far. #XXXX * [ENHANCEMENT] Ring: Add the `cortex_ring_member_zonal_ownership_percent{name, member, zone}` metric, reporting the fraction of its own zone's token space owned by each ring member. With zone-aware replication a write is routed within a single zone, so the existing `cortex_ring_member_ownership_percent`, which is computed over the merged token list of all zones, does not reflect the hash range a member actually serves. Reported when ring detailed metrics and zone awareness are both enabled. #7910 * [ENHANCEMENT] Ingester: Add experimental `-ingester.use-ring-ownership-for-limits` (requires zone-aware replication). It converts global series and metadata limits to per-ingester limits using the ingester's actual share of each tenant's hash space within its zone, instead of an equal share, which throttles tenants early on an unbalanced ring. Shares ignore `-distributor.extend-writes`, so a tenant can be throttled early while an instance is JOINING, LEAVING or PENDING. Exposes `cortex_ingester_ring_ownership_share{user}` and `cortex_ingester_ring_ownership_computations_total`. #7954 #7961 * [ENHANCEMENT] Distributor: Support partial write for Prometheus Remote Write 2.0 requests. Invalid series are now skipped and reported together in the `400` response instead of rejecting the whole batch, the valid ones are written, and the `X-Prometheus-Remote-Write-*-Written` response headers are set even when a `400` is returned. #7761 diff --git a/docs/blocks-storage/compactor.md b/docs/blocks-storage/compactor.md index 23c03136fb2..daf67b251fd 100644 --- a/docs/blocks-storage/compactor.md +++ b/docs/blocks-storage/compactor.md @@ -144,6 +144,17 @@ compactor: # CLI flag: -compactor.compaction-concurrency [compaction_concurrency: | default = 1] + # How long to let a compaction that is already running finish once shutdown + # has been requested, before cancelling it. As soon as shutdown is requested + # the compactor stops planning new compaction groups and stops picking up + # further tenants, regardless of this setting. 0 cancels the running + # compaction immediately, discarding the work it has done so far. A compaction + # is only allowed to finish if the process is given at least this long to + # terminate, so this value should be below the deployment's termination grace + # period. + # CLI flag: -compactor.compaction-drain-timeout + [compaction_drain_timeout: | default = 0s] + # How frequently compactor should run blocks cleanup and maintenance, as well # as update the bucket index. # CLI flag: -compactor.cleanup-interval diff --git a/docs/configuration/config-file-reference.md b/docs/configuration/config-file-reference.md index 9fd5b281df8..2f2df333c2e 100644 --- a/docs/configuration/config-file-reference.md +++ b/docs/configuration/config-file-reference.md @@ -3146,6 +3146,16 @@ The `compactor_config` configures the compactor for the blocks storage. # CLI flag: -compactor.compaction-concurrency [compaction_concurrency: | default = 1] +# How long to let a compaction that is already running finish once shutdown has +# been requested, before cancelling it. As soon as shutdown is requested the +# compactor stops planning new compaction groups and stops picking up further +# tenants, regardless of this setting. 0 cancels the running compaction +# immediately, discarding the work it has done so far. A compaction is only +# allowed to finish if the process is given at least this long to terminate, so +# this value should be below the deployment's termination grace period. +# CLI flag: -compactor.compaction-drain-timeout +[compaction_drain_timeout: | default = 0s] + # How frequently compactor should run blocks cleanup and maintenance, as well as # update the bucket index. # CLI flag: -compactor.cleanup-interval diff --git a/pkg/compactor/compactor.go b/pkg/compactor/compactor.go index 33f7c1ebce0..05c1633739c 100644 --- a/pkg/compactor/compactor.go +++ b/pkg/compactor/compactor.go @@ -60,6 +60,7 @@ var ( supportedShardingStrategies = []string{util.ShardingStrategyDefault, util.ShardingStrategyShuffle} errInvalidShardingStrategy = errors.New("invalid sharding strategy") errInvalidBlockMergeFanIn = errors.New("invalid block merge fan-in, the value must not be negative") + errInvalidCompactionDrainTimeout = errors.New("invalid compaction drain timeout, the value must not be negative") errInvalidTenantShardSize = errors.New("invalid tenant shard size, the value must be greater than 0") supportedCompactionStrategies = []string{util.CompactionStrategyDefault, util.CompactionStrategyPartitioning} errInvalidCompactionStrategy = errors.New("invalid compaction strategy") @@ -269,6 +270,7 @@ type Config struct { CompactionInterval time.Duration `yaml:"compaction_interval"` CompactionRetries int `yaml:"compaction_retries"` CompactionConcurrency int `yaml:"compaction_concurrency"` + CompactionDrainTimeout time.Duration `yaml:"compaction_drain_timeout"` CleanupInterval time.Duration `yaml:"cleanup_interval"` CleanupConcurrency int `yaml:"cleanup_concurrency"` DeletionDelay time.Duration `yaml:"deletion_delay"` @@ -333,6 +335,7 @@ func (cfg *Config) RegisterFlags(f *flag.FlagSet) { f.DurationVar(&cfg.CompactionInterval, "compactor.compaction-interval", time.Hour, "The frequency at which the compaction runs") f.IntVar(&cfg.CompactionRetries, "compactor.compaction-retries", 3, "How many times to retry a failed compaction within a single compaction run.") f.IntVar(&cfg.CompactionConcurrency, "compactor.compaction-concurrency", 1, "Max number of concurrent compactions running.") + f.DurationVar(&cfg.CompactionDrainTimeout, "compactor.compaction-drain-timeout", 0, "How long to let a compaction that is already running finish once shutdown has been requested, before cancelling it. As soon as shutdown is requested the compactor stops planning new compaction groups and stops picking up further tenants, regardless of this setting. 0 cancels the running compaction immediately, discarding the work it has done so far. A compaction is only allowed to finish if the process is given at least this long to terminate, so this value should be below the deployment's termination grace period.") f.DurationVar(&cfg.CleanupInterval, "compactor.cleanup-interval", 15*time.Minute, "How frequently compactor should run blocks cleanup and maintenance, as well as update the bucket index.") f.IntVar(&cfg.CleanupConcurrency, "compactor.cleanup-concurrency", 20, "Max number of tenants for which blocks cleanup and maintenance should run concurrently.") f.BoolVar(&cfg.ShardingEnabled, "compactor.sharding-enabled", false, "Shard tenants across multiple compactor instances. Sharding is required if you run multiple compactor instances, in order to coordinate compactions and avoid race conditions leading to the same tenant blocks simultaneously compacted by different instances.") @@ -391,6 +394,10 @@ func (cfg *Config) Validate(limits validation.Limits) error { return errInvalidBlockMergeFanIn } + if cfg.CompactionDrainTimeout < 0 { + return errInvalidCompactionDrainTimeout + } + // Make sure a valid sharding strategy is being used if !slices.Contains(supportedShardingStrategies, cfg.ShardingStrategy) { return errInvalidShardingStrategy @@ -810,6 +817,29 @@ func (c *Compactor) stopping(_ error) error { return nil } +// compactionContext detaches from ctx so an in-flight compaction can finish +// after shutdown, for up to drainTimeout. Zero returns ctx itself. +func compactionContext(ctx context.Context, drainTimeout time.Duration) (context.Context, context.CancelFunc) { + if drainTimeout <= 0 { + return ctx, func() {} + } + + compactionCtx, cancel := context.WithCancel(context.WithoutCancel(ctx)) + go func() { + select { + case <-ctx.Done(): + select { + case <-time.After(drainTimeout): + case <-compactionCtx.Done(): + } + case <-compactionCtx.Done(): + } + cancel() + }() + + return compactionCtx, cancel +} + func (c *Compactor) running(ctx context.Context) error { // Ensure an initial cleanup occurred as first thing when running compactor. if err := services.StartAndAwaitRunning(ctx, c.blocksCleaner); err != nil { @@ -821,6 +851,9 @@ func (c *Compactor) running(ctx context.Context) error { go c.userIndexUpdateLoop(ctx) } + compactionCtx, cancelCompaction := compactionContext(ctx, c.compactorCfg.CompactionDrainTimeout) + defer cancelCompaction() + // Run an initial compaction before starting the interval. // Insert jitter right before compaction starts to avoid multiple starting compactor to be in sync select { @@ -828,7 +861,7 @@ func (c *Compactor) running(ctx context.Context) error { return ctx.Err() case <-time.After(time.Duration(rand.Int63n(int64(float64(c.compactorCfg.CompactionInterval) * 0.1)))): } - c.compactUsers(ctx) + c.compactUsers(ctx, compactionCtx) ticker := time.NewTicker(c.compactorCfg.CompactionInterval) defer ticker.Stop() @@ -839,7 +872,7 @@ func (c *Compactor) running(ctx context.Context) error { // Insert jitter right before compaction starts, so that there will always // have jitter even compaction time is longer than CompactionInterval time.Sleep(time.Duration(rand.Int63n(int64(float64(c.compactorCfg.CompactionInterval) * 0.1)))) - c.compactUsers(ctx) + c.compactUsers(ctx, compactionCtx) case <-ctx.Done(): return nil case err := <-c.ringSubservicesWatcher.Chan(): @@ -848,7 +881,9 @@ func (c *Compactor) running(ctx context.Context) error { } } -func (c *Compactor) compactUsers(ctx context.Context) { +// ctx decides whether another tenant is picked up; compactionCtx runs the +// compaction and can outlive ctx by -compactor.compaction-drain-timeout. +func (c *Compactor) compactUsers(ctx, compactionCtx context.Context) { succeeded := false interrupted := false compactionErrorCount := 0 @@ -934,9 +969,9 @@ func (c *Compactor) compactUsers(ctx context.Context) { level.Info(c.logger).Log("msg", "starting compaction of user blocks", "user", userID) - if err = c.compactUserWithRetries(ctx, userID); err != nil { + if err = c.compactUserWithRetries(compactionCtx, ctx, userID); err != nil { // TODO: patch thanos error types to support errors.Is(err, context.Canceled) here - if ctx.Err() != nil && ctx.Err() == context.Canceled { + if compactionCtx.Err() != nil && compactionCtx.Err() == context.Canceled { interrupted = true level.Info(c.logger).Log("msg", "interrupting compaction of user blocks", "user", userID) return @@ -981,7 +1016,7 @@ func (c *Compactor) compactUsers(ctx context.Context) { succeeded = true } -func (c *Compactor) compactUserWithRetries(ctx context.Context, userID string) error { +func (c *Compactor) compactUserWithRetries(ctx, shutdownCtx context.Context, userID string) error { var lastErr error retries := backoff.New(ctx, backoff.Config{ @@ -991,7 +1026,7 @@ func (c *Compactor) compactUserWithRetries(ctx context.Context, userID string) e }) for retries.Ongoing() { - lastErr = c.compactUser(ctx, userID) + lastErr = c.compactUser(ctx, shutdownCtx, userID) if lastErr == nil { return nil } @@ -1021,7 +1056,35 @@ func (c *Compactor) compactUserWithRetries(ctx context.Context, userID string) e return lastErr } -func (c *Compactor) compactUser(ctx context.Context, userID string) error { +// shutdownGatedGrouper stops building new groups at shutdown. Under the +// partitioning strategy, building a group claims its partition in the bucket. +type shutdownGatedGrouper struct { + shutdownCtx context.Context + grouper compact.Grouper +} + +func (g *shutdownGatedGrouper) Groups(blocks map[ulid.ULID]*metadata.Meta) ([]*compact.Group, error) { + if g.shutdownCtx.Err() != nil { + return nil, nil + } + return g.grouper.Groups(blocks) +} + +// shutdownGatedPlanner stops planning groups already queued at shutdown. An +// empty plan is a group with nothing to do and does not ask for a rerun. +type shutdownGatedPlanner struct { + shutdownCtx context.Context + planner compact.Planner +} + +func (p *shutdownGatedPlanner) Plan(ctx context.Context, metasByMinTime []*metadata.Meta, errChan chan error, extensions any) ([]*metadata.Meta, error) { + if p.shutdownCtx.Err() != nil { + return nil, nil + } + return p.planner.Plan(ctx, metasByMinTime, errChan, extensions) +} + +func (c *Compactor) compactUser(ctx, shutdownCtx context.Context, userID string) error { bucket := newParquetFilteredBucket(bucket.NewUserBucketClient(userID, c.bucketClient, c.limits)) reg := prometheus.NewRegistry() @@ -1116,11 +1179,18 @@ func (c *Compactor) compactUser(ctx context.Context, userID string) error { currentCtx, cancel := context.WithCancel(ctx) defer cancel() + + planner := c.blocksPlannerFactory(currentCtx, bucket, ulogger, c.compactorCfg, noCompactMarkerFilter, c.ringLifecycler, userID, c.blockVisitMarkerReadFailed, c.blockVisitMarkerWriteFailed, c.compactorMetrics, ignoreDeletionMarkFilter) + grouper := c.blocksGrouperFactory(currentCtx, c.compactorCfg, bucket, ulogger, c.BlocksMarkedForNoCompaction, c.blockVisitMarkerReadFailed, c.blockVisitMarkerWriteFailed, syncerMetrics, c.compactorMetrics, c.ring, c.ringLifecycler, c.limits, userID, noCompactMarkerFilter, c.ingestionReplicationFactor) + if c.compactorCfg.CompactionDrainTimeout > 0 { + planner = &shutdownGatedPlanner{shutdownCtx: shutdownCtx, planner: planner} + grouper = &shutdownGatedGrouper{shutdownCtx: shutdownCtx, grouper: grouper} + } compactor, err := compact.NewBucketCompactorWithCheckerAndCallback( ulogger, syncer, - c.blocksGrouperFactory(currentCtx, c.compactorCfg, bucket, ulogger, c.BlocksMarkedForNoCompaction, c.blockVisitMarkerReadFailed, c.blockVisitMarkerWriteFailed, syncerMetrics, c.compactorMetrics, c.ring, c.ringLifecycler, c.limits, userID, noCompactMarkerFilter, c.ingestionReplicationFactor), - c.blocksPlannerFactory(currentCtx, bucket, ulogger, c.compactorCfg, noCompactMarkerFilter, c.ringLifecycler, userID, c.blockVisitMarkerReadFailed, c.blockVisitMarkerWriteFailed, c.compactorMetrics, ignoreDeletionMarkFilter), + grouper, + planner, c.blocksCompactor, c.blockDeletableCheckerFactory(currentCtx, bucket, ulogger), c.compactionLifecycleCallbackFactory(currentCtx, bucket, ulogger, c.compactorCfg.MetaSyncConcurrency, c.compactorCfg.BlockMergeFanIn, c.compactDirForUser(userID), userID, c.compactorMetrics), diff --git a/pkg/compactor/compactor_paritioning_test.go b/pkg/compactor/compactor_paritioning_test.go index 1dff481f066..470051b8bc2 100644 --- a/pkg/compactor/compactor_paritioning_test.go +++ b/pkg/compactor/compactor_paritioning_test.go @@ -1630,7 +1630,7 @@ func TestPartitionCompactor_DeleteLocalSyncFiles(t *testing.T) { // Run a compaction cycle on the first compactor: it is alone in the ring, so // it owns (and syncs) all the users. - c1.compactUsers(context.Background()) + c1.compactUsers(context.Background(), context.Background()) require.Equal(t, numUsers, len(c1.listTenantsWithMetaSyncDirectories())) require.NoError(t, os.Mkdir(c1.metaSyncDirForUser("new-user"), 0600)) @@ -1660,14 +1660,14 @@ func TestPartitionCompactor_DeleteLocalSyncFiles(t *testing.T) { // Run a compaction cycle on the second compactor: with pinned tokens it owns // exactly half of the users and creates a meta-sync directory for each of them. - c2.compactUsers(context.Background()) + c2.compactUsers(context.Background(), context.Background()) // Let's check how many users second compactor has. c2Users := len(c2.listTenantsWithMetaSyncDirectories()) require.Equal(t, numUsers/2, c2Users) // Force new compaction cycle on first compactor. It will run the cleanup of un-owned users at the end of compaction cycle. - c1.compactUsers(context.Background()) + c1.compactUsers(context.Background(), context.Background()) c1Users := len(c1.listTenantsWithMetaSyncDirectories()) // Now compactor 1 should have cleaned the sync files of the users it no longer diff --git a/pkg/compactor/compactor_test.go b/pkg/compactor/compactor_test.go index abb9268ea19..76bf749299c 100644 --- a/pkg/compactor/compactor_test.go +++ b/pkg/compactor/compactor_test.go @@ -17,6 +17,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "testing" "time" @@ -1628,6 +1629,11 @@ func prepareConfig() Config { } func prepare(t *testing.T, compactorCfg Config, bucketClient objstore.InstrumentedBucket, limits *validation.Limits) (*Compactor, *tsdbCompactorMock, *tsdbPlannerMock, *concurrency.SyncBuffer, prometheus.Gatherer) { + return prepareWithGrouperFactory(t, compactorCfg, bucketClient, limits, nil) +} + +// A nil grouperFactory keeps the factory the sharding strategy selects. +func prepareWithGrouperFactory(t *testing.T, compactorCfg Config, bucketClient objstore.InstrumentedBucket, limits *validation.Limits, grouperFactory BlocksGrouperFactory) (*Compactor, *tsdbCompactorMock, *tsdbPlannerMock, *concurrency.SyncBuffer, prometheus.Gatherer) { storageCfg := cortex_tsdb.BlocksStorageConfig{} flagext.DefaultValues(&storageCfg) storageCfg.BucketStore.BlockDiscoveryStrategy = string(cortex_tsdb.RecursiveDiscovery) @@ -1666,9 +1672,12 @@ func prepare(t *testing.T, compactorCfg Config, bucketClient objstore.Instrument } var blocksGrouperFactory BlocksGrouperFactory - if compactorCfg.ShardingStrategy == util.ShardingStrategyShuffle { + switch { + case grouperFactory != nil: + blocksGrouperFactory = grouperFactory + case compactorCfg.ShardingStrategy == util.ShardingStrategyShuffle: blocksGrouperFactory = ShuffleShardingGrouperFactory - } else { + default: blocksGrouperFactory = DefaultBlocksGrouperFactory } @@ -1930,7 +1939,7 @@ func TestCompactor_DeleteLocalSyncFiles(t *testing.T) { // Run a compaction cycle on the first compactor: it is alone in the ring, so // it owns (and syncs) all the users. - c1.compactUsers(context.Background()) + c1.compactUsers(context.Background(), context.Background()) require.Equal(t, numUsers, len(c1.listTenantsWithMetaSyncDirectories())) require.NoError(t, os.Mkdir(c1.metaSyncDirForUser("new-user"), 0600)) @@ -1960,14 +1969,14 @@ func TestCompactor_DeleteLocalSyncFiles(t *testing.T) { // Run a compaction cycle on the second compactor: with pinned tokens it owns // exactly half of the users and creates a meta-sync directory for each of them. - c2.compactUsers(context.Background()) + c2.compactUsers(context.Background(), context.Background()) // Let's check how many users second compactor has. c2Users := len(c2.listTenantsWithMetaSyncDirectories()) require.Equal(t, numUsers/2, c2Users) // Force new compaction cycle on first compactor. It will run the cleanup of un-owned users at the end of compaction cycle. - c1.compactUsers(context.Background()) + c1.compactUsers(context.Background(), context.Background()) c1Users := len(c1.listTenantsWithMetaSyncDirectories()) // Now compactor 1 should have cleaned the sync files of the users it no longer @@ -2071,6 +2080,268 @@ func TestCompactor_ShouldNotTreatInterruptionsAsErrors(t *testing.T) { require.NotContains(t, logs.String(), `level=error`) } +func TestCompactor_ShouldLetRunningCompactionFinishOnShutdownWhenDrainTimeoutIsSet(t *testing.T) { + bucketClient := objstore.WithNoopInstr(objstore.NewInMemBucket()) + id := ulid.MustNew(ulid.Now(), rand.Reader) + require.NoError(t, bucketClient.Upload(context.Background(), "user-1/"+id.String()+"/meta.json", strings.NewReader(mockBlockMetaJSON(id.String())))) + + createTSDBBlock(t, bucketClient, "user-1", 10, 20, map[string]string{"__name__": "Teste"}) + createTSDBBlock(t, bucketClient, "user-1", 20, 30, map[string]string{"__name__": "Teste"}) + + cfg := prepareConfig() + cfg.CompactionDrainTimeout = time.Minute + + c, _, tsdbPlanner, _, registry := prepare(t, cfg, bucketClient, nil) + + planCalled := make(chan struct{}) + releasePlan := make(chan struct{}) + var planCtxErr error + var once sync.Once + + tsdbPlanner.On("Plan", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]*metadata.Meta{}, nil).Run(func(args mock.Arguments) { + once.Do(func() { + close(planCalled) + <-releasePlan + planCtxErr = args.Get(0).(context.Context).Err() + }) + }) + + ctx, cancel := context.WithCancel(context.Background()) + require.NoError(t, services.StartAndAwaitRunning(ctx, c)) + + // Cancelling the start context cancels the service context synchronously. + <-planCalled + cancel() + close(releasePlan) + + require.NoError(t, services.StopAndAwaitTerminated(context.Background(), c)) + + assert.NoError(t, planCtxErr) + + assert.NoError(t, prom_testutil.GatherAndCompare(registry, strings.NewReader(` + # TYPE cortex_compactor_runs_completed_total counter + # HELP cortex_compactor_runs_completed_total Total number of compaction runs successfully completed. + cortex_compactor_runs_completed_total 1 + + # TYPE cortex_compactor_runs_interrupted_total counter + # HELP cortex_compactor_runs_interrupted_total Total number of compaction runs interrupted. + cortex_compactor_runs_interrupted_total 0 + + # TYPE cortex_compactor_runs_failed_total counter + # HELP cortex_compactor_runs_failed_total Total number of compaction runs failed. + cortex_compactor_runs_failed_total 0 + `), + "cortex_compactor_runs_completed_total", + "cortex_compactor_runs_interrupted_total", + "cortex_compactor_runs_failed_total", + )) +} + +func TestCompactor_ShouldCancelRunningCompactionWhenDrainTimeoutExpires(t *testing.T) { + bucketClient := objstore.WithNoopInstr(objstore.NewInMemBucket()) + id := ulid.MustNew(ulid.Now(), rand.Reader) + require.NoError(t, bucketClient.Upload(context.Background(), "user-1/"+id.String()+"/meta.json", strings.NewReader(mockBlockMetaJSON(id.String())))) + + createTSDBBlock(t, bucketClient, "user-1", 10, 20, map[string]string{"__name__": "Teste"}) + createTSDBBlock(t, bucketClient, "user-1", 20, 30, map[string]string{"__name__": "Teste"}) + + cfg := prepareConfig() + cfg.CompactionDrainTimeout = 100 * time.Millisecond + + c, _, tsdbPlanner, _, _ := prepare(t, cfg, bucketClient, nil) + + planCalled := make(chan struct{}) + planCtxErr := make(chan error, 1) + var once sync.Once + + tsdbPlanner.On("Plan", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]*metadata.Meta{}, nil).Run(func(args mock.Arguments) { + once.Do(func() { + planCtx := args.Get(0).(context.Context) + close(planCalled) + select { + case <-planCtx.Done(): + case <-time.After(10 * time.Second): + } + planCtxErr <- planCtx.Err() + }) + }) + + ctx, cancel := context.WithCancel(context.Background()) + require.NoError(t, services.StartAndAwaitRunning(ctx, c)) + + <-planCalled + cancel() + + assert.Equal(t, context.Canceled, <-planCtxErr) + + require.NoError(t, services.StopAndAwaitTerminated(context.Background(), c)) +} + +// Stands in for the sharding groupers, which produce several groups per pass. +type duplicatingGrouper struct { + grouper compact.Grouper +} + +func (g *duplicatingGrouper) Groups(blocks map[ulid.ULID]*metadata.Meta) ([]*compact.Group, error) { + groups, err := g.grouper.Groups(blocks) + if err != nil { + return nil, err + } + + out := make([]*compact.Group, 0, len(groups)*2) + out = append(out, groups...) + out = append(out, groups...) + return out, nil +} + +func TestCompactor_ShouldStopPlanningNewGroupsOnceShutdownIsRequested(t *testing.T) { + bucketClient := objstore.WithNoopInstr(objstore.NewInMemBucket()) + id := ulid.MustNew(ulid.Now(), rand.Reader) + require.NoError(t, bucketClient.Upload(context.Background(), "user-1/"+id.String()+"/meta.json", strings.NewReader(mockBlockMetaJSON(id.String())))) + + b1 := createTSDBBlock(t, bucketClient, "user-1", 10, 20, map[string]string{"__name__": "Teste"}) + b2 := createTSDBBlock(t, bucketClient, "user-1", 20, 30, map[string]string{"__name__": "Teste"}) + + cfg := prepareConfig() + cfg.CompactionDrainTimeout = 3 * time.Second + + c, tsdbCompactor, tsdbPlanner, _, registry := prepareWithGrouperFactory(t, cfg, bucketClient, nil, func(ctx context.Context, cfg Config, bkt objstore.InstrumentedBucket, logger log.Logger, blocksMarkedForNoCompact prometheus.Counter, blockVisitMarkerReadFailed prometheus.Counter, blockVisitMarkerWriteFailed prometheus.Counter, syncerMetrics *compact.SyncerMetrics, compactorMetrics *compactorMetrics, r *ring.Ring, ringLifecycler *ring.Lifecycler, limit Limits, userID string, noCompactionMarkFilter *compact.GatherNoCompactionMarkFilter, ingestionReplicationFactor int) compact.Grouper { + return &duplicatingGrouper{ + grouper: DefaultBlocksGrouperFactory(ctx, cfg, bkt, logger, blocksMarkedForNoCompact, blockVisitMarkerReadFailed, blockVisitMarkerWriteFailed, syncerMetrics, compactorMetrics, r, ringLifecycler, limit, userID, noCompactionMarkFilter, ingestionReplicationFactor), + } + }) + + // An empty compaction result makes thanos ask for another pass. + tsdbCompactor.On("CompactWithBlockPopulator", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]ulid.ULID{}, nil) + + planCalled := make(chan struct{}) + releasePlan := make(chan struct{}) + var once sync.Once + + tsdbPlanner.On("Plan", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]*metadata.Meta{ + { + ULID: b1, + MinTime: 10, + MaxTime: 20, + // Non-zero samples stop thanos marking the sources for deletion. + Stats: tsdb.BlockStats{NumSamples: 1}, + }, + { + ULID: b2, + MinTime: 20, + MaxTime: 30, + Stats: tsdb.BlockStats{NumSamples: 1}, + }, + }, nil).Run(func(mock.Arguments) { + once.Do(func() { + close(planCalled) + <-releasePlan + }) + }) + + ctx, cancel := context.WithCancel(context.Background()) + require.NoError(t, services.StartAndAwaitRunning(ctx, c)) + + <-planCalled + cancel() + close(releasePlan) + + require.NoError(t, services.StopAndAwaitTerminated(context.Background(), c)) + + tsdbPlanner.AssertNumberOfCalls(t, "Plan", 1) + + assert.NoError(t, prom_testutil.GatherAndCompare(registry, strings.NewReader(` + # TYPE cortex_compactor_runs_completed_total counter + # HELP cortex_compactor_runs_completed_total Total number of compaction runs successfully completed. + cortex_compactor_runs_completed_total 1 + + # TYPE cortex_compactor_runs_interrupted_total counter + # HELP cortex_compactor_runs_interrupted_total Total number of compaction runs interrupted. + cortex_compactor_runs_interrupted_total 0 + `), + "cortex_compactor_runs_completed_total", + "cortex_compactor_runs_interrupted_total", + )) +} + +type countingGrouper struct { + calls *atomic.Int64 + grouper compact.Grouper +} + +func (g *countingGrouper) Groups(blocks map[ulid.ULID]*metadata.Meta) ([]*compact.Group, error) { + g.calls.Add(1) + return g.grouper.Groups(blocks) +} + +func TestCompactor_ShouldStopBuildingGroupsOnceShutdownIsRequested(t *testing.T) { + bucketClient := objstore.WithNoopInstr(objstore.NewInMemBucket()) + id := ulid.MustNew(ulid.Now(), rand.Reader) + require.NoError(t, bucketClient.Upload(context.Background(), "user-1/"+id.String()+"/meta.json", strings.NewReader(mockBlockMetaJSON(id.String())))) + + b1 := createTSDBBlock(t, bucketClient, "user-1", 10, 20, map[string]string{"__name__": "Teste"}) + b2 := createTSDBBlock(t, bucketClient, "user-1", 20, 30, map[string]string{"__name__": "Teste"}) + + cfg := prepareConfig() + cfg.CompactionDrainTimeout = 3 * time.Second + + var groupsCalls atomic.Int64 + grouperFactory := func(ctx context.Context, cfg Config, bkt objstore.InstrumentedBucket, logger log.Logger, blocksMarkedForNoCompact prometheus.Counter, blockVisitMarkerReadFailed prometheus.Counter, blockVisitMarkerWriteFailed prometheus.Counter, syncerMetrics *compact.SyncerMetrics, compactorMetrics *compactorMetrics, r *ring.Ring, ringLifecycler *ring.Lifecycler, limit Limits, userID string, noCompactionMarkFilter *compact.GatherNoCompactionMarkFilter, ingestionReplicationFactor int) compact.Grouper { + return &countingGrouper{ + calls: &groupsCalls, + grouper: DefaultBlocksGrouperFactory(ctx, cfg, bkt, logger, blocksMarkedForNoCompact, blockVisitMarkerReadFailed, blockVisitMarkerWriteFailed, syncerMetrics, compactorMetrics, r, ringLifecycler, limit, userID, noCompactionMarkFilter, ingestionReplicationFactor), + } + } + + c, tsdbCompactor, tsdbPlanner, _, registry := prepareWithGrouperFactory(t, cfg, bucketClient, nil, grouperFactory) + + // An empty compaction result makes thanos run another pass over the tenant. + tsdbCompactor.On("CompactWithBlockPopulator", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]ulid.ULID{}, nil) + + planCalled := make(chan struct{}) + releasePlan := make(chan struct{}) + var once sync.Once + + tsdbPlanner.On("Plan", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]*metadata.Meta{ + { + ULID: b1, + MinTime: 10, + MaxTime: 20, + Stats: tsdb.BlockStats{NumSamples: 1}, + }, + { + ULID: b2, + MinTime: 20, + MaxTime: 30, + Stats: tsdb.BlockStats{NumSamples: 1}, + }, + }, nil).Run(func(mock.Arguments) { + once.Do(func() { + close(planCalled) + <-releasePlan + }) + }) + + ctx, cancel := context.WithCancel(context.Background()) + require.NoError(t, services.StartAndAwaitRunning(ctx, c)) + + <-planCalled + cancel() + close(releasePlan) + + require.NoError(t, services.StopAndAwaitTerminated(context.Background(), c)) + + assert.Equal(t, int64(1), groupsCalls.Load()) + + assert.NoError(t, prom_testutil.GatherAndCompare(registry, strings.NewReader(` + # TYPE cortex_compactor_runs_completed_total counter + # HELP cortex_compactor_runs_completed_total Total number of compaction runs successfully completed. + cortex_compactor_runs_completed_total 1 + `), + "cortex_compactor_runs_completed_total", + )) +} + func TestCompactor_ShouldNotFailCompactionIfAccessDeniedErrDuringMetaSync(t *testing.T) { t.Parallel() diff --git a/schemas/cortex-config-schema.json b/schemas/cortex-config-schema.json index 4a45fe56684..35b1375e7e1 100644 --- a/schemas/cortex-config-schema.json +++ b/schemas/cortex-config-schema.json @@ -3820,6 +3820,13 @@ "type": "number", "x-cli-flag": "compactor.compaction-concurrency" }, + "compaction_drain_timeout": { + "default": "0s", + "description": "How long to let a compaction that is already running finish once shutdown has been requested, before cancelling it. As soon as shutdown is requested the compactor stops planning new compaction groups and stops picking up further tenants, regardless of this setting. 0 cancels the running compaction immediately, discarding the work it has done so far. A compaction is only allowed to finish if the process is given at least this long to terminate, so this value should be below the deployment's termination grace period.", + "type": "string", + "x-cli-flag": "compactor.compaction-drain-timeout", + "x-format": "duration" + }, "compaction_interval": { "default": "1h0m0s", "description": "The frequency at which the compaction runs", From 36b21e26238efd8147b9fa8d3a894e242fae819a Mon Sep 17 00:00:00 2001 From: Alex Le Date: Thu, 26 Nov 2026 21:14:13 +0000 Subject: [PATCH 2/5] Compactor: reference the PR number in the CHANGELOG entry Signed-off-by: Alex Le --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ac7748a89dc..d290fdbf3e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ * [FEATURE] Distributor: Add experimental OTLP metrics ingestion over gRPC (`opentelemetry.proto.collector.metrics.v1.MetricsService/Export`) on the gRPC server port. Enable it with `-distributor.otlp.grpc-enabled`. The tenant is read from the `X-Scope-OrgID` gRPC metadata, and the request size is limited by `-server.grpc-max-recv-msg-size-bytes`. #7873 * [FEATURE] Storage: Add support for Alibaba Cloud OSS as a backend for blocks, ruler, and alertmanager storage. Configured via `-.oss.*` flags with `backend: oss`. #7907 * [ENHANCEMENT] Compactor: Add `-compactor.block-ranges-compaction-delay` to configure the compaction group graceful period per `-compactor.block-ranges` entry, matched by position. A larger block range can now be held back until its sub-ranges have settled, instead of every range sharing one period derived from `-compactor.cleanup-interval`. Leaving it empty, and any range without an entry, keeps the current behaviour of twice `-compactor.cleanup-interval`. The delay is a lower bound: groups only become eligible on a compaction run, so the effective wait can be up to `-compactor.compaction-interval` longer. Only used by the partitioning compaction strategy. #7916 -* [ENHANCEMENT] Compactor: Add `-compactor.compaction-drain-timeout`. When set, a compaction that is already running when shutdown is requested is allowed to finish, for up to this duration, instead of being cancelled. The compactor stops planning new compaction groups and stops picking up further tenants as soon as shutdown is requested. Defaults to 0, which cancels the running compaction immediately and discards the work it has done so far. #XXXX +* [ENHANCEMENT] Compactor: Add `-compactor.compaction-drain-timeout`. When set, a compaction that is already running when shutdown is requested is allowed to finish, for up to this duration, instead of being cancelled. The compactor stops planning new compaction groups and stops picking up further tenants as soon as shutdown is requested. Defaults to 0, which cancels the running compaction immediately and discards the work it has done so far. #7973 * [ENHANCEMENT] Ring: Add the `cortex_ring_member_zonal_ownership_percent{name, member, zone}` metric, reporting the fraction of its own zone's token space owned by each ring member. With zone-aware replication a write is routed within a single zone, so the existing `cortex_ring_member_ownership_percent`, which is computed over the merged token list of all zones, does not reflect the hash range a member actually serves. Reported when ring detailed metrics and zone awareness are both enabled. #7910 * [ENHANCEMENT] Ingester: Add experimental `-ingester.use-ring-ownership-for-limits` (requires zone-aware replication). It converts global series and metadata limits to per-ingester limits using the ingester's actual share of each tenant's hash space within its zone, instead of an equal share, which throttles tenants early on an unbalanced ring. Shares ignore `-distributor.extend-writes`, so a tenant can be throttled early while an instance is JOINING, LEAVING or PENDING. Exposes `cortex_ingester_ring_ownership_share{user}` and `cortex_ingester_ring_ownership_computations_total`. #7954 #7961 * [ENHANCEMENT] Distributor: Support partial write for Prometheus Remote Write 2.0 requests. Invalid series are now skipped and reported together in the `400` response instead of rejecting the whole batch, the valid ones are written, and the `X-Prometheus-Remote-Write-*-Written` response headers are set even when a `400` is returned. #7761 From 04343ff9286484d78e87768d9e6960592475a90a Mon Sep 17 00:00:00 2001 From: Alex Le Date: Thu, 26 Nov 2026 21:23:04 +0000 Subject: [PATCH 3/5] Compactor: use go.uber.org/atomic in the shutdown drain tests Signed-off-by: Alex Le --- pkg/compactor/compactor_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/compactor/compactor_test.go b/pkg/compactor/compactor_test.go index 76bf749299c..a1d8372abe9 100644 --- a/pkg/compactor/compactor_test.go +++ b/pkg/compactor/compactor_test.go @@ -17,7 +17,6 @@ import ( "strconv" "strings" "sync" - "sync/atomic" "testing" "time" @@ -35,6 +34,7 @@ import ( "github.com/thanos-io/thanos/pkg/block" "github.com/thanos-io/thanos/pkg/block/metadata" "github.com/thanos-io/thanos/pkg/compact" + "go.uber.org/atomic" "gopkg.in/yaml.v2" "github.com/cortexproject/cortex/pkg/ring" From 8e9c8403a67a2767dc0b74ef3f2f190f4ead92ee Mon Sep 17 00:00:00 2001 From: Alex Le Date: Fri, 27 Nov 2026 21:35:41 +0000 Subject: [PATCH 4/5] Compactor: build the TSDB compactor and bucket client with the drain context The TSDB compactor keeps the context it is built with and checks it while merging, so building it in starting() with the service context aborted the merge at shutdown even with a drain timeout set. Only the block download and upload, which use the context thanos passes down, were protected. Create the drain context in starting() and pass it to both the blocks compactor factory and the bucket client factory. The GCS bucket client builds its token source with that context, and for credential types other than service account keys a token refresh sends its request with it, so a refresh during the drain would otherwise fail. The test mock now records the context its factory was given, so a test can assert the merge context survives shutdown. Signed-off-by: Alex Le --- pkg/compactor/compactor.go | 26 +++++++++----- pkg/compactor/compactor_test.go | 64 +++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 9 deletions(-) diff --git a/pkg/compactor/compactor.go b/pkg/compactor/compactor.go index 05c1633739c..a3e5aa16e2a 100644 --- a/pkg/compactor/compactor.go +++ b/pkg/compactor/compactor.go @@ -466,6 +466,9 @@ type Compactor struct { // Client used to run operations on the bucket storing blocks. bucketClient objstore.InstrumentedBucket + compactionCtx context.Context + cancelCompaction context.CancelFunc + // Ring used for sharding compactions. ringLifecycler *ring.Lifecycler ring *ring.Ring @@ -664,23 +667,30 @@ func newCompactor( } // Start the compactor. -func (c *Compactor) starting(ctx context.Context) error { +func (c *Compactor) starting(ctx context.Context) (err error) { begin := time.Now() defer func() { c.CompactorStartDurationSeconds.Set(time.Since(begin).Seconds()) level.Info(c.logger).Log("msg", "compactor started", "duration", time.Since(begin), "duration_ms", time.Since(begin).Milliseconds()) }() - var err error + // The TSDB compactor and the GCS token source keep the context they are + // built with, so both are built with the compaction context. + c.compactionCtx, c.cancelCompaction = compactionContext(ctx, c.compactorCfg.CompactionDrainTimeout) + defer func() { + if err != nil { + c.cancelCompaction() + } + }() // Create bucket client. - c.bucketClient, err = c.bucketClientFactory(ctx) + c.bucketClient, err = c.bucketClientFactory(c.compactionCtx) if err != nil { return errors.Wrap(err, "failed to create bucket client") } // Create blocks compactor dependencies. - c.blocksCompactor, c.blocksPlannerFactory, err = c.blocksCompactorFactory(ctx, c.compactorCfg, c.logger, c.registerer) + c.blocksCompactor, c.blocksPlannerFactory, err = c.blocksCompactorFactory(c.compactionCtx, c.compactorCfg, c.logger, c.registerer) if err != nil { return errors.Wrap(err, "failed to initialize compactor dependencies") } @@ -807,6 +817,7 @@ func (c *Compactor) stopping(_ error) error { defer func() { level.Info(c.logger).Log("msg", "compactor stopped", "duration", time.Since(begin), "duration_ms", time.Since(begin).Milliseconds()) }() + defer c.cancelCompaction() ctx := context.Background() @@ -851,9 +862,6 @@ func (c *Compactor) running(ctx context.Context) error { go c.userIndexUpdateLoop(ctx) } - compactionCtx, cancelCompaction := compactionContext(ctx, c.compactorCfg.CompactionDrainTimeout) - defer cancelCompaction() - // Run an initial compaction before starting the interval. // Insert jitter right before compaction starts to avoid multiple starting compactor to be in sync select { @@ -861,7 +869,7 @@ func (c *Compactor) running(ctx context.Context) error { return ctx.Err() case <-time.After(time.Duration(rand.Int63n(int64(float64(c.compactorCfg.CompactionInterval) * 0.1)))): } - c.compactUsers(ctx, compactionCtx) + c.compactUsers(ctx, c.compactionCtx) ticker := time.NewTicker(c.compactorCfg.CompactionInterval) defer ticker.Stop() @@ -872,7 +880,7 @@ func (c *Compactor) running(ctx context.Context) error { // Insert jitter right before compaction starts, so that there will always // have jitter even compaction time is longer than CompactionInterval time.Sleep(time.Duration(rand.Int63n(int64(float64(c.compactorCfg.CompactionInterval) * 0.1)))) - c.compactUsers(ctx, compactionCtx) + c.compactUsers(ctx, c.compactionCtx) case <-ctx.Done(): return nil case err := <-c.ringSubservicesWatcher.Chan(): diff --git a/pkg/compactor/compactor_test.go b/pkg/compactor/compactor_test.go index a1d8372abe9..9168e51a03c 100644 --- a/pkg/compactor/compactor_test.go +++ b/pkg/compactor/compactor_test.go @@ -1663,6 +1663,7 @@ func prepareWithGrouperFactory(t *testing.T, compactorCfg Config, bucketClient o } blocksCompactorFactory := func(ctx context.Context, cfg Config, logger log.Logger, reg prometheus.Registerer) (compact.Compactor, PlannerFactory, error) { + tsdbCompactor.ctx = ctx return tsdbCompactor, func(ctx context.Context, bkt objstore.InstrumentedBucket, _ log.Logger, _ Config, noCompactMarkFilter *compact.GatherNoCompactionMarkFilter, ringLifecycle *ring.Lifecycler, _ string, _ prometheus.Counter, _ prometheus.Counter, _ *compactorMetrics, _ *block.IgnoreDeletionMarkFilter) compact.Planner { tsdbPlanner.noCompactMarkFilters = append(tsdbPlanner.noCompactMarkFilters, noCompactMarkFilter) @@ -1689,6 +1690,9 @@ func prepareWithGrouperFactory(t *testing.T, compactorCfg Config, bucketClient o type tsdbCompactorMock struct { mock.Mock + + // A real TSDB compactor checks the context it was built with while merging. + ctx context.Context } func (m *tsdbCompactorMock) Plan(dir string) ([]string, error) { @@ -2264,6 +2268,66 @@ func TestCompactor_ShouldStopPlanningNewGroupsOnceShutdownIsRequested(t *testing )) } +func TestCompactor_ShouldNotCancelTheMergeOnShutdownWhenDrainTimeoutIsSet(t *testing.T) { + bucketClient := objstore.WithNoopInstr(objstore.NewInMemBucket()) + id := ulid.MustNew(ulid.Now(), rand.Reader) + require.NoError(t, bucketClient.Upload(context.Background(), "user-1/"+id.String()+"/meta.json", strings.NewReader(mockBlockMetaJSON(id.String())))) + + b1 := createTSDBBlock(t, bucketClient, "user-1", 10, 20, map[string]string{"__name__": "Teste"}) + b2 := createTSDBBlock(t, bucketClient, "user-1", 20, 30, map[string]string{"__name__": "Teste"}) + + cfg := prepareConfig() + cfg.CompactionDrainTimeout = time.Minute + + c, tsdbCompactor, tsdbPlanner, _, registry := prepare(t, cfg, bucketClient, nil) + + mergeCalled := make(chan struct{}) + releaseMerge := make(chan struct{}) + var mergeCtxErr error + var once sync.Once + + tsdbCompactor.On("CompactWithBlockPopulator", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]ulid.ULID{}, nil).Run(func(mock.Arguments) { + once.Do(func() { + close(mergeCalled) + <-releaseMerge + mergeCtxErr = tsdbCompactor.ctx.Err() + }) + }) + tsdbPlanner.On("Plan", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]*metadata.Meta{ + { + ULID: b1, + MinTime: 10, + MaxTime: 20, + Stats: tsdb.BlockStats{NumSamples: 1}, + }, + { + ULID: b2, + MinTime: 20, + MaxTime: 30, + Stats: tsdb.BlockStats{NumSamples: 1}, + }, + }, nil) + + ctx, cancel := context.WithCancel(context.Background()) + require.NoError(t, services.StartAndAwaitRunning(ctx, c)) + + <-mergeCalled + cancel() + close(releaseMerge) + + require.NoError(t, services.StopAndAwaitTerminated(context.Background(), c)) + + assert.NoError(t, mergeCtxErr) + + assert.NoError(t, prom_testutil.GatherAndCompare(registry, strings.NewReader(` + # TYPE cortex_compactor_runs_completed_total counter + # HELP cortex_compactor_runs_completed_total Total number of compaction runs successfully completed. + cortex_compactor_runs_completed_total 1 + `), + "cortex_compactor_runs_completed_total", + )) +} + type countingGrouper struct { calls *atomic.Int64 grouper compact.Grouper From 14e836885f0965559154821da18408d1b40f9d90 Mon Sep 17 00:00:00 2001 From: Alex Le Date: Mon, 30 Nov 2026 17:32:08 +0000 Subject: [PATCH 5/5] Compactor: stay in the ring and stop retrying while draining The ring subservices were started with the service context, so the lifecycler left the ring as soon as shutdown started, while the compaction was still draining. With the default sharding strategy, which has no visit markers, another compactor then took over the tenant and compacted the same blocks. Start them with the compaction context instead. stopping() already stops them explicitly, so the instance now leaves the ring once the drain ends. A compaction that failed with a retriable error during the drain was retried on the compaction context. The retry built no groups because of the shutdown gate and returned nil, so the failure was reported as a success. Stop retrying once shutdown has been requested and handle the last error as when retries run out. Signed-off-by: Alex Le --- pkg/compactor/compactor.go | 12 +++- pkg/compactor/compactor_test.go | 118 ++++++++++++++++++++++++++++++++ 2 files changed, 127 insertions(+), 3 deletions(-) diff --git a/pkg/compactor/compactor.go b/pkg/compactor/compactor.go index a3e5aa16e2a..60b64ed7387 100644 --- a/pkg/compactor/compactor.go +++ b/pkg/compactor/compactor.go @@ -674,8 +674,8 @@ func (c *Compactor) starting(ctx context.Context) (err error) { level.Info(c.logger).Log("msg", "compactor started", "duration", time.Since(begin), "duration_ms", time.Since(begin).Milliseconds()) }() - // The TSDB compactor and the GCS token source keep the context they are - // built with, so both are built with the compaction context. + // The TSDB compactor, the GCS token source and the ring lifecycler keep the + // context they are started with, so all three use the compaction context. c.compactionCtx, c.cancelCompaction = compactionContext(ctx, c.compactorCfg.CompactionDrainTimeout) defer func() { if err != nil { @@ -745,7 +745,7 @@ func (c *Compactor) starting(ctx context.Context) (err error) { c.ringSubservicesWatcher = services.NewFailureWatcher() c.ringSubservicesWatcher.WatchManager(c.ringSubservices) - err = services.StartManagerAndAwaitHealthy(ctx, c.ringSubservices) + err = services.StartManagerAndAwaitHealthy(c.compactionCtx, c.ringSubservices) } if err != nil { @@ -1053,6 +1053,12 @@ func (c *Compactor) compactUserWithRetries(ctx, shutdownCtx context.Context, use } c.compactorMetrics.compactionErrorsCount.WithLabelValues(userID, retriableError).Inc() + // Break rather than return, so lastErr is handled as when retries run + // out: a completed or visited partition is not counted as a failure. + if shutdownCtx.Err() != nil { + break + } + retries.Wait() } diff --git a/pkg/compactor/compactor_test.go b/pkg/compactor/compactor_test.go index 9168e51a03c..6ddcdb8274c 100644 --- a/pkg/compactor/compactor_test.go +++ b/pkg/compactor/compactor_test.go @@ -2328,6 +2328,124 @@ func TestCompactor_ShouldNotCancelTheMergeOnShutdownWhenDrainTimeoutIsSet(t *tes )) } +func TestCompactor_ShouldStayInTheRingWhileDraining(t *testing.T) { + bucketClient := objstore.WithNoopInstr(objstore.NewInMemBucket()) + id := ulid.MustNew(ulid.Now(), rand.Reader) + require.NoError(t, bucketClient.Upload(context.Background(), "user-1/"+id.String()+"/meta.json", strings.NewReader(mockBlockMetaJSON(id.String())))) + + b1 := createTSDBBlock(t, bucketClient, "user-1", 10, 20, map[string]string{"__name__": "Teste"}) + b2 := createTSDBBlock(t, bucketClient, "user-1", 20, 30, map[string]string{"__name__": "Teste"}) + + ringStore, closer := consul.NewInMemoryClient(ring.GetCodec(), log.NewNopLogger(), nil) + t.Cleanup(func() { assert.NoError(t, closer.Close()) }) + + cfg := prepareConfig() + cfg.CompactionDrainTimeout = time.Minute + cfg.ShardingEnabled = true + cfg.ShardingRing.InstanceID = "compactor-1" + cfg.ShardingRing.InstanceAddr = "1.2.3.4" + cfg.ShardingRing.KVStore.Mock = ringStore + + c, tsdbCompactor, tsdbPlanner, _, _ := prepare(t, cfg, bucketClient, nil) + + mergeCalled := make(chan struct{}) + releaseMerge := make(chan struct{}) + var once sync.Once + + tsdbCompactor.On("CompactWithBlockPopulator", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]ulid.ULID{}, nil).Run(func(mock.Arguments) { + once.Do(func() { + close(mergeCalled) + <-releaseMerge + }) + }) + tsdbPlanner.On("Plan", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]*metadata.Meta{ + { + ULID: b1, + MinTime: 10, + MaxTime: 20, + Stats: tsdb.BlockStats{NumSamples: 1}, + }, + { + ULID: b2, + MinTime: 20, + MaxTime: 30, + Stats: tsdb.BlockStats{NumSamples: 1}, + }, + }, nil) + + isActive := func() bool { + d, err := ringStore.Get(context.Background(), ringKey) + require.NoError(t, err) + desc, ok := d.(*ring.Desc) + if !ok { + return false + } + instance, ok := desc.Ingesters[cfg.ShardingRing.InstanceID] + return ok && instance.State == ring.ACTIVE + } + + ctx, cancel := context.WithCancel(context.Background()) + require.NoError(t, services.StartAndAwaitRunning(ctx, c)) + + <-mergeCalled + cancel() + + assert.Never(t, func() bool { return !isActive() }, 2*time.Second, 50*time.Millisecond) + + close(releaseMerge) + require.NoError(t, services.StopAndAwaitTerminated(context.Background(), c)) + + assert.False(t, isActive()) +} + +func TestCompactor_ShouldNotRetryAFailedCompactionAfterShutdown(t *testing.T) { + bucketClient := objstore.WithNoopInstr(objstore.NewInMemBucket()) + id := ulid.MustNew(ulid.Now(), rand.Reader) + require.NoError(t, bucketClient.Upload(context.Background(), "user-1/"+id.String()+"/meta.json", strings.NewReader(mockBlockMetaJSON(id.String())))) + + createTSDBBlock(t, bucketClient, "user-1", 10, 20, map[string]string{"__name__": "Teste"}) + createTSDBBlock(t, bucketClient, "user-1", 20, 30, map[string]string{"__name__": "Teste"}) + + cfg := prepareConfig() + cfg.CompactionDrainTimeout = time.Minute + + c, _, tsdbPlanner, _, registry := prepare(t, cfg, bucketClient, nil) + + planCalled := make(chan struct{}) + releasePlan := make(chan struct{}) + var once sync.Once + + // A planning error is retriable, unlike a merge error, which thanos halts on. + tsdbPlanner.On("Plan", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]*metadata.Meta{}, errors.New("plan failed")).Run(func(mock.Arguments) { + once.Do(func() { + close(planCalled) + <-releasePlan + }) + }) + + ctx, cancel := context.WithCancel(context.Background()) + require.NoError(t, services.StartAndAwaitRunning(ctx, c)) + + <-planCalled + cancel() + close(releasePlan) + + require.NoError(t, services.StopAndAwaitTerminated(context.Background(), c)) + + assert.NoError(t, prom_testutil.GatherAndCompare(registry, strings.NewReader(` + # TYPE cortex_compactor_runs_completed_total counter + # HELP cortex_compactor_runs_completed_total Total number of compaction runs successfully completed. + cortex_compactor_runs_completed_total 0 + + # TYPE cortex_compactor_runs_failed_total counter + # HELP cortex_compactor_runs_failed_total Total number of compaction runs failed. + cortex_compactor_runs_failed_total 1 + `), + "cortex_compactor_runs_completed_total", + "cortex_compactor_runs_failed_total", + )) +} + type countingGrouper struct { calls *atomic.Int64 grouper compact.Grouper