Skip to content

Commit d9ba0a5

Browse files
authored
Compactor: add per-time-range backlog metrics and oldest level 1 block (#7959)
* Compactor: add per-time-range backlog metrics and oldest level 1 block Add the time_range_milliseconds label to cortex_compactor_remaining_planned_compactions and cortex_compactor_oldest_partition_offset. Both were summed over every compaction time range, so the smallest range, where a backlog matters soonest, could not be read on its own. Every configured -compactor.block-ranges entry is reported on each run, so a range with nothing outstanding reads zero instead of holding the value from the run that last saw work for it. Per-tenant deletion of the two metrics now matches on the user label alone, because DeleteLabelValues silently does nothing once a vec has two labels. Add cortex_compactor_oldest_level_1_block_offset_seconds, reporting per tenant how long ago the oldest level 1 block still listed in the bucket index was uploaded. cortex_compactor_oldest_partition_offset covers a block only once it has been planned into a partition group, so a block that is never planned is invisible to it. Blocks marked for deletion or for no compaction are excluded, and upload time is used rather than the block's own time range so that late or backfilled samples do not read as a backlog. The bucket index entry carries the block's compaction level to support this. Entries are copied forward rather than re-read from meta.json, so an entry written before the field existed reports an unknown level and is skipped. UpdateIndex returns the set of blocks marked for no compaction, which the index does not carry, in place of the count that was derived from the same listing. Signed-off-by: Alex Le <leqiyue@amazon.com> * Compactor: reference the PR number in the CHANGELOG entries Signed-off-by: Alex Le <leqiyue@amazon.com> --------- Signed-off-by: Alex Le <leqiyue@amazon.com>
1 parent 1df15b8 commit d9ba0a5

11 files changed

Lines changed: 266 additions & 91 deletions

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
## master / unreleased
44

55
* [CHANGE] Ingester: Make `close_idle_tsdb_timeout` a per-tenant limit (`-limits.close-idle-tsdb-timeout`). `-blocks-storage.tsdb.close-idle-tsdb-timeout` is deprecated and will be removed in v1.24.0. A positive `close_idle_tsdb_timeout` must now be at least `query_store_after` when `query_ingesters_within` is 0. #7813
6+
* [CHANGE] Compactor: Add the `time_range_milliseconds` label to `cortex_compactor_remaining_planned_compactions` and `cortex_compactor_oldest_partition_offset`, reporting them per compaction time range instead of summed over all of them. #7959
67
* [FEATURE] Ruler: Add experimental support for federated rule groups. A rule group listing tenants in its `source_tenants` field is evaluated against those tenants while the resulting series and alerts are written to the tenant owning the rule group. Enabled with `-ruler.enable-federated-rules` (requires `-tenant-federation.enabled`), and restricted to selected tenants with `-ruler.allowed-federated-tenants` and `-ruler.disallowed-federated-tenants`. #7828
78
* [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
89
* [FEATURE] Storage: Add support for Alibaba Cloud OSS as a backend for blocks, ruler, and alertmanager storage. Configured via `-<prefix>.oss.*` flags with `backend: oss`. #7907
@@ -24,6 +25,7 @@
2425
* [ENHANCEMENT] Querier: Add `-querier.pool-iterator-batches-buf` flag to pool mergeIterator scratch buffers via sync.Pool, reducing per-iterator memory allocation. #7765
2526
* [ENHANCEMENT] Upgrade promql-engine to latest. #7841
2627
* [ENHANCEMENT] Ruler: Add new limit `-ruler.list-rules-max-rules` on the total number of rules returned by the Prometheus ListRules API. Responses exceeding the limit are truncated on a rule group boundary and return a `groupNextToken` for retrieving the remaining groups. A rule group is never split, so a single group larger than the limit is still returned whole. Defaults to 0, which is unlimited. #7785
28+
* [ENHANCEMENT] Compactor: Add the `cortex_compactor_oldest_level_1_block_offset_seconds` metric, reporting per tenant how long ago the oldest level 1 block still listed in the bucket index was uploaded. Blocks marked for deletion or for no compaction are excluded. The bucket index entry now carries the block's compaction level; an entry written before this reports an unknown level and is skipped. #7959
2729
* [BUGFIX] Update prometheus alertmanager version to v0.34.1 to apply upstream inhibit rule bug fixes. #7877
2830
* [BUGFIX] Tenant Federation: Fix regex tenant federation not working in single binary mode, and failing with `multiple org IDs present` when a matched tenant ID contains regex metacharacters and also matches other tenants as a regex. #7869
2931
* [BUGFIX] Query Frontend: Fix the data selection time window computed for an instant query sent without a `time` parameter. The default evaluation time was passed to `util.ParseTimeParam` in milliseconds, but that helper formats the default and parses it as seconds, so the value overflowed `UnixNano()` and wrapped to a timestamp decades away from `now`. This made the `data_select_min_time` and `data_select_max_time` query stats wrong, and stopped the `time_window` query attribute of query priority and query rejection from matching such queries correctly. #7880

‎docs/guides/partitioning-compactor.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,6 @@ Note: `compactor.partition-series-count` is using sum of series count of all par
4747
- `cortex_compactor_group_partition_count`: can be used to keep track of how many partitions being compacted for each time range.
4848
- `cortex_compactor_group_compactions_not_planned_total`: can be used to alarm any compaction was failed to be planned due to error.
4949
- `cortex_compact_group_compaction_duration_seconds`: can be used to monitor compaction duration of each time range compactions.
50-
- `cortex_compactor_oldest_partition_offset`: can be used to monitor when was the oldest compaction that is still not completed.
50+
- `cortex_compactor_oldest_partition_offset`: can be used to monitor when was the oldest compaction that is still not completed. The `time_range_milliseconds` label is the compaction time range, so an alert can target one range on its own.
51+
- `cortex_compactor_remaining_planned_compactions`: can be used to monitor the compaction backlog, per compaction time range in the `time_range_milliseconds` label.
52+
- `cortex_compactor_oldest_level_1_block_offset_seconds`: can be used to monitor how long the oldest block the ingesters uploaded has been waiting for the smallest range compaction, whether or not it has been planned into a partition group. A block marked for deletion or for no compaction is not counted.

‎pkg/compactor/blocks_cleaner.go‎

Lines changed: 73 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ type BlocksCleaner struct {
8585
remainingPlannedCompactions *prometheus.GaugeVec
8686
inProgressCompactions *prometheus.GaugeVec
8787
oldestPartitionGroupOffset *prometheus.GaugeVec
88+
oldestLevel1BlockOffset *prometheus.GaugeVec
8889
enqueueJobFailed *prometheus.CounterVec
8990
}
9091

@@ -112,8 +113,8 @@ func NewBlocksCleaner(
112113
}, commonLabels)
113114
oldestPartitionGroupOffset = promauto.With(reg).NewGaugeVec(prometheus.GaugeOpts{
114115
Name: "cortex_compactor_oldest_partition_offset",
115-
Help: "Time in seconds between now and the oldest created partition group not completed. Only available with shuffle-sharding strategy and partitioning compaction strategy",
116-
}, commonLabels)
116+
Help: "Time in seconds between now and the oldest created partition group not completed, per compaction time range. Only available with shuffle-sharding strategy and partitioning compaction strategy",
117+
}, append(commonLabels, compactionLabels...))
117118
}
118119

119120
c := &BlocksCleaner{
@@ -194,6 +195,10 @@ func NewBlocksCleaner(
194195
remainingPlannedCompactions: remainingPlannedCompactions,
195196
inProgressCompactions: inProgressCompactions,
196197
oldestPartitionGroupOffset: oldestPartitionGroupOffset,
198+
oldestLevel1BlockOffset: promauto.With(reg).NewGaugeVec(prometheus.GaugeOpts{
199+
Name: "cortex_compactor_oldest_level_1_block_offset_seconds",
200+
Help: "Time in seconds between now and the upload time of the oldest level 1 block still listed in the tenant's bucket index, excluding blocks marked for deletion. 0 when the tenant has no such block.",
201+
}, commonLabels),
197202
enqueueJobFailed: promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
198203
Name: "cortex_compactor_enqueue_cleaner_job_failed_total",
199204
Help: "Total number of cleaner jobs failed to be enqueued.",
@@ -457,11 +462,13 @@ func (c *BlocksCleaner) deleteUserMetrics(userID string) {
457462
c.tenantBlocksMarkedForNoCompaction.DeleteLabelValues(userID)
458463
c.tenantPartialBlocks.DeleteLabelValues(userID)
459464
c.tenantBucketIndexLastUpdate.DeleteLabelValues(userID)
465+
c.oldestLevel1BlockOffset.DeleteLabelValues(userID)
460466
if c.cfg.ShardingStrategy == util.ShardingStrategyShuffle {
461-
c.remainingPlannedCompactions.DeleteLabelValues(userID)
467+
// Both vecs carry a time range label, so the user has to be matched on its own.
468+
c.remainingPlannedCompactions.DeletePartialMatch(prometheus.Labels{userLabelName: userID})
462469
if c.cfg.CompactionStrategy == util.CompactionStrategyPartitioning {
463470
c.inProgressCompactions.DeleteLabelValues(userID)
464-
c.oldestPartitionGroupOffset.DeleteLabelValues(userID)
471+
c.oldestPartitionGroupOffset.DeletePartialMatch(prometheus.Labels{userLabelName: userID})
465472
}
466473
}
467474
}
@@ -716,7 +723,7 @@ func (c *BlocksCleaner) cleanUser(ctx context.Context, userLogger log.Logger, us
716723
w.EnableParquet()
717724
}
718725

719-
idx, partials, totalBlocksBlocksMarkedForNoCompaction, err := w.UpdateIndex(ctx, idx)
726+
idx, partials, blocksMarkedForNoCompaction, err := w.UpdateIndex(ctx, idx)
720727
if err != nil {
721728
idxs.Status = bucketindex.GenericError
722729
return err
@@ -781,16 +788,17 @@ func (c *BlocksCleaner) cleanUser(ctx context.Context, userLogger log.Logger, us
781788
}
782789
level.Info(userLogger).Log("msg", "finish writing new index", "duration", time.Since(begin), "duration_ms", time.Since(begin).Milliseconds())
783790
}
784-
c.updateBucketMetrics(userID, parquetEnabled, idx, float64(len(partials)), float64(totalBlocksBlocksMarkedForNoCompaction))
791+
c.updateBucketMetrics(userID, parquetEnabled, idx, float64(len(partials)), blocksMarkedForNoCompaction)
785792
return nil
786793
}
787794

788-
func (c *BlocksCleaner) updateBucketMetrics(userID string, parquetEnabled bool, idx *bucketindex.Index, partials, totalBlocksBlocksMarkedForNoCompaction float64) {
795+
func (c *BlocksCleaner) updateBucketMetrics(userID string, parquetEnabled bool, idx *bucketindex.Index, partials float64, blocksMarkedForNoCompaction map[ulid.ULID]struct{}) {
789796
c.tenantBlocks.WithLabelValues(userID).Set(float64(len(idx.Blocks)))
790797
c.tenantBlocksMarkedForDelete.WithLabelValues(userID).Set(float64(len(idx.BlockDeletionMarks)))
791-
c.tenantBlocksMarkedForNoCompaction.WithLabelValues(userID).Set(totalBlocksBlocksMarkedForNoCompaction)
798+
c.tenantBlocksMarkedForNoCompaction.WithLabelValues(userID).Set(float64(len(blocksMarkedForNoCompaction)))
792799
c.tenantPartialBlocks.WithLabelValues(userID).Set(float64(partials))
793800
c.tenantBucketIndexLastUpdate.WithLabelValues(userID).SetToCurrentTime()
801+
c.oldestLevel1BlockOffset.WithLabelValues(userID).Set(oldestLevel1BlockOffsetSeconds(idx, blocksMarkedForNoCompaction, time.Now()))
794802
if parquetEnabled {
795803
c.tenantParquetBlocks.WithLabelValues(userID).Set(float64(len(idx.ParquetBlocks())))
796804
remainingBlocksToConvert := 0
@@ -803,6 +811,40 @@ func (c *BlocksCleaner) updateBucketMetrics(userID string, parquetEnabled bool,
803811
}
804812
}
805813

814+
// oldestLevel1BlockOffsetSeconds returns how long ago the oldest level 1 block still listed
815+
// in the bucket index was uploaded, or 0 if there is none. A block marked for deletion has
816+
// already been compacted and one marked for no compaction never will be, so neither says
817+
// anything about whether compaction is keeping up. Upload time is used rather than the
818+
// block's own time range so that late or backfilled samples do not read as a backlog. An
819+
// entry written before the index carried a compaction level reports 0 and is skipped.
820+
func oldestLevel1BlockOffsetSeconds(idx *bucketindex.Index, blocksMarkedForNoCompaction map[ulid.ULID]struct{}, now time.Time) float64 {
821+
markedForDeletion := make(map[ulid.ULID]struct{}, len(idx.BlockDeletionMarks))
822+
for _, mark := range idx.BlockDeletionMarks {
823+
markedForDeletion[mark.ID] = struct{}{}
824+
}
825+
826+
oldestUploadedAt := int64(0)
827+
for _, b := range idx.Blocks {
828+
if b.CompactionLevel != 1 {
829+
continue
830+
}
831+
if _, deleted := markedForDeletion[b.ID]; deleted {
832+
continue
833+
}
834+
if _, noCompact := blocksMarkedForNoCompaction[b.ID]; noCompact {
835+
continue
836+
}
837+
if oldestUploadedAt == 0 || b.UploadedAt < oldestUploadedAt {
838+
oldestUploadedAt = b.UploadedAt
839+
}
840+
}
841+
842+
if oldestUploadedAt == 0 {
843+
return 0
844+
}
845+
return float64(now.Unix() - oldestUploadedAt)
846+
}
847+
806848
func (c *BlocksCleaner) cleanPartitionedGroupInfo(ctx context.Context, userBucket objstore.InstrumentedBucket, userLogger log.Logger, userID string) {
807849
existentPartitionedGroupInfo, err := c.iterPartitionGroups(ctx, userBucket, userLogger)
808850
if err != nil {
@@ -883,24 +925,36 @@ func (c *BlocksCleaner) emitUserPartitionMetrics(ctx context.Context, userLogger
883925
return
884926
}
885927

886-
remainingCompactions := 0
928+
// Every configured range is reported so one with nothing outstanding reads zero instead
929+
// of holding its last value.
930+
remainingCompactions := make(map[int64]int)
931+
oldestPartitionGroup := make(map[int64]*PartitionedGroupInfo)
932+
for _, timeRange := range c.cfg.BlockRanges {
933+
remainingCompactions[timeRange] = 0
934+
oldestPartitionGroup[timeRange] = nil
935+
}
887936
inProgressCompactions := 0
888-
var oldestPartitionGroup *PartitionedGroupInfo
889937
defer func() {
890-
c.remainingPlannedCompactions.WithLabelValues(userID).Set(float64(remainingCompactions))
891938
c.inProgressCompactions.WithLabelValues(userID).Set(float64(inProgressCompactions))
892-
if oldestPartitionGroup != nil {
893-
c.oldestPartitionGroupOffset.WithLabelValues(userID).Set(float64(time.Now().Unix() - oldestPartitionGroup.CreationTime))
894-
level.Debug(userLogger).Log("msg", "partition group info with oldest creation time", "partitioned_group_id", oldestPartitionGroup.PartitionedGroupID, "creation_time", oldestPartitionGroup.CreationTimeString())
895-
} else {
896-
c.oldestPartitionGroupOffset.WithLabelValues(userID).Set(0)
939+
for timeRange, count := range remainingCompactions {
940+
c.remainingPlannedCompactions.WithLabelValues(userID, timeRangeLabelValue(timeRange)).Set(float64(count))
941+
}
942+
for timeRange, group := range oldestPartitionGroup {
943+
timeRangeLabel := timeRangeLabelValue(timeRange)
944+
if group == nil {
945+
c.oldestPartitionGroupOffset.WithLabelValues(userID, timeRangeLabel).Set(0)
946+
continue
947+
}
948+
c.oldestPartitionGroupOffset.WithLabelValues(userID, timeRangeLabel).Set(float64(time.Now().Unix() - group.CreationTime))
949+
level.Debug(userLogger).Log("msg", "partition group info with oldest creation time", "time_range", timeRange, "partitioned_group_id", group.PartitionedGroupID, "creation_time", group.CreationTimeString())
897950
}
898951
}()
899952
for partitionedGroupInfo, extraInfo := range existentPartitionedGroupInfo {
900-
remainingCompactions += extraInfo.status.PendingPartitions
953+
timeRange := partitionedGroupInfo.RangeEnd - partitionedGroupInfo.RangeStart
954+
remainingCompactions[timeRange] += extraInfo.status.PendingPartitions
901955
inProgressCompactions += extraInfo.status.InProgressPartitions
902-
if oldestPartitionGroup == nil || partitionedGroupInfo.CreationTime < oldestPartitionGroup.CreationTime {
903-
oldestPartitionGroup = partitionedGroupInfo
956+
if oldest := oldestPartitionGroup[timeRange]; oldest == nil || partitionedGroupInfo.CreationTime < oldest.CreationTime {
957+
oldestPartitionGroup[timeRange] = partitionedGroupInfo
904958
}
905959
}
906960
}

0 commit comments

Comments
 (0)