Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/rfc/hook-framework.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
- 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.
- Opt-in per host via topic-key registration; a registered host never skips, so off and loss are distinguishable.

### Contract
Expand Down
63 changes: 57 additions & 6 deletions submitqueue/core/hookevent/hookevent.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@
//
// 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. The gateway
// 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
// 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
Expand All @@ -43,11 +45,17 @@
// does not hold back the finish, so a hook can see the finish first.
// - The queue drops a repeated event id only until the first copy is consumed
// and collected, seconds later.
// - A request.failed payload is what the summary says when the event is
// published. When a later copy of the finish fills in details the first
// lacked, its event keeps the same id, so hooks only see them if the queue
// forgot the first. Repair resends carry what their caller knows, which
// makes this rare.
package hookevent

import (
"crypto/sha256"
"fmt"
"unicode/utf8"

basehook "github.com/uber/submitqueue/api/base/hook"
"github.com/uber/submitqueue/submitqueue/entity"
Expand Down Expand Up @@ -76,6 +84,26 @@ 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.
const (
// PayloadKeyQueue holds the request's queue.
PayloadKeyQueue = "queue"
// PayloadKeyRequestID holds the request id, unique within its queue.
PayloadKeyRequestID = "request_id"
// PayloadKeyChangeURI holds the URI of the change the event is about.
PayloadKeyChangeURI = "change_uri"
// PayloadKeyFailureCategory holds the failure's entity.FailureCategory.
PayloadKeyFailureCategory = "failure_category"
// PayloadKeyFailureReason holds the failure's reason, cut to maxFailureReasonRunes.
PayloadKeyFailureReason = "failure_reason"
)

// 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.
const maxFailureReasonRunes = 8192

// finishedTypeByStatus maps each finished status that has an event to its type.
var finishedTypeByStatus = map[entity.RequestStatus]Type{
entity.RequestStatusLanded: TypeRequestLanded,
Expand Down Expand Up @@ -105,22 +133,45 @@ func NewRequestFinished(summary entity.RequestSummary) []*basehook.HookEvent {
func newRequestEvents(eventType Type, summary entity.RequestSummary, version int32, timestampMs int64) []*basehook.HookEvent {
events := make([]*basehook.HookEvent, 0, len(summary.ChangeURIs))
for _, uri := range summary.ChangeURIs {
fields := map[string]*structpb.Value{
PayloadKeyQueue: structpb.NewStringValue(summary.Queue),
PayloadKeyRequestID: structpb.NewStringValue(summary.RequestID),
PayloadKeyChangeURI: structpb.NewStringValue(uri),
}
if eventType == TypeRequestFailed {
addFailureFields(fields, summary)
}
events = append(events, &basehook.HookEvent{
Id: basehook.NewEventID(Source, string(eventType), changeSubject(summary, uri), version),
Source: Source,
Type: string(eventType),
TimestampMs: timestampMs,
Version: version,
Payload: &structpb.Struct{Fields: map[string]*structpb.Value{
"queue": structpb.NewStringValue(summary.Queue),
"request_id": structpb.NewStringValue(summary.RequestID),
"change_uri": structpb.NewStringValue(uri),
}},
Payload: &structpb.Struct{Fields: fields},
})
}
return events
}

// addFailureFields copies only the classified category and the reason, 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)
}
if summary.LastError != "" {
fields[PayloadKeyFailureReason] = structpb.NewStringValue(truncateRunes(summary.LastError, maxFailureReasonRunes))
}
}

func truncateRunes(text string, max int) string {
if utf8.RuneCountInString(text) <= max {
return text
}
runes := []rune(text)
return string(runes[:max-1]) + "…"
}

// changeSubject identifies one change of a request across queues. Request IDs
// are only unique within a queue, and queue names and URIs contain the id
// separator, so every part is length-prefixed and hashed into one separator-free
Expand Down
69 changes: 69 additions & 0 deletions submitqueue/core/hookevent/hookevent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package hookevent

import (
"strings"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -144,3 +145,71 @@ func eventIDs(events []*basehook.HookEvent) []string {
}
return ids
}

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: "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 without a category",
status: entity.RequestStatusError,
lastError: "land failed",
wantReason: "land failed",
},
{
name: "a long reason is cut",
status: entity.RequestStatusError,
lastError: longReason,
wantReason: strings.Repeat("é", maxFailureReasonRunes-1) + "…",
},
{
name: "failed with no details",
status: entity.RequestStatusError,
metadata: map[string]string{"resent": "true"},
},
{
name: "landed carries no failure fields",
status: entity.RequestStatusLanded,
lastError: "ignored",
metadata: map[string]string{entity.RequestLogMetadataKeyFailureCategory: "build_failed"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
summary := entity.RequestSummary{RequestID: "1", Queue: "q", ChangeURIs: []string{"uri/1"}, Status: tt.status, RequestVersion: 2, LastError: tt.lastError, Metadata: tt.metadata}

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)
}
keys := make([]string, 0, len(fields))
for key := range fields {
keys = append(keys, key)
}
assert.ElementsMatch(t, wantKeys, keys)
})
}
}
2 changes: 1 addition & 1 deletion submitqueue/gateway/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
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.

## Final log recovery

Expand Down
48 changes: 48 additions & 0 deletions submitqueue/gateway/core/request/materializer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,54 @@ func TestMaterializer_KeepsFinishedDetails(t *testing.T) {
}
}

func TestMaterializer_RepublishesTheSameFailedPayload(t *testing.T) {
failed := testRequestSummary()
failed.Status, failed.RequestVersion, failed.StatusTimestampMs, failed.Version = entity.RequestStatusError, 2, 20, 4
failed.LastError = "no build passed"
failed.Metadata = map[string]string{entity.RequestLogMetadataKeyFailureCategory: string(entity.FailureCategoryBuildFailed), "batch_id": "b1"}
statusLog := func(timestampMs int64, lastError string, metadata map[string]string) entity.RequestLog {
return entity.RequestLog{Queue: "q", RequestID: "1", Type: entity.RequestLogTypeStatus, Status: entity.RequestStatusError, RequestVersion: 2, TimestampMs: timestampMs, LastError: lastError, Metadata: metadata}
}

tests := []struct {
name string
log entity.RequestLog
wantUpdate bool
}{
{name: "a resend", log: statusLog(30, "", map[string]string{"resent": "true"}), wantUpdate: true},
{name: "a redelivered original", log: statusLog(20, failed.LastError, failed.Metadata)},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
var messages []entityqueue.Message
registry := newHookRegistry(t, ctrl, func(msg entityqueue.Message) error {
messages = append(messages, msg)
return nil
})
f := newMaterializerReceiptFixture(ctrl, WithHookPublishing(registry))
f.logs.EXPECT().Insert(gomock.Any(), tt.log).Return(nil)
f.summaries.EXPECT().Get(gomock.Any(), failed.RequestID).Return(failed, nil)
if tt.wantUpdate {
f.summaries.EXPECT().Update(gomock.Any(), gomock.Any(), failed.Version, failed.Version+1).Return(nil)
}
f.uris.EXPECT().Create(gomock.Any(), gomock.Any()).Return(nil).AnyTimes()
f.receipts.EXPECT().Create(gomock.Any(), gomock.Any()).Return(nil).AnyTimes()

require.NoError(t, f.materializer.PersistLog(context.Background(), tt.log))

want := hookevent.NewRequestFinished(failed)
require.Len(t, messages, len(want))
for i, msg := range messages {
event := &basehook.HookEvent{}
require.NoError(t, basehook.Unmarshal(msg.Payload, event))
assert.Equal(t, want[i].GetId(), event.GetId())
assert.Equal(t, want[i].GetPayload().AsMap(), event.GetPayload().AsMap())
}
})
}
}

func TestMaterializer_PublishesRequestHookEvents(t *testing.T) {
accepting := testRequestSummary()
accepted := accepting
Expand Down
Loading