diff --git a/service/stovepipe/server/BUILD.bazel b/service/stovepipe/server/BUILD.bazel index bc4fb90a2..3c53b353a 100644 --- a/service/stovepipe/server/BUILD.bazel +++ b/service/stovepipe/server/BUILD.bazel @@ -31,6 +31,7 @@ go_library( "//stovepipe/controller/buildsignal:go_default_library", "//stovepipe/controller/dlq:go_default_library", "//stovepipe/controller/fix:go_default_library", + "//stovepipe/controller/issueagemetrics:go_default_library", "//stovepipe/controller/issuetrack:go_default_library", "//stovepipe/controller/periodicmetrics:go_default_library", "//stovepipe/controller/process:go_default_library", diff --git a/service/stovepipe/server/main.go b/service/stovepipe/server/main.go index d11b20c29..2c9daa1e0 100644 --- a/service/stovepipe/server/main.go +++ b/service/stovepipe/server/main.go @@ -53,6 +53,7 @@ import ( "github.com/uber/submitqueue/stovepipe/controller/buildsignal" "github.com/uber/submitqueue/stovepipe/controller/dlq" "github.com/uber/submitqueue/stovepipe/controller/fix" + "github.com/uber/submitqueue/stovepipe/controller/issueagemetrics" "github.com/uber/submitqueue/stovepipe/controller/issuetrack" "github.com/uber/submitqueue/stovepipe/controller/periodicmetrics" "github.com/uber/submitqueue/stovepipe/controller/process" @@ -368,8 +369,10 @@ func seedPeriodicMetrics(ctx context.Context, registry consumer.TopicRegistry, t defer cancel() for _, queue := range tenants { - if err := periodicmetrics.Schedule(ctx, registry, stovepipemq.TopicKeyQueueHealthMetrics, queue); err != nil { - return fmt.Errorf("schedule metrics for queue %q: %w", queue, err) + for _, key := range []consumer.TopicKey{stovepipemq.TopicKeyQueueHealthMetrics, stovepipemq.TopicKeyIssueAgeMetrics} { + if err := periodicmetrics.Schedule(ctx, registry, key, queue); err != nil { + return fmt.Errorf("schedule %s for queue %q: %w", key, queue, err) + } } } return nil @@ -400,6 +403,15 @@ func registerPrimaryControllers( } count++ + issueAgeController := periodicmetrics.NewController( + logger, issueagemetrics.NewTask(scope, store), + stovepipemq.TopicKeyIssueAgeMetrics, "stovepipe-issueagemetrics", + ) + if err := c.Register(issueAgeController); err != nil { + return count, fmt.Errorf("failed to register issue age metrics controller: %w", err) + } + count++ + processController := process.NewController( logger, scope, @@ -543,6 +555,13 @@ func newTopicRegistry(q extqueue.Queue, subscriberName string) (consumer.TopicRe // The recurring task must survive crashes and failed postponements indefinitely. metricsSubscription.Retry.MaxAttempts = 0 metricsSubscription.DLQ.Enabled = false + + issueAgeSubscription := extqueue.SingleMessageSubscriptionConfig( + subscriberName, "stovepipe-issueagemetrics", + ) + issueAgeSubscription.Retry.MaxAttempts = 0 + issueAgeSubscription.DLQ.Enabled = false + return consumer.NewTopicRegistry([]consumer.TopicConfig{ { Key: stovepipemq.TopicKeyQueueHealthMetrics, @@ -550,6 +569,12 @@ func newTopicRegistry(q extqueue.Queue, subscriberName string) (consumer.TopicRe Queue: q, Subscription: metricsSubscription, }, + { + Key: stovepipemq.TopicKeyIssueAgeMetrics, + Name: "issueagemetrics", + Queue: q, + Subscription: issueAgeSubscription, + }, { Key: stovepipemq.TopicKeyProcess, Name: "process", diff --git a/service/stovepipe/server/main_test.go b/service/stovepipe/server/main_test.go index 5aa1d4adf..1bdf00643 100644 --- a/service/stovepipe/server/main_test.go +++ b/service/stovepipe/server/main_test.go @@ -124,7 +124,7 @@ func TestValidationStagesHaveRecovery(t *testing.T) { _, primary, deadLetter := registeredControllers(t) recoveryKeys := topicKeys(deadLetter) for _, controller := range primary { - if controller.TopicKey() == stovepipemq.TopicKeyQueueHealthMetrics { + if controller.TopicKey() == stovepipemq.TopicKeyQueueHealthMetrics || controller.TopicKey() == stovepipemq.TopicKeyIssueAgeMetrics { continue } t.Run(controller.Name(), func(t *testing.T) { @@ -135,46 +135,54 @@ func TestValidationStagesHaveRecovery(t *testing.T) { func TestMetricsWorkersShareRecurringTask(t *testing.T) { registry, primary, _ := registeredControllers(t) - assert.Contains(t, topicKeys(primary), stovepipemq.TopicKeyQueueHealthMetrics) - topic, ok := registry.TopicName(stovepipemq.TopicKeyQueueHealthMetrics) - require.True(t, ok) - assert.Equal(t, "queuehealthmetrics", topic) - - for _, controller := range primary { - if controller.TopicKey() == stovepipemq.TopicKeyQueueHealthMetrics { - assert.Equal(t, "queuehealthmetrics", controller.Name()) - } - } - - first, ok := registry.SubscriptionConfig(stovepipemq.TopicKeyQueueHealthMetrics, "stovepipe-queuehealthmetrics") - require.True(t, ok) otherRegistry, err := newTopicRegistry(nil, "other-worker") require.NoError(t, err) - second, ok := otherRegistry.SubscriptionConfig(stovepipemq.TopicKeyQueueHealthMetrics, "stovepipe-queuehealthmetrics") - require.True(t, ok) - assert.Equal(t, first.ConsumerGroup, second.ConsumerGroup) - assert.NotEqual(t, first.SubscriberName, second.SubscriberName) - assert.Zero(t, first.Retry.MaxAttempts) - assert.False(t, first.DLQ.Enabled) - assert.Equal(t, 1, first.BatchSize) + for _, key := range []consumer.TopicKey{stovepipemq.TopicKeyQueueHealthMetrics, stovepipemq.TopicKeyIssueAgeMetrics} { + t.Run(key.String(), func(t *testing.T) { + assert.Contains(t, topicKeys(primary), key) + name, ok := registry.TopicName(key) + require.True(t, ok) + assert.Equal(t, key.String(), name) + + group := "stovepipe-" + key.String() + first, ok := registry.SubscriptionConfig(key, group) + require.True(t, ok) + second, ok := otherRegistry.SubscriptionConfig(key, group) + require.True(t, ok) + assert.Equal(t, first.ConsumerGroup, second.ConsumerGroup) + assert.NotEqual(t, first.SubscriberName, second.SubscriberName) + assert.Zero(t, first.Retry.MaxAttempts) + assert.False(t, first.DLQ.Enabled) + assert.Equal(t, 1, first.BatchSize) + }) + } } func TestSeedPeriodicMetricsReturnsWhenQueuePublishStalls(t *testing.T) { - synctest.Test(t, func(t *testing.T) { - ctrl := gomock.NewController(t) - queue := queuemock.NewMockQueue(ctrl) - publisher := queuemock.NewMockPublisher(ctrl) - queue.EXPECT().Publisher().Return(publisher) - publisher.EXPECT().Publish(gomock.Any(), "queuehealthmetrics", gomock.Any()). - DoAndReturn(func(ctx context.Context, _ string, _ entityqueue.Message) error { - <-ctx.Done() - return ctx.Err() + for _, topic := range []string{"queuehealthmetrics", "issueagemetrics"} { + t.Run(topic, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctrl := gomock.NewController(t) + queue := queuemock.NewMockQueue(ctrl) + publisher := queuemock.NewMockPublisher(ctrl) + calls := 1 + if topic == "issueagemetrics" { + calls++ + publisher.EXPECT().Publish(gomock.Any(), "queuehealthmetrics", gomock.Any()).Return(nil) + } + queue.EXPECT().Publisher().Return(publisher).Times(calls) + publisher.EXPECT().Publish(gomock.Any(), topic, gomock.Any()). + DoAndReturn(func(ctx context.Context, _ string, _ entityqueue.Message) error { + <-ctx.Done() + return ctx.Err() + }) + registry, err := newTopicRegistry(queue, "subscriber") + require.NoError(t, err) + + require.ErrorIs(t, seedPeriodicMetrics(context.Background(), registry, []string{"monorepo/main"}), context.DeadlineExceeded) }) - registry, err := newTopicRegistry(queue, "subscriber") - require.NoError(t, err) - - require.ErrorIs(t, seedPeriodicMetrics(context.Background(), registry, []string{"monorepo/main"}), context.DeadlineExceeded) - }) + }) + } } func TestFixRegistration(t *testing.T) { @@ -403,3 +411,25 @@ func TestFakeSourceControlFactorySharesPromotionPerQueue(t *testing.T) { require.NoError(t, err) assert.Empty(t, current) } + +func TestSeedPeriodicMetricsSchedulesBothTasksForEveryQueue(t *testing.T) { + ctrl := gomock.NewController(t) + queue := queuemock.NewMockQueue(ctrl) + publisher := queuemock.NewMockPublisher(ctrl) + queue.EXPECT().Publisher().Return(publisher).Times(4) + for _, topic := range []string{"queuehealthmetrics", "issueagemetrics"} { + for _, tenant := range []string{"first-queue", "second-queue"} { + publisher.EXPECT().Publish(gomock.Any(), topic, gomock.Any()). + DoAndReturn(func(_ context.Context, _ string, message entityqueue.Message) error { + assert.Equal(t, tenant, message.Tenant) + assert.Equal(t, tenant, message.PartitionKey) + assert.Equal(t, topic, message.ID) + return nil + }) + } + } + registry, err := newTopicRegistry(queue, "subscriber") + require.NoError(t, err) + + require.NoError(t, seedPeriodicMetrics(context.Background(), registry, []string{"first-queue", "second-queue"})) +} diff --git a/stovepipe/controller/issueagemetrics/BUILD.bazel b/stovepipe/controller/issueagemetrics/BUILD.bazel new file mode 100644 index 000000000..7f492a5b5 --- /dev/null +++ b/stovepipe/controller/issueagemetrics/BUILD.bazel @@ -0,0 +1,30 @@ +load("@rules_go//go:def.bzl", "go_library", "go_test") + +go_library( + name = "go_default_library", + srcs = ["issueagemetrics.go"], + importpath = "github.com/uber/submitqueue/stovepipe/controller/issueagemetrics", + visibility = ["//visibility:public"], + deps = [ + "//platform/metrics:go_default_library", + "//stovepipe/controller/periodicmetrics:go_default_library", + "//stovepipe/entity:go_default_library", + "//stovepipe/extension/storage:go_default_library", + "@com_github_uber_go_tally//:go_default_library", + ], +) + +go_test( + name = "go_default_test", + srcs = ["issueagemetrics_test.go"], + embed = [":go_default_library"], + deps = [ + "//stovepipe/entity:go_default_library", + "//stovepipe/extension/storage:go_default_library", + "//stovepipe/extension/storage/mock:go_default_library", + "@com_github_stretchr_testify//assert:go_default_library", + "@com_github_stretchr_testify//require:go_default_library", + "@com_github_uber_go_tally//:go_default_library", + "@org_uber_go_mock//gomock:go_default_library", + ], +) diff --git a/stovepipe/controller/issueagemetrics/README.md b/stovepipe/controller/issueagemetrics/README.md new file mode 100644 index 000000000..3777c9620 --- /dev/null +++ b/stovepipe/controller/issueagemetrics/README.md @@ -0,0 +1,47 @@ +# Issue-age metrics + +`NewTask` supplies an issue-age collector to the shared [periodic controller](../periodicmetrics/README.md). It reads issue storage and does not depend on source control or queue-health collection. + +The reference host registers it on topic `issueagemetrics`, in group `stovepipe-issueagemetrics`, and seeds one recurring delivery per queue. Metrics use the `stovepipe.issueagemetrics` prefix and a `queue` tag. + +Each observation scans the queue's open-issue index and validates its entries +against lifecycle summaries. Age starts when the current occurrence opens or +reopens; repeated failure reports do not reset it. An issue remains open until a +resolution is recorded, so its age is not proof of continuous failure or queue +blockage. + +| Gauge | Value | +| --- | --- | +| `open_issues` | Total currently open issues | +| `oldest_open_issue_age_seconds` | Maximum open-issue age in seconds; zero for an empty backlog | +| `open_issues_by_age` | Open-issue count in each mutually exclusive `age_bucket` | +| `issue_snapshot_timestamp_seconds` | Completion time of the last successful full scan, in Unix seconds | + +The three backlog gauges also have `task_`-prefixed versions tagged by `task` +and `scope` (`task` for task-wide issues, `unit` otherwise). The unprefixed +gauges are queue totals: do not add them to their task breakdowns. Unit labels, +build IDs, and request IDs are not metric dimensions. + +Issue-age bands have boundaries at 1m, 5m, 10m, 15m, 30m, 45m, 1h, 2h, 4h, +8h, 12h, 1d, 2d, 7d, 14d, and 30d. Lower bounds are inclusive and +upper bounds exclusive. Labels use Go duration notation, such as +`0s_to_1m0s`, `1m0s_to_5m0s`, and `720h0m0s_plus`. These are snapshot count +gauges, not cumulative histogram observations. + +Every successful scan emits all age bands, including zeros. The worker also +keeps emitting zeros for task/scope combinations it previously observed. +After a worker handoff, a disappearing task's old worker series must age out; +dashboards must use fresh samples rather than carrying old worker values +forward or summing replicas' snapshots. + +Scans are eventually consistent, not transactional snapshots. All ages use +the scan's start time; concurrent changes can appear in the next observation. +A failed or canceled scan publishes no backlog gauges or success timestamp. +Use the success timestamp to detect stale observations rather than treating +missing data as an empty backlog. + +`issue_snapshot.start` counts attempts and `issue_snapshot.finish` records scan +duration and count with `result=success|error|cancel`, following the standard +operation metrics. Storage-factory failures emit `issue_snapshot_storage_errors` +before a scan can start. `issue_timestamp_future` counts opening timestamps +ahead of the sampling clock; their ages are clamped to zero. diff --git a/stovepipe/controller/issueagemetrics/issueagemetrics.go b/stovepipe/controller/issueagemetrics/issueagemetrics.go new file mode 100644 index 000000000..174549e84 --- /dev/null +++ b/stovepipe/controller/issueagemetrics/issueagemetrics.go @@ -0,0 +1,222 @@ +// Copyright (c) 2026 Uber Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package issueagemetrics collects age snapshots of currently open issues. +package issueagemetrics + +import ( + "context" + "fmt" + "sync" + "time" + + "github.com/uber-go/tally" + "github.com/uber/submitqueue/platform/metrics" + "github.com/uber/submitqueue/stovepipe/controller/periodicmetrics" + "github.com/uber/submitqueue/stovepipe/entity" + "github.com/uber/submitqueue/stovepipe/extension/storage" +) + +const ( + _issuePageSize = 200 + _metricsName = "issueagemetrics" +) + +var _issueAgeBuckets = [...]time.Duration{ + time.Minute, + 5 * time.Minute, + 10 * time.Minute, + 15 * time.Minute, + 30 * time.Minute, + 45 * time.Minute, + time.Hour, + 2 * time.Hour, + 4 * time.Hour, + 8 * time.Hour, + 12 * time.Hour, + 24 * time.Hour, + 48 * time.Hour, + 7 * 24 * time.Hour, + 14 * 24 * time.Hour, + 30 * 24 * time.Hour, +} + +type task struct { + scope tally.Scope + stores storage.Factory + now func() time.Time + issueMetricsMu sync.Mutex + issueGroups map[string]map[issueMetricGroup]struct{} +} + +func NewTask(scope tally.Scope, stores storage.Factory) periodicmetrics.Task { + return &task{ + scope: scope, + stores: stores, + now: time.Now, + issueGroups: make(map[string]map[issueMetricGroup]struct{}), + } +} + +func (c *task) Observe(ctx context.Context, queue string) error { + if queue == "" { + return fmt.Errorf("cannot observe an unnamed queue") + } + + stores, err := c.stores.For(storage.Config{QueueName: queue}) + if err != nil { + metrics.NamedCounter(c.scope, _metricsName, "issue_snapshot_storage_errors", 1, metrics.NewTag("queue", queue)) + return fmt.Errorf("resolve issue storage for queue %q: %w", queue, err) + } + return c.observeIssues(ctx, queue, stores) +} + +type issueMetricGroup struct { + task string + scope string +} + +type issueAges struct { + count int + oldest time.Duration + buckets []int +} + +func (a *issueAges) add(age time.Duration) { + if a.buckets == nil { + a.buckets = make([]int, len(_issueAgeBuckets)+1) + } + a.count++ + a.oldest = max(a.oldest, age) + + bucket := 0 + for bucket < len(_issueAgeBuckets) && age >= _issueAgeBuckets[bucket] { + bucket++ + } + a.buckets[bucket]++ +} + +func (c *task) observeIssues(ctx context.Context, queue string, stores storage.Storage) (retErr error) { + queueTag := metrics.NewTag("queue", queue) + op := metrics.Begin(c.scope.SubScope(_metricsName), "issue_snapshot", metrics.StorageLatencyBuckets, queueTag) + defer func() { op.Complete(retErr) }() + + now := c.now() + openIssues := stores.GetOpenIssueStore() + summaries := stores.GetIssueSummaryStore() + bounds := storage.OpenIssueRange{Limit: _issuePageSize} + groups := make(map[issueMetricGroup]*issueAges) + var total issueAges + + for { + if err := ctx.Err(); err != nil { + return err + } + + page, err := openIssues.List(ctx, bounds) + if err != nil { + return fmt.Errorf("list open issues for queue %q: %w", queue, err) + } + + for _, issue := range page { + if err := ctx.Err(); err != nil { + return err + } + + summary, err := summaries.Get(ctx, issue.TaskID, issue.UnitID) + if err != nil { + return fmt.Errorf("read open issue summary for queue %q: %w", queue, err) + } + if summary.TaskID != issue.TaskID || summary.UnitID != issue.UnitID { + return fmt.Errorf("open issue disagrees with summary identity for queue %q", queue) + } + if err := summary.Validate(); err != nil { + return fmt.Errorf("invalid open issue summary for queue %q: %w", queue, err) + } + if summary.Status != entity.IssueStatusOpen || summary.FirstSeenBuildID != issue.FirstSeenBuildID { + continue + } + + age := now.Sub(time.UnixMilli(summary.ChangedAtMs)) + if age < 0 { + metrics.NamedCounter(c.scope, _metricsName, "issue_timestamp_future", 1, queueTag) + age = 0 + } + + group := issueMetricGroup{task: issue.TaskID, scope: "unit"} + if issue.UnitID == "" { + group.scope = "task" + } + if groups[group] == nil { + groups[group] = &issueAges{} + } + groups[group].add(age) + total.add(age) + } + + if len(page) < bounds.Limit { + break + } + last := page[len(page)-1] + bounds.After = storage.OpenIssueCursor{TaskID: last.TaskID, UnitID: last.UnitID} + } + + if err := ctx.Err(); err != nil { + return err + } + + c.issueMetricsMu.Lock() + defer c.issueMetricsMu.Unlock() + + if c.issueGroups[queue] == nil { + c.issueGroups[queue] = make(map[issueMetricGroup]struct{}) + } + for group := range groups { + c.issueGroups[queue][group] = struct{}{} + } + + // Keep zeroing previously seen task series while this worker owns the queue. + for group := range c.issueGroups[queue] { + ages := groups[group] + if ages == nil { + ages = &issueAges{} + } + c.reportIssueAges("task_", *ages, queueTag, + metrics.NewTag("task", group.task), metrics.NewTag("scope", group.scope)) + } + c.reportIssueAges("", total, queueTag) + metrics.NamedGauge(c.scope, _metricsName, "issue_snapshot_timestamp_seconds", float64(c.now().Unix()), queueTag) + return nil +} + +func (c *task) reportIssueAges(prefix string, ages issueAges, tags ...metrics.Tag) { + metrics.NamedGauge(c.scope, _metricsName, prefix+"open_issues", float64(ages.count), tags...) + metrics.NamedGauge(c.scope, _metricsName, prefix+"oldest_open_issue_age_seconds", ages.oldest.Seconds(), tags...) + + lower := time.Duration(0) + for bucket := 0; bucket <= len(_issueAgeBuckets); bucket++ { + label := lower.String() + "_plus" + if bucket < len(_issueAgeBuckets) { + upper := _issueAgeBuckets[bucket] + label = lower.String() + "_to_" + upper.String() + lower = upper + } + count := 0 + if len(ages.buckets) > bucket { + count = ages.buckets[bucket] + } + bucketTags := append([]metrics.Tag{metrics.NewTag("age_bucket", label)}, tags...) + metrics.NamedGauge(c.scope, _metricsName, prefix+"open_issues_by_age", float64(count), bucketTags...) + } +} diff --git a/stovepipe/controller/issueagemetrics/issueagemetrics_test.go b/stovepipe/controller/issueagemetrics/issueagemetrics_test.go new file mode 100644 index 000000000..17e3fbbd3 --- /dev/null +++ b/stovepipe/controller/issueagemetrics/issueagemetrics_test.go @@ -0,0 +1,417 @@ +// Copyright (c) 2026 Uber Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package issueagemetrics + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/uber-go/tally" + "github.com/uber/submitqueue/stovepipe/entity" + "github.com/uber/submitqueue/stovepipe/extension/storage" + storagemock "github.com/uber/submitqueue/stovepipe/extension/storage/mock" + "go.uber.org/mock/gomock" +) + +const ( + _testNowMs = int64(1_700_000_000_123) + _testQueue = "example-queue" + _counterPrefix = "stovepipe.issueagemetrics." + _queueTagSuffix = "+queue=example-queue" +) + +type taskMocks struct { + stores *storagemock.MockFactory + store *storagemock.MockStorage + openIssues *storagemock.MockOpenIssueStore + summaries *storagemock.MockIssueSummaryStore +} + +func newTestTask(t *testing.T, ctrl *gomock.Controller) (*task, taskMocks, tally.TestScope) { + t.Helper() + + m := taskMocks{ + stores: storagemock.NewMockFactory(ctrl), + store: storagemock.NewMockStorage(ctrl), + openIssues: storagemock.NewMockOpenIssueStore(ctrl), + summaries: storagemock.NewMockIssueSummaryStore(ctrl), + } + scope := tally.NewTestScope("stovepipe", nil) + c := NewTask(scope, m.stores).(*task) + c.now = func() time.Time { return time.UnixMilli(_testNowMs) } + return c, m, scope +} + +func TestIssueAgeObserve(t *testing.T) { + t.Parallel() + + t.Run("open issues without queue health dependencies", func(t *testing.T) { + ctrl := gomock.NewController(t) + c, m, scope := newTestTask(t, ctrl) + m.stores.EXPECT().For(storage.Config{QueueName: _testQueue}).Return(m.store, nil) + m.store.EXPECT().GetOpenIssueStore().Return(m.openIssues) + m.store.EXPECT().GetIssueSummaryStore().Return(m.summaries) + expectIssuePage(m, storage.OpenIssueRange{Limit: _issuePageSize}, + []entity.IssueSummary{openIssueSummary("buildtest", "unit", time.Hour)}) + + require.NoError(t, c.Observe(context.Background(), _testQueue)) + assertIssueGauge(t, scope.Snapshot(), "open_issues", 1, nil) + }) + + t.Run("missing queue", func(t *testing.T) { + ctrl := gomock.NewController(t) + c, _, scope := newTestTask(t, ctrl) + require.Error(t, c.Observe(context.Background(), "")) + assert.Empty(t, scope.Snapshot().Gauges()) + }) + + t.Run("storage unavailable", func(t *testing.T) { + ctrl := gomock.NewController(t) + c, m, scope := newTestTask(t, ctrl) + m.stores.EXPECT().For(storage.Config{QueueName: _testQueue}).Return(nil, assert.AnError) + require.ErrorIs(t, c.Observe(context.Background(), _testQueue), assert.AnError) + assert.Empty(t, scope.Snapshot().Gauges()) + assertCounter(t, scope.Snapshot(), "issue_snapshot_storage_errors") + }) +} + +func openIssueSummary(task, unit string, age time.Duration) entity.IssueSummary { + return entity.IssueSummary{ + TaskID: task, UnitID: unit, Status: entity.IssueStatusOpen, + FirstSeenBuildID: "build/1", BuildID: "build/1", RequestID: "1", + ChangedAtMs: time.UnixMilli(_testNowMs).Add(-age).UnixMilli(), Version: 1, + } +} + +func expectIssuePage(m taskMocks, bounds storage.OpenIssueRange, summaries []entity.IssueSummary) { + page := make([]entity.OpenIssue, 0, len(summaries)) + for _, summary := range summaries { + page = append(page, entity.OpenIssue{ + TaskID: summary.TaskID, UnitID: summary.UnitID, FirstSeenBuildID: summary.FirstSeenBuildID, + }) + m.summaries.EXPECT().Get(gomock.Any(), summary.TaskID, summary.UnitID).Return(summary, nil) + } + m.openIssues.EXPECT().List(gomock.Any(), bounds).Return(page, nil) +} + +func assertIssueGauge(t *testing.T, snapshot tally.Snapshot, name string, want float64, tags map[string]string) { + t.Helper() + + tagsWithQueue := map[string]string{"queue": _testQueue} + for key, value := range tags { + tagsWithQueue[key] = value + } + var matches int + for _, gauge := range snapshot.Gauges() { + if gauge.Name() == _counterPrefix+name && assert.ObjectsAreEqual(tagsWithQueue, gauge.Tags()) { + assert.Equal(t, want, gauge.Value(), "%s %v", name, tags) + matches++ + } + } + require.Equal(t, 1, matches, "missing gauge %s %v", name, tags) +} + +func TestObserveIssues_AgeDistribution(t *testing.T) { + t.Parallel() + + ctrl := gomock.NewController(t) + c, m, scope := newTestTask(t, ctrl) + m.store.EXPECT().GetOpenIssueStore().Return(m.openIssues) + m.store.EXPECT().GetIssueSummaryStore().Return(m.summaries) + + var summaries []entity.IssueSummary + ages := []time.Duration{0} + for _, boundary := range _issueAgeBuckets { + ages = append(ages, boundary-time.Millisecond, boundary) + } + ages = append(ages, 60*24*time.Hour) + for i, age := range ages { + summaries = append(summaries, openIssueSummary("buildtest", fmt.Sprintf("unit/%03d", i), age)) + } + summaries = append(summaries, openIssueSummary("buildtest", "", 2*time.Hour)) + expectIssuePage(m, storage.OpenIssueRange{Limit: _issuePageSize}, summaries) + + require.NoError(t, c.observeIssues(context.Background(), _testQueue, m.store)) + + snapshot := scope.Snapshot() + assertIssueGauge(t, snapshot, "open_issues", float64(len(summaries)), nil) + assertIssueGauge(t, snapshot, "oldest_open_issue_age_seconds", (60 * 24 * time.Hour).Seconds(), nil) + assertIssueGauge(t, snapshot, "issue_snapshot_timestamp_seconds", float64(_testNowMs/1000), nil) + assertIssueGauge(t, snapshot, "task_open_issues", float64(len(ages)), + map[string]string{"task": "buildtest", "scope": "unit"}) + assertIssueGauge(t, snapshot, "task_open_issues", 1, + map[string]string{"task": "buildtest", "scope": "task"}) + assertIssueGauge(t, snapshot, "task_oldest_open_issue_age_seconds", (2 * time.Hour).Seconds(), + map[string]string{"task": "buildtest", "scope": "task"}) + + lower := time.Duration(0) + for i := 0; i <= len(_issueAgeBuckets); i++ { + label := lower.String() + "_plus" + want := float64(2) + if i < len(_issueAgeBuckets) { + upper := _issueAgeBuckets[i] + label = lower.String() + "_to_" + upper.String() + if lower == 2*time.Hour { + want++ + } + lower = upper + } + assertIssueGauge(t, snapshot, "open_issues_by_age", want, map[string]string{"age_bucket": label}) + } + + var successCount int64 + for _, histogram := range snapshot.Histograms() { + if histogram.Name() == _counterPrefix+"issue_snapshot.finish" && histogram.Tags()["result"] == "success" { + for _, count := range histogram.Durations() { + successCount += count + } + } + } + assert.EqualValues(t, 1, successCount) +} + +func TestObserveIssues_PaginatesPastStaleEntries(t *testing.T) { + t.Parallel() + + ctrl := gomock.NewController(t) + c, m, scope := newTestTask(t, ctrl) + m.store.EXPECT().GetOpenIssueStore().Return(m.openIssues) + m.store.EXPECT().GetIssueSummaryStore().Return(m.summaries) + + page := make([]entity.OpenIssue, 0, _issuePageSize) + for i := 0; i < _issuePageSize; i++ { + unit := fmt.Sprintf("unit/%03d", i) + page = append(page, entity.OpenIssue{TaskID: "buildtest", UnitID: unit, FirstSeenBuildID: "old"}) + summary := openIssueSummary("buildtest", unit, time.Hour) + if i%2 == 0 { + summary.Status = entity.IssueStatusClosed + } + m.summaries.EXPECT().Get(gomock.Any(), "buildtest", unit).Return(summary, nil) + } + bounds := storage.OpenIssueRange{Limit: _issuePageSize} + m.openIssues.EXPECT().List(gomock.Any(), bounds).Return(page, nil) + + bounds.After = storage.OpenIssueCursor{TaskID: "buildtest", UnitID: "unit/199"} + reopened := openIssueSummary("buildtest", "unit/200", 5*time.Minute) + reopened.FirstSeenBuildID = "build/2" + reopened.BuildID = "build/2" + expectIssuePage(m, bounds, []entity.IssueSummary{reopened}) + + require.NoError(t, c.observeIssues(context.Background(), _testQueue, m.store)) + + assertIssueGauge(t, scope.Snapshot(), "open_issues", 1, nil) + assertIssueGauge(t, scope.Snapshot(), "oldest_open_issue_age_seconds", (5 * time.Minute).Seconds(), nil) +} + +func TestObserveIssues_EmptyBacklogClearsPreviousSeries(t *testing.T) { + t.Parallel() + + ctrl := gomock.NewController(t) + c, m, scope := newTestTask(t, ctrl) + m.store.EXPECT().GetOpenIssueStore().Return(m.openIssues).Times(2) + m.store.EXPECT().GetIssueSummaryStore().Return(m.summaries).Times(2) + + bounds := storage.OpenIssueRange{Limit: _issuePageSize} + first := openIssueSummary("buildtest", "unit", time.Hour) + expectIssuePage(m, bounds, []entity.IssueSummary{first}) + require.NoError(t, c.observeIssues(context.Background(), _testQueue, m.store)) + + m.openIssues.EXPECT().List(gomock.Any(), bounds).Return(nil, nil) + c.now = func() time.Time { return time.UnixMilli(_testNowMs).Add(time.Minute) } + require.NoError(t, c.observeIssues(context.Background(), _testQueue, m.store)) + + snapshot := scope.Snapshot() + for _, gauge := range snapshot.Gauges() { + if gauge.Name() != _counterPrefix+"issue_snapshot_timestamp_seconds" { + assert.Zero(t, gauge.Value(), "%s %v", gauge.Name(), gauge.Tags()) + } + } + assertIssueGauge(t, snapshot, "open_issues", 0, nil) + assertIssueGauge(t, snapshot, "task_open_issues", 0, + map[string]string{"task": "buildtest", "scope": "unit"}) + assertIssueGauge(t, snapshot, "issue_snapshot_timestamp_seconds", float64(_testNowMs/1000+60), nil) +} + +func TestObserveIssues_LaterPageFailureDiscardsCollectedAges(t *testing.T) { + t.Parallel() + + ctrl := gomock.NewController(t) + c, m, scope := newTestTask(t, ctrl) + m.store.EXPECT().GetOpenIssueStore().Return(m.openIssues) + m.store.EXPECT().GetIssueSummaryStore().Return(m.summaries) + + var summaries []entity.IssueSummary + for i := 0; i < _issuePageSize; i++ { + summaries = append(summaries, openIssueSummary("buildtest", fmt.Sprintf("unit/%03d", i), time.Hour)) + } + expectIssuePage(m, storage.OpenIssueRange{Limit: _issuePageSize}, summaries) + m.openIssues.EXPECT().List(gomock.Any(), storage.OpenIssueRange{ + Limit: _issuePageSize, After: storage.OpenIssueCursor{TaskID: "buildtest", UnitID: "unit/199"}, + }).Return(nil, assert.AnError) + + require.ErrorIs(t, c.observeIssues(context.Background(), _testQueue, m.store), assert.AnError) + assert.Empty(t, scope.Snapshot().Gauges()) +} + +func TestObserveIssues_ClockAdvancesWithoutNewReports(t *testing.T) { + t.Parallel() + + ctrl := gomock.NewController(t) + c, m, scope := newTestTask(t, ctrl) + m.store.EXPECT().GetOpenIssueStore().Return(m.openIssues).Times(2) + m.store.EXPECT().GetIssueSummaryStore().Return(m.summaries).Times(2) + summary := openIssueSummary("buildtest", "unit", time.Hour) + for i := 0; i < 2; i++ { + expectIssuePage(m, storage.OpenIssueRange{Limit: _issuePageSize}, []entity.IssueSummary{summary}) + c.now = func() time.Time { return time.UnixMilli(_testNowMs).Add(time.Duration(i) * time.Minute) } + require.NoError(t, c.observeIssues(context.Background(), _testQueue, m.store)) + assertIssueGauge(t, scope.Snapshot(), "oldest_open_issue_age_seconds", (time.Hour + time.Duration(i)*time.Minute).Seconds(), nil) + } +} + +func TestObserveIssues_FutureTimestamp(t *testing.T) { + t.Parallel() + + ctrl := gomock.NewController(t) + c, m, scope := newTestTask(t, ctrl) + m.store.EXPECT().GetOpenIssueStore().Return(m.openIssues) + m.store.EXPECT().GetIssueSummaryStore().Return(m.summaries) + expectIssuePage(m, storage.OpenIssueRange{Limit: _issuePageSize}, + []entity.IssueSummary{openIssueSummary("buildtest", "unit", -time.Minute)}) + + require.NoError(t, c.observeIssues(context.Background(), _testQueue, m.store)) + + assertIssueGauge(t, scope.Snapshot(), "open_issues", 1, nil) + assertIssueGauge(t, scope.Snapshot(), "oldest_open_issue_age_seconds", 0, nil) + assertCounter(t, scope.Snapshot(), "issue_timestamp_future") +} + +func TestObserveIssues_DoesNotPublishPartialSnapshot(t *testing.T) { + t.Parallel() + + for _, test := range []struct { + name string + fail func(context.CancelFunc, taskMocks) + }{ + { + name: "page read fails", + fail: func(_ context.CancelFunc, m taskMocks) { + m.openIssues.EXPECT().List(gomock.Any(), gomock.Any()).Return(nil, assert.AnError) + }, + }, + { + name: "summary read fails", + fail: func(_ context.CancelFunc, m taskMocks) { + m.openIssues.EXPECT().List(gomock.Any(), gomock.Any()).Return( + []entity.OpenIssue{{TaskID: "buildtest", UnitID: "unit"}}, nil) + m.summaries.EXPECT().Get(gomock.Any(), "buildtest", "unit").Return(entity.IssueSummary{}, assert.AnError) + }, + }, + { + name: "summary is missing", + fail: func(_ context.CancelFunc, m taskMocks) { + m.openIssues.EXPECT().List(gomock.Any(), gomock.Any()).Return( + []entity.OpenIssue{{TaskID: "buildtest", UnitID: "unit"}}, nil) + m.summaries.EXPECT().Get(gomock.Any(), "buildtest", "unit").Return(entity.IssueSummary{}, storage.ErrNotFound) + }, + }, + { + name: "summary identity disagrees", + fail: func(_ context.CancelFunc, m taskMocks) { + m.openIssues.EXPECT().List(gomock.Any(), gomock.Any()).Return( + []entity.OpenIssue{{TaskID: "buildtest", UnitID: "unit"}}, nil) + m.summaries.EXPECT().Get(gomock.Any(), "buildtest", "unit"). + Return(openIssueSummary("other", "unit", time.Hour), nil) + }, + }, + { + name: "summary has no timestamp", + fail: func(_ context.CancelFunc, m taskMocks) { + m.openIssues.EXPECT().List(gomock.Any(), gomock.Any()).Return( + []entity.OpenIssue{{TaskID: "buildtest", UnitID: "unit"}}, nil) + summary := openIssueSummary("buildtest", "unit", time.Hour) + summary.ChangedAtMs = 0 + m.summaries.EXPECT().Get(gomock.Any(), "buildtest", "unit").Return(summary, nil) + }, + }, + { + name: "deadline exceeded", + fail: func(_ context.CancelFunc, m taskMocks) { + m.openIssues.EXPECT().List(gomock.Any(), gomock.Any()).Return(nil, context.DeadlineExceeded) + }, + }, + { + name: "canceled after final page", + fail: func(cancel context.CancelFunc, m taskMocks) { + m.openIssues.EXPECT().List(gomock.Any(), gomock.Any()). + DoAndReturn(func(context.Context, storage.OpenIssueRange) ([]entity.OpenIssue, error) { + cancel() + return nil, nil + }) + }, + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + + ctrl := gomock.NewController(t) + c, m, scope := newTestTask(t, ctrl) + m.store.EXPECT().GetOpenIssueStore().Return(m.openIssues).Times(2) + m.store.EXPECT().GetIssueSummaryStore().Return(m.summaries).Times(2) + + expectIssuePage(m, storage.OpenIssueRange{Limit: _issuePageSize}, + []entity.IssueSummary{openIssueSummary("buildtest", "unit", time.Hour)}) + require.NoError(t, c.observeIssues(context.Background(), _testQueue, m.store)) + before := scope.Snapshot().Gauges() + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + test.fail(cancel, m) + c.now = func() time.Time { return time.UnixMilli(_testNowMs).Add(time.Hour) } + require.Error(t, c.observeIssues(ctx, _testQueue, m.store)) + + after := scope.Snapshot() + require.Equal(t, len(before), len(after.Gauges())) + for key, gauge := range before { + assert.Equal(t, gauge.Value(), after.Gauges()[key].Value(), key) + } + }) + } +} + +func TestObserveIssues_AlreadyCanceled(t *testing.T) { + t.Parallel() + + ctrl := gomock.NewController(t) + c, m, scope := newTestTask(t, ctrl) + m.store.EXPECT().GetOpenIssueStore().Return(m.openIssues) + m.store.EXPECT().GetIssueSummaryStore().Return(m.summaries) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + assert.ErrorIs(t, c.observeIssues(ctx, _testQueue, m.store), context.Canceled) + assert.Empty(t, scope.Snapshot().Gauges()) +} + +func assertCounter(t *testing.T, snapshot tally.Snapshot, name string) { + t.Helper() + counter, ok := snapshot.Counters()[_counterPrefix+name+_queueTagSuffix] + require.True(t, ok) + assert.EqualValues(t, 1, counter.Value()) +} diff --git a/stovepipe/controller/periodicmetrics/README.md b/stovepipe/controller/periodicmetrics/README.md index c3308ba8b..4e8e3cd26 100644 --- a/stovepipe/controller/periodicmetrics/README.md +++ b/stovepipe/controller/periodicmetrics/README.md @@ -24,3 +24,7 @@ cancellation returns an error instead. A worker crash can cause a repeat sample. The queue-health task, topic, and message ID are named `queuehealthmetrics`. Its consumer group is `stovepipe-queuehealthmetrics`, and it is partitioned by queue. See [queue-health metrics](../queuehealthmetrics/README.md) for its observations. + +The issue-age task uses topic and message ID `issueagemetrics`, with consumer group +`stovepipe-issueagemetrics`. It is also partitioned by queue, independently within +its own topic. See [issue-age metrics](../issueagemetrics/README.md). diff --git a/stovepipe/controller/periodicmetrics/controller_test.go b/stovepipe/controller/periodicmetrics/controller_test.go index df3427538..4733659ce 100644 --- a/stovepipe/controller/periodicmetrics/controller_test.go +++ b/stovepipe/controller/periodicmetrics/controller_test.go @@ -210,3 +210,30 @@ func metricsDelivery(t *testing.T, ctrl *gomock.Controller) *consumermock.MockDe delivery.EXPECT().Message().Return(entityqueue.Message{Tenant: _testQueue, PartitionKey: _testQueue, Payload: payload}) return delivery } + +func TestScheduleUsesIndependentTopicsAndTaskIdentities(t *testing.T) { + ctrl := gomock.NewController(t) + queue := queuemock.NewMockQueue(ctrl) + publisher := queuemock.NewMockPublisher(ctrl) + queue.EXPECT().Publisher().Return(publisher).Times(2) + published := make(map[string]entityqueue.Message) + publisher.EXPECT().Publish(gomock.Any(), gomock.Any(), gomock.Any()). + DoAndReturn(func(_ context.Context, topic string, message entityqueue.Message) error { + published[topic] = message + return nil + }).Times(2) + registry, err := consumer.NewTopicRegistry([]consumer.TopicConfig{ + {Key: stovepipemq.TopicKeyQueueHealthMetrics, Name: "queuehealthmetrics", Queue: queue}, + {Key: stovepipemq.TopicKeyIssueAgeMetrics, Name: "issueagemetrics", Queue: queue}, + }) + require.NoError(t, err) + for _, key := range []consumer.TopicKey{stovepipemq.TopicKeyQueueHealthMetrics, stovepipemq.TopicKeyIssueAgeMetrics} { + require.NoError(t, Schedule(context.Background(), registry, key, _testQueue)) + } + require.Len(t, published, 2) + assert.NotEqual(t, published["queuehealthmetrics"].ID, published["issueagemetrics"].ID) + for _, message := range published { + assert.Equal(t, _testQueue, message.PartitionKey) + assert.Equal(t, _testQueue, message.Tenant) + } +} diff --git a/stovepipe/core/messagequeue/README.md b/stovepipe/core/messagequeue/README.md index bfa987f66..719fd061a 100644 --- a/stovepipe/core/messagequeue/README.md +++ b/stovepipe/core/messagequeue/README.md @@ -7,6 +7,7 @@ Payloads are defined in proto3 (`proto/`, generated into `protopb/`) and seriali ## Stages - **queuehealthmetrics** (`TopicKeyQueueHealthMetrics`, `PeriodicMetrics`) — a shared periodic trigger delivered to the queue-health task's controller registration. The topic selects the task, and the payload selects the queue. Replicas seed the same identity and hold it between observations. See the [periodic controller](../../controller/periodicmetrics/README.md) and [queue-health task](../../controller/queuehealthmetrics/README.md). +- **issueagemetrics** (`TopicKeyIssueAgeMetrics`, `PeriodicMetrics`) — the same trigger contract on a separate topic, delivered to the issue-age task's independent controller registration. See [issue-age metrics](../../controller/issueagemetrics/README.md). - **process** (`TopicKeyProcess`, `ProcessRequest`) — ingest publishes the minted request id here once it accepts a new head; the process controller reloads the `Request` from storage and decides the build strategy. Only the id travels: producer and consumer share the store, so messages stay small and redelivery is idempotent. - **build** (`TopicKeyBuild`, `BuildRequest`) — process publishes the request id here once its build scope (`BuildStrategy`/`BaseURI`) is decided; the build controller reloads the `Request`, triggers the build, and persists the resulting `Build`. Partitioned by request id. diff --git a/stovepipe/core/messagequeue/messagequeue_test.go b/stovepipe/core/messagequeue/messagequeue_test.go index 7aeb73dfa..533a3fd70 100644 --- a/stovepipe/core/messagequeue/messagequeue_test.go +++ b/stovepipe/core/messagequeue/messagequeue_test.go @@ -90,6 +90,7 @@ func TestTopicKeysBindEveryTopicKey(t *testing.T) { keys := []TopicKey{ TopicKeyQueueHealthMetrics, + TopicKeyIssueAgeMetrics, TopicKeyProcess, TopicKeyBuild, TopicKeyBuildSignal, diff --git a/stovepipe/core/messagequeue/proto/periodicmetrics.proto b/stovepipe/core/messagequeue/proto/periodicmetrics.proto index 25c9a3155..551cf5efc 100644 --- a/stovepipe/core/messagequeue/proto/periodicmetrics.proto +++ b/stovepipe/core/messagequeue/proto/periodicmetrics.proto @@ -27,6 +27,7 @@ option java_package = "com.uber.submitqueue.stovepipe.messagequeue"; // The carrying topic selects the task; the payload is shared scheduling data. message PeriodicMetrics { option (uber.base.messagequeue.topic_keys) = "queuehealthmetrics"; + option (uber.base.messagequeue.topic_keys) = "issueagemetrics"; // queue_name is the queue whose metrics are sampled. string queue_name = 1; diff --git a/stovepipe/core/messagequeue/protopb/periodicmetrics.pb.go b/stovepipe/core/messagequeue/protopb/periodicmetrics.pb.go index e49246f43..85e23d729 100644 --- a/stovepipe/core/messagequeue/protopb/periodicmetrics.pb.go +++ b/stovepipe/core/messagequeue/protopb/periodicmetrics.pb.go @@ -88,10 +88,10 @@ var File_periodicmetrics_proto protoreflect.FileDescriptor const file_periodicmetrics_proto_rawDesc = "" + "\n" + - "\x15periodicmetrics.proto\x12\x1buber.stovepipe.messagequeue\x1a.api/base/messagequeue/proto/messagequeue.proto\"H\n" + + "\x15periodicmetrics.proto\x12\x1buber.stovepipe.messagequeue\x1a.api/base/messagequeue/proto/messagequeue.proto\"[\n" + "\x0fPeriodicMetrics\x12\x1d\n" + "\n" + - "queue_name\x18\x01 \x01(\tR\tqueueName:\x16\x8a\xb5\x18\x12queuehealthmetricsB\x86\x01\n" + + "queue_name\x18\x01 \x01(\tR\tqueueName:)\x8a\xb5\x18\x12queuehealthmetrics\x8a\xb5\x18\x0fissueagemetricsB\x86\x01\n" + "+com.uber.submitqueue.stovepipe.messagequeueB\x14PeriodicMetricsProtoP\x01Z?github.com/uber/submitqueue/stovepipe/core/messagequeue/protopbb\x06proto3" var ( diff --git a/stovepipe/core/messagequeue/topics.go b/stovepipe/core/messagequeue/topics.go index 28812e886..90ec13dff 100644 --- a/stovepipe/core/messagequeue/topics.go +++ b/stovepipe/core/messagequeue/topics.go @@ -26,6 +26,9 @@ const ( // TopicKeyQueueHealthMetrics carries recurring health observations, partitioned by queue. TopicKeyQueueHealthMetrics TopicKey = "queuehealthmetrics" + // TopicKeyIssueAgeMetrics carries recurring issue-age observations, partitioned by queue. + TopicKeyIssueAgeMetrics TopicKey = "issueagemetrics" + // TopicKeyProcess carries newly accepted requests from ingest to the process // stage. ingest publishes a ProcessRequest (the request id) here; the process // controller consumes it, reloads the Request, and decides the build strategy.