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
4 changes: 4 additions & 0 deletions submitqueue/entity/request_log.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ import (
"time"
)

// RequestLogMetadataKeyResent marks a terminal request log that repeats a status
// already written. It stays on the log in History but never reaches a summary.
const RequestLogMetadataKeyResent = "resent"

// RequestStatus is where a request is in the pipeline. It is customer-friendly and can be displayed to the user.
// It is different from the request state, which is internal and used to implement a state machine. Request statuses can be
// generally added freely by the system without breaking the state machine.
Expand Down
2 changes: 2 additions & 0 deletions submitqueue/gateway/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ The gateway owns the request log read model and is the only service that reads i

The materializer appends every audit event, selects the current authoritative winner, and repairs the queue projection. The normal orchestrator pipeline does not read or write the request-log store directly.

A finished status keeps the reason and metadata it was first recorded with. When the orchestrator repairs a request already in that state it resends the terminal log marked `resent`, with whatever details the repairing path knows, which may differ from the original's or be none. So a log restating the summary's finished status and request version only fills details the summary lacks, whichever copy arrives first, and the `resent` marker stays in History, never in the summary.

## 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.
Expand Down
58 changes: 50 additions & 8 deletions submitqueue/gateway/core/request/materializer.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,16 +94,9 @@ func (m *Materializer) PersistLog(ctx context.Context, log entity.RequestLog) er
}

beforeUpdate, updatedSummary := summary, false
if logWins(log, summary) {
if updated, ok := projectLog(log, summary); ok {
oldVersion := summary.Version
newVersion := oldVersion + 1
updated := summary
updated.Status = log.Status
updated.RequestVersion = log.RequestVersion
updated.StatusTimestampMs = log.TimestampMs
updated.LastError = log.LastError
updated.Metadata = cloneMetadata(log.Metadata)

if err := summaries.Update(ctx, updated, oldVersion, newVersion); err != nil {
if errors.Is(err, basestorage.ErrVersionMismatch) {
continue
Expand Down Expand Up @@ -206,6 +199,55 @@ func logRestatesSummary(log entity.RequestLog, summary entity.RequestSummary) bo
return log.Type == entity.RequestLogTypeStatus && log.Status == summary.Status && log.RequestVersion == summary.RequestVersion
}

// projectLog returns the summary log projects onto, and false when it changes
// nothing. A winning log replaces the status and its details. A log restating a
// finished status and version only fills details the summary lacks, whatever its
// timestamp: a resend carries none of the original's and can reach the gateway
// before it, and the announced finish must keep describing the same failure.
func projectLog(log entity.RequestLog, summary entity.RequestSummary) (entity.RequestSummary, bool) {
restatesFinish := isTerminalStatus(log.Status) && logRestatesSummary(log, summary)
updated := summary
switch {
case logWins(log, summary):
updated.Status = log.Status
updated.RequestVersion = log.RequestVersion
updated.StatusTimestampMs = log.TimestampMs
updated.LastError, updated.Metadata = log.LastError, summaryMetadata(log.Metadata)
if restatesFinish {
updated.LastError, updated.Metadata = fillFinishedDetails(log, summary)
}
return updated, true
case restatesFinish:
updated.LastError, updated.Metadata = fillFinishedDetails(log, summary)
return updated, updated.LastError != summary.LastError || !maps.Equal(updated.Metadata, summary.Metadata)
default:
return summary, false
}
}

// fillFinishedDetails keeps the summary's reason and metadata and adds what log has that they lack.
func fillFinishedDetails(log entity.RequestLog, summary entity.RequestSummary) (string, map[string]string) {
lastError := summary.LastError
if lastError == "" {
lastError = log.LastError
}
metadata := summaryMetadata(summary.Metadata)
for key, value := range summaryMetadata(log.Metadata) {
if _, ok := metadata[key]; !ok {
metadata[key] = value
}
}
return lastError, metadata
}

// summaryMetadata copies a log's metadata for a summary, without the resent
// marker: it describes one log, not the request.
func summaryMetadata(metadata map[string]string) map[string]string {
summary := cloneMetadata(metadata)
delete(summary, entity.RequestLogMetadataKeyResent)
return summary
}

func isTerminalStatus(status entity.RequestStatus) bool {
return entity.IsRequestStateTerminal(entity.RequestState(status))
}
Expand Down
94 changes: 94 additions & 0 deletions submitqueue/gateway/core/request/materializer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,100 @@ func TestMaterializer_RecordsLifecycleMetrics(t *testing.T) {
}
}

func TestMaterializer_KeepsFinishedDetails(t *testing.T) {
failed := testRequestSummary()
failed.Status, failed.RequestVersion, failed.StatusTimestampMs, failed.Version = entity.RequestStatusError, 2, 20, 4
failed.LastError, failed.Metadata = "build failed", map[string]string{"batch_id": "b1"}
started := testRequestSummary()
started.Status, started.RequestVersion, started.StatusTimestampMs, started.Version = entity.RequestStatusStarted, 1, 15, 3
failedByResend := failed
failedByResend.StatusTimestampMs, failedByResend.LastError, failedByResend.Metadata = 30, "", map[string]string{}
resend := entity.RequestLog{Queue: "q", RequestID: "1", Type: entity.RequestLogTypeStatus, Status: entity.RequestStatusError, RequestVersion: 2, TimestampMs: 30, LastError: "dead lettered", Metadata: map[string]string{"batch_id": "b9", "dlq.failure_count": "3", "resent": "true"}}
bareResend := resend
bareResend.LastError, bareResend.Metadata = "", map[string]string{"resent": "true"}
original := entity.RequestLog{Queue: "q", RequestID: "1", Type: entity.RequestLogTypeStatus, Status: entity.RequestStatusError, RequestVersion: 2, TimestampMs: 20, LastError: "build failed", Metadata: map[string]string{"batch_id": "b1"}}
laterVersion := original
laterVersion.RequestVersion, laterVersion.TimestampMs, laterVersion.LastError, laterVersion.Metadata = 3, 40, "land failed", map[string]string{"batch_id": "b2"}

tests := []struct {
name string
before entity.RequestSummary
log entity.RequestLog
wantUpdate bool
wantLastError string
wantMetadata map[string]string
}{
{
name: "a resend after the original keeps its details and only fills what they lack",
before: failed,
log: resend,
wantUpdate: true,
wantLastError: "build failed",
wantMetadata: map[string]string{"batch_id": "b1", "dlq.failure_count": "3"},
},
{
name: "a resend without details after the original keeps them",
before: failed,
log: bareResend,
wantUpdate: true,
wantLastError: "build failed",
wantMetadata: map[string]string{"batch_id": "b1"},
},
{
name: "a resend whose original never arrived records its details without the resent marker",
before: started,
log: resend,
wantUpdate: true,
wantLastError: "dead lettered",
wantMetadata: map[string]string{"batch_id": "b9", "dlq.failure_count": "3"},
},
{
name: "the original after a bare resend fills the missing reason despite its older timestamp",
before: failedByResend,
log: original,
wantUpdate: true,
wantLastError: "build failed",
wantMetadata: map[string]string{"batch_id": "b1"},
},
{
name: "a redelivered original changes nothing",
before: failed,
log: original,
},
{
name: "a later finished version replaces the details",
before: failed,
log: laterVersion,
wantUpdate: true,
wantLastError: "land failed",
wantMetadata: map[string]string{"batch_id": "b2"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f := newMaterializerReceiptFixture(gomock.NewController(t))
f.logs.EXPECT().Insert(gomock.Any(), tt.log).Return(nil)
f.summaries.EXPECT().Get(gomock.Any(), tt.before.RequestID).Return(tt.before, nil)
var got entity.RequestSummary
if tt.wantUpdate {
f.summaries.EXPECT().Update(gomock.Any(), gomock.Any(), tt.before.Version, tt.before.Version+1).DoAndReturn(func(_ context.Context, updated entity.RequestSummary, _, _ int32) error {
got = updated
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))

if tt.wantUpdate {
assert.Equal(t, tt.wantLastError, got.LastError)
assert.Equal(t, tt.wantMetadata, got.Metadata)
}
})
}
}

func TestMaterializer_PublishesRequestHookEvents(t *testing.T) {
accepting := testRequestSummary()
accepted := accepting
Expand Down
17 changes: 11 additions & 6 deletions submitqueue/orchestrator/controller/cancel/cancel.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ func (c *Controller) Process(ctx context.Context, delivery consumer.Delivery) er

// The cancellation may be terminal even though its final log was never published.
if request.State == entity.RequestStateCancelled {
return corerequest.ResendTerminalRequestLog(ctx, c.registry, request)
return corerequest.ResendTerminalRequestLog(ctx, c.registry, request, "", cancelMetadata(cancelReq.Reason))
}

// Other terminal outcomes belong to their winning writer and are left untouched.
Expand Down Expand Up @@ -264,11 +264,7 @@ func (c *Controller) findBatches(ctx context.Context, store orchstorage.Storage,
// reports TerminationDiverged and we simply ack — the other writer owns the
// terminal log for the state it wrote.
func (c *Controller) cancelRequest(ctx context.Context, store orchstorage.Storage, request entity.Request, reason string) error {
metadata := map[string]string{}
if reason != "" {
metadata["reason"] = reason
}
res, err := corerequest.TerminateRequest(ctx, store, c.registry, request.ID, entity.RequestStateCancelled, "", metadata)
res, err := corerequest.TerminateRequest(ctx, store, c.registry, request.ID, entity.RequestStateCancelled, "", cancelMetadata(reason))
if err != nil {
metrics.NamedCounter(c.metricsScope, opName, "request_terminate_errors", 1, metrics.TagsFromContext(ctx)...)
return fmt.Errorf("failed to cancel request %s: %w", request.ID, err)
Expand Down Expand Up @@ -385,3 +381,12 @@ func (c *Controller) TopicKey() consumer.TopicKey {
func (c *Controller) ConsumerGroup() string {
return c.consumerGroup
}

// cancelMetadata is the cancelled request log's metadata: the caller's reason, when given.
func cancelMetadata(reason string) map[string]string {
metadata := map[string]string{}
if reason != "" {
metadata["reason"] = reason
}
return metadata
}
42 changes: 42 additions & 0 deletions submitqueue/orchestrator/controller/cancel/cancel_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,48 @@ func TestProcess_AlreadyTerminal_NoOp(t *testing.T) {
require.NoError(t, err)
}

func TestProcess_AlreadyCancelled_ResendsTerminalLog(t *testing.T) {
tests := []struct {
name string
reason string
wantMetadata map[string]string
}{
{name: "with the cancel reason", reason: "user asked", wantMetadata: map[string]string{"reason": "user asked", entity.RequestLogMetadataKeyResent: "true"}},
{name: "without a reason", wantMetadata: map[string]string{entity.RequestLogMetadataKeyResent: "true"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
registry, pub := newRegistry(t, ctrl)
var logs []entity.RequestLog
pub.EXPECT().Publish(gomock.Any(), "log", gomock.Any()).DoAndReturn(
func(_ context.Context, _ string, msg entityqueue.Message) error {
logEntry, err := sqmq.UnmarshalRequestLog(msg.Payload)
require.NoError(t, err)
logs = append(logs, logEntry)
return nil
},
)

reqStore := storagemock.NewMockRequestStore(ctrl)
reqStore.EXPECT().Get(gomock.Any(), "1").Return(entity.Request{
ID: "1", Queue: "q", State: entity.RequestStateCancelled, Version: 5,
}, nil)
store := orchstoragemock.NewMockStorage(ctrl)
store.EXPECT().GetQueueBatchStateStore().Return(newQueueBatchStateStore(ctrl)).AnyTimes()
store.EXPECT().GetRequestStore().Return(reqStore).AnyTimes()

controller := newController(t, store, registry)
require.NoError(t, controller.Process(context.Background(), newDelivery(t, ctrl, cancelPayload(t, "1", tt.reason), "1")))

require.Len(t, logs, 1)
assert.Equal(t, entity.RequestStatusCancelled, logs[0].Status)
assert.Equal(t, int32(5), logs[0].RequestVersion)
assert.Equal(t, tt.wantMetadata, logs[0].Metadata)
})
}
}

func TestProcess_RequestNotFound_Retryable(t *testing.T) {
ctrl := gomock.NewController(t)
registry, _ := newRegistry(t, ctrl)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,14 @@ func (c *Controller) Process(ctx context.Context, delivery consumer.Delivery) er
"partition_key", msg.PartitionKey,
)

// The failed conflict check may be terminal even though its final log was never published.
// The failed conflict check may be terminal even though its final log was never
// published. A redelivered failure carries the same result, so the resend can say why.
if request.State == entity.RequestStateError {
return corerequest.ResendTerminalRequestLog(ctx, c.registry, request)
var reason string
if result.Outcome != runwaypb.Outcome_SUCCEEDED {
reason = result.Reason
}
return corerequest.ResendTerminalRequestLog(ctx, c.registry, request, reason, nil)
}

if entity.IsRequestStateHalted(request.State) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -244,3 +244,59 @@ func TestProcess_HaltedRequestSkips(t *testing.T) {
msg := entityqueue.NewMessage(testRequestID, resultPayload(t, res), testQueue, nil)
require.NoError(t, controller.Process(context.Background(), newDelivery(ctrl, msg)))
}

func TestProcess_ErrorRequestResendsTerminalLog(t *testing.T) {
tests := []struct {
name string
result runwaymq.MergeResult
wantLastError string
}{
{
name: "a redelivered failure says why",
result: runwaymq.MergeResult{Id: testRequestID, Outcome: runwaypb.Outcome_FAILED, Reason: "conflict in foo.go"},
wantLastError: "conflict in foo.go",
},
{
name: "a success cannot say why the request failed",
result: runwaymq.MergeResult{Id: testRequestID, Outcome: runwaypb.Outcome_SUCCEEDED},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
reqStore := storagemock.NewMockRequestStore(ctrl)
reqStore.EXPECT().Get(gomock.Any(), testRequestID).Return(
entity.Request{ID: testRequestID, Queue: testQueue, State: entity.RequestStateError, Version: 2}, nil)
store := orchstoragemock.NewMockStorage(ctrl)
store.EXPECT().GetRequestStore().Return(reqStore).AnyTimes()

var logs []entity.RequestLog
pub := queuemock.NewMockPublisher(ctrl)
pub.EXPECT().Publish(gomock.Any(), "log", gomock.Any()).DoAndReturn(
func(_ context.Context, _ string, msg entityqueue.Message) error {
logEntry, err := sqmq.UnmarshalRequestLog(msg.Payload)
require.NoError(t, err)
logs = append(logs, logEntry)
return nil
},
)
q := queuemock.NewMockQueue(ctrl)
q.EXPECT().Publisher().Return(pub).AnyTimes()
registry, err := consumer.NewTopicRegistry([]consumer.TopicConfig{{Key: topickey.TopicKeyLog, Name: "log", Queue: q}})
require.NoError(t, err)
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")

msg := entityqueue.NewMessage(testRequestID, resultPayload(t, tt.result), testQueue, nil)
require.NoError(t, controller.Process(context.Background(), newDelivery(ctrl, msg)))

require.Len(t, logs, 1)
assert.Equal(t, entity.RequestStatusError, logs[0].Status)
assert.Equal(t, int32(2), logs[0].RequestVersion)
assert.Equal(t, tt.wantLastError, logs[0].LastError)
assert.Equal(t, "true", logs[0].Metadata[entity.RequestLogMetadataKeyResent])
})
}
}
3 changes: 2 additions & 1 deletion submitqueue/orchestrator/controller/validate/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,9 @@ func (c *Controller) Process(ctx context.Context, delivery consumer.Delivery) er
)

// The rejection may be terminal even though its final log was never published.
// This delivery cannot tell why the request was rejected, so the resend has no reason.
if request.State == entity.RequestStateError {
return corerequest.ResendTerminalRequestLog(ctx, c.registry, request)
return corerequest.ResendTerminalRequestLog(ctx, c.registry, request, "", nil)
}

// Cancellation intent halts forward progress even before the terminal outcome.
Expand Down
Loading
Loading