From f653dcce1d44d86926ab49ad92a7f186a73857a7 Mon Sep 17 00:00:00 2001 From: Chenghan Ying <125171961+roychying@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:28:21 -0800 Subject: [PATCH] feat(submitqueue): Name the in-flight request a duplicate repeats in its failed hook event --- doc/rfc/hook-framework.md | 2 +- submitqueue/core/hookevent/hookevent.go | 27 +++++--- submitqueue/core/hookevent/hookevent_test.go | 62 ++++++++++--------- submitqueue/entity/failure_category.go | 4 ++ submitqueue/gateway/README.md | 2 +- .../controller/validate/validate.go | 9 +-- .../controller/validate/validate_test.go | 62 +++++++++++++------ 7 files changed, 108 insertions(+), 60 deletions(-) diff --git a/doc/rfc/hook-framework.md b/doc/rfc/hook-framework.md index 199a8952c..bc33e972d 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. 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, 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. - Opt-in per host via topic-key registration; a registered host never skips, so off and loss are distinguishable. ### Contract diff --git a/submitqueue/core/hookevent/hookevent.go b/submitqueue/core/hookevent/hookevent.go index af1959f7c..b4455ebd7 100644 --- a/submitqueue/core/hookevent/hookevent.go +++ b/submitqueue/core/hookevent/hookevent.go @@ -26,7 +26,8 @@ // Each status announces one event per change of the request, so a hook that // 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 and reason, when the request has +// 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 // 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 @@ -84,8 +85,8 @@ const ( TypeRequestCancelled Type = "request.cancelled" ) -// Payload keys. PayloadKeyFailureCategory and PayloadKeyFailureReason appear -// only on request.failed, and only when the request has a value for them. +// Payload keys. The failure keys appear only on request.failed, and only when +// the request has a value for them. const ( // PayloadKeyQueue holds the request's queue. PayloadKeyQueue = "queue" @@ -97,8 +98,18 @@ const ( PayloadKeyFailureCategory = "failure_category" // PayloadKeyFailureReason holds the failure's reason, cut to maxFailureReasonRunes. PayloadKeyFailureReason = "failure_reason" + // PayloadKeyDuplicateOf holds the id of the in-flight request a duplicate repeats. + PayloadKeyDuplicateOf = "duplicate_of" ) +// 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, +} + // maxFailureReasonRunes bounds a failure reason in a payload. A reason can be // long free text from a validator or a merge backend; the bound keeps enough of // a merge backend's command output for a hook to show the author. @@ -153,11 +164,13 @@ func newRequestEvents(eventType Type, summary entity.RequestSummary, version int return events } -// addFailureFields copies only the classified category and the reason, never the -// rest of the summary's metadata, which can hold internal diagnostics. +// addFailureFields copies the reason and the allowlisted failure metadata, never +// the rest of the summary's metadata, which can hold internal diagnostics. func addFailureFields(fields map[string]*structpb.Value, summary entity.RequestSummary) { - if category := summary.Metadata[entity.RequestLogMetadataKeyFailureCategory]; category != "" { - fields[PayloadKeyFailureCategory] = structpb.NewStringValue(category) + for metadataKey, payloadKey := range failureMetadataPayloadKeys { + if value := summary.Metadata[metadataKey]; value != "" { + fields[payloadKey] = structpb.NewStringValue(value) + } } if summary.LastError != "" { fields[PayloadKeyFailureReason] = structpb.NewStringValue(truncateRunes(summary.LastError, maxFailureReasonRunes)) diff --git a/submitqueue/core/hookevent/hookevent_test.go b/submitqueue/core/hookevent/hookevent_test.go index 80095a480..627504055 100644 --- a/submitqueue/core/hookevent/hookevent_test.go +++ b/submitqueue/core/hookevent/hookevent_test.go @@ -149,32 +149,44 @@ func eventIDs(events []*basehook.HookEvent) []string { func TestNewRequestFinished_FailureFields(t *testing.T) { longReason := strings.Repeat("é", maxFailureReasonRunes+10) tests := []struct { - name string - status entity.RequestStatus - lastError string - metadata map[string]string - wantCategory string - wantReason string + name string + status entity.RequestStatus + lastError string + metadata map[string]string + wantFields map[string]string }{ { - name: "failed with a category and a reason", - status: entity.RequestStatusError, - lastError: "custom validation failed: missing approval", - metadata: map[string]string{entity.RequestLogMetadataKeyFailureCategory: "validation_rejected", "dlq.original_topic": "validate"}, - wantCategory: "validation_rejected", - wantReason: "custom validation failed: missing approval", + name: "failed with a category and a reason", + status: entity.RequestStatusError, + lastError: "custom validation failed: missing approval", + metadata: map[string]string{entity.RequestLogMetadataKeyFailureCategory: "validation_rejected", "dlq.original_topic": "validate"}, + wantFields: map[string]string{ + PayloadKeyFailureCategory: "validation_rejected", + PayloadKeyFailureReason: "custom validation failed: missing approval", + }, + }, + { + name: "a duplicate names the request it repeats", + status: entity.RequestStatusError, + lastError: "request 94 is a duplicate of in-flight request 93", + metadata: map[string]string{entity.RequestLogMetadataKeyFailureCategory: "duplicate", entity.RequestLogMetadataKeyDuplicateOf: "93"}, + wantFields: map[string]string{ + PayloadKeyFailureCategory: "duplicate", + PayloadKeyFailureReason: "request 94 is a duplicate of in-flight request 93", + PayloadKeyDuplicateOf: "93", + }, }, { name: "failed without a category", status: entity.RequestStatusError, lastError: "land failed", - wantReason: "land failed", + wantFields: map[string]string{PayloadKeyFailureReason: "land failed"}, }, { name: "a long reason is cut", status: entity.RequestStatusError, lastError: longReason, - wantReason: strings.Repeat("é", maxFailureReasonRunes-1) + "…", + wantFields: map[string]string{PayloadKeyFailureReason: strings.Repeat("é", maxFailureReasonRunes-1) + "…"}, }, { name: "failed with no details", @@ -185,7 +197,7 @@ func TestNewRequestFinished_FailureFields(t *testing.T) { name: "landed carries no failure fields", status: entity.RequestStatusLanded, lastError: "ignored", - metadata: map[string]string{entity.RequestLogMetadataKeyFailureCategory: "build_failed"}, + metadata: map[string]string{entity.RequestLogMetadataKeyFailureCategory: "build_failed", entity.RequestLogMetadataKeyDuplicateOf: "93"}, }, } for _, tt := range tests { @@ -195,21 +207,15 @@ func TestNewRequestFinished_FailureFields(t *testing.T) { events := NewRequestFinished(summary) require.Len(t, events, 1) - fields := events[0].GetPayload().GetFields() - assert.Equal(t, tt.wantCategory, fields[PayloadKeyFailureCategory].GetStringValue()) - assert.Equal(t, tt.wantReason, fields[PayloadKeyFailureReason].GetStringValue()) - wantKeys := []string{PayloadKeyQueue, PayloadKeyRequestID, PayloadKeyChangeURI} - if tt.wantCategory != "" { - wantKeys = append(wantKeys, PayloadKeyFailureCategory) - } - if tt.wantReason != "" { - wantKeys = append(wantKeys, PayloadKeyFailureReason) + got := map[string]string{} + for key, value := range events[0].GetPayload().GetFields() { + got[key] = value.GetStringValue() } - keys := make([]string, 0, len(fields)) - for key := range fields { - keys = append(keys, key) + want := map[string]string{PayloadKeyQueue: "q", PayloadKeyRequestID: "1", PayloadKeyChangeURI: "uri/1"} + for key, value := range tt.wantFields { + want[key] = value } - assert.ElementsMatch(t, wantKeys, keys) + assert.Equal(t, want, got) }) } } diff --git a/submitqueue/entity/failure_category.go b/submitqueue/entity/failure_category.go index 980740436..2f63cb4c8 100644 --- a/submitqueue/entity/failure_category.go +++ b/submitqueue/entity/failure_category.go @@ -38,6 +38,10 @@ const ( // error status's FailureCategory. It is absent when the failure was not classified. const RequestLogMetadataKeyFailureCategory = "failure_category" +// RequestLogMetadataKeyDuplicateOf is the request log metadata key holding the +// ID of the in-flight request that a FailureCategoryDuplicate request duplicates. +const RequestLogMetadataKeyDuplicateOf = "duplicate_of" + // FailureCategoryMetadata returns metadata with category recorded under // RequestLogMetadataKeyFailureCategory, leaving metadata itself unchanged. An // unknown category records nothing. diff --git a/submitqueue/gateway/README.md b/submitqueue/gateway/README.md index eb05becae..1475affd9 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` and its reason as `failure_reason`, 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`, and for a duplicate the in-flight request as `duplicate_of`, when it has them. ## Final log recovery diff --git a/submitqueue/orchestrator/controller/validate/validate.go b/submitqueue/orchestrator/controller/validate/validate.go index f1e37d0f9..e3aacac79 100644 --- a/submitqueue/orchestrator/controller/validate/validate.go +++ b/submitqueue/orchestrator/controller/validate/validate.go @@ -175,7 +175,8 @@ func (c *Controller) Process(ctx context.Context, delivery consumer.Delivery) er "duplicate_id", dupID, ) coremetrics.NamedCounter(c.metricsScope, "process", "duplicate_requests", 1, coremetrics.TagsFromContext(ctx)...) - return c.reject(ctx, store, request.ID, fmt.Sprintf("request %s is a duplicate of in-flight request %s", request.ID, dupID), entity.FailureCategoryDuplicate) + return c.reject(ctx, store, request.ID, fmt.Sprintf("request %s is a duplicate of in-flight request %s", request.ID, dupID), entity.FailureCategoryDuplicate, + map[string]string{entity.RequestLogMetadataKeyDuplicateOf: dupID}) } // Fetch change metadata @@ -221,7 +222,7 @@ func (c *Controller) Process(ctx context.Context, delivery consumer.Delivery) er "queue", request.Queue, "error", err.Error(), ) - return c.reject(ctx, store, request.ID, fmt.Sprintf("custom validation failed: %v", err), entity.FailureCategoryValidationRejected) + return c.reject(ctx, store, request.ID, fmt.Sprintf("custom validation failed: %v", err), entity.FailureCategoryValidationRejected, nil) } } } @@ -270,8 +271,8 @@ func (c *Controller) Process(ctx context.Context, delivery consumer.Delivery) er // Only an infra failure while terminating (storage/publish) is returned as an // error so the delivery is retried; the request itself is never re-queued for // validation once rejected. -func (c *Controller) reject(ctx context.Context, store orchstorage.Storage, requestID, reason string, category entity.FailureCategory) error { - if _, err := corerequest.TerminateRequest(ctx, store, c.registry, requestID, entity.RequestStateError, reason, entity.FailureCategoryMetadata(nil, category)); err != nil { +func (c *Controller) reject(ctx context.Context, store orchstorage.Storage, requestID, reason string, category entity.FailureCategory, metadata map[string]string) error { + if _, err := corerequest.TerminateRequest(ctx, store, c.registry, requestID, entity.RequestStateError, reason, entity.FailureCategoryMetadata(metadata, category)); err != nil { coremetrics.NamedCounter(c.metricsScope, "process", "terminate_errors", 1, coremetrics.TagsFromContext(ctx)...) return fmt.Errorf("failed to terminate rejected request %s: %w", requestID, err) } diff --git a/submitqueue/orchestrator/controller/validate/validate_test.go b/submitqueue/orchestrator/controller/validate/validate_test.go index dc7a59845..4d1a60b05 100644 --- a/submitqueue/orchestrator/controller/validate/validate_test.go +++ b/submitqueue/orchestrator/controller/validate/validate_test.go @@ -107,14 +107,33 @@ func newTestController( cs *storagemock.MockChangeStore, publishErr error, ) *Controller { + controller, _ := newTestControllerWithLogs(t, ctrl, store, cs, publishErr) + return controller +} + +// newTestControllerWithLogs is newTestController that also records every request +// log the controller publishes. +func newTestControllerWithLogs( + t *testing.T, + ctrl *gomock.Controller, + store *orchstoragemock.MockStorage, + cs *storagemock.MockChangeStore, + publishErr error, +) (*Controller, *[]entity.RequestLog) { logger := zaptest.NewLogger(t).Sugar() scope := tally.NoopScope + var logs []entity.RequestLog store.EXPECT().GetChangeStore().Return(cs).AnyTimes() mockPub := queuemock.NewMockPublisher(ctrl) mockPub.EXPECT().Publish(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn( func(ctx context.Context, topic string, msg entityqueue.Message) error { + if topic == "log" { + log, err := sqmq.UnmarshalRequestLog(msg.Payload) + require.NoError(t, err) + logs = append(logs, log) + } return publishErr }, ).AnyTimes() @@ -151,7 +170,7 @@ func newTestController( storageFactory := orchstoragemock.NewMockFactory(ctrl) storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() - return NewController(logger, scope, storageFactory, registry, cpFactory, nil, runwaymq.TopicKeyMergeConflictCheck, topickey.TopicKeyValidate, "orchestrator-validate") + return NewController(logger, scope, storageFactory, registry, cpFactory, nil, runwaymq.TopicKeyMergeConflictCheck, topickey.TopicKeyValidate, "orchestrator-validate"), &logs } func TestNewController(t *testing.T) { @@ -413,14 +432,14 @@ func TestController_Process_DuplicateDetection(t *testing.T) { ) tests := []struct { - name string - requestURIs []string // URIs on the new request; defaults to [uriA] - byURI map[string][]entity.ChangeRecord // GetByURI mock returns - ownerLookup map[string]entity.Request - ownerNotFound map[string]bool - ownerErr map[string]error - wantRejected bool - wantUnexpected bool + name string + requestURIs []string // URIs on the new request; defaults to [uriA] + byURI map[string][]entity.ChangeRecord // GetByURI mock returns + ownerLookup map[string]entity.Request + ownerNotFound map[string]bool + ownerErr map[string]error + wantDuplicateOf string // the in-flight request the new one duplicates; empty when it proceeds + wantUnexpected bool }{ { name: "no overlap proceeds", @@ -434,7 +453,7 @@ func TestController_Process_DuplicateDetection(t *testing.T) { ownerLookup: map[string]entity.Request{ dupRequestID: {ID: dupRequestID, Queue: queueName, State: entity.RequestStateStarted, Version: 1}, }, - wantRejected: true, + wantDuplicateOf: dupRequestID, }, { name: "overlap with terminal owner is skipped", @@ -462,7 +481,7 @@ func TestController_Process_DuplicateDetection(t *testing.T) { ownerLookup: map[string]entity.Request{ dupRequestID: {ID: dupRequestID, Queue: queueName, State: entity.RequestStateValidated, Version: 2}, }, - wantRejected: true, + wantDuplicateOf: dupRequestID, }, { name: "first URI's owner is terminal, second URI's owner is live", @@ -475,7 +494,7 @@ func TestController_Process_DuplicateDetection(t *testing.T) { terminalReqID: {ID: terminalReqID, State: entity.RequestStateError, Version: 3}, anotherReqID: {ID: anotherReqID, State: entity.RequestStateProcessing, Version: 4}, }, - wantRejected: true, + wantDuplicateOf: anotherReqID, }, { // Store doesn't exclude self; controller filters by RequestID and must not look up its own row. @@ -495,7 +514,7 @@ func TestController_Process_DuplicateDetection(t *testing.T) { ownerLookup: map[string]entity.Request{ dupRequestID: {ID: dupRequestID, Queue: queueName, State: entity.RequestStateStarted, Version: 1}, }, - wantRejected: true, + wantDuplicateOf: dupRequestID, }, { name: "owner lookup unexpected error propagates", @@ -540,7 +559,7 @@ func TestController_Process_DuplicateDetection(t *testing.T) { for id, e := range tt.ownerErr { mockReqStore.EXPECT().Get(gomock.Any(), id).Return(entity.Request{}, e) } - if tt.wantRejected { + if tt.wantDuplicateOf != "" { // A detected duplicate is terminated (Started → Error) rather than // dead-lettered, then the delivery is acked. mockReqStore.EXPECT().Update(gomock.Any(), requestWithState(request, entity.RequestStateError), int32(1), int32(2)).Return(nil) @@ -558,7 +577,7 @@ func TestController_Process_DuplicateDetection(t *testing.T) { // and claims each fetched change via Create. Accept any Create. cs.EXPECT().Create(gomock.Any(), gomock.Any()).Return(nil).AnyTimes() - controller := newTestController(t, ctrl, store, cs, nil) + controller, logs := newTestControllerWithLogs(t, ctrl, store, cs, nil) msg := entityqueue.NewMessage(request.ID, requestIDPayload(t, request.ID), request.Queue, nil) msg.Tenant = request.Queue @@ -572,10 +591,14 @@ func TestController_Process_DuplicateDetection(t *testing.T) { case tt.wantUnexpected: require.Error(t, err) assert.False(t, errs.IsUserError(err), "owner lookup failure should not be a user error") - case tt.wantRejected: + case tt.wantDuplicateOf != "": // If we get an expected failure, the request is terminated, and the delivery acked (no error, no DLQ). // The terminal CAS is asserted via the UpdateState expectation above. require.NoError(t, err) + require.NotEmpty(t, *logs) + terminal := (*logs)[len(*logs)-1] + assert.Equal(t, entity.RequestStatusError, terminal.Status) + assert.Equal(t, tt.wantDuplicateOf, terminal.Metadata[entity.RequestLogMetadataKeyDuplicateOf]) default: require.NoError(t, err) } @@ -980,8 +1003,9 @@ func TestController_Reject_RecordsFailureCategory(t *testing.T) { tests := []struct { name string category entity.FailureCategory + metadata map[string]string }{ - {name: "duplicate", category: entity.FailureCategoryDuplicate}, + {name: "duplicate", category: entity.FailureCategoryDuplicate, metadata: map[string]string{entity.RequestLogMetadataKeyDuplicateOf: "6"}}, {name: "validation rejected", category: entity.FailureCategoryValidationRejected}, } for _, tt := range tests { @@ -1007,10 +1031,10 @@ func TestController_Reject_RecordsFailureCategory(t *testing.T) { require.NoError(t, err) controller := &Controller{registry: registry, metricsScope: tally.NoopScope} - require.NoError(t, controller.reject(context.Background(), store, request.ID, "rejected", tt.category)) + require.NoError(t, controller.reject(context.Background(), store, request.ID, "rejected", tt.category, tt.metadata)) assert.Equal(t, "rejected", gotLog.LastError) - assert.Equal(t, string(tt.category), gotLog.Metadata[entity.RequestLogMetadataKeyFailureCategory]) + assert.Equal(t, entity.FailureCategoryMetadata(tt.metadata, tt.category), gotLog.Metadata) }) } }