diff --git a/submitqueue/core/messagequeue/topics.go b/submitqueue/core/messagequeue/topics.go index a2bb0e5e6..310ce0d0c 100644 --- a/submitqueue/core/messagequeue/topics.go +++ b/submitqueue/core/messagequeue/topics.go @@ -59,3 +59,7 @@ const ( // speculate) on the conclude publish and read by conclude to stamp the request's // terminal log; absent on the landed and cancelled paths. const MetadataKeyFailureReason = "failure_reason" + +// MetadataKeyFailureCategory is the conclude message's metadata attribute carrying +// a failed batch's entity.FailureCategory, set and read beside MetadataKeyFailureReason. +const MetadataKeyFailureCategory = "failure_category" diff --git a/submitqueue/core/topickey/topickey.go b/submitqueue/core/topickey/topickey.go index e7fbf92a4..c9f0afdf5 100644 --- a/submitqueue/core/topickey/topickey.go +++ b/submitqueue/core/topickey/topickey.go @@ -47,4 +47,6 @@ const ( TopicKeyLog = messagequeue.TopicKeyLog // MetadataKeyFailureReason is the conclude message metadata attribute for a failed batch's reason. MetadataKeyFailureReason = messagequeue.MetadataKeyFailureReason + // MetadataKeyFailureCategory is the conclude message metadata attribute for a failed batch's failure category. + MetadataKeyFailureCategory = messagequeue.MetadataKeyFailureCategory ) diff --git a/submitqueue/entity/BUILD.bazel b/submitqueue/entity/BUILD.bazel index 6e1561ab1..8659ab566 100644 --- a/submitqueue/entity/BUILD.bazel +++ b/submitqueue/entity/BUILD.bazel @@ -11,6 +11,7 @@ go_library( "change_provider.go", "change_record.go", "conflict.go", + "failure_category.go", "land.go", "list.go", "path_build.go", @@ -40,6 +41,7 @@ go_test( srcs = [ "batch_test.go", "build_test.go", + "failure_category_test.go", "request_log_test.go", "request_test.go", "speculation_test.go", diff --git a/submitqueue/entity/failure_category.go b/submitqueue/entity/failure_category.go new file mode 100644 index 000000000..980740436 --- /dev/null +++ b/submitqueue/entity/failure_category.go @@ -0,0 +1,53 @@ +// Copyright (c) 2025 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 entity + +// FailureCategory is the kind of failure that ended a request in error, as a +// user would act on it. The empty value means the failure was not classified. +type FailureCategory string + +const ( + // FailureCategoryUnknown means the failure was not classified. + FailureCategoryUnknown FailureCategory = "" + // FailureCategoryDuplicate means another in-flight request already holds one of the request's changes. + FailureCategoryDuplicate FailureCategory = "duplicate" + // FailureCategoryValidationRejected means a validation rule rejected the request. + FailureCategoryValidationRejected FailureCategory = "validation_rejected" + // FailureCategoryBuildFailed means no build that could land the request passed. + FailureCategoryBuildFailed FailureCategory = "build_failed" + // FailureCategoryLandFailed means merging the request into the target branch failed or was refused, + // whether by a conflict or another merge failure. + FailureCategoryLandFailed FailureCategory = "land_failed" + // FailureCategoryInternalError means SubmitQueue itself could not finish processing the request. + FailureCategoryInternalError FailureCategory = "internal_error" +) + +// RequestLogMetadataKeyFailureCategory is the request log metadata key holding an +// error status's FailureCategory. It is absent when the failure was not classified. +const RequestLogMetadataKeyFailureCategory = "failure_category" + +// FailureCategoryMetadata returns metadata with category recorded under +// RequestLogMetadataKeyFailureCategory, leaving metadata itself unchanged. An +// unknown category records nothing. +func FailureCategoryMetadata(metadata map[string]string, category FailureCategory) map[string]string { + withCategory := make(map[string]string, len(metadata)+1) + for key, value := range metadata { + withCategory[key] = value + } + if category != FailureCategoryUnknown { + withCategory[RequestLogMetadataKeyFailureCategory] = string(category) + } + return withCategory +} diff --git a/submitqueue/entity/failure_category_test.go b/submitqueue/entity/failure_category_test.go new file mode 100644 index 000000000..5cde40afd --- /dev/null +++ b/submitqueue/entity/failure_category_test.go @@ -0,0 +1,47 @@ +// Copyright (c) 2025 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 entity + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestFailureCategoryMetadata(t *testing.T) { + tests := []struct { + name string + metadata map[string]string + category FailureCategory + want map[string]string + }{ + {name: "no metadata", category: FailureCategoryBuildFailed, want: map[string]string{RequestLogMetadataKeyFailureCategory: "build_failed"}}, + {name: "adds to existing metadata", metadata: map[string]string{"batch_id": "b1"}, category: FailureCategoryLandFailed, want: map[string]string{"batch_id": "b1", RequestLogMetadataKeyFailureCategory: "land_failed"}}, + {name: "unknown category records nothing", metadata: map[string]string{"batch_id": "b1"}, want: map[string]string{"batch_id": "b1"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + original := map[string]string{} + for key, value := range tt.metadata { + original[key] = value + } + + assert.Equal(t, tt.want, FailureCategoryMetadata(tt.metadata, tt.category)) + if tt.metadata != nil { + assert.Equal(t, original, tt.metadata) + } + }) + } +} diff --git a/submitqueue/orchestrator/controller/conclude/BUILD.bazel b/submitqueue/orchestrator/controller/conclude/BUILD.bazel index 5bafcd6e2..023e79266 100644 --- a/submitqueue/orchestrator/controller/conclude/BUILD.bazel +++ b/submitqueue/orchestrator/controller/conclude/BUILD.bazel @@ -11,6 +11,7 @@ go_library( "//platform/metrics:go_default_library", "//submitqueue/core/messagequeue:go_default_library", "//submitqueue/core/topickey:go_default_library", + "//submitqueue/entity:go_default_library", "//submitqueue/orchestrator/core/batch:go_default_library", "//submitqueue/orchestrator/extension/storage:go_default_library", "@com_github_uber_go_tally//:go_default_library", diff --git a/submitqueue/orchestrator/controller/conclude/conclude.go b/submitqueue/orchestrator/controller/conclude/conclude.go index 99ff68f56..91e6c4a92 100644 --- a/submitqueue/orchestrator/controller/conclude/conclude.go +++ b/submitqueue/orchestrator/controller/conclude/conclude.go @@ -24,6 +24,7 @@ import ( "github.com/uber/submitqueue/platform/metrics" sqmq "github.com/uber/submitqueue/submitqueue/core/messagequeue" "github.com/uber/submitqueue/submitqueue/core/topickey" + "github.com/uber/submitqueue/submitqueue/entity" corebatch "github.com/uber/submitqueue/submitqueue/orchestrator/core/batch" orchstorage "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage" "go.uber.org/zap" @@ -108,7 +109,7 @@ func (c *Controller) Process(ctx context.Context, delivery consumer.Delivery) er "partition_key", msg.PartitionKey, ) - return corebatch.ConcludeBatchRequests(ctx, store, c.registry, c.logger, c.metricsScope, batch, msg.Metadata[topickey.MetadataKeyFailureReason]) + return corebatch.ConcludeBatchRequests(ctx, store, c.registry, c.logger, c.metricsScope, batch, msg.Metadata[topickey.MetadataKeyFailureReason], entity.FailureCategory(msg.Metadata[topickey.MetadataKeyFailureCategory])) } // Name returns the controller name for logging and metrics. diff --git a/submitqueue/orchestrator/controller/conclude/conclude_test.go b/submitqueue/orchestrator/controller/conclude/conclude_test.go index 62d1cb162..1ac097a92 100644 --- a/submitqueue/orchestrator/controller/conclude/conclude_test.go +++ b/submitqueue/orchestrator/controller/conclude/conclude_test.go @@ -501,7 +501,7 @@ func TestController_Process_FailedBatchCarriesReasonToRequestLog(t *testing.T) { }, ) - msg := entityqueue.NewMessage(batch.ID, batchIDPayload(t, batch.ID), batch.Queue, map[string]string{topickey.MetadataKeyFailureReason: reason}) + msg := entityqueue.NewMessage(batch.ID, batchIDPayload(t, batch.ID), batch.Queue, map[string]string{topickey.MetadataKeyFailureReason: reason, topickey.MetadataKeyFailureCategory: string(entity.FailureCategoryBuildFailed)}) msg.Tenant = batch.Queue delivery := consumermock.NewMockDelivery(ctrl) delivery.EXPECT().Message().Return(msg).AnyTimes() @@ -511,6 +511,7 @@ func TestController_Process_FailedBatchCarriesReasonToRequestLog(t *testing.T) { assert.Equal(t, entity.RequestStatusError, logged.Status) assert.Equal(t, reason, logged.LastError) + assert.Equal(t, string(entity.FailureCategoryBuildFailed), logged.Metadata[entity.RequestLogMetadataKeyFailureCategory]) } func TestController_Process_StorageFailure(t *testing.T) { diff --git a/submitqueue/orchestrator/controller/dlq/README.md b/submitqueue/orchestrator/controller/dlq/README.md index f28c50593..23545a6d2 100644 --- a/submitqueue/orchestrator/controller/dlq/README.md +++ b/submitqueue/orchestrator/controller/dlq/README.md @@ -22,7 +22,7 @@ When the Request is absent, Start reports the failed submission through an Error Conclude repairs terminal queue membership before fan-out and never changes the batch state. Every non-terminal state, including Landing, returns an error, as do missing records and invalid payload identities. The same final delivery retries until member writes and log publication complete; it does not republish a fresh conclude message. -Newly failed members use the original message’s `failure_reason` metadata, not a later DLQ infrastructure error. Newly landed or cancelled members carry no LastError. Already-matching terminal members repair their status logs; a different terminal winner is logged and preserved without overwriting it. Queue-wide dependent reconsideration is outside conclusion’s fan-out contract. +Newly failed members use the original message’s `failure_reason` and `failure_category` metadata, not a later DLQ infrastructure error. Every other reconciler classifies the request it fails as `internal_error`. Newly landed or cancelled members carry no LastError. Already-matching terminal members repair their status logs; a different terminal winner is logged and preserved without overwriting it. Queue-wide dependent reconsideration is outside conclusion’s fan-out contract. ## Terminal outputs and ownership diff --git a/submitqueue/orchestrator/controller/dlq/conclude.go b/submitqueue/orchestrator/controller/dlq/conclude.go index 32de63bd3..b42b39f0e 100644 --- a/submitqueue/orchestrator/controller/dlq/conclude.go +++ b/submitqueue/orchestrator/controller/dlq/conclude.go @@ -23,6 +23,7 @@ import ( "github.com/uber/submitqueue/platform/consumer" sqmq "github.com/uber/submitqueue/submitqueue/core/messagequeue" "github.com/uber/submitqueue/submitqueue/core/topickey" + "github.com/uber/submitqueue/submitqueue/entity" corebatch "github.com/uber/submitqueue/submitqueue/orchestrator/core/batch" orchstorage "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage" "go.uber.org/zap" @@ -76,7 +77,7 @@ func (c *concludeController) Process(ctx context.Context, delivery consumer.Deli if err := corebatch.EnsureRecord(ctx, store, batch); err != nil { return err } - return corebatch.ConcludeBatchRequests(ctx, store, c.registry, c.logger, c.metricsScope, batch, msg.Metadata[topickey.MetadataKeyFailureReason]) + return corebatch.ConcludeBatchRequests(ctx, store, c.registry, c.logger, c.metricsScope, batch, msg.Metadata[topickey.MetadataKeyFailureReason], entity.FailureCategory(msg.Metadata[topickey.MetadataKeyFailureCategory])) } func (c *concludeController) Name() string { return string(c.topicKey) } diff --git a/submitqueue/orchestrator/controller/dlq/conclude_test.go b/submitqueue/orchestrator/controller/dlq/conclude_test.go index bd84c2a78..d46731df6 100644 --- a/submitqueue/orchestrator/controller/dlq/conclude_test.go +++ b/submitqueue/orchestrator/controller/dlq/conclude_test.go @@ -37,7 +37,7 @@ func concludeDelivery(t *testing.T, ctrl *gomock.Controller, reason string) cons t.Helper() payload, err := sqmq.MarshalID(sqmq.TopicKeyConclude, "9", "q") require.NoError(t, err) - message := queue.NewMessage("conclude", payload, "q", map[string]string{topickey.MetadataKeyFailureReason: reason}) + message := queue.NewMessage("conclude", payload, "q", map[string]string{topickey.MetadataKeyFailureReason: reason, topickey.MetadataKeyFailureCategory: string(entity.FailureCategoryLandFailed)}) message.Tenant = "q" delivery := consumermock.NewMockDelivery(ctrl) delivery.EXPECT().Message().Return(message).AnyTimes() @@ -51,10 +51,11 @@ func TestDLQConcludeController_TerminalOutcomes(t *testing.T) { requestState entity.RequestState status entity.RequestStatus lastError string + category entity.FailureCategory }{ - {entity.BatchStateSucceeded, entity.RequestStateLanded, entity.RequestStatusLanded, ""}, - {entity.BatchStateFailed, entity.RequestStateError, entity.RequestStatusError, "merge conflict"}, - {entity.BatchStateCancelled, entity.RequestStateCancelled, entity.RequestStatusCancelled, ""}, + {entity.BatchStateSucceeded, entity.RequestStateLanded, entity.RequestStatusLanded, "", entity.FailureCategoryUnknown}, + {entity.BatchStateFailed, entity.RequestStateError, entity.RequestStatusError, "merge conflict", entity.FailureCategoryLandFailed}, + {entity.BatchStateCancelled, entity.RequestStateCancelled, entity.RequestStatusCancelled, "", entity.FailureCategoryUnknown}, } { t.Run(string(tt.batchState), func(t *testing.T) { ctrl := gomock.NewController(t) @@ -75,6 +76,7 @@ func TestDLQConcludeController_TerminalOutcomes(t *testing.T) { assert.Equal(t, tt.status, log.Status) assert.Equal(t, tt.lastError, log.LastError) assert.Equal(t, "9", log.Metadata["batch_id"]) + assert.Equal(t, string(tt.category), log.Metadata[entity.RequestLogMetadataKeyFailureCategory]) return nil }) storageFactory := orchstoragemock.NewMockFactory(ctrl) diff --git a/submitqueue/orchestrator/controller/dlq/dlq.go b/submitqueue/orchestrator/controller/dlq/dlq.go index 98ab771e0..aa96acd4e 100644 --- a/submitqueue/orchestrator/controller/dlq/dlq.go +++ b/submitqueue/orchestrator/controller/dlq/dlq.go @@ -88,7 +88,7 @@ func primaryTopicKey(dlqKey consumer.TopicKey) consumer.TopicKey { // read well in a display surface where a JSON blob would not. func failureContext(delivery consumer.Delivery) (string, map[string]string) { dmeta := delivery.Metadata() - metadata := make(map[string]string, len(dmeta)) + metadata := map[string]string{entity.RequestLogMetadataKeyFailureCategory: string(entity.FailureCategoryInternalError)} for _, key := range []string{"dlq.original_topic", "dlq.failure_count", "dlq.failed_at"} { if v, ok := dmeta[key]; ok && v != "" { metadata[key] = v @@ -142,6 +142,12 @@ func flattenDetail(prefix string, detail map[string]any, out map[string]string) // metadata and is exposed through Status and History for diagnosis, alongside // metadata carrying the rest of the failure context. // +// A known gap: a request already in Error gets this dead letter's details on +// its resend. When the original log never reached the gateway, for example a +// rejection whose log publish kept failing until the message dead-lettered, +// they become its only record, internal_error included. When it did, the +// gateway keeps it and only adds the dlq.* keys the summary lacked. +// // A request in RequestStateCancelling is reconciled to RequestStateError, not // left in place: DLQ means the pipeline failed to converge, so we cannot // confirm the cancel completed cleanly. Writing Error is the honest signal and @@ -186,7 +192,11 @@ func failRequest(ctx context.Context, store orchstorage.Storage, registry consum // attempt may have crashed after updating the batch. Succeeded and Cancelled // are different terminal outcomes and do not fan out errors. // lastError and metadata are propagated to each member request's terminal -// Error log. +// Error log. A known gap: a batch that already failed but whose conclude has +// not run yet gets this dead letter's details, internal_error included, and the +// conclude that follows only resends, so its category does not replace them. +// The batch's failure travels only on its conclude message, so nothing better +// is available here. // // It reports whether it transitioned the batch. A caller that only wants to act // on real progress — republishing to wake the queue, say — can then tell a diff --git a/submitqueue/orchestrator/controller/dlq/request_test.go b/submitqueue/orchestrator/controller/dlq/request_test.go index dc60b102d..c56febe2a 100644 --- a/submitqueue/orchestrator/controller/dlq/request_test.go +++ b/submitqueue/orchestrator/controller/dlq/request_test.go @@ -137,6 +137,7 @@ func TestDLQRequestController_Process_RequestIDPayload(t *testing.T) { registry := newTestLogRegistry(t, ctrl, 1, func(log entity.RequestLog) error { assert.Equal(t, "boom", log.LastError) + assert.Equal(t, string(entity.FailureCategoryInternalError), log.Metadata[entity.RequestLogMetadataKeyFailureCategory]) return nil }) diff --git a/submitqueue/orchestrator/controller/dlq/start_test.go b/submitqueue/orchestrator/controller/dlq/start_test.go index e9d15775a..71abaa733 100644 --- a/submitqueue/orchestrator/controller/dlq/start_test.go +++ b/submitqueue/orchestrator/controller/dlq/start_test.go @@ -158,6 +158,7 @@ func TestDLQStartController_ReconcilesOnlyError(t *testing.T) { assert.Zero(t, writes) assert.Zero(t, logs[0].RequestVersion) assert.Equal(t, "boom", logs[0].LastError) + assert.Equal(t, string(entity.FailureCategoryInternalError), logs[0].Metadata[entity.RequestLogMetadataKeyFailureCategory]) return } assert.Equal(t, landRequest.Change, persisted.Change) diff --git a/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal.go b/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal.go index 20e2389cc..957bf12fe 100644 --- a/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal.go +++ b/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal.go @@ -117,11 +117,11 @@ func (c *Controller) Process(ctx context.Context, delivery consumer.Delivery) er // The failed conflict check may be terminal even though its final log was never // published. A redelivered failure carries the same result, so the resend can say why. if request.State == entity.RequestStateError { - var reason string - if result.Outcome != runwaypb.Outcome_SUCCEEDED { - reason = result.Reason + if result.Outcome == runwaypb.Outcome_SUCCEEDED { + return corerequest.ResendTerminalRequestLog(ctx, c.registry, request, "", nil) } - return corerequest.ResendTerminalRequestLog(ctx, c.registry, request, reason, nil) + reason, metadata := failure(result) + return corerequest.ResendTerminalRequestLog(ctx, c.registry, request, reason, metadata) } if entity.IsRequestStateHalted(request.State) { @@ -139,7 +139,7 @@ func (c *Controller) Process(ctx context.Context, delivery consumer.Delivery) er "request_id", request.ID, "reason", result.Reason, ) - if err := c.failRequest(ctx, store, request, result.Reason); err != nil { + if err := c.failRequest(ctx, store, request, result); err != nil { metrics.NamedCounter(c.metricsScope, opName, "fail_errors", 1, metrics.TagsFromContext(ctx)...) return fmt.Errorf("failed to fail request %s: %w", request.ID, err) } @@ -169,11 +169,17 @@ func (c *Controller) Process(ctx context.Context, delivery consumer.Delivery) er return nil // Success - message will be acked } -func (c *Controller) failRequest(ctx context.Context, store orchstorage.Storage, request entity.Request, reason string) error { - _, err := corerequest.TerminateRequest(ctx, store, c.registry, request.ID, entity.RequestStateError, reason, nil) +func (c *Controller) failRequest(ctx context.Context, store orchstorage.Storage, request entity.Request, result *runwaymq.MergeResult) error { + reason, metadata := failure(result) + _, err := corerequest.TerminateRequest(ctx, store, c.registry, request.ID, entity.RequestStateError, reason, metadata) return err } +// failure is the reason and request log metadata a failed check result gives its request. +func failure(result *runwaymq.MergeResult) (string, map[string]string) { + return result.Reason, entity.FailureCategoryMetadata(nil, entity.FailureCategoryLandFailed) +} + // publishRequestID publishes a request ID to the given topic key, stamped with // and partitioned by the request's queue. // diff --git a/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal_test.go b/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal_test.go index 4626014b5..e6ab5c9f9 100644 --- a/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal_test.go +++ b/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal_test.go @@ -190,6 +190,7 @@ func TestProcess_NotLandableMarksRequestError(t *testing.T) { assert.Equal(t, entity.RequestStatusError, logEntry.Status) assert.Equal(t, int32(2), logEntry.RequestVersion) assert.Equal(t, "conflict in foo.go", logEntry.LastError) + assert.Equal(t, string(entity.FailureCategoryLandFailed), logEntry.Metadata[entity.RequestLogMetadataKeyFailureCategory]) } func TestFailRequest_UpdateFailureLeavesRequestUnchanged(t *testing.T) { @@ -209,7 +210,7 @@ func TestFailRequest_UpdateFailureLeavesRequestUnchanged(t *testing.T) { controller := NewController(zaptest.NewLogger(t).Sugar(), tally.NoopScope, storageFactory, consumer.TopicRegistry{}, runwaymq.TopicKeyMergeConflictCheckSignal, "orchestrator-landconflictsignal") - err := controller.failRequest(context.Background(), store, request, "conflict") + err := controller.failRequest(context.Background(), store, request, &runwaymq.MergeResult{Id: testRequestID, Outcome: runwaypb.Outcome_FAILED, Reason: "conflict"}) require.Error(t, err) assert.Equal(t, entity.RequestStateStarted, request.State) assert.Equal(t, int32(1), request.Version) @@ -250,11 +251,13 @@ func TestProcess_ErrorRequestResendsTerminalLog(t *testing.T) { name string result runwaymq.MergeResult wantLastError string + wantCategory entity.FailureCategory }{ { name: "a redelivered failure says why", result: runwaymq.MergeResult{Id: testRequestID, Outcome: runwaypb.Outcome_FAILED, Reason: "conflict in foo.go"}, wantLastError: "conflict in foo.go", + wantCategory: entity.FailureCategoryLandFailed, }, { name: "a success cannot say why the request failed", @@ -297,6 +300,7 @@ func TestProcess_ErrorRequestResendsTerminalLog(t *testing.T) { assert.Equal(t, int32(2), logs[0].RequestVersion) assert.Equal(t, tt.wantLastError, logs[0].LastError) assert.Equal(t, "true", logs[0].Metadata[entity.RequestLogMetadataKeyResent]) + assert.Equal(t, string(tt.wantCategory), logs[0].Metadata[entity.RequestLogMetadataKeyFailureCategory]) }) } } diff --git a/submitqueue/orchestrator/controller/landsignal/landsignal.go b/submitqueue/orchestrator/controller/landsignal/landsignal.go index 81e690bc0..cff140e6d 100644 --- a/submitqueue/orchestrator/controller/landsignal/landsignal.go +++ b/submitqueue/orchestrator/controller/landsignal/landsignal.go @@ -190,7 +190,10 @@ func (c *Controller) Process(ctx context.Context, delivery consumer.Delivery) er func (c *Controller) fanout(ctx context.Context, batchID, queue, failureReason string) error { var concludeMeta map[string]string if failureReason != "" { - concludeMeta = map[string]string{topickey.MetadataKeyFailureReason: failureReason} + concludeMeta = map[string]string{ + topickey.MetadataKeyFailureReason: failureReason, + topickey.MetadataKeyFailureCategory: string(entity.FailureCategoryLandFailed), + } } if err := c.publish(ctx, topickey.TopicKeyConclude, publish.IntentID(batchID, "conclude", "landed"), batchID, queue, concludeMeta); err != nil { metrics.NamedCounter(c.metricsScope, "process", "publish_conclude_errors", 1, metrics.TagsFromContext(ctx)...) diff --git a/submitqueue/orchestrator/controller/landsignal/landsignal_test.go b/submitqueue/orchestrator/controller/landsignal/landsignal_test.go index f4d9d27d7..9a837593d 100644 --- a/submitqueue/orchestrator/controller/landsignal/landsignal_test.go +++ b/submitqueue/orchestrator/controller/landsignal/landsignal_test.go @@ -265,6 +265,7 @@ func TestProcess_NotLandedMarksBatchFailed(t *testing.T) { // the request's terminal log; the speculate wake-up carries none. assert.Equal(t, "conflict in foo.go", byTopic["conclude"].Metadata[topickey.MetadataKeyFailureReason]) assert.Empty(t, byTopic["speculate"].Metadata[topickey.MetadataKeyFailureReason]) + assert.Equal(t, string(entity.FailureCategoryLandFailed), byTopic["conclude"].Metadata[topickey.MetadataKeyFailureCategory]) } func TestProcess_CancellingShortCircuit(t *testing.T) { diff --git a/submitqueue/orchestrator/controller/speculate/finalize.go b/submitqueue/orchestrator/controller/speculate/finalize.go index a1889d8a0..e76858803 100644 --- a/submitqueue/orchestrator/controller/speculate/finalize.go +++ b/submitqueue/orchestrator/controller/speculate/finalize.go @@ -271,7 +271,11 @@ func (c *Controller) commitOutcome(ctx context.Context, snap *snapshot, batch en // Attributed here rather than at each leaf: this is the one place that // knows which batch the whole commit is for, and the finalize loop runs it // over every decided batch in the queue — rarely the one on the message. - landed, err := c.applyOutcome(ctx, snap.store, batch, decision, snap.isTrigger(batch.ID)) + var concludeMeta map[string]string + if decision == outcomeFail { + concludeMeta = speculationFailureMetadata(snap.pathSets[batch.ID], *snap) + } + landed, err := c.applyOutcome(ctx, snap.store, batch, decision, snap.isTrigger(batch.ID), concludeMeta) if err != nil { return landed, c.attributed(ctx, err, entity.BatchSubject(batch.ID)) } @@ -310,7 +314,9 @@ func (c *Controller) recordOutcome(snap *snapshot, batchID string, decision outc // consumer can act on an outcome a lost compare-and-swap refused to write. The // cost is a dispatch that fails on a batch finalize no longer walks, which the // recovery message and Process's self-heal exist to repair. -func (c *Controller) applyOutcome(ctx context.Context, store orchstorage.Storage, batch entity.Batch, decision outcome, isTriggerBatch bool) (bool, error) { +// +// concludeMeta is the failure a failed batch carries to conclude. +func (c *Controller) applyOutcome(ctx context.Context, store orchstorage.Storage, batch entity.Batch, decision outcome, isTriggerBatch bool, concludeMeta map[string]string) (bool, error) { var state entity.BatchState switch decision { @@ -363,10 +369,7 @@ func (c *Controller) applyOutcome(ctx context.Context, store orchstorage.Storage // A failed batch carries its reason to conclude on the message, so the // requests' terminal log records why speculation could not land it. // Cancellation carries none — the cancel path owns that reason. - var concludeMeta map[string]string - if decision == outcomeFail { - concludeMeta = map[string]string{topickey.MetadataKeyFailureReason: "no speculation path could pass; every viable build failed or was cancelled"} - } + // // Named for the run that decided it, so a redelivery re-deriving the // same outcome does not conclude the batch twice, and so it stays // distinct from the conclude landsignal sends for a landed batch. @@ -380,6 +383,38 @@ func (c *Controller) applyOutcome(ctx context.Context, store orchstorage.Storage return true, nil } +// speculationFailureMetadata is the conclude metadata of a head with no viable +// future. A live path whose build failed makes it the change's build failure. +// When every live path was cancelled instead, by the CI provider or anyone but +// SubmitQueue, nothing showed the change broken, so it fails as an internal +// error the author can resubmit. hasNoViableFuture needs a live path, so the +// last case is a guard that claims neither. +func speculationFailureMetadata(set entity.SpeculationPathSet, snap snapshot) map[string]string { + cancelled := false + for _, entry := range set.Paths { + if assumptionBroken(entry.Path, snap) { + continue + } + switch entry.Status { + case entity.SpeculationPathStatusFailed: + return failureMetadata("no speculation path could pass; every viable build failed or was cancelled", entity.FailureCategoryBuildFailed) + case entity.SpeculationPathStatusCancelled: + cancelled = true + } + } + if cancelled { + return failureMetadata("no speculation path could pass; every viable build was cancelled", entity.FailureCategoryInternalError) + } + return failureMetadata("no speculation path could pass", entity.FailureCategoryInternalError) +} + +func failureMetadata(reason string, category entity.FailureCategory) map[string]string { + return map[string]string{ + topickey.MetadataKeyFailureReason: reason, + topickey.MetadataKeyFailureCategory: string(category), + } +} + // dispatchLand reports speculation finished and hands the batch to the land // stage. The stable ID means a redelivery or the Landing self-heal dedupes // against the request already sent instead of landing twice; the status goes diff --git a/submitqueue/orchestrator/controller/speculate/outcome_test.go b/submitqueue/orchestrator/controller/speculate/outcome_test.go index 72df64518..c9eae6862 100644 --- a/submitqueue/orchestrator/controller/speculate/outcome_test.go +++ b/submitqueue/orchestrator/controller/speculate/outcome_test.go @@ -18,6 +18,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/uber/submitqueue/submitqueue/core/topickey" "github.com/uber/submitqueue/submitqueue/entity" ) @@ -386,6 +387,61 @@ func TestHasNoViableFuture(t *testing.T) { } } +func TestSpeculationFailureMetadata(t *testing.T) { + live := pathOver(entity.DependencyAssumptionSucceeds, entity.DependencyAssumptionSucceeds) + broken := pathOver(entity.DependencyAssumptionFails, entity.DependencyAssumptionSucceeds) + settled := snapWith(entity.BatchStateSucceeded, entity.BatchStateSucceeded) + failed := entryFor(live, entity.SpeculationPathStatusFailed) + cancelled := entryFor(live, entity.SpeculationPathStatusCancelled) + brokenFailed := entryFor(broken, entity.SpeculationPathStatusFailed) + + tests := []struct { + name string + set entity.SpeculationPathSet + wantReason string + wantCategory entity.FailureCategory + }{ + { + name: "a live build failed", + set: setOf(failed), + wantReason: "no speculation path could pass; every viable build failed or was cancelled", + wantCategory: entity.FailureCategoryBuildFailed, + }, + { + name: "a live build failed and another was cancelled", + set: setOf(cancelled, failed), + wantReason: "no speculation path could pass; every viable build failed or was cancelled", + wantCategory: entity.FailureCategoryBuildFailed, + }, + { + name: "every live build was cancelled", + set: setOf(cancelled), + wantReason: "no speculation path could pass; every viable build was cancelled", + wantCategory: entity.FailureCategoryInternalError, + }, + { + name: "only a build on a broken assumption failed", + set: setOf(brokenFailed, cancelled), + wantReason: "no speculation path could pass; every viable build was cancelled", + wantCategory: entity.FailureCategoryInternalError, + }, + { + name: "no live path failed or was cancelled", + set: setOf(brokenFailed), + wantReason: "no speculation path could pass", + wantCategory: entity.FailureCategoryInternalError, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, map[string]string{ + topickey.MetadataKeyFailureReason: tt.wantReason, + topickey.MetadataKeyFailureCategory: string(tt.wantCategory), + }, speculationFailureMetadata(tt.set, settled)) + }) + } +} + func TestDecide(t *testing.T) { headBatch := entity.Batch{ID: head, Dependencies: []string{dep1, dep2}} allResolved := snapWith(entity.BatchStateSucceeded, entity.BatchStateSucceeded) diff --git a/submitqueue/orchestrator/controller/speculate/run_test.go b/submitqueue/orchestrator/controller/speculate/run_test.go index 3d349509c..08dc09b42 100644 --- a/submitqueue/orchestrator/controller/speculate/run_test.go +++ b/submitqueue/orchestrator/controller/speculate/run_test.go @@ -797,6 +797,7 @@ func TestRun_FailedHeadConcludesAfterTheStateWrite(t *testing.T) { require.Len(t, h.messages, 1) assert.Equal(t, "no speculation path could pass; every viable build failed or was cancelled", h.messages[0].Metadata[topickey.MetadataKeyFailureReason]) + assert.Equal(t, string(entity.FailureCategoryBuildFailed), h.messages[0].Metadata[topickey.MetadataKeyFailureCategory]) } func TestRun_ProviderCancellationExhaustsHead(t *testing.T) { @@ -826,7 +827,9 @@ func TestRun_ProviderCancellationExhaustsHead(t *testing.T) { require.NoError(t, h.run(head)) assert.Equal(t, []string{"conclude"}, h.published) - assert.Equal(t, "no speculation path could pass; every viable build failed or was cancelled", h.messages[0].Metadata[topickey.MetadataKeyFailureReason]) + // No build showed the change broken, so the author is not told to fix it. + assert.Equal(t, "no speculation path could pass; every viable build was cancelled", h.messages[0].Metadata[topickey.MetadataKeyFailureReason]) + assert.Equal(t, string(entity.FailureCategoryInternalError), h.messages[0].Metadata[topickey.MetadataKeyFailureCategory]) assert.Zero(t, h.spec.calls) } diff --git a/submitqueue/orchestrator/controller/validate/validate.go b/submitqueue/orchestrator/controller/validate/validate.go index c624f8395..f1e37d0f9 100644 --- a/submitqueue/orchestrator/controller/validate/validate.go +++ b/submitqueue/orchestrator/controller/validate/validate.go @@ -135,6 +135,9 @@ func (c *Controller) Process(ctx context.Context, delivery consumer.Delivery) er // The rejection may be terminal even though its final log was never published. // This delivery cannot tell why the request was rejected, so the resend has no reason. + // A known gap: when the rejection's own log never went out, this resend is the + // only one, and the request finishes with no reason or category. + // The orchestrator does not store the verdict. if request.State == entity.RequestStateError { return corerequest.ResendTerminalRequestLog(ctx, c.registry, request, "", nil) } @@ -172,7 +175,7 @@ func (c *Controller) Process(ctx context.Context, delivery consumer.Delivery) er "duplicate_id", dupID, ) coremetrics.NamedCounter(c.metricsScope, "process", "duplicate_requests", 1, coremetrics.TagsFromContext(ctx)...) - return c.reject(ctx, store, request.ID, fmt.Sprintf("request %s is a duplicate of in-flight request %s", request.ID, dupID)) + return c.reject(ctx, store, request.ID, fmt.Sprintf("request %s is a duplicate of in-flight request %s", request.ID, dupID), entity.FailureCategoryDuplicate) } // Fetch change metadata @@ -218,7 +221,7 @@ func (c *Controller) Process(ctx context.Context, delivery consumer.Delivery) er "queue", request.Queue, "error", err.Error(), ) - return c.reject(ctx, store, request.ID, fmt.Sprintf("custom validation failed: %v", err)) + return c.reject(ctx, store, request.ID, fmt.Sprintf("custom validation failed: %v", err), entity.FailureCategoryValidationRejected) } } } @@ -267,8 +270,8 @@ func (c *Controller) Process(ctx context.Context, delivery consumer.Delivery) er // Only an infra failure while terminating (storage/publish) is returned as an // error so the delivery is retried; the request itself is never re-queued for // validation once rejected. -func (c *Controller) reject(ctx context.Context, store orchstorage.Storage, requestID, reason string) error { - if _, err := corerequest.TerminateRequest(ctx, store, c.registry, requestID, entity.RequestStateError, reason, nil); err != nil { +func (c *Controller) reject(ctx context.Context, store orchstorage.Storage, requestID, reason string, category entity.FailureCategory) error { + if _, err := corerequest.TerminateRequest(ctx, store, c.registry, requestID, entity.RequestStateError, reason, entity.FailureCategoryMetadata(nil, category)); err != nil { coremetrics.NamedCounter(c.metricsScope, "process", "terminate_errors", 1, coremetrics.TagsFromContext(ctx)...) return fmt.Errorf("failed to terminate rejected request %s: %w", requestID, err) } diff --git a/submitqueue/orchestrator/controller/validate/validate_test.go b/submitqueue/orchestrator/controller/validate/validate_test.go index f74bf527f..dc7a59845 100644 --- a/submitqueue/orchestrator/controller/validate/validate_test.go +++ b/submitqueue/orchestrator/controller/validate/validate_test.go @@ -802,6 +802,7 @@ func TestController_Process_CustomValidatorFails(t *testing.T) { assert.Equal(t, entity.RequestStatusError, gotLog.Status) assert.Equal(t, int32(2), gotLog.RequestVersion) assert.Contains(t, gotLog.LastError, "some validation error") + assert.Equal(t, string(entity.FailureCategoryValidationRejected), gotLog.Metadata[entity.RequestLogMetadataKeyFailureCategory]) } // A validator that could not validate has said nothing about the request, so @@ -974,3 +975,42 @@ func TestController_Process_CustomValidatorFailure_TerminationPublishFails(t *te require.Error(t, err) assert.ErrorContains(t, err, "failed to terminate rejected request") } + +func TestController_Reject_RecordsFailureCategory(t *testing.T) { + tests := []struct { + name string + category entity.FailureCategory + }{ + {name: "duplicate", category: entity.FailureCategoryDuplicate}, + {name: "validation rejected", category: entity.FailureCategoryValidationRejected}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ctrl := gomock.NewController(t) + request := entity.Request{ID: "7", Queue: "q", State: entity.RequestStateStarted, Version: 1} + requests := storagemock.NewMockRequestStore(ctrl) + requests.EXPECT().Get(gomock.Any(), request.ID).Return(request, nil) + requests.EXPECT().Update(gomock.Any(), requestWithState(request, entity.RequestStateError), int32(1), int32(2)).Return(nil) + store := orchstoragemock.NewMockStorage(ctrl) + store.EXPECT().GetRequestStore().Return(requests).AnyTimes() + var gotLog entity.RequestLog + pub := queuemock.NewMockPublisher(ctrl) + pub.EXPECT().Publish(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, msg entityqueue.Message) error { + log, err := sqmq.UnmarshalRequestLog(msg.Payload) + require.NoError(t, err) + gotLog = log + return nil + }) + q := queuemock.NewMockQueue(ctrl) + q.EXPECT().Publisher().Return(pub).AnyTimes() + registry, err := consumer.NewTopicRegistry([]consumer.TopicConfig{{Key: topickey.TopicKeyLog, Name: "log", Queue: q}}) + require.NoError(t, err) + controller := &Controller{registry: registry, metricsScope: tally.NoopScope} + + require.NoError(t, controller.reject(context.Background(), store, request.ID, "rejected", tt.category)) + + assert.Equal(t, "rejected", gotLog.LastError) + assert.Equal(t, string(tt.category), gotLog.Metadata[entity.RequestLogMetadataKeyFailureCategory]) + }) + } +} diff --git a/submitqueue/orchestrator/core/batch/conclude.go b/submitqueue/orchestrator/core/batch/conclude.go index 38f4492eb..775b7fa40 100644 --- a/submitqueue/orchestrator/core/batch/conclude.go +++ b/submitqueue/orchestrator/core/batch/conclude.go @@ -31,8 +31,8 @@ import ( // ConcludeBatchRequests reconciles each member with the authoritative terminal batch outcome. // Matching terminal requests repair their status logs; different terminal winners remain unchanged. // A missing member or failed write/publish is an error so redelivery retains unfinished work. -// failureReason applies only to Failed batches, not successful or cancelled outcomes. -func ConcludeBatchRequests(ctx context.Context, store orchstorage.Storage, registry consumer.TopicRegistry, logger *zap.SugaredLogger, scope tally.Scope, batch entity.Batch, failureReason string) error { +// failureReason and failureCategory apply only to Failed batches, not successful or cancelled outcomes. +func ConcludeBatchRequests(ctx context.Context, store orchstorage.Storage, registry consumer.TopicRegistry, logger *zap.SugaredLogger, scope tally.Scope, batch entity.Batch, failureReason string, failureCategory entity.FailureCategory) error { requestState, err := batchStateToRequestState(batch.State) if err != nil { metrics.NamedCounter(scope, "process", "unexpected_state_errors", 1, metrics.TagsFromContext(ctx)...) @@ -40,12 +40,11 @@ func ConcludeBatchRequests(ctx context.Context, store orchstorage.Storage, regis } if requestState != entity.RequestStateError { - failureReason = "" + failureReason, failureCategory = "", entity.FailureCategoryUnknown } + metadata := entity.FailureCategoryMetadata(map[string]string{"batch_id": batch.ID}, failureCategory) for _, requestID := range batch.Contains { - res, err := corerequest.TerminateRequest(ctx, store, registry, requestID, requestState, failureReason, map[string]string{ - "batch_id": batch.ID, - }) + res, err := corerequest.TerminateRequest(ctx, store, registry, requestID, requestState, failureReason, metadata) if err != nil { metrics.NamedCounter(scope, "process", "terminate_errors", 1, metrics.TagsFromContext(ctx)...) return fmt.Errorf("failed to terminate request %s for batch %s: %w", requestID, batch.ID, err)