From dc48e92ae6820da16dd8b3486bb4bad50f13cc1a Mon Sep 17 00:00:00 2001 From: Chenghan Ying <125171961+roychying@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:38:09 -0800 Subject: [PATCH 1/2] feat(runway): Classify failed merges and name conflicting files so a request can fail as a merge conflict --- api/runway/messagequeue/proto/merge.proto | 21 +++ api/runway/messagequeue/protopb/merge.pb.go | 136 ++++++++++++++---- doc/rfc/hook-framework.md | 2 +- runway/controller/merge/merge.go | 8 +- runway/controller/merge/merge_test.go | 51 +++++++ .../mergeconflictcheck/mergeconflictcheck.go | 8 +- .../mergeconflictcheck_test.go | 51 +++++++ runway/extension/merger/BUILD.bazel | 17 ++- runway/extension/merger/git/git_merger.go | 46 ++++-- .../extension/merger/git/git_merger_test.go | 36 ++++- runway/extension/merger/merger.go | 35 +++++ runway/extension/merger/merger_test.go | 49 +++++++ submitqueue/core/hookevent/hookevent.go | 13 +- submitqueue/core/hookevent/hookevent_test.go | 11 ++ submitqueue/core/messagequeue/topics.go | 4 + submitqueue/core/topickey/topickey.go | 2 + submitqueue/entity/failure_category.go | 34 ++++- submitqueue/entity/failure_category_test.go | 22 +++ submitqueue/gateway/README.md | 2 +- .../controller/conclude/BUILD.bazel | 2 - .../controller/conclude/conclude.go | 4 +- .../controller/conclude/conclude_test.go | 98 ++++++++----- .../orchestrator/controller/dlq/conclude.go | 4 +- .../landconflictsignal/landconflictsignal.go | 3 +- .../landconflictsignal_test.go | 124 ++++++++++------ .../controller/landsignal/BUILD.bazel | 1 + .../controller/landsignal/landsignal.go | 25 ++-- .../controller/landsignal/landsignal_test.go | 115 +++++++++------ .../orchestrator/core/batch/BUILD.bazel | 3 + .../orchestrator/core/batch/conclude.go | 67 ++++++++- .../orchestrator/core/batch/failure_test.go | 64 +++++++++ .../orchestrator/core/request/BUILD.bazel | 6 + .../orchestrator/core/request/land_failure.go | 34 +++++ .../core/request/land_failure_test.go | 62 ++++++++ 34 files changed, 944 insertions(+), 216 deletions(-) create mode 100644 runway/extension/merger/merger_test.go create mode 100644 submitqueue/orchestrator/core/batch/failure_test.go create mode 100644 submitqueue/orchestrator/core/request/land_failure.go create mode 100644 submitqueue/orchestrator/core/request/land_failure_test.go diff --git a/api/runway/messagequeue/proto/merge.proto b/api/runway/messagequeue/proto/merge.proto index 5ab44e55e..37acecff1 100644 --- a/api/runway/messagequeue/proto/merge.proto +++ b/api/runway/messagequeue/proto/merge.proto @@ -106,6 +106,20 @@ enum Outcome { FAILED = 2; } +// FailureKind classifies why a FAILED result failed, so a consumer can act on it +// without parsing reason. +enum FailureKind { + // FAILURE_KIND_UNSPECIFIED is the zero value: the failure was not classified, + // or the result did not fail. + FAILURE_KIND_UNSPECIFIED = 0; + // FAILURE_KIND_CONFLICT means the steps did not apply cleanly onto the merge + // target; the author has to rebase before the request can succeed. + FAILURE_KIND_CONFLICT = 1; + // FAILURE_KIND_INVALID_REQUEST means the request itself was malformed or + // unsupported, so retrying it unchanged fails the same way. + FAILURE_KIND_INVALID_REQUEST = 2; +} + // MergeResult is the payload Runway publishes to the corresponding signal queue // (merge-conflict-check-signal for a check, merge-signal for a merge) once a // request completes. @@ -129,4 +143,11 @@ message MergeResult { // queue_name echoes the caller-provided queue name from the request, so the // consumer can route the result by queue without loading state first. string queue_name = 5; + // failure_kind classifies a FAILED outcome. Unspecified on success, and when + // the failure was not classified. + FailureKind failure_kind = 6; + // conflicting_files lists the paths that did not apply cleanly, when + // failure_kind is FAILURE_KIND_CONFLICT and the merger could tell. Paths are + // relative to the repository root. + repeated string conflicting_files = 7; } diff --git a/api/runway/messagequeue/protopb/merge.pb.go b/api/runway/messagequeue/protopb/merge.pb.go index e1bbd6aef..89dc18bdc 100644 --- a/api/runway/messagequeue/protopb/merge.pb.go +++ b/api/runway/messagequeue/protopb/merge.pb.go @@ -95,6 +95,63 @@ func (Outcome) EnumDescriptor() ([]byte, []int) { return file_merge_proto_rawDescGZIP(), []int{0} } +// FailureKind classifies why a FAILED result failed, so a consumer can act on it +// without parsing reason. +type FailureKind int32 + +const ( + // FAILURE_KIND_UNSPECIFIED is the zero value: the failure was not classified, + // or the result did not fail. + FailureKind_FAILURE_KIND_UNSPECIFIED FailureKind = 0 + // FAILURE_KIND_CONFLICT means the steps did not apply cleanly onto the merge + // target; the author has to rebase before the request can succeed. + FailureKind_FAILURE_KIND_CONFLICT FailureKind = 1 + // FAILURE_KIND_INVALID_REQUEST means the request itself was malformed or + // unsupported, so retrying it unchanged fails the same way. + FailureKind_FAILURE_KIND_INVALID_REQUEST FailureKind = 2 +) + +// Enum value maps for FailureKind. +var ( + FailureKind_name = map[int32]string{ + 0: "FAILURE_KIND_UNSPECIFIED", + 1: "FAILURE_KIND_CONFLICT", + 2: "FAILURE_KIND_INVALID_REQUEST", + } + FailureKind_value = map[string]int32{ + "FAILURE_KIND_UNSPECIFIED": 0, + "FAILURE_KIND_CONFLICT": 1, + "FAILURE_KIND_INVALID_REQUEST": 2, + } +) + +func (x FailureKind) Enum() *FailureKind { + p := new(FailureKind) + *p = x + return p +} + +func (x FailureKind) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (FailureKind) Descriptor() protoreflect.EnumDescriptor { + return file_merge_proto_enumTypes[1].Descriptor() +} + +func (FailureKind) Type() protoreflect.EnumType { + return &file_merge_proto_enumTypes[1] +} + +func (x FailureKind) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use FailureKind.Descriptor instead. +func (FailureKind) EnumDescriptor() ([]byte, []int) { + return file_merge_proto_rawDescGZIP(), []int{1} +} + // MergeStep is one step of an ordered merge: a single change applied with a // strategy. Runway applies the steps of a request in order on top of the merge // target; the ordering encodes the base-layering (earlier steps are the @@ -381,9 +438,16 @@ type MergeResult struct { Steps []*StepResult `protobuf:"bytes,4,rep,name=steps,proto3" json:"steps,omitempty"` // queue_name echoes the caller-provided queue name from the request, so the // consumer can route the result by queue without loading state first. - QueueName string `protobuf:"bytes,5,opt,name=queue_name,json=queueName,proto3" json:"queue_name,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + QueueName string `protobuf:"bytes,5,opt,name=queue_name,json=queueName,proto3" json:"queue_name,omitempty"` + // failure_kind classifies a FAILED outcome. Unspecified on success, and when + // the failure was not classified. + FailureKind FailureKind `protobuf:"varint,6,opt,name=failure_kind,json=failureKind,proto3,enum=uber.runway.messagequeue.FailureKind" json:"failure_kind,omitempty"` + // conflicting_files lists the paths that did not apply cleanly, when + // failure_kind is FAILURE_KIND_CONFLICT and the merger could tell. Paths are + // relative to the repository root. + ConflictingFiles []string `protobuf:"bytes,7,rep,name=conflicting_files,json=conflictingFiles,proto3" json:"conflicting_files,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *MergeResult) Reset() { @@ -451,6 +515,20 @@ func (x *MergeResult) GetQueueName() string { return "" } +func (x *MergeResult) GetFailureKind() FailureKind { + if x != nil { + return x.FailureKind + } + return FailureKind_FAILURE_KIND_UNSPECIFIED +} + +func (x *MergeResult) GetConflictingFiles() []string { + if x != nil { + return x.ConflictingFiles + } + return nil +} + var File_merge_proto protoreflect.FileDescriptor const file_merge_proto_rawDesc = "" + @@ -472,19 +550,25 @@ const file_merge_proto_rawDesc = "" + "StepResult\x12\x17\n" + "\astep_id\x18\x01 \x01(\tR\x06stepId\x12>\n" + "\aoutputs\x18\x02 \x03(\v2$.uber.runway.messagequeue.StepOutputR\aoutputs\x12\x16\n" + - "\x06reason\x18\x03 \x01(\tR\x06reason\"\xfe\x01\n" + + "\x06reason\x18\x03 \x01(\tR\x06reason\"\xf5\x02\n" + "\vMergeResult\x12\x0e\n" + "\x02id\x18\x01 \x01(\tR\x02id\x12;\n" + "\aoutcome\x18\x02 \x01(\x0e2!.uber.runway.messagequeue.OutcomeR\aoutcome\x12\x16\n" + "\x06reason\x18\x03 \x01(\tR\x06reason\x12:\n" + "\x05steps\x18\x04 \x03(\v2$.uber.runway.messagequeue.StepResultR\x05steps\x12\x1d\n" + "\n" + - "queue_name\x18\x05 \x01(\tR\tqueueName:/\x8a\xb5\x18\x1bmerge-conflict-check-signal\x8a\xb5\x18\fmerge-signal*=\n" + + "queue_name\x18\x05 \x01(\tR\tqueueName\x12H\n" + + "\ffailure_kind\x18\x06 \x01(\x0e2%.uber.runway.messagequeue.FailureKindR\vfailureKind\x12+\n" + + "\x11conflicting_files\x18\a \x03(\tR\x10conflictingFiles:/\x8a\xb5\x18\x1bmerge-conflict-check-signal\x8a\xb5\x18\fmerge-signal*=\n" + "\aOutcome\x12\x17\n" + "\x13OUTCOME_UNSPECIFIED\x10\x00\x12\r\n" + "\tSUCCEEDED\x10\x01\x12\n" + "\n" + - "\x06FAILED\x10\x02Bu\n" + + "\x06FAILED\x10\x02*h\n" + + "\vFailureKind\x12\x1c\n" + + "\x18FAILURE_KIND_UNSPECIFIED\x10\x00\x12\x19\n" + + "\x15FAILURE_KIND_CONFLICT\x10\x01\x12 \n" + + "\x1cFAILURE_KIND_INVALID_REQUEST\x10\x02Bu\n" + "(com.uber.submitqueue.runway.messagequeueB\n" + "MergeProtoP\x01Z;github.com/uber/submitqueue/api/runway/messagequeue/protopbb\x06proto3" @@ -500,30 +584,32 @@ func file_merge_proto_rawDescGZIP() []byte { return file_merge_proto_rawDescData } -var file_merge_proto_enumTypes = make([]protoimpl.EnumInfo, 1) +var file_merge_proto_enumTypes = make([]protoimpl.EnumInfo, 2) var file_merge_proto_msgTypes = make([]protoimpl.MessageInfo, 5) var file_merge_proto_goTypes = []any{ (Outcome)(0), // 0: uber.runway.messagequeue.Outcome - (*MergeStep)(nil), // 1: uber.runway.messagequeue.MergeStep - (*MergeRequest)(nil), // 2: uber.runway.messagequeue.MergeRequest - (*StepOutput)(nil), // 3: uber.runway.messagequeue.StepOutput - (*StepResult)(nil), // 4: uber.runway.messagequeue.StepResult - (*MergeResult)(nil), // 5: uber.runway.messagequeue.MergeResult - (*protopb.Change)(nil), // 6: uber.base.change.Change - (protopb1.Strategy)(0), // 7: uber.base.mergestrategy.Strategy + (FailureKind)(0), // 1: uber.runway.messagequeue.FailureKind + (*MergeStep)(nil), // 2: uber.runway.messagequeue.MergeStep + (*MergeRequest)(nil), // 3: uber.runway.messagequeue.MergeRequest + (*StepOutput)(nil), // 4: uber.runway.messagequeue.StepOutput + (*StepResult)(nil), // 5: uber.runway.messagequeue.StepResult + (*MergeResult)(nil), // 6: uber.runway.messagequeue.MergeResult + (*protopb.Change)(nil), // 7: uber.base.change.Change + (protopb1.Strategy)(0), // 8: uber.base.mergestrategy.Strategy } var file_merge_proto_depIdxs = []int32{ - 6, // 0: uber.runway.messagequeue.MergeStep.change:type_name -> uber.base.change.Change - 7, // 1: uber.runway.messagequeue.MergeStep.strategy:type_name -> uber.base.mergestrategy.Strategy - 1, // 2: uber.runway.messagequeue.MergeRequest.steps:type_name -> uber.runway.messagequeue.MergeStep - 3, // 3: uber.runway.messagequeue.StepResult.outputs:type_name -> uber.runway.messagequeue.StepOutput + 7, // 0: uber.runway.messagequeue.MergeStep.change:type_name -> uber.base.change.Change + 8, // 1: uber.runway.messagequeue.MergeStep.strategy:type_name -> uber.base.mergestrategy.Strategy + 2, // 2: uber.runway.messagequeue.MergeRequest.steps:type_name -> uber.runway.messagequeue.MergeStep + 4, // 3: uber.runway.messagequeue.StepResult.outputs:type_name -> uber.runway.messagequeue.StepOutput 0, // 4: uber.runway.messagequeue.MergeResult.outcome:type_name -> uber.runway.messagequeue.Outcome - 4, // 5: uber.runway.messagequeue.MergeResult.steps:type_name -> uber.runway.messagequeue.StepResult - 6, // [6:6] is the sub-list for method output_type - 6, // [6:6] is the sub-list for method input_type - 6, // [6:6] is the sub-list for extension type_name - 6, // [6:6] is the sub-list for extension extendee - 0, // [0:6] is the sub-list for field type_name + 5, // 5: uber.runway.messagequeue.MergeResult.steps:type_name -> uber.runway.messagequeue.StepResult + 1, // 6: uber.runway.messagequeue.MergeResult.failure_kind:type_name -> uber.runway.messagequeue.FailureKind + 7, // [7:7] is the sub-list for method output_type + 7, // [7:7] is the sub-list for method input_type + 7, // [7:7] is the sub-list for extension type_name + 7, // [7:7] is the sub-list for extension extendee + 0, // [0:7] is the sub-list for field type_name } func init() { file_merge_proto_init() } @@ -536,7 +622,7 @@ func file_merge_proto_init() { File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_merge_proto_rawDesc), len(file_merge_proto_rawDesc)), - NumEnums: 1, + NumEnums: 2, NumMessages: 5, NumExtensions: 0, NumServices: 0, diff --git a/doc/rfc/hook-framework.md b/doc/rfc/hook-framework.md index bc33e972d..5ab48542f 100644 --- a/doc/rfc/hook-framework.md +++ b/doc/rfc/hook-framework.md @@ -52,7 +52,7 @@ Delivery promise: - Partition key = subject id; per-subject order only. - Replay finding the target state already written → republish (idempotent). Beyond it → superseded; the event may be lost. Named, accepted gap. - RPC-caused transitions are at-most-once; needing the guarantee means publishing from the first queue-driven stage. -- SubmitQueue request events follow the gateway's request summary, the status users see, rather than pipeline transitions, so a hook agrees with the UI even for a request whose start failed before the orchestrator saved it. Each status announces one event per change, so a hook retrying one change's failure never repeats another's. A finish is announced on every delivery of a log that restates it, which keeps the replay rule above: a failed publish fails the delivery and its redelivery republishes. `request.received` is published by the update that takes the request out of `accepting`, normally inside `Land`, which makes it RPC-caused and at-most-once: a failed publish is only counted. A later status announces it only when `Land` failed to record `accepted` at all. The events cross from the gateway to the orchestrator's hook stage, so their payload carries the change's URI, which never changes, and `request.failed` adds the failure's category and reason, cut to 8192 characters, and a duplicate's in-flight request id. The summary keeps the details a finish was first recorded with, so a restated finish republishes the same payload. The rest of the summary's metadata, which can hold internal diagnostics, stays out of the payload. +- SubmitQueue request events follow the gateway's request summary, the status users see, rather than pipeline transitions, so a hook agrees with the UI even for a request whose start failed before the orchestrator saved it. Each status announces one event per change, so a hook retrying one change's failure never repeats another's. A finish is announced on every delivery of a log that restates it, which keeps the replay rule above: a failed publish fails the delivery and its redelivery republishes. `request.received` is published by the update that takes the request out of `accepting`, normally inside `Land`, which makes it RPC-caused and at-most-once: a failed publish is only counted. A later status announces it only when `Land` failed to record `accepted` at all. The events cross from the gateway to the orchestrator's hook stage, so their payload carries the change's URI, which never changes, and `request.failed` adds the failure's category and reason, cut to 8192 characters, a duplicate's in-flight request id, and a merge conflict's paths. The summary keeps the details a finish was first recorded with, so a restated finish republishes the same payload. The rest of the summary's metadata, which can hold internal diagnostics, stays out of the payload. - Opt-in per host via topic-key registration; a registered host never skips, so off and loss are distinguishable. ### Contract diff --git a/runway/controller/merge/merge.go b/runway/controller/merge/merge.go index 15f33299f..f72394c6a 100644 --- a/runway/controller/merge/merge.go +++ b/runway/controller/merge/merge.go @@ -126,9 +126,11 @@ func (c *Controller) Process(ctx context.Context, delivery consumer.Delivery) er ) } failed := &runwaymq.MergeResult{ - Id: request.GetId(), - Outcome: runwaypb.Outcome_FAILED, - Reason: err.Error(), + Id: request.GetId(), + Outcome: runwaypb.Outcome_FAILED, + Reason: err.Error(), + FailureKind: merger.FailureKind(err), + ConflictingFiles: merger.ConflictingFiles(err), } // A merger that lands step by step reports the steps that landed before // the failure; they stay landed, so the caller must see them. diff --git a/runway/controller/merge/merge_test.go b/runway/controller/merge/merge_test.go index 488935d15..8ecb3f9d6 100644 --- a/runway/controller/merge/merge_test.go +++ b/runway/controller/merge/merge_test.go @@ -398,3 +398,54 @@ func TestProcess_DeserializeError(t *testing.T) { require.Error(t, controller.Process(context.Background(), delivery)) } + +func TestProcess_FailureKind(t *testing.T) { + tests := []struct { + name string + err error + wantKind runwaypb.FailureKind + wantFiles []string + }{ + { + name: "conflict naming its files", + err: &merger.ConflictError{Files: []string{"foo.go"}, Err: fmt.Errorf("conflict in foo.go: %w", merger.ErrConflict)}, + wantKind: runwaypb.FailureKind_FAILURE_KIND_CONFLICT, + wantFiles: []string{"foo.go"}, + }, + {name: "conflict without files", err: fmt.Errorf("conflict: %w", merger.ErrConflict), wantKind: runwaypb.FailureKind_FAILURE_KIND_CONFLICT}, + {name: "invalid request", err: fmt.Errorf("bad strategy: %w", merger.ErrInvalidRequest), wantKind: runwaypb.FailureKind_FAILURE_KIND_INVALID_REQUEST}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ctrl := gomock.NewController(t) + m := mergermock.NewMockMerger(ctrl) + m.EXPECT().Merge(gomock.Any(), gomock.Any()).Return(nil, tt.err) + factory := mergermock.NewMockFactory(ctrl) + factory.EXPECT().For(merger.Config{QueueName: testQueue}).Return(m, nil) + var gotPayload []byte + pub := queuemock.NewMockPublisher(ctrl) + pub.EXPECT().Publish(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn( + func(_ context.Context, _ string, msg entityqueue.Message) error { + gotPayload = msg.Payload + return nil + }, + ) + q := queuemock.NewMockQueue(ctrl) + q.EXPECT().Publisher().Return(pub).AnyTimes() + registry, err := consumer.NewTopicRegistry([]consumer.TopicConfig{ + {Key: runwaymq.TopicKeyMergeSignal, Name: "merge-signal", Queue: q}, + }) + require.NoError(t, err) + controller := newController(t, factory, registry) + req := &runwaymq.MergeRequest{Id: testID, QueueName: testQueue, Steps: []*runwaymq.MergeStep{{StepId: "step-1"}}} + + require.NoError(t, controller.Process(context.Background(), newDelivery(t, ctrl, requestPayload(t, req)))) + + result := &runwaymq.MergeResult{} + require.NoError(t, runwaymq.Unmarshal(gotPayload, result)) + assert.Equal(t, runwaypb.Outcome_FAILED, result.Outcome) + assert.Equal(t, tt.wantKind, result.FailureKind) + assert.Equal(t, tt.wantFiles, result.ConflictingFiles) + }) + } +} diff --git a/runway/controller/mergeconflictcheck/mergeconflictcheck.go b/runway/controller/mergeconflictcheck/mergeconflictcheck.go index 7c5dd771b..874627c1a 100644 --- a/runway/controller/mergeconflictcheck/mergeconflictcheck.go +++ b/runway/controller/mergeconflictcheck/mergeconflictcheck.go @@ -126,9 +126,11 @@ func (c *Controller) Process(ctx context.Context, delivery consumer.Delivery) er ) } result = &runwaymq.MergeResult{ - Id: request.GetId(), - Outcome: runwaypb.Outcome_FAILED, - Reason: err.Error(), + Id: request.GetId(), + Outcome: runwaypb.Outcome_FAILED, + Reason: err.Error(), + FailureKind: merger.FailureKind(err), + ConflictingFiles: merger.ConflictingFiles(err), } } diff --git a/runway/controller/mergeconflictcheck/mergeconflictcheck_test.go b/runway/controller/mergeconflictcheck/mergeconflictcheck_test.go index aee38de34..7c706d7e1 100644 --- a/runway/controller/mergeconflictcheck/mergeconflictcheck_test.go +++ b/runway/controller/mergeconflictcheck/mergeconflictcheck_test.go @@ -340,3 +340,54 @@ func TestProcess_DeserializeError(t *testing.T) { require.Error(t, controller.Process(context.Background(), delivery)) } + +func TestProcess_FailureKind(t *testing.T) { + tests := []struct { + name string + err error + wantKind runwaypb.FailureKind + wantFiles []string + }{ + { + name: "conflict naming its files", + err: &merger.ConflictError{Files: []string{"foo.go"}, Err: fmt.Errorf("conflict in foo.go: %w", merger.ErrConflict)}, + wantKind: runwaypb.FailureKind_FAILURE_KIND_CONFLICT, + wantFiles: []string{"foo.go"}, + }, + {name: "conflict without files", err: fmt.Errorf("conflict: %w", merger.ErrConflict), wantKind: runwaypb.FailureKind_FAILURE_KIND_CONFLICT}, + {name: "invalid request", err: fmt.Errorf("bad strategy: %w", merger.ErrInvalidRequest), wantKind: runwaypb.FailureKind_FAILURE_KIND_INVALID_REQUEST}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ctrl := gomock.NewController(t) + m := mergermock.NewMockMerger(ctrl) + m.EXPECT().CheckMergeability(gomock.Any(), gomock.Any()).Return(nil, tt.err) + factory := mergermock.NewMockFactory(ctrl) + factory.EXPECT().For(merger.Config{QueueName: testQueue}).Return(m, nil) + var gotPayload []byte + pub := queuemock.NewMockPublisher(ctrl) + pub.EXPECT().Publish(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn( + func(_ context.Context, _ string, msg entityqueue.Message) error { + gotPayload = msg.Payload + return nil + }, + ) + q := queuemock.NewMockQueue(ctrl) + q.EXPECT().Publisher().Return(pub).AnyTimes() + registry, err := consumer.NewTopicRegistry([]consumer.TopicConfig{ + {Key: runwaymq.TopicKeyMergeConflictCheckSignal, Name: "merge-conflict-check-signal", Queue: q}, + }) + require.NoError(t, err) + controller := newController(t, factory, registry) + req := &runwaymq.MergeRequest{Id: testID, QueueName: testQueue, Steps: []*runwaymq.MergeStep{{StepId: "step-1"}}} + + require.NoError(t, controller.Process(context.Background(), newDelivery(t, ctrl, requestPayload(t, req)))) + + result := &runwaymq.MergeResult{} + require.NoError(t, runwaymq.Unmarshal(gotPayload, result)) + assert.Equal(t, runwaypb.Outcome_FAILED, result.Outcome) + assert.Equal(t, tt.wantKind, result.FailureKind) + assert.Equal(t, tt.wantFiles, result.ConflictingFiles) + }) + } +} diff --git a/runway/extension/merger/BUILD.bazel b/runway/extension/merger/BUILD.bazel index 2485e033b..fc08fa363 100644 --- a/runway/extension/merger/BUILD.bazel +++ b/runway/extension/merger/BUILD.bazel @@ -1,4 +1,4 @@ -load("@rules_go//go:def.bzl", "go_library") +load("@rules_go//go:def.bzl", "go_library", "go_test") go_library( name = "go_default_library", @@ -8,5 +8,18 @@ go_library( ], importpath = "github.com/uber/submitqueue/runway/extension/merger", visibility = ["//visibility:public"], - deps = ["//api/runway/messagequeue:go_default_library"], + deps = [ + "//api/runway/messagequeue:go_default_library", + "//api/runway/messagequeue/protopb:go_default_library", + ], +) + +go_test( + name = "go_default_test", + srcs = ["merger_test.go"], + embed = [":go_default_library"], + deps = [ + "//api/runway/messagequeue/protopb:go_default_library", + "@com_github_stretchr_testify//assert:go_default_library", + ], ) diff --git a/runway/extension/merger/git/git_merger.go b/runway/extension/merger/git/git_merger.go index 2a9e250ce..e5a8b8885 100644 --- a/runway/extension/merger/git/git_merger.go +++ b/runway/extension/merger/git/git_merger.go @@ -65,10 +65,10 @@ package git import ( - "bytes" "context" "errors" "fmt" + "sort" "strings" "sync" @@ -577,7 +577,7 @@ func (m *gitMerger) applyMerge(ctx context.Context, rs resolvedStep) (applied, e if err != nil { // Read the index before aborting clears it; a non-zero exit alone // does not establish that anything collided. - conflicted := m.hasUnmergedPaths(ctx) + conflicted := m.unmergedPaths(ctx) _, _ = m.run(ctx, "merge", "--abort") return applied{}, m.classifyMergeFailure(ref, o, conflicted, err) } @@ -677,19 +677,19 @@ func (m *gitMerger) promote(ctx context.Context, req *runwaymq.MergeRequest, rs // classifyMergeFailure distinguishes invalid requests and content conflicts // from Git infrastructure failures. A non-conflict preserves its command error // so the service error processor can classify the diagnostic. -func (m *gitMerger) classifyMergeFailure(ref changeRef, out []byte, conflicted bool, cause error) error { +func (m *gitMerger) classifyMergeFailure(ref changeRef, out []byte, conflicted []string, cause error) error { detail := strings.TrimSpace(string(out)) if strings.Contains(detail, "refusing to merge unrelated histories") { coremetrics.NamedCounter(m.metricsScope, "merge", "unrelated_histories", 1) return fmt.Errorf("%w: %s shares no history with the merge target; integrating an imported history requires the merger to allow unrelated histories", merger.ErrInvalidRequest, ref.Label) } - if !conflicted { + if len(conflicted) == 0 { coremetrics.NamedCounter(m.metricsScope, "merge", "merge_errors", 1) return fmt.Errorf("git merge %s: %w", ref.SHA, cause) } coremetrics.NamedCounter(m.metricsScope, "merge", "merge_conflicts", 1) - return fmt.Errorf("%w: git merge %s: %s", merger.ErrConflict, ref.SHA, detail) + return &merger.ConflictError{Files: conflicted, Err: fmt.Errorf("%w: git merge %s: %s", merger.ErrConflict, ref.SHA, detail)} } // pickStepChanges applies every change in the step, in order, returning the @@ -771,26 +771,50 @@ func (m *gitMerger) cherryPickRange(ctx context.Context, base, head string) erro // Ask the index what happened before aborting clears it. A non-zero // exit alone does not establish a conflict; without unmerged paths, // preserve the command error for infrastructure classification. - conflicted := m.hasUnmergedPaths(ctx) + conflicted := m.unmergedPaths(ctx) _, _ = m.run(ctx, "cherry-pick", "--abort") detail := strings.TrimSpace(string(out)) - if !conflicted { + if len(conflicted) == 0 { coremetrics.NamedCounter(m.metricsScope, "merge", "cherry_pick_errors", 1) return fmt.Errorf("git cherry-pick %s..%s: %w", base, head, err) } coremetrics.NamedCounter(m.metricsScope, "merge", "cherry_pick_conflicts", 1) - return fmt.Errorf("%w: git cherry-pick %s..%s: %s", merger.ErrConflict, base, head, detail) + return &merger.ConflictError{Files: conflicted, Err: fmt.Errorf("%w: git cherry-pick %s..%s: %s", merger.ErrConflict, base, head, detail)} } return nil } -// hasUnmergedPaths reports whether the index holds conflicted entries. That is +// unmergedPaths returns the paths the index holds as conflicted, if any. That is // what separates a genuine content conflict from any other reason a git // invocation exited non-zero, and it has to be read before the operation is // aborted, since aborting clears the index. -func (m *gitMerger) hasUnmergedPaths(ctx context.Context) bool { +func (m *gitMerger) unmergedPaths(ctx context.Context) []string { out, err := m.run(ctx, "ls-files", "--unmerged") - return err == nil && len(bytes.TrimSpace(out)) > 0 + if err != nil { + return nil + } + return parseUnmergedPaths(out) +} + +// parseUnmergedPaths reads `git ls-files --unmerged` output, one +// " \t" line per conflicted stage, into the sorted, +// distinct paths. +func parseUnmergedPaths(out []byte) []string { + seen := map[string]struct{}{} + var paths []string + for _, line := range strings.Split(string(out), "\n") { + _, path, ok := strings.Cut(line, "\t") + if !ok || path == "" { + continue + } + if _, dup := seen[path]; dup { + continue + } + seen[path] = struct{}{} + paths = append(paths, path) + } + sort.Strings(paths) + return paths } // mergeBase returns the best common ancestor of two commits, or "" when they diff --git a/runway/extension/merger/git/git_merger_test.go b/runway/extension/merger/git/git_merger_test.go index fcf8e225a..f76f77380 100644 --- a/runway/extension/merger/git/git_merger_test.go +++ b/runway/extension/merger/git/git_merger_test.go @@ -121,6 +121,7 @@ func TestCherryPickRange_RealConflictIsErrConflict(t *testing.T) { err := m.cherryPickRange(context.Background(), conflictingSHA+"^", conflictingSHA) require.Error(t, err) assert.True(t, errors.Is(err, merger.ErrConflict)) + assert.Equal(t, []string{"hello.txt"}, merger.ConflictingFiles(err)) assert.True(t, f.checkoutClean(t), "the aborted pick must leave no conflicted index behind") } @@ -492,26 +493,24 @@ func TestClassifyMergeFailure(t *testing.T) { tests := []struct { name string out string - conflicted bool + conflicted []string wantConflict bool wantInvalid bool }{ { name: "content conflict", out: "CONFLICT (content): Merge conflict in a.txt", - conflicted: true, + conflicted: []string{"a.txt"}, wantConflict: true, }, { name: "unrelated histories", out: "fatal: refusing to merge unrelated histories", - conflicted: false, wantInvalid: true, }, { - name: "infrastructure failure", - out: "fatal: unable to read tree", - conflicted: false, + name: "infrastructure failure", + out: "fatal: unable to read tree", }, } @@ -522,6 +521,9 @@ func TestClassifyMergeFailure(t *testing.T) { require.Error(t, err) assert.Equal(t, tt.wantConflict, errors.Is(err, merger.ErrConflict)) assert.Equal(t, tt.wantInvalid, errors.Is(err, merger.ErrInvalidRequest)) + if tt.wantConflict { + assert.Equal(t, tt.conflicted, merger.ConflictingFiles(err)) + } if !tt.wantConflict && !tt.wantInvalid { assert.ErrorIs(t, err, cause) } @@ -529,6 +531,28 @@ func TestClassifyMergeFailure(t *testing.T) { } } +func TestParseUnmergedPaths(t *testing.T) { + tests := []struct { + name string + out string + want []string + }{ + {name: "nothing unmerged", out: ""}, + { + name: "each path once, sorted", + out: "100644 1111111111111111111111111111111111111111 1\tz.txt\n" + + "100644 2222222222222222222222222222222222222222 2\tz.txt\n" + + "100644 3333333333333333333333333333333333333333 3\tdir/a b.txt\n", + want: []string{"dir/a b.txt", "z.txt"}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, parseUnmergedPaths([]byte(tt.out))) + }) + } +} + // --- change provider consistency --- // newUnrunnableMerger builds a Merger whose git executable does not exist, so diff --git a/runway/extension/merger/merger.go b/runway/extension/merger/merger.go index ae3c18c7d..b3ec9e6ef 100644 --- a/runway/extension/merger/merger.go +++ b/runway/extension/merger/merger.go @@ -25,6 +25,7 @@ import ( "errors" runwaymq "github.com/uber/submitqueue/api/runway/messagequeue" + runwaypb "github.com/uber/submitqueue/api/runway/messagequeue/protopb" ) // ErrConflict signals that the ordered steps could not be applied cleanly. @@ -39,6 +40,40 @@ var ErrConflict = errors.New("merge conflict") // failure result rather than nacking into an infinite retry / dead-letter. var ErrInvalidRequest = errors.New("invalid merge request") +// ConflictError is an ErrConflict that names the paths that did not apply, for a +// merger that can tell. Files are repository-relative; empty when unknown. +type ConflictError struct { + // Files are the conflicting paths, relative to the repository root. + Files []string + // Err is the underlying conflict error; it must wrap ErrConflict. + Err error +} + +func (e *ConflictError) Error() string { return e.Err.Error() } + +func (e *ConflictError) Unwrap() error { return e.Err } + +// FailureKind classifies a terminal merge error for a FAILED result. +func FailureKind(err error) runwaypb.FailureKind { + switch { + case errors.Is(err, ErrConflict): + return runwaypb.FailureKind_FAILURE_KIND_CONFLICT + case errors.Is(err, ErrInvalidRequest): + return runwaypb.FailureKind_FAILURE_KIND_INVALID_REQUEST + default: + return runwaypb.FailureKind_FAILURE_KIND_UNSPECIFIED + } +} + +// ConflictingFiles returns the paths a ConflictError in err's chain names, or nil. +func ConflictingFiles(err error) []string { + var conflict *ConflictError + if errors.As(err, &conflict) { + return conflict.Files + } + return nil +} + // IsTerminal reports whether err is a terminal merge outcome — one the client // must be told about via a FAILED result rather than retried. Controllers use // it to decide between publishing a FAILED result (ack) and nacking for retry. diff --git a/runway/extension/merger/merger_test.go b/runway/extension/merger/merger_test.go new file mode 100644 index 000000000..8a2a50fdf --- /dev/null +++ b/runway/extension/merger/merger_test.go @@ -0,0 +1,49 @@ +// 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 merger + +import ( + "errors" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + runwaypb "github.com/uber/submitqueue/api/runway/messagequeue/protopb" +) + +func TestFailureKind(t *testing.T) { + tests := []struct { + name string + err error + wantKind runwaypb.FailureKind + wantFiles []string + }{ + {name: "conflict", err: fmt.Errorf("%w: git merge abc", ErrConflict), wantKind: runwaypb.FailureKind_FAILURE_KIND_CONFLICT}, + { + name: "conflict naming its files", + err: fmt.Errorf("step 1: %w", &ConflictError{Files: []string{"a.go", "b/c.go"}, Err: fmt.Errorf("%w: git merge abc", ErrConflict)}), + wantKind: runwaypb.FailureKind_FAILURE_KIND_CONFLICT, + wantFiles: []string{"a.go", "b/c.go"}, + }, + {name: "invalid request", err: fmt.Errorf("%w: unknown strategy", ErrInvalidRequest), wantKind: runwaypb.FailureKind_FAILURE_KIND_INVALID_REQUEST}, + {name: "other error", err: errors.New("push rejected"), wantKind: runwaypb.FailureKind_FAILURE_KIND_UNSPECIFIED}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.wantKind, FailureKind(tt.err)) + assert.Equal(t, tt.wantFiles, ConflictingFiles(tt.err)) + }) + } +} diff --git a/submitqueue/core/hookevent/hookevent.go b/submitqueue/core/hookevent/hookevent.go index b4455ebd7..e5f7d2ac7 100644 --- a/submitqueue/core/hookevent/hookevent.go +++ b/submitqueue/core/hookevent/hookevent.go @@ -27,8 +27,9 @@ // retries one change's failed side effect never repeats the others'. Payloads // carry the queue, the request id, and that change's URI. A request.failed // payload also carries the failure's category, its reason, and the details a -// category has (such as the request a duplicate repeats), when the request has -// them, so a hook can say why without asking for the summary. The gateway +// category has (the request a duplicate repeats, a merge conflict's paths), +// when the request has them, so a hook can say why without asking for the +// summary. The gateway // publishes these events and the orchestrator's hook stage consumes them, and a // hook there cannot read the gateway's store, so the payload carries what a // hook needs to reach the change. A request's URIs never change, so they cannot @@ -100,14 +101,18 @@ const ( PayloadKeyFailureReason = "failure_reason" // PayloadKeyDuplicateOf holds the id of the in-flight request a duplicate repeats. PayloadKeyDuplicateOf = "duplicate_of" + // PayloadKeyConflictingFiles holds a merge conflict's paths, one per line + // (see entity.SplitConflictingFiles), at most entity.MaxConflictingFiles. + PayloadKeyConflictingFiles = "conflicting_files" ) // failureMetadataPayloadKeys maps the summary metadata a failed payload may carry // to its payload key. Anything else in the metadata, such as dead-letter // diagnostics, stays out of hook events. var failureMetadataPayloadKeys = map[string]string{ - entity.RequestLogMetadataKeyFailureCategory: PayloadKeyFailureCategory, - entity.RequestLogMetadataKeyDuplicateOf: PayloadKeyDuplicateOf, + entity.RequestLogMetadataKeyFailureCategory: PayloadKeyFailureCategory, + entity.RequestLogMetadataKeyDuplicateOf: PayloadKeyDuplicateOf, + entity.RequestLogMetadataKeyConflictingFiles: PayloadKeyConflictingFiles, } // maxFailureReasonRunes bounds a failure reason in a payload. A reason can be diff --git a/submitqueue/core/hookevent/hookevent_test.go b/submitqueue/core/hookevent/hookevent_test.go index 627504055..22e0234a8 100644 --- a/submitqueue/core/hookevent/hookevent_test.go +++ b/submitqueue/core/hookevent/hookevent_test.go @@ -176,6 +176,17 @@ func TestNewRequestFinished_FailureFields(t *testing.T) { PayloadKeyDuplicateOf: "93", }, }, + { + name: "a merge conflict names its files", + status: entity.RequestStatusError, + lastError: "merge conflict: foo.go", + metadata: map[string]string{entity.RequestLogMetadataKeyFailureCategory: "merge_conflict", entity.RequestLogMetadataKeyConflictingFiles: "foo.go\nbar.go"}, + wantFields: map[string]string{ + PayloadKeyFailureCategory: "merge_conflict", + PayloadKeyFailureReason: "merge conflict: foo.go", + PayloadKeyConflictingFiles: "foo.go\nbar.go", + }, + }, { name: "failed without a category", status: entity.RequestStatusError, diff --git a/submitqueue/core/messagequeue/topics.go b/submitqueue/core/messagequeue/topics.go index 310ce0d0c..1fbc119ba 100644 --- a/submitqueue/core/messagequeue/topics.go +++ b/submitqueue/core/messagequeue/topics.go @@ -63,3 +63,7 @@ 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" + +// MetadataKeyConflictingFiles is the conclude message's metadata attribute carrying +// a merge-conflicted batch's conflicting paths, encoded by entity.JoinConflictingFiles. +const MetadataKeyConflictingFiles = "conflicting_files" diff --git a/submitqueue/core/topickey/topickey.go b/submitqueue/core/topickey/topickey.go index c9f0afdf5..8427fd705 100644 --- a/submitqueue/core/topickey/topickey.go +++ b/submitqueue/core/topickey/topickey.go @@ -49,4 +49,6 @@ const ( MetadataKeyFailureReason = messagequeue.MetadataKeyFailureReason // MetadataKeyFailureCategory is the conclude message metadata attribute for a failed batch's failure category. MetadataKeyFailureCategory = messagequeue.MetadataKeyFailureCategory + // MetadataKeyConflictingFiles is the conclude message metadata attribute for a merge-conflicted batch's paths. + MetadataKeyConflictingFiles = messagequeue.MetadataKeyConflictingFiles ) diff --git a/submitqueue/entity/failure_category.go b/submitqueue/entity/failure_category.go index 2f63cb4c8..d3f1beb8f 100644 --- a/submitqueue/entity/failure_category.go +++ b/submitqueue/entity/failure_category.go @@ -14,6 +14,8 @@ package entity +import "strings" + // 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 @@ -27,8 +29,11 @@ const ( 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. + // FailureCategoryMergeConflict means the request's changes do not apply cleanly onto the target + // branch; the author has to rebase before it can land. + FailureCategoryMergeConflict FailureCategory = "merge_conflict" + // FailureCategoryLandFailed means merging the request into the target branch failed or was refused + // for a reason other than a conflict. FailureCategoryLandFailed FailureCategory = "land_failed" // FailureCategoryInternalError means SubmitQueue itself could not finish processing the request. FailureCategoryInternalError FailureCategory = "internal_error" @@ -42,6 +47,31 @@ const RequestLogMetadataKeyFailureCategory = "failure_category" // ID of the in-flight request that a FailureCategoryDuplicate request duplicates. const RequestLogMetadataKeyDuplicateOf = "duplicate_of" +// RequestLogMetadataKeyConflictingFiles is the request log metadata key holding +// a FailureCategoryMergeConflict request's conflicting paths, as written by +// JoinConflictingFiles. It is absent when the merge backend could not tell. +const RequestLogMetadataKeyConflictingFiles = "conflicting_files" + +// MaxConflictingFiles bounds how many conflicting paths a request records. +const MaxConflictingFiles = 10 + +// JoinConflictingFiles encodes at most MaxConflictingFiles paths, one per line, +// for RequestLogMetadataKeyConflictingFiles. +func JoinConflictingFiles(files []string) string { + if len(files) > MaxConflictingFiles { + files = files[:MaxConflictingFiles] + } + return strings.Join(files, "\n") +} + +// SplitConflictingFiles decodes a JoinConflictingFiles value. +func SplitConflictingFiles(value string) []string { + if value == "" { + return nil + } + return strings.Split(value, "\n") +} + // FailureCategoryMetadata returns metadata with category recorded under // RequestLogMetadataKeyFailureCategory, leaving metadata itself unchanged. An // unknown category records nothing. diff --git a/submitqueue/entity/failure_category_test.go b/submitqueue/entity/failure_category_test.go index 5cde40afd..4ddfc4279 100644 --- a/submitqueue/entity/failure_category_test.go +++ b/submitqueue/entity/failure_category_test.go @@ -15,6 +15,7 @@ package entity import ( + "fmt" "testing" "github.com/stretchr/testify/assert" @@ -45,3 +46,24 @@ func TestFailureCategoryMetadata(t *testing.T) { }) } } + +func TestConflictingFiles(t *testing.T) { + many := make([]string, MaxConflictingFiles+2) + for i := range many { + many[i] = fmt.Sprintf("f%d.go", i) + } + tests := []struct { + name string + files []string + want []string + }{ + {name: "none"}, + {name: "a few", files: []string{"a.go", "dir/b.go"}, want: []string{"a.go", "dir/b.go"}}, + {name: "capped", files: many, want: many[:MaxConflictingFiles]}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, SplitConflictingFiles(JoinConflictingFiles(tt.files))) + }) + } +} diff --git a/submitqueue/gateway/README.md b/submitqueue/gateway/README.md index 1475affd9..e89940ae3 100644 --- a/submitqueue/gateway/README.md +++ b/submitqueue/gateway/README.md @@ -29,7 +29,7 @@ A finished status keeps the reason and metadata it was first recorded with. When ## Request hook events -The materializer publishes SubmitQueue's request hook events (`submitqueue/core/hookevent`) to the `submitqueue-hook` topic, which the orchestrator pipeline's hook stage consumes, one event per change of the request. The update that takes the summary out of `accepting` announces `request.received`, once. That is normally `Land`, and a later log only when `Land` failed to record `accepted`; a failed receipt publish is only counted on `request_hook.publish_errors` and never repeated. Every delivery of a log that restates a `landed`, `error` or `cancelled` summary announces `request.landed`, `request.failed` or `request.cancelled`, so a failed publish is returned and the log's redelivery repairs it; a copy that arrives after the queue has forgotten the event id reaches hooks twice. Events therefore follow the summary users see, including a request whose start failed before the orchestrator saved it, and a stale or unfinished log publishes nothing. A `request.failed` payload also carries the summary's `failure_category`, its reason as `failure_reason`, and for a duplicate the in-flight request as `duplicate_of`, when it has them. +The materializer publishes SubmitQueue's request hook events (`submitqueue/core/hookevent`) to the `submitqueue-hook` topic, which the orchestrator pipeline's hook stage consumes, one event per change of the request. The update that takes the summary out of `accepting` announces `request.received`, once. That is normally `Land`, and a later log only when `Land` failed to record `accepted`; a failed receipt publish is only counted on `request_hook.publish_errors` and never repeated. Every delivery of a log that restates a `landed`, `error` or `cancelled` summary announces `request.landed`, `request.failed` or `request.cancelled`, so a failed publish is returned and the log's redelivery repairs it; a copy that arrives after the queue has forgotten the event id reaches hooks twice. Events therefore follow the summary users see, including a request whose start failed before the orchestrator saved it, and a stale or unfinished log publishes nothing. A `request.failed` payload also carries the summary's `failure_category`, its reason as `failure_reason`, for a duplicate the in-flight request as `duplicate_of`, and for a merge conflict its paths as `conflicting_files`, when it has them. ## Final log recovery diff --git a/submitqueue/orchestrator/controller/conclude/BUILD.bazel b/submitqueue/orchestrator/controller/conclude/BUILD.bazel index 023e79266..69bf1040f 100644 --- a/submitqueue/orchestrator/controller/conclude/BUILD.bazel +++ b/submitqueue/orchestrator/controller/conclude/BUILD.bazel @@ -10,8 +10,6 @@ go_library( "//platform/consumer:go_default_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 91e6c4a92..98cf09e48 100644 --- a/submitqueue/orchestrator/controller/conclude/conclude.go +++ b/submitqueue/orchestrator/controller/conclude/conclude.go @@ -23,8 +23,6 @@ import ( "github.com/uber/submitqueue/platform/consumer" "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" @@ -109,7 +107,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], entity.FailureCategory(msg.Metadata[topickey.MetadataKeyFailureCategory])) + return corebatch.ConcludeBatchRequests(ctx, store, c.registry, c.logger, c.metricsScope, batch, corebatch.FailureFromConcludeMetadata(msg.Metadata)) } // 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 1ac097a92..3361b2496 100644 --- a/submitqueue/orchestrator/controller/conclude/conclude_test.go +++ b/submitqueue/orchestrator/controller/conclude/conclude_test.go @@ -466,52 +466,76 @@ func TestController_Process(t *testing.T) { // reaches the request's terminal error log, instead of the empty message the // request used to carry. func TestController_Process_FailedBatchCarriesReasonToRequestLog(t *testing.T) { - ctrl := gomock.NewController(t) - - const reason = "merge failed: conflict in pkg/a/foo.go" - batch := entity.Batch{ - ID: "9", - Queue: "test-queue", - Contains: []string{"9"}, - State: entity.BatchStateFailed, - Version: 2, + tests := []struct { + name string + metadata map[string]string + }{ + { + name: "build failed", + metadata: map[string]string{ + topickey.MetadataKeyFailureReason: "no speculation path could pass", + topickey.MetadataKeyFailureCategory: string(entity.FailureCategoryBuildFailed), + }, + }, + { + name: "merge conflict with its files", + metadata: map[string]string{ + topickey.MetadataKeyFailureReason: "merge failed: conflict in pkg/a/foo.go", + topickey.MetadataKeyFailureCategory: string(entity.FailureCategoryMergeConflict), + topickey.MetadataKeyConflictingFiles: "pkg/a/foo.go", + }, + }, } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ctrl := gomock.NewController(t) - batchStore := storagemock.NewMockBatchStore(ctrl) - batchStore.EXPECT().Get(gomock.Any(), batch.ID).Return(batch, nil) + batch := entity.Batch{ + ID: "9", + Queue: "test-queue", + Contains: []string{"9"}, + State: entity.BatchStateFailed, + Version: 2, + } - request := entity.Request{ID: "9", Queue: "test-queue", Version: 1, State: entity.RequestStateProcessing} - requestStore := storagemock.NewMockRequestStore(ctrl) - requestStore.EXPECT().Get(gomock.Any(), "9").Return(request, nil) - requestStore.EXPECT().Update(gomock.Any(), requestWithState(request, entity.RequestStateError), int32(1), int32(2)).Return(nil) + batchStore := storagemock.NewMockBatchStore(ctrl) + batchStore.EXPECT().Get(gomock.Any(), batch.ID).Return(batch, nil) - store := orchstoragemock.NewMockStorage(ctrl) - store.EXPECT().GetBatchStore().Return(batchStore).AnyTimes() - store.EXPECT().GetRequestStore().Return(requestStore).AnyTimes() + request := entity.Request{ID: "9", Queue: "test-queue", Version: 1, State: entity.RequestStateProcessing} + requestStore := storagemock.NewMockRequestStore(ctrl) + requestStore.EXPECT().Get(gomock.Any(), "9").Return(request, nil) + requestStore.EXPECT().Update(gomock.Any(), requestWithState(request, entity.RequestStateError), int32(1), int32(2)).Return(nil) - controller, pub := newTestController(t, ctrl, store, false) + store := orchstoragemock.NewMockStorage(ctrl) + store.EXPECT().GetBatchStore().Return(batchStore).AnyTimes() + store.EXPECT().GetRequestStore().Return(requestStore).AnyTimes() - var logged entity.RequestLog - 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) - logged = log - return nil - }, - ) + controller, pub := newTestController(t, ctrl, store, false) - 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() - delivery.EXPECT().Attempt().Return(1).AnyTimes() + var logged entity.RequestLog + 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) + logged = log + return nil + }, + ) - require.NoError(t, controller.Process(context.Background(), delivery)) + msg := entityqueue.NewMessage(batch.ID, batchIDPayload(t, batch.ID), batch.Queue, tt.metadata) + msg.Tenant = batch.Queue + delivery := consumermock.NewMockDelivery(ctrl) + delivery.EXPECT().Message().Return(msg).AnyTimes() + delivery.EXPECT().Attempt().Return(1).AnyTimes() - assert.Equal(t, entity.RequestStatusError, logged.Status) - assert.Equal(t, reason, logged.LastError) - assert.Equal(t, string(entity.FailureCategoryBuildFailed), logged.Metadata[entity.RequestLogMetadataKeyFailureCategory]) + require.NoError(t, controller.Process(context.Background(), delivery)) + + assert.Equal(t, entity.RequestStatusError, logged.Status) + assert.Equal(t, tt.metadata[topickey.MetadataKeyFailureReason], logged.LastError) + assert.Equal(t, tt.metadata[topickey.MetadataKeyFailureCategory], logged.Metadata[entity.RequestLogMetadataKeyFailureCategory]) + assert.Equal(t, tt.metadata[topickey.MetadataKeyConflictingFiles], logged.Metadata[entity.RequestLogMetadataKeyConflictingFiles]) + }) + } } func TestController_Process_StorageFailure(t *testing.T) { diff --git a/submitqueue/orchestrator/controller/dlq/conclude.go b/submitqueue/orchestrator/controller/dlq/conclude.go index b42b39f0e..2879040f7 100644 --- a/submitqueue/orchestrator/controller/dlq/conclude.go +++ b/submitqueue/orchestrator/controller/dlq/conclude.go @@ -22,8 +22,6 @@ import ( entityqueue "github.com/uber/submitqueue/platform/base/messagequeue" "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" @@ -77,7 +75,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], entity.FailureCategory(msg.Metadata[topickey.MetadataKeyFailureCategory])) + return corebatch.ConcludeBatchRequests(ctx, store, c.registry, c.logger, c.metricsScope, batch, corebatch.FailureFromConcludeMetadata(msg.Metadata)) } func (c *concludeController) Name() string { return string(c.topicKey) } diff --git a/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal.go b/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal.go index 957bf12fe..63c4a694c 100644 --- a/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal.go +++ b/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal.go @@ -177,7 +177,8 @@ func (c *Controller) failRequest(ctx context.Context, store orchstorage.Storage, // 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) + category, details := corerequest.LandFailure(result) + return result.Reason, entity.FailureCategoryMetadata(details, category) } // publishRequestID publishes a request ID to the given topic key, stamped with diff --git a/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal_test.go b/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal_test.go index e6ab5c9f9..4469b18fb 100644 --- a/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal_test.go +++ b/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal_test.go @@ -139,58 +139,80 @@ func TestProcess_LandablePublishesToBatch(t *testing.T) { } func TestProcess_NotLandableMarksRequestError(t *testing.T) { - ctrl := gomock.NewController(t) + tests := []struct { + name string + kind runwaypb.FailureKind + files []string + wantCategory entity.FailureCategory + wantFiles string + }{ + {name: "unclassified failure", wantCategory: entity.FailureCategoryLandFailed}, + {name: "invalid request", kind: runwaypb.FailureKind_FAILURE_KIND_INVALID_REQUEST, wantCategory: entity.FailureCategoryLandFailed}, + { + name: "conflict naming its files", + kind: runwaypb.FailureKind_FAILURE_KIND_CONFLICT, + files: []string{"foo.go", "bar.go"}, + wantCategory: entity.FailureCategoryMergeConflict, + wantFiles: "foo.go\nbar.go", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ctrl := gomock.NewController(t) - reqStore := storagemock.NewMockRequestStore(ctrl) - request := entity.Request{ID: testRequestID, Queue: testQueue, State: entity.RequestStateStarted, Version: 1} - reqStore.EXPECT().Get(gomock.Any(), testRequestID).Return(request, nil).Times(2) - // The request is driven to terminal Error inline (version 1 -> 2). - reqStore.EXPECT().Update(gomock.Any(), requestWithState(request, entity.RequestStateError), int32(1), int32(2)).Return(nil) + reqStore := storagemock.NewMockRequestStore(ctrl) + request := entity.Request{ID: testRequestID, Queue: testQueue, State: entity.RequestStateStarted, Version: 1} + reqStore.EXPECT().Get(gomock.Any(), testRequestID).Return(request, nil).Times(2) + // The request is driven to terminal Error inline (version 1 -> 2). + reqStore.EXPECT().Update(gomock.Any(), requestWithState(request, entity.RequestStateError), int32(1), int32(2)).Return(nil) - store := orchstoragemock.NewMockStorage(ctrl) - store.EXPECT().GetRequestStore().Return(reqStore).AnyTimes() + store := orchstoragemock.NewMockStorage(ctrl) + store.EXPECT().GetRequestStore().Return(reqStore).AnyTimes() - // One publish is expected — the terminal log entry to the log topic. A publish - // to the batch topic would be a bug (gomock fails on the unexpected 2nd call). - var gotTopic string - var gotPayload []byte - pub := queuemock.NewMockPublisher(ctrl) - pub.EXPECT().Publish(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn( - func(_ context.Context, topic string, msg entityqueue.Message) error { - gotTopic = topic - gotPayload = msg.Payload - return nil - }, - ) - q := queuemock.NewMockQueue(ctrl) - q.EXPECT().Publisher().Return(pub).AnyTimes() - registry, err := consumer.NewTopicRegistry( - []consumer.TopicConfig{ - {Key: topickey.TopicKeyBatch, Name: "batch", Queue: q}, - {Key: topickey.TopicKeyLog, Name: "log", Queue: q}, - }, - ) - require.NoError(t, err) + // One publish is expected — the terminal log entry to the log topic. A publish + // to the batch topic would be a bug (gomock fails on the unexpected 2nd call). + var gotTopic string + var gotPayload []byte + pub := queuemock.NewMockPublisher(ctrl) + pub.EXPECT().Publish(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn( + func(_ context.Context, topic string, msg entityqueue.Message) error { + gotTopic = topic + gotPayload = msg.Payload + return nil + }, + ) + q := queuemock.NewMockQueue(ctrl) + q.EXPECT().Publisher().Return(pub).AnyTimes() + registry, err := consumer.NewTopicRegistry( + []consumer.TopicConfig{ + {Key: topickey.TopicKeyBatch, Name: "batch", Queue: q}, + {Key: topickey.TopicKeyLog, Name: "log", Queue: q}, + }, + ) + require.NoError(t, err) - storageFactory := orchstoragemock.NewMockFactory(ctrl) - storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() - controller := NewController(zaptest.NewLogger(t).Sugar(), tally.NoopScope, storageFactory, registry, - runwaymq.TopicKeyMergeConflictCheckSignal, "orchestrator-landconflictsignal") + controller := NewController(zaptest.NewLogger(t).Sugar(), tally.NoopScope, storageFactory, registry, + runwaymq.TopicKeyMergeConflictCheckSignal, "orchestrator-landconflictsignal") - res := runwaymq.MergeResult{Id: testRequestID, Outcome: runwaypb.Outcome_FAILED, Reason: "conflict in foo.go"} - msg := entityqueue.NewMessage(testRequestID, resultPayload(t, res), testQueue, nil) - // Not-landable is an expected terminal outcome, so Process acks (no error). - require.NoError(t, controller.Process(context.Background(), newDelivery(ctrl, msg))) + res := runwaymq.MergeResult{Id: testRequestID, Outcome: runwaypb.Outcome_FAILED, Reason: "conflict in foo.go", FailureKind: tt.kind, ConflictingFiles: tt.files} + msg := entityqueue.NewMessage(testRequestID, resultPayload(t, res), testQueue, nil) + // Not-landable is an expected terminal outcome, so Process acks (no error). + require.NoError(t, controller.Process(context.Background(), newDelivery(ctrl, msg))) - // The single publish is the terminal log entry carrying the conflict reason. - assert.Equal(t, "log", gotTopic) - logEntry, err := sqmq.UnmarshalRequestLog(gotPayload) - require.NoError(t, err) - 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]) + // The single publish is the terminal log entry carrying the conflict reason. + assert.Equal(t, "log", gotTopic) + logEntry, err := sqmq.UnmarshalRequestLog(gotPayload) + require.NoError(t, err) + 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(tt.wantCategory), logEntry.Metadata[entity.RequestLogMetadataKeyFailureCategory]) + assert.Equal(t, tt.wantFiles, logEntry.Metadata[entity.RequestLogMetadataKeyConflictingFiles]) + }) + } } func TestFailRequest_UpdateFailureLeavesRequestUnchanged(t *testing.T) { @@ -252,6 +274,7 @@ func TestProcess_ErrorRequestResendsTerminalLog(t *testing.T) { result runwaymq.MergeResult wantLastError string wantCategory entity.FailureCategory + wantFiles string }{ { name: "a redelivered failure says why", @@ -259,6 +282,16 @@ func TestProcess_ErrorRequestResendsTerminalLog(t *testing.T) { wantLastError: "conflict in foo.go", wantCategory: entity.FailureCategoryLandFailed, }, + { + name: "a redelivered conflict names its files", + result: runwaymq.MergeResult{ + Id: testRequestID, Outcome: runwaypb.Outcome_FAILED, Reason: "merge conflict", + FailureKind: runwaypb.FailureKind_FAILURE_KIND_CONFLICT, ConflictingFiles: []string{"a.go", "b.go"}, + }, + wantLastError: "merge conflict", + wantCategory: entity.FailureCategoryMergeConflict, + wantFiles: "a.go\nb.go", + }, { name: "a success cannot say why the request failed", result: runwaymq.MergeResult{Id: testRequestID, Outcome: runwaypb.Outcome_SUCCEEDED}, @@ -301,6 +334,7 @@ func TestProcess_ErrorRequestResendsTerminalLog(t *testing.T) { 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]) + assert.Equal(t, tt.wantFiles, logs[0].Metadata[entity.RequestLogMetadataKeyConflictingFiles]) }) } } diff --git a/submitqueue/orchestrator/controller/landsignal/BUILD.bazel b/submitqueue/orchestrator/controller/landsignal/BUILD.bazel index 9c806b9e6..dbe344958 100644 --- a/submitqueue/orchestrator/controller/landsignal/BUILD.bazel +++ b/submitqueue/orchestrator/controller/landsignal/BUILD.bazel @@ -16,6 +16,7 @@ go_library( "//submitqueue/core/topickey:go_default_library", "//submitqueue/entity:go_default_library", "//submitqueue/orchestrator/core/batch:go_default_library", + "//submitqueue/orchestrator/core/request:go_default_library", "//submitqueue/orchestrator/extension/storage:go_default_library", "@com_github_uber_go_tally//:go_default_library", "@org_uber_go_zap//:go_default_library", diff --git a/submitqueue/orchestrator/controller/landsignal/landsignal.go b/submitqueue/orchestrator/controller/landsignal/landsignal.go index cff140e6d..ea162798f 100644 --- a/submitqueue/orchestrator/controller/landsignal/landsignal.go +++ b/submitqueue/orchestrator/controller/landsignal/landsignal.go @@ -36,6 +36,7 @@ import ( "github.com/uber/submitqueue/submitqueue/core/topickey" "github.com/uber/submitqueue/submitqueue/entity" corebatch "github.com/uber/submitqueue/submitqueue/orchestrator/core/batch" + corerequest "github.com/uber/submitqueue/submitqueue/orchestrator/core/request" orchstorage "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage" "go.uber.org/zap" ) @@ -131,11 +132,12 @@ func (c *Controller) Process(ctx context.Context, delivery consumer.Delivery) er // the batch, so it reaches the request's terminal log without becoming durable // batch state. Empty on the landed path. Computed before the idempotency check // so a redelivered failed batch re-fans-out with its reason intact. - var failureReason string + var failure corebatch.Failure if result.Outcome != runwaypb.Outcome_SUCCEEDED { - failureReason = result.Reason - if failureReason == "" { - failureReason = "land failed" + failure.Category, failure.Details = corerequest.LandFailure(result) + failure.Reason = result.Reason + if failure.Reason == "" { + failure.Reason = "land failed" } } @@ -149,7 +151,7 @@ func (c *Controller) Process(ctx context.Context, delivery consumer.Delivery) er metrics.NamedCounter(c.metricsScope, opName, "state_update_errors", 1, metrics.TagsFromContext(ctx)...) return err } - return c.fanout(ctx, batch.ID, batch.Queue, failureReason) + return c.fanout(ctx, batch.ID, batch.Queue, failure) } var newState entity.BatchState @@ -174,7 +176,7 @@ func (c *Controller) Process(ctx context.Context, delivery consumer.Delivery) er return err } - return c.fanout(ctx, batch.ID, batch.Queue, failureReason) + return c.fanout(ctx, batch.ID, batch.Queue, failure) } // fanout publishes the batch ID to conclude (so requests are updated) and to @@ -187,15 +189,8 @@ func (c *Controller) Process(ctx context.Context, delivery consumer.Delivery) er // scoped the same way because speculate publishes there too when a batch goes // terminal on its own; the two mean the same thing but are decided at // different moments, so neither may swallow the other. -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, - topickey.MetadataKeyFailureCategory: string(entity.FailureCategoryLandFailed), - } - } - if err := c.publish(ctx, topickey.TopicKeyConclude, publish.IntentID(batchID, "conclude", "landed"), batchID, queue, concludeMeta); err != nil { +func (c *Controller) fanout(ctx context.Context, batchID, queue string, failure corebatch.Failure) error { + if err := c.publish(ctx, topickey.TopicKeyConclude, publish.IntentID(batchID, "conclude", "landed"), batchID, queue, failure.ConcludeMetadata()); err != nil { metrics.NamedCounter(c.metricsScope, "process", "publish_conclude_errors", 1, metrics.TagsFromContext(ctx)...) return fmt.Errorf("failed to publish to conclude: %w", err) } diff --git a/submitqueue/orchestrator/controller/landsignal/landsignal_test.go b/submitqueue/orchestrator/controller/landsignal/landsignal_test.go index 9a837593d..a9c78c1c8 100644 --- a/submitqueue/orchestrator/controller/landsignal/landsignal_test.go +++ b/submitqueue/orchestrator/controller/landsignal/landsignal_test.go @@ -218,54 +218,75 @@ func TestProcess_FanoutDoesNotCollideWithTheBatchAnnouncement(t *testing.T) { } func TestProcess_NotLandedMarksBatchFailed(t *testing.T) { - ctrl := gomock.NewController(t) - - batchStore := storagemock.NewMockBatchStore(ctrl) - batch := entity.Batch{ - ID: testBatchID, - Queue: testQueue, - Contains: []string{"1"}, - Dependencies: []string{"0"}, - State: entity.BatchStateLanding, - Version: 3, - } - batchStore.EXPECT().Get(gomock.Any(), testBatchID).Return(batch, nil) - // The failed transition records only the terminal state; the reason travels - // to conclude on the message, not on the batch. - batchStore.EXPECT().Update(gomock.Any(), batchWithState(batch, entity.BatchStateFailed), int32(3), int32(4)).Return(nil) - - store := orchstoragemock.NewMockStorage(ctrl) - store.EXPECT().GetQueueBatchStateStore().Return(newQueueBatchStateStore(ctrl)).AnyTimes() - store.EXPECT().GetBatchStore().Return(batchStore).AnyTimes() - - byTopic := map[string]entityqueue.Message{} - pub := queuemock.NewMockPublisher(ctrl) - pub.EXPECT().Publish(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn( - func(_ context.Context, topic string, msg entityqueue.Message) error { - byTopic[topic] = msg - return nil + tests := []struct { + name string + kind runwaypb.FailureKind + files []string + wantCategory entity.FailureCategory + wantFiles string + }{ + {name: "unclassified failure", wantCategory: entity.FailureCategoryLandFailed}, + { + name: "conflict naming its files", + kind: runwaypb.FailureKind_FAILURE_KIND_CONFLICT, + files: []string{"foo.go"}, + wantCategory: entity.FailureCategoryMergeConflict, + wantFiles: "foo.go", }, - ).AnyTimes() - q := queuemock.NewMockQueue(ctrl) - q.EXPECT().Publisher().Return(pub).AnyTimes() - registry, err := consumer.NewTopicRegistry([]consumer.TopicConfig{ - {Key: topickey.TopicKeyConclude, Name: "conclude", Queue: q}, - {Key: topickey.TopicKeySpeculate, Name: "speculate", Queue: q}, - }) - require.NoError(t, err) - - res := runwaymq.MergeResult{Id: testBatchID, Outcome: runwaypb.Outcome_FAILED, Reason: "conflict in foo.go"} - msg := entityqueue.NewMessage(testBatchID, resultPayload(t, res), testQueue, nil) - // Not-landed is an expected terminal outcome, so Process acks (no error). - require.NoError(t, newController(t, store, registry).Process(context.Background(), newDelivery(ctrl, msg))) - - require.Contains(t, byTopic, "conclude") - require.Contains(t, byTopic, "speculate") - // The land failure reason rides the conclude message so conclude can stamp it on - // 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]) + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ctrl := gomock.NewController(t) + + batchStore := storagemock.NewMockBatchStore(ctrl) + batch := entity.Batch{ + ID: testBatchID, + Queue: testQueue, + Contains: []string{"1"}, + Dependencies: []string{"0"}, + State: entity.BatchStateLanding, + Version: 3, + } + batchStore.EXPECT().Get(gomock.Any(), testBatchID).Return(batch, nil) + // The failed transition records only the terminal state; the reason travels + // to conclude on the message, not on the batch. + batchStore.EXPECT().Update(gomock.Any(), batchWithState(batch, entity.BatchStateFailed), int32(3), int32(4)).Return(nil) + + store := orchstoragemock.NewMockStorage(ctrl) + store.EXPECT().GetQueueBatchStateStore().Return(newQueueBatchStateStore(ctrl)).AnyTimes() + store.EXPECT().GetBatchStore().Return(batchStore).AnyTimes() + + byTopic := map[string]entityqueue.Message{} + pub := queuemock.NewMockPublisher(ctrl) + pub.EXPECT().Publish(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn( + func(_ context.Context, topic string, msg entityqueue.Message) error { + byTopic[topic] = msg + return nil + }, + ).AnyTimes() + q := queuemock.NewMockQueue(ctrl) + q.EXPECT().Publisher().Return(pub).AnyTimes() + registry, err := consumer.NewTopicRegistry([]consumer.TopicConfig{ + {Key: topickey.TopicKeyConclude, Name: "conclude", Queue: q}, + {Key: topickey.TopicKeySpeculate, Name: "speculate", Queue: q}, + }) + require.NoError(t, err) + + res := runwaymq.MergeResult{Id: testBatchID, Outcome: runwaypb.Outcome_FAILED, Reason: "conflict in foo.go", FailureKind: tt.kind, ConflictingFiles: tt.files} + msg := entityqueue.NewMessage(testBatchID, resultPayload(t, res), testQueue, nil) + // Not-landed is an expected terminal outcome, so Process acks (no error). + require.NoError(t, newController(t, store, registry).Process(context.Background(), newDelivery(ctrl, msg))) + + require.Contains(t, byTopic, "conclude") + require.Contains(t, byTopic, "speculate") + // The land failure reason rides the conclude message so conclude can stamp it on + // 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(tt.wantCategory), byTopic["conclude"].Metadata[topickey.MetadataKeyFailureCategory]) + assert.Equal(t, tt.wantFiles, byTopic["conclude"].Metadata[topickey.MetadataKeyConflictingFiles]) + }) + } } func TestProcess_CancellingShortCircuit(t *testing.T) { diff --git a/submitqueue/orchestrator/core/batch/BUILD.bazel b/submitqueue/orchestrator/core/batch/BUILD.bazel index a8c811921..d499ab640 100644 --- a/submitqueue/orchestrator/core/batch/BUILD.bazel +++ b/submitqueue/orchestrator/core/batch/BUILD.bazel @@ -13,6 +13,7 @@ go_library( deps = [ "//platform/consumer:go_default_library", "//platform/metrics:go_default_library", + "//submitqueue/core/topickey:go_default_library", "//submitqueue/entity:go_default_library", "//submitqueue/extension/storage:go_default_library", "//submitqueue/orchestrator/core/request:go_default_library", @@ -26,12 +27,14 @@ go_library( go_test( name = "go_default_test", srcs = [ + "failure_test.go", "find_test.go", "list_test.go", "transition_test.go", ], embed = [":go_default_library"], deps = [ + "//submitqueue/core/topickey:go_default_library", "//submitqueue/entity:go_default_library", "//submitqueue/extension/storage:go_default_library", "//submitqueue/extension/storage/mock:go_default_library", diff --git a/submitqueue/orchestrator/core/batch/conclude.go b/submitqueue/orchestrator/core/batch/conclude.go index 775b7fa40..e5836dcd4 100644 --- a/submitqueue/orchestrator/core/batch/conclude.go +++ b/submitqueue/orchestrator/core/batch/conclude.go @@ -21,6 +21,7 @@ import ( "github.com/uber-go/tally" "github.com/uber/submitqueue/platform/consumer" "github.com/uber/submitqueue/platform/metrics" + "github.com/uber/submitqueue/submitqueue/core/topickey" "github.com/uber/submitqueue/submitqueue/entity" "github.com/uber/submitqueue/submitqueue/extension/storage" corerequest "github.com/uber/submitqueue/submitqueue/orchestrator/core/request" @@ -28,11 +29,63 @@ import ( "go.uber.org/zap" ) +// Failure describes why a batch failed, for its members' terminal logs. It +// travels on the conclude message's metadata, never as durable batch state. +type Failure struct { + // Reason is the human-readable reason; empty on the landed and cancelled paths. + Reason string + // Category classifies the failure; unknown when not classified. + Category entity.FailureCategory + // Details holds request log metadata beyond the category, such as conflicting files. + Details map[string]string +} + +// failureDetailKeys maps the conclude metadata a Failure's details may carry to +// the request log metadata key it lands under. +var failureDetailKeys = map[string]string{ + topickey.MetadataKeyConflictingFiles: entity.RequestLogMetadataKeyConflictingFiles, +} + +// FailureFromConcludeMetadata reads the Failure a conclude message carries. +func FailureFromConcludeMetadata(metadata map[string]string) Failure { + failure := Failure{ + Reason: metadata[topickey.MetadataKeyFailureReason], + Category: entity.FailureCategory(metadata[topickey.MetadataKeyFailureCategory]), + } + for messageKey, logKey := range failureDetailKeys { + if value := metadata[messageKey]; value != "" { + if failure.Details == nil { + failure.Details = map[string]string{} + } + failure.Details[logKey] = value + } + } + return failure +} + +// ConcludeMetadata encodes the Failure for a conclude message; nil when there is +// no reason, which is the landed and cancelled paths. +func (f Failure) ConcludeMetadata() map[string]string { + if f.Reason == "" { + return nil + } + metadata := map[string]string{topickey.MetadataKeyFailureReason: f.Reason} + if f.Category != entity.FailureCategoryUnknown { + metadata[topickey.MetadataKeyFailureCategory] = string(f.Category) + } + for messageKey, logKey := range failureDetailKeys { + if value := f.Details[logKey]; value != "" { + metadata[messageKey] = value + } + } + return metadata +} + // 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 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 { +// failure 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, failure Failure) error { requestState, err := batchStateToRequestState(batch.State) if err != nil { metrics.NamedCounter(scope, "process", "unexpected_state_errors", 1, metrics.TagsFromContext(ctx)...) @@ -40,11 +93,15 @@ func ConcludeBatchRequests(ctx context.Context, store orchstorage.Storage, regis } if requestState != entity.RequestStateError { - failureReason, failureCategory = "", entity.FailureCategoryUnknown + failure = Failure{} + } + base := map[string]string{"batch_id": batch.ID} + for key, value := range failure.Details { + base[key] = value } - metadata := entity.FailureCategoryMetadata(map[string]string{"batch_id": batch.ID}, failureCategory) + metadata := entity.FailureCategoryMetadata(base, failure.Category) for _, requestID := range batch.Contains { - res, err := corerequest.TerminateRequest(ctx, store, registry, requestID, requestState, failureReason, metadata) + res, err := corerequest.TerminateRequest(ctx, store, registry, requestID, requestState, failure.Reason, 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) diff --git a/submitqueue/orchestrator/core/batch/failure_test.go b/submitqueue/orchestrator/core/batch/failure_test.go new file mode 100644 index 000000000..c9c5d40b5 --- /dev/null +++ b/submitqueue/orchestrator/core/batch/failure_test.go @@ -0,0 +1,64 @@ +// 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 batch + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/uber/submitqueue/submitqueue/core/topickey" + "github.com/uber/submitqueue/submitqueue/entity" +) + +func TestFailure_ConcludeMetadata(t *testing.T) { + tests := []struct { + name string + failure Failure + wantMetadata map[string]string + }{ + {name: "no failure", failure: Failure{}}, + { + name: "a reason and a category", + failure: Failure{Reason: "land failed", Category: entity.FailureCategoryLandFailed}, + wantMetadata: map[string]string{ + topickey.MetadataKeyFailureReason: "land failed", + topickey.MetadataKeyFailureCategory: "land_failed", + }, + }, + { + name: "a conflict with its files", + failure: Failure{ + Reason: "merge conflict", + Category: entity.FailureCategoryMergeConflict, + Details: map[string]string{entity.RequestLogMetadataKeyConflictingFiles: "a.go\nb.go"}, + }, + wantMetadata: map[string]string{ + topickey.MetadataKeyFailureReason: "merge conflict", + topickey.MetadataKeyFailureCategory: "merge_conflict", + topickey.MetadataKeyConflictingFiles: "a.go\nb.go", + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + metadata := tt.failure.ConcludeMetadata() + + assert.Equal(t, tt.wantMetadata, metadata) + if tt.failure.Reason != "" { + assert.Equal(t, tt.failure, FailureFromConcludeMetadata(metadata)) + } + }) + } +} diff --git a/submitqueue/orchestrator/core/request/BUILD.bazel b/submitqueue/orchestrator/core/request/BUILD.bazel index c05271af8..b65c01651 100644 --- a/submitqueue/orchestrator/core/request/BUILD.bazel +++ b/submitqueue/orchestrator/core/request/BUILD.bazel @@ -3,6 +3,7 @@ load("@rules_go//go:def.bzl", "go_library", "go_test") go_library( name = "go_default_library", srcs = [ + "land_failure.go", "log.go", "terminal_log.go", "terminate.go", @@ -10,6 +11,8 @@ go_library( importpath = "github.com/uber/submitqueue/submitqueue/orchestrator/core/request", visibility = ["//visibility:public"], deps = [ + "//api/runway/messagequeue:go_default_library", + "//api/runway/messagequeue/protopb:go_default_library", "//platform/consumer:go_default_library", "//platform/publish:go_default_library", "//submitqueue/core/messagequeue:go_default_library", @@ -23,11 +26,14 @@ go_library( go_test( name = "go_default_test", srcs = [ + "land_failure_test.go", "log_test.go", "terminate_test.go", ], embed = [":go_default_library"], deps = [ + "//api/runway/messagequeue:go_default_library", + "//api/runway/messagequeue/protopb:go_default_library", "//platform/base/messagequeue:go_default_library", "//platform/consumer:go_default_library", "//platform/extension/messagequeue/mock:go_default_library", diff --git a/submitqueue/orchestrator/core/request/land_failure.go b/submitqueue/orchestrator/core/request/land_failure.go new file mode 100644 index 000000000..24da78c21 --- /dev/null +++ b/submitqueue/orchestrator/core/request/land_failure.go @@ -0,0 +1,34 @@ +// 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 request + +import ( + runwaymq "github.com/uber/submitqueue/api/runway/messagequeue" + runwaypb "github.com/uber/submitqueue/api/runway/messagequeue/protopb" + "github.com/uber/submitqueue/submitqueue/entity" +) + +// LandFailure classifies a failed merge result: a conflict the author has to +// rebase, with the conflicting paths when the merge backend named them, or any +// other land failure. details holds request log metadata beyond the category. +func LandFailure(result *runwaymq.MergeResult) (category entity.FailureCategory, details map[string]string) { + if result.GetFailureKind() != runwaypb.FailureKind_FAILURE_KIND_CONFLICT { + return entity.FailureCategoryLandFailed, nil + } + if files := result.GetConflictingFiles(); len(files) > 0 { + details = map[string]string{entity.RequestLogMetadataKeyConflictingFiles: entity.JoinConflictingFiles(files)} + } + return entity.FailureCategoryMergeConflict, details +} diff --git a/submitqueue/orchestrator/core/request/land_failure_test.go b/submitqueue/orchestrator/core/request/land_failure_test.go new file mode 100644 index 000000000..600e3755b --- /dev/null +++ b/submitqueue/orchestrator/core/request/land_failure_test.go @@ -0,0 +1,62 @@ +// 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 request + +import ( + "testing" + + "github.com/stretchr/testify/assert" + runwaymq "github.com/uber/submitqueue/api/runway/messagequeue" + runwaypb "github.com/uber/submitqueue/api/runway/messagequeue/protopb" + "github.com/uber/submitqueue/submitqueue/entity" +) + +func TestLandFailure(t *testing.T) { + tests := []struct { + name string + result *runwaymq.MergeResult + wantCategory entity.FailureCategory + wantDetails map[string]string + }{ + { + name: "conflict naming its files", + result: &runwaymq.MergeResult{FailureKind: runwaypb.FailureKind_FAILURE_KIND_CONFLICT, ConflictingFiles: []string{"a.go", "b.go"}}, + wantCategory: entity.FailureCategoryMergeConflict, + wantDetails: map[string]string{entity.RequestLogMetadataKeyConflictingFiles: "a.go\nb.go"}, + }, + { + name: "conflict without files", + result: &runwaymq.MergeResult{FailureKind: runwaypb.FailureKind_FAILURE_KIND_CONFLICT}, + wantCategory: entity.FailureCategoryMergeConflict, + }, + { + name: "invalid request", + result: &runwaymq.MergeResult{FailureKind: runwaypb.FailureKind_FAILURE_KIND_INVALID_REQUEST}, + wantCategory: entity.FailureCategoryLandFailed, + }, + { + name: "unclassified failure", + result: &runwaymq.MergeResult{}, + wantCategory: entity.FailureCategoryLandFailed, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + category, details := LandFailure(tt.result) + assert.Equal(t, tt.wantCategory, category) + assert.Equal(t, tt.wantDetails, details) + }) + } +} From b160d7988c397d9c9713e19ca3a77eb4f5ba23fc Mon Sep 17 00:00:00 2001 From: Chenghan Ying <125171961+roychying@users.noreply.github.com> Date: Tue, 1 Dec 2026 09:53:44 -0800 Subject: [PATCH 2/2] fix(runway): Report a moved promote target and GitHub's unexplained merge failure as rejected merges, not conflicts --- doc/rfc/runway/workflow.md | 2 +- runway/README.md | 2 +- runway/extension/merger/git/README.md | 2 +- runway/extension/merger/git/git_merger.go | 5 ++-- .../extension/merger/git/git_merger_test.go | 8 +++++-- runway/extension/merger/github/README.md | 3 ++- .../extension/merger/github/github_merger.go | 5 ++-- .../merger/github/github_merger_test.go | 10 ++++---- runway/extension/merger/merger.go | 9 ++++++- runway/extension/merger/merger_test.go | 24 +++++++++++-------- 10 files changed, 44 insertions(+), 26 deletions(-) diff --git a/doc/rfc/runway/workflow.md b/doc/rfc/runway/workflow.md index 0fa6d5767..466afc9fc 100644 --- a/doc/rfc/runway/workflow.md +++ b/doc/rfc/runway/workflow.md @@ -67,7 +67,7 @@ Runway is stateless and the sole responder on the client's correlation id: Submi Failures split into two classes: -- **Named terminal outcomes** — a merge conflict or an invalid request (an unknown/unsupported strategy, a malformed change URI, or an invalid `PROMOTE` composition). These can never succeed on retry, so the controller publishes a `FAILED` `MergeResult` (with a reason) and acks, rather than nacking. The merger surfaces them as the `ErrConflict` / `ErrInvalidRequest` sentinels; `IsTerminal` is the single classification point. +- **Named terminal outcomes** — a merge conflict, an invalid request (an unknown/unsupported strategy, a malformed change URI, or an invalid `PROMOTE` composition), or a merge the backend rejected without calling it a conflict (a `PROMOTE` target the branch moved past, a merge GitHub reports as failed). These can never succeed on retry, so the controller publishes a `FAILED` `MergeResult` (with a reason) and acks, rather than nacking. The merger surfaces them as the `ErrConflict` / `ErrInvalidRequest` / `ErrRejected` sentinels; `IsTerminal` is the single classification point. Only `ErrConflict` is classified as `FAILURE_KIND_CONFLICT`. - **Infrastructure faults** — fetch/network/auth failures, a push rejected for a reason other than a moved tip, and so on. These are nacked for retry. diff --git a/runway/README.md b/runway/README.md index a45d66bad..d681d6371 100644 --- a/runway/README.md +++ b/runway/README.md @@ -18,6 +18,6 @@ Each controller deserializes the `MergeRequest`, obtains a `Merger` for the requ ## Failure handling -A merge outcome the controller can name is published as a `FAILED` result and acked, not retried: a merge conflict (`merger.ErrConflict`) or an invalid request (`merger.ErrInvalidRequest` — unknown strategy, malformed change URI, invalid PROMOTE composition). The `merger.IsTerminal` helper draws that line. Any other error is an infrastructure fault and is nacked for retry. +A merge outcome the controller can name is published as a `FAILED` result and acked, not retried: a merge conflict (`merger.ErrConflict`), an invalid request (`merger.ErrInvalidRequest` — unknown strategy, malformed change URI, invalid PROMOTE composition), or a merge the backend rejected without calling it a conflict (`merger.ErrRejected`). The `merger.IsTerminal` helper draws that line. Any other error is an infrastructure fault and is nacked for retry. Because Runway is stateless and the sole responder on the client's correlation id, a request that exhausts retries (or hits an unexpected fault) must still resolve the client. The inbound topics dead-letter by default; the [`dlq`](controller/dlq) reconciler drains those `_dlq` topics and republishes a `FAILED` `MergeResult` to the signal topic so the correlation id never hangs. diff --git a/runway/extension/merger/git/README.md b/runway/extension/merger/git/README.md index 0d14b7659..2b049267a 100644 --- a/runway/extension/merger/git/README.md +++ b/runway/extension/merger/git/README.md @@ -81,7 +81,7 @@ For a committing merge nothing reaches the remote until every step has applied c ## Failure classification -A merge conflict surfaces as `merger.ErrConflict`. An unusable request surfaces as `merger.ErrInvalidRequest`: an unsupported strategy or URI scheme, a malformed URI, an invalid `PROMOTE` composition, a commit a reachable remote cannot supply, a change whose head has moved on, or a change sharing no history with the target under a picking strategy. Both are terminal — the controller publishes a `FAILED` result rather than retrying. Everything else (network/auth/push faults, and an unreachable remote) is returned as a plain error for the consumer to retry. +A merge conflict surfaces as `merger.ErrConflict`. A `PROMOTE` whose commit is no longer a fast-forward of the target, because the target moved, surfaces as `merger.ErrRejected`: the change may still apply, so it is not a conflict. An unusable request surfaces as `merger.ErrInvalidRequest`: an unsupported strategy or URI scheme, a malformed URI, an invalid `PROMOTE` composition, a commit a reachable remote cannot supply, a change whose head has moved on, or a change sharing no history with the target under a picking strategy. All three are terminal — the controller publishes a `FAILED` result rather than retrying. Everything else (network/auth/push faults, and an unreachable remote) is returned as a plain error for the consumer to retry. The distinction between the last two matters operationally: a commit that is missing while the remote answers is a property of the request, whereas a remote that will not answer is a property of the moment. diff --git a/runway/extension/merger/git/git_merger.go b/runway/extension/merger/git/git_merger.go index e5a8b8885..25109d8df 100644 --- a/runway/extension/merger/git/git_merger.go +++ b/runway/extension/merger/git/git_merger.go @@ -646,13 +646,14 @@ func (m *gitMerger) promote(ctx context.Context, req *runwaymq.MergeRequest, rs return promoteResult(req, rs, sha, commit), nil } - // Only a true fast-forward is allowed; divergence is a terminal conflict. + // Only a true fast-forward is allowed; divergence is terminal. It is not a + // conflict: the target moved, and the change may still apply to it. fastForward, err := m.isAncestor(ctx, tip, sha) if err != nil { return nil, err } if !fastForward { - return nil, fmt.Errorf("%w: promote target %s is not a fast-forward of %s", merger.ErrConflict, sha, tip) + return nil, fmt.Errorf("%w: promote target %s is not a fast-forward of %s", merger.ErrRejected, sha, tip) } if !commit { diff --git a/runway/extension/merger/git/git_merger_test.go b/runway/extension/merger/git/git_merger_test.go index f76f77380..cdbf00920 100644 --- a/runway/extension/merger/git/git_merger_test.go +++ b/runway/extension/merger/git/git_merger_test.go @@ -466,7 +466,9 @@ func TestMerge_Promote_Divergent(t *testing.T) { m := f.newMerger(t, mergestrategypb.Strategy_REBASE) _, err := m.Merge(context.Background(), req("b", stepOf(mergestrategypb.Strategy_PROMOTE, "s1", uri(divSHA)))) require.Error(t, err) - assert.True(t, errors.Is(err, merger.ErrConflict)) + assert.True(t, errors.Is(err, merger.ErrRejected)) + assert.False(t, errors.Is(err, merger.ErrConflict), "the target moved; the change may still apply") + assert.True(t, merger.IsTerminal(err)) assert.Equal(t, mainBefore, f.remoteHEAD(t)) } @@ -1281,7 +1283,9 @@ func TestCheckMergeability_PromoteDivergent(t *testing.T) { m := f.newMerger(t, mergestrategypb.Strategy_REBASE) _, err := m.CheckMergeability(context.Background(), req("b", stepOf(mergestrategypb.Strategy_PROMOTE, "s1", uri(divSHA)))) require.Error(t, err) - assert.True(t, errors.Is(err, merger.ErrConflict)) + assert.True(t, errors.Is(err, merger.ErrRejected)) + assert.False(t, errors.Is(err, merger.ErrConflict), "the target moved; the change may still apply") + assert.True(t, merger.IsTerminal(err)) assert.Equal(t, mainBefore, f.remoteHEAD(t)) } diff --git a/runway/extension/merger/github/README.md b/runway/extension/merger/github/README.md index 13727a2bd..35ccd7c4c 100644 --- a/runway/extension/merger/github/README.md +++ b/runway/extension/merger/github/README.md @@ -49,7 +49,8 @@ A redelivered request converges instead of merging twice. Already-merged pull re ## Failure classification - `merger.ErrInvalidRequest` (terminal): a malformed or foreign URI, an unsupported strategy, a stale head, a closed or draft pull request, a step that is not a stack based on the target, or GitHub refusing the merge as asked (HTTP 400/422, e.g. required checks not satisfied). -- `merger.ErrConflict` (terminal): a pull request that is not mergeable at the check, or a merge GitHub reports as failed. GitHub does not separate a conflict from other merge failures there; its message is the reason. +- `merger.ErrConflict` (terminal): a pull request that is not mergeable at the check. +- `merger.ErrRejected` (terminal): a merge GitHub reports as failed. GitHub does not separate a conflict from a rule or a moved head there, so it is not classified as a conflict; its message is the reason. - `ErrMergePending` (retryable, via this package's `Classifier`): GitHub had not settled a merge, or a pull request's mergeability, within the poll budget. The work is still in flight on GitHub's side. - Anything else is a plain error. HTTP rejections keep their status code (`platform/http.StatusError`) so `platform/errs/http` can retry a 5xx or 429 and dead-letter a 403 or 404. A 404 is not treated as terminal here: GitHub answers 404 for a repository the token cannot see, and that is a deployment fault, not a property of the request. diff --git a/runway/extension/merger/github/github_merger.go b/runway/extension/merger/github/github_merger.go index 6643ffcff..bcc31af80 100644 --- a/runway/extension/merger/github/github_merger.go +++ b/runway/extension/merger/github/github_merger.go @@ -312,8 +312,9 @@ func (m *githubMerger) mergeStack(ctx context.Context, step *runwaymq.MergeStep, return nil case mergeStatusFailed: // GitHub does not separate a conflict from a rule or head-moved - // failure here; all are terminal, and its message is the reason. - return fmt.Errorf("%w: step %q: GitHub failed to merge %s: %s", merger.ErrConflict, step.GetStepId(), top.ref.Label, status.Details.Message) + // failure here; all are terminal, none is known to be a conflict, and + // its message is the reason. + return fmt.Errorf("%w: step %q: GitHub failed to merge %s: %s", merger.ErrRejected, step.GetStepId(), top.ref.Label, status.Details.Message) default: return fmt.Errorf("unexpected merge status %q for %s", status.Status, top.ref.Label) } diff --git a/runway/extension/merger/github/github_merger_test.go b/runway/extension/merger/github/github_merger_test.go index 201132312..c7d603a5f 100644 --- a/runway/extension/merger/github/github_merger_test.go +++ b/runway/extension/merger/github/github_merger_test.go @@ -430,13 +430,13 @@ func TestMerge(t *testing.T) { }, }, { - name: "failed merge is a conflict", + name: "failed merge is rejected, not a conflict", setup: func(f *fakeGitHub) { f.addPull(1, testTarget) f.finalStatus = mergeStatusFailed }, req: request(step("s1", mergestrategypb.Strategy_REBASE, uri(1))), - wantErr: merger.ErrConflict, + wantErr: merger.ErrRejected, wantFailedStep: "s1", wantSubmits: []submitCall{{number: 1, req: asyncMergeRequest{SHA: headSHA(1), MergeMethod: "rebase", MergeAction: mergeActionDirect}}}, }, @@ -498,7 +498,7 @@ func TestMerge(t *testing.T) { wantSubmits: []submitCall{{number: 1, req: asyncMergeRequest{SHA: headSHA(1), MergeMethod: "rebase", MergeAction: mergeActionDirect}}}, }, { - name: "merge GitHub fails after a landed step is a conflict", + name: "merge GitHub fails after a landed step is rejected", setup: func(f *fakeGitHub) { f.addPull(1, testTarget) f.addPull(2, testTarget) @@ -508,7 +508,7 @@ func TestMerge(t *testing.T) { step("s1", mergestrategypb.Strategy_REBASE, uri(1)), step("s2", mergestrategypb.Strategy_REBASE, uri(2)), ), - wantErr: merger.ErrConflict, + wantErr: merger.ErrRejected, wantOutputs: map[string][]string{"s1": {mergeSHA(1)}}, wantFailedStep: "s2", wantSubmits: []submitCall{ @@ -529,7 +529,7 @@ func TestMerge(t *testing.T) { step("s2", mergestrategypb.Strategy_REBASE, uri(2)), step("s3", mergestrategypb.Strategy_REBASE, uri(3)), ), - wantErr: merger.ErrConflict, + wantErr: merger.ErrRejected, wantOutputs: map[string][]string{"s1": {mergeSHA(1)}}, wantFailedStep: "s2", wantSubmits: []submitCall{ diff --git a/runway/extension/merger/merger.go b/runway/extension/merger/merger.go index b3ec9e6ef..57d8914c0 100644 --- a/runway/extension/merger/merger.go +++ b/runway/extension/merger/merger.go @@ -40,6 +40,13 @@ var ErrConflict = errors.New("merge conflict") // failure result rather than nacking into an infinite retry / dead-letter. var ErrInvalidRequest = errors.New("invalid merge request") +// ErrRejected signals that the merge backend refused the steps without saying +// they conflict: the target moved past the commit to promote, or the backend +// reported a failure it does not separate from a rule or a moved head. Like +// ErrConflict it is terminal, but the change may still apply cleanly, so it is +// not classified as a conflict. +var ErrRejected = errors.New("merge rejected") + // ConflictError is an ErrConflict that names the paths that did not apply, for a // merger that can tell. Files are repository-relative; empty when unknown. type ConflictError struct { @@ -78,7 +85,7 @@ func ConflictingFiles(err error) []string { // must be told about via a FAILED result rather than retried. Controllers use // it to decide between publishing a FAILED result (ack) and nacking for retry. func IsTerminal(err error) bool { - return errors.Is(err, ErrConflict) || errors.Is(err, ErrInvalidRequest) + return errors.Is(err, ErrConflict) || errors.Is(err, ErrInvalidRequest) || errors.Is(err, ErrRejected) } // Merger performs version-control operations against a single merge target. diff --git a/runway/extension/merger/merger_test.go b/runway/extension/merger/merger_test.go index 8a2a50fdf..abaaec690 100644 --- a/runway/extension/merger/merger_test.go +++ b/runway/extension/merger/merger_test.go @@ -25,25 +25,29 @@ import ( func TestFailureKind(t *testing.T) { tests := []struct { - name string - err error - wantKind runwaypb.FailureKind - wantFiles []string + name string + err error + wantKind runwaypb.FailureKind + wantFiles []string + wantTerminal bool }{ - {name: "conflict", err: fmt.Errorf("%w: git merge abc", ErrConflict), wantKind: runwaypb.FailureKind_FAILURE_KIND_CONFLICT}, + {name: "conflict", err: fmt.Errorf("%w: git merge abc", ErrConflict), wantKind: runwaypb.FailureKind_FAILURE_KIND_CONFLICT, wantTerminal: true}, { - name: "conflict naming its files", - err: fmt.Errorf("step 1: %w", &ConflictError{Files: []string{"a.go", "b/c.go"}, Err: fmt.Errorf("%w: git merge abc", ErrConflict)}), - wantKind: runwaypb.FailureKind_FAILURE_KIND_CONFLICT, - wantFiles: []string{"a.go", "b/c.go"}, + name: "conflict naming its files", + err: fmt.Errorf("step 1: %w", &ConflictError{Files: []string{"a.go", "b/c.go"}, Err: fmt.Errorf("%w: git merge abc", ErrConflict)}), + wantKind: runwaypb.FailureKind_FAILURE_KIND_CONFLICT, + wantFiles: []string{"a.go", "b/c.go"}, + wantTerminal: true, }, - {name: "invalid request", err: fmt.Errorf("%w: unknown strategy", ErrInvalidRequest), wantKind: runwaypb.FailureKind_FAILURE_KIND_INVALID_REQUEST}, + {name: "invalid request", err: fmt.Errorf("%w: unknown strategy", ErrInvalidRequest), wantKind: runwaypb.FailureKind_FAILURE_KIND_INVALID_REQUEST, wantTerminal: true}, + {name: "rejected", err: fmt.Errorf("%w: promote target is not a fast-forward", ErrRejected), wantKind: runwaypb.FailureKind_FAILURE_KIND_UNSPECIFIED, wantTerminal: true}, {name: "other error", err: errors.New("push rejected"), wantKind: runwaypb.FailureKind_FAILURE_KIND_UNSPECIFIED}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert.Equal(t, tt.wantKind, FailureKind(tt.err)) assert.Equal(t, tt.wantFiles, ConflictingFiles(tt.err)) + assert.Equal(t, tt.wantTerminal, IsTerminal(tt.err)) }) } }