From 47024cdfccec1468525c04db4e291881ebe9bbf6 Mon Sep 17 00:00:00 2001 From: mnoah1 Date: Fri, 4 Dec 2026 20:46:47 +0000 Subject: [PATCH] feat(stovepipe): store executor callbacks and versioned fix observations Summary: ## Why? Preserve the executor callback separately from the status that changes as the fix is observed. ## What? Implements the storage portion of the design in #1192. Introduce the queue-scoped report contract, MySQL schema and conditional writes for fix tracking. Test Plan: The MySQL fix-report tests cover identical keys in different queues and optimistic version conflicts. Revert Plan: Revert this change after reverting any dependent stack entries. --- doc/rfc/stovepipe/fix-tracking.md | 6 +- stovepipe/entity/BUILD.bazel | 1 + stovepipe/entity/fix_report.go | 62 +++++++++++ stovepipe/extension/storage/BUILD.bazel | 1 + stovepipe/extension/storage/README.md | 2 + .../extension/storage/fix_report_store.go | 35 ++++++ stovepipe/extension/storage/mock/BUILD.bazel | 1 + .../storage/mock/fix_report_store_mock.go | 100 +++++++++++++++++ .../extension/storage/mock/storage_mock.go | 14 +++ stovepipe/extension/storage/mysql/BUILD.bazel | 2 + .../storage/mysql/fix_report_store.go | 101 ++++++++++++++++++ .../storage/mysql/fix_report_store_test.go | 53 +++++++++ .../storage/mysql/schema/fix_report.sql | 9 ++ stovepipe/extension/storage/mysql/storage.go | 6 ++ stovepipe/extension/storage/storage.go | 3 + .../extension/storage/mysql/storage_test.go | 44 ++++++++ 16 files changed, 437 insertions(+), 3 deletions(-) create mode 100644 stovepipe/entity/fix_report.go create mode 100644 stovepipe/extension/storage/fix_report_store.go create mode 100644 stovepipe/extension/storage/mock/fix_report_store_mock.go create mode 100644 stovepipe/extension/storage/mysql/fix_report_store.go create mode 100644 stovepipe/extension/storage/mysql/fix_report_store_test.go create mode 100644 stovepipe/extension/storage/mysql/schema/fix_report.sql diff --git a/doc/rfc/stovepipe/fix-tracking.md b/doc/rfc/stovepipe/fix-tracking.md index 6ce7d9bcf..eac97c4c2 100644 --- a/doc/rfc/stovepipe/fix-tracking.md +++ b/doc/rfc/stovepipe/fix-tracking.md @@ -7,7 +7,7 @@ Stovepipe tracks three different facts: **the backend accepted work**, **a chang | When | What Stovepipe retains | What the user sees | |---|---|---| | A registered executor accepts an issue opening | An `issue_repair` receipt with the executor's `fix_id`, and an association between that fix and the request. A fix can cover multiple openings or requests. | **Fix accepted** (`fix_submitted`), once per opening and executor. No link is promised. | -| The executor delivers `RecordFixResult` | An immutable report, then a fix-tracking task identifying that report. Without a callback, acceptance alone does not start polling. | No new history event: a callback is not evidence that a change exists. | +| The executor delivers `RecordFixReport` | An immutable report, then a fix-tracking task identifying that report. Without a callback, acceptance alone does not start polling. | No new history event: a callback is not evidence that a change exists. | | The executor verifies a published or reused change | The first observation of its canonical URL, shared across all reports for the fix. | **Fix available** (`fix_available`), once per associated request, executor, fix and distinct URL. Other changes can still be pending. | A callback can arrive before the submission receipt. The worker retains verified URLs even when no request is associated yet. Both sides write first, then read the other side: a new association checks for known URLs, and a new observation checks for associated requests. Replaying either step fills in missing history using the same event ID. It never rewrites **Fix accepted**. Read both events through the [request history API](request-history-api.md); `fix_available` is a history event, not a hook notification. @@ -15,8 +15,8 @@ A callback can arrive before the submission receipt. The worker retains verified ## Integrating a custom fixer 1. **Register and submit.** In host wiring, have `fixer.Factory.For` return a queue-local `Registration` with a stable ID and your `RepairExecutor`. Do not reuse that ID for another backend. `Submit` receives a batch and returns a `Submission` per accepted or deliberately skipped opening: return the backend run ID as `FixID`, or return a `SkipReason`, not both. Deduplicate backend submissions by issue opening across retries, even when the batch changes. If some items were accepted before an error, return their receipts alongside the error. -2. **Carry the run identity into each job.** A trusted callback producer calls `RecordFixResult` with the same `queue`, `executor_id`, and `fix_id` and an executor-owned JSON object encoded in `result_json` (at most 256 KiB). No request ID is needed. Omit `report_id` for a single report; use a stable occurrence ID for each additional report. Include the backend identifiers needed to resolve that occurrence in the payload. Retry an uncertain delivery with the same identity and serialized payload: whitespace is compacted, but object keys are not reordered. A different payload for the same occurrence returns `ALREADY_EXISTS`; progress is not reported by overwriting it. -3. **Verify, don't resubmit.** Implement the optional `ResultTracker` on the same registered executor. `ObserveFix` must be read-only and safe to repeat concurrently. Resolve the *specific* run or child job named by the report, not the latest change on a branch. Return `pending` while publication is outstanding, not an error. Include all verified canonical HTTP(S) links for that report in `ChangeURLs`, even while pending, and mark reused links in `ExistingChangeURLs`. A dry run has no verified change to return. Return a dependency error when the lookup itself fails. +2. **Carry the run identity into each job.** A trusted callback producer calls `RecordFixReport` with the same `queue`, `executor_id`, and `fix_id` and an executor-owned JSON object encoded in `payload_json` (at most 256 KiB). No request ID is needed. Omit `report_id` for a single report; use a stable occurrence ID for each additional report. Include the backend identifiers needed to resolve that occurrence in the payload. Retry an uncertain delivery with the same identity and serialized payload: whitespace is compacted, but object keys are not reordered. A different payload for the same occurrence returns `ALREADY_EXISTS`; progress is not reported by overwriting it. +3. **Verify, don't resubmit.** Implement the optional `ReportTracker` on the same registered executor. `ObserveFix` must be read-only and safe to repeat concurrently. Resolve the *specific* run or child job named by the report, not the latest change on a branch. Return `pending` while publication is outstanding, not an error. Include all verified canonical HTTP(S) links for that report in `ChangeURLs`, even while pending, and mark reused links in `ExistingChangeURLs`. A dry run has no verified change to return. Return a dependency error when the lookup itself fails. For example, a formatter accepts two issues from one request under `fix_id=run-42`. Its dispatcher sends an unnamed report; its two workers report `job/17/completed` and `job/18/completed`, **both under `run-42`**. Worker 17 can finish before the dispatcher reports. If its output is not yet published, `ObserveFix` returns `pending`; when the backend links job 17 to PR 81, that request gets a link to PR 81 without waiting for job 18. If job 18 finds the same PR, history still shows one link. A different PR gets its own entry. diff --git a/stovepipe/entity/BUILD.bazel b/stovepipe/entity/BUILD.bazel index a1581e434..40d3b9394 100644 --- a/stovepipe/entity/BUILD.bazel +++ b/stovepipe/entity/BUILD.bazel @@ -5,6 +5,7 @@ go_library( srcs = [ "build.go", "build_issue.go", + "fix_report.go", "get_issues_by_request_id.go", "ingest.go", "issue_history.go", diff --git a/stovepipe/entity/fix_report.go b/stovepipe/entity/fix_report.go new file mode 100644 index 000000000..6f6f7bdc2 --- /dev/null +++ b/stovepipe/entity/fix_report.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 entity + +import "encoding/json" + +// FixReport is an immutable callback from a repair executor; it need not describe a terminal outcome. +type FixReport struct { + // Queue scopes the repair submission and its reports. + Queue string + // ExecutorID scopes the opaque FixID within the queue. + ExecutorID string + // FixID is the executor-issued identifier shared by the associated submissions. + FixID string + // Payload is an executor-owned JSON object, at most 256 KiB. + Payload json.RawMessage +} + +// FixState is the observed lifecycle of one accepted fix. +type FixState string + +const ( + FixStateSkipped FixState = "skipped" + FixStatePending FixState = "pending" + FixStateSucceeded FixState = "succeeded" + FixStateFailed FixState = "failed" + FixStateInconclusive FixState = "inconclusive" +) + +// FixObservation is a complete snapshot of an executor's known outcome. +type FixObservation struct { + // State is pending until the executor has a terminal outcome. + State FixState `json:"state"` + // ChangeURLs contains all known published or existing changes for this fix. + ChangeURLs []string `json:"change_urls,omitempty"` + // ExistingChangeURLs is the subset identified as pre-existing rather than newly published. + ExistingChangeURLs []string `json:"existing_change_urls,omitempty"` + // Reason is a stable outcome detail, empty when none is available. + Reason string `json:"reason,omitempty"` +} + +// FixTrackingState is the versioned progress for an immutable fix report. +type FixTrackingState struct { + // FixObservation is the most recently recorded outcome. + FixObservation + // NextCheckAt is the earliest time for another check, in Unix milliseconds. Zero for terminal outcomes. + NextCheckAt int64 `json:"next_check_at,omitempty"` + // Version is the number of recorded observations. Zero means no observation has been recorded. + Version int32 `json:"-"` +} diff --git a/stovepipe/extension/storage/BUILD.bazel b/stovepipe/extension/storage/BUILD.bazel index f8d5acbd2..761ec8694 100644 --- a/stovepipe/extension/storage/BUILD.bazel +++ b/stovepipe/extension/storage/BUILD.bazel @@ -5,6 +5,7 @@ go_library( srcs = [ "build_issue_store.go", "build_store.go", + "fix_report_store.go", "issue_log_store.go", "issue_repair_store.go", "issue_state_store.go", diff --git a/stovepipe/extension/storage/README.md b/stovepipe/extension/storage/README.md index eb2775d4e..011fcc33a 100644 --- a/stovepipe/extension/storage/README.md +++ b/stovepipe/extension/storage/README.md @@ -56,6 +56,8 @@ The MySQL primary key contains the queue, build ID, task ID, and unit ID directl `BuildIssue.FixID` is the legacy single-executor repair association. An empty ID means no association is recorded. `Update` uses the existing entity CAS convention: it guards `oldVersion` and writes `newVersion`, returning `ErrVersionMismatch` for a stale or missing record. The caller owns version arithmetic and repair policy; storage does not enforce a per-build submission limit. Observation identity and membership survive recovery. +`FixReportStore` retains one immutable result per `(queue, executor ID, fix ID)`. It is independent of `issue_repair` so a callback can arrive before the submission is committed. A queue-scoped `Get` joins the two by executor and fix ID without an index over issue memberships. A separate, versioned tracking snapshot is updated without rewriting the callback. + `IssueRepairStore` retains versioned submission state keyed by the complete opening identity and executor ID. Pending rows have empty fix IDs and skip reasons. Create never overwrites existing state; Update replaces a snapshot guarded by its version. The controller creates pending rows and owns submission outcomes; executors own metadata and must preserve other fields when updating. Both writers reload on version conflicts before reapplying their edits. Fix IDs are not unique: an executor can accept multiple issues in one external request. Executor-owned metadata remains a `map[string]string` in Go and is serialized to the non-null JSON `metadata` column. Nil and empty maps are equivalent; empty metadata is stored as `{}`. String values may contain serialized JSON without interpretation by the store. Apply `mysql/schema/issue_repair.sql` before deploying the new readers and writers. Host adapters own backend-specific dispatch limits. The schema's `CREATE TABLE IF NOT EXISTS` does not alter existing tables. ## Request metadata diff --git a/stovepipe/extension/storage/fix_report_store.go b/stovepipe/extension/storage/fix_report_store.go new file mode 100644 index 000000000..2e8d2a566 --- /dev/null +++ b/stovepipe/extension/storage/fix_report_store.go @@ -0,0 +1,35 @@ +// 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 storage + +//go:generate mockgen -source=fix_report_store.go -destination=mock/fix_report_store_mock.go -package=mock + +import ( + "context" + + "github.com/uber/submitqueue/stovepipe/entity" +) + +// FixReportStore retains immutable executor reports within one queue. +type FixReportStore interface { + // Create returns ErrAlreadyExists if the executor and fix ID already have a report. + Create(context.Context, entity.FixReport) error + // Get returns ErrNotFound when the key has no recorded report. + Get(ctx context.Context, executorID, fixID string) (entity.FixReport, error) + // GetTrackingState yields a zero snapshot for an existing report not yet checked. + GetTrackingState(ctx context.Context, executorID, fixID string) (entity.FixTrackingState, error) + // UpdateTrackingState replaces progress without changing the callback payload. + UpdateTrackingState(ctx context.Context, executorID, fixID string, snapshot entity.FixTrackingState, oldVersion, newVersion int32) error +} diff --git a/stovepipe/extension/storage/mock/BUILD.bazel b/stovepipe/extension/storage/mock/BUILD.bazel index e00a133f4..0ccad6591 100644 --- a/stovepipe/extension/storage/mock/BUILD.bazel +++ b/stovepipe/extension/storage/mock/BUILD.bazel @@ -5,6 +5,7 @@ go_library( srcs = [ "build_issue_store_mock.go", "build_store_mock.go", + "fix_report_store_mock.go", "issue_log_store_mock.go", "issue_repair_store_mock.go", "issue_state_store_mock.go", diff --git a/stovepipe/extension/storage/mock/fix_report_store_mock.go b/stovepipe/extension/storage/mock/fix_report_store_mock.go new file mode 100644 index 000000000..c4667b7ac --- /dev/null +++ b/stovepipe/extension/storage/mock/fix_report_store_mock.go @@ -0,0 +1,100 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: fix_report_store.go +// +// Generated by this command: +// +// mockgen -source=fix_report_store.go -destination=mock/fix_report_store_mock.go -package=mock +// + +// Package mock is a generated GoMock package. +package mock + +import ( + context "context" + reflect "reflect" + + entity "github.com/uber/submitqueue/stovepipe/entity" + gomock "go.uber.org/mock/gomock" +) + +// MockFixReportStore is a mock of FixReportStore interface. +type MockFixReportStore struct { + ctrl *gomock.Controller + recorder *MockFixReportStoreMockRecorder + isgomock struct{} +} + +// MockFixReportStoreMockRecorder is the mock recorder for MockFixReportStore. +type MockFixReportStoreMockRecorder struct { + mock *MockFixReportStore +} + +// NewMockFixReportStore creates a new mock instance. +func NewMockFixReportStore(ctrl *gomock.Controller) *MockFixReportStore { + mock := &MockFixReportStore{ctrl: ctrl} + mock.recorder = &MockFixReportStoreMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockFixReportStore) EXPECT() *MockFixReportStoreMockRecorder { + return m.recorder +} + +// Create mocks base method. +func (m *MockFixReportStore) Create(arg0 context.Context, arg1 entity.FixReport) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Create", arg0, arg1) + ret0, _ := ret[0].(error) + return ret0 +} + +// Create indicates an expected call of Create. +func (mr *MockFixReportStoreMockRecorder) Create(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockFixReportStore)(nil).Create), arg0, arg1) +} + +// Get mocks base method. +func (m *MockFixReportStore) Get(ctx context.Context, executorID, fixID string) (entity.FixReport, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Get", ctx, executorID, fixID) + ret0, _ := ret[0].(entity.FixReport) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Get indicates an expected call of Get. +func (mr *MockFixReportStoreMockRecorder) Get(ctx, executorID, fixID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockFixReportStore)(nil).Get), ctx, executorID, fixID) +} + +// GetTrackingState mocks base method. +func (m *MockFixReportStore) GetTrackingState(ctx context.Context, executorID, fixID string) (entity.FixTrackingState, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTrackingState", ctx, executorID, fixID) + ret0, _ := ret[0].(entity.FixTrackingState) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetTrackingState indicates an expected call of GetTrackingState. +func (mr *MockFixReportStoreMockRecorder) GetTrackingState(ctx, executorID, fixID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTrackingState", reflect.TypeOf((*MockFixReportStore)(nil).GetTrackingState), ctx, executorID, fixID) +} + +// UpdateTrackingState mocks base method. +func (m *MockFixReportStore) UpdateTrackingState(ctx context.Context, executorID, fixID string, snapshot entity.FixTrackingState, oldVersion, newVersion int32) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UpdateTrackingState", ctx, executorID, fixID, snapshot, oldVersion, newVersion) + ret0, _ := ret[0].(error) + return ret0 +} + +// UpdateTrackingState indicates an expected call of UpdateTrackingState. +func (mr *MockFixReportStoreMockRecorder) UpdateTrackingState(ctx, executorID, fixID, snapshot, oldVersion, newVersion any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateTrackingState", reflect.TypeOf((*MockFixReportStore)(nil).UpdateTrackingState), ctx, executorID, fixID, snapshot, oldVersion, newVersion) +} diff --git a/stovepipe/extension/storage/mock/storage_mock.go b/stovepipe/extension/storage/mock/storage_mock.go index cf2f78253..32b26e1dd 100644 --- a/stovepipe/extension/storage/mock/storage_mock.go +++ b/stovepipe/extension/storage/mock/storage_mock.go @@ -107,6 +107,20 @@ func (mr *MockStorageMockRecorder) GetBuildStore() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBuildStore", reflect.TypeOf((*MockStorage)(nil).GetBuildStore)) } +// GetFixReportStore mocks base method. +func (m *MockStorage) GetFixReportStore() storage.FixReportStore { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetFixReportStore") + ret0, _ := ret[0].(storage.FixReportStore) + return ret0 +} + +// GetFixReportStore indicates an expected call of GetFixReportStore. +func (mr *MockStorageMockRecorder) GetFixReportStore() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetFixReportStore", reflect.TypeOf((*MockStorage)(nil).GetFixReportStore)) +} + // GetIssueLogStore mocks base method. func (m *MockStorage) GetIssueLogStore() storage.IssueLogStore { m.ctrl.T.Helper() diff --git a/stovepipe/extension/storage/mysql/BUILD.bazel b/stovepipe/extension/storage/mysql/BUILD.bazel index d67b35bc7..db888b27f 100644 --- a/stovepipe/extension/storage/mysql/BUILD.bazel +++ b/stovepipe/extension/storage/mysql/BUILD.bazel @@ -5,6 +5,7 @@ go_library( srcs = [ "build_issue_store.go", "build_store.go", + "fix_report_store.go", "issue_log_store.go", "issue_repair_store.go", "issue_state_store.go", @@ -45,6 +46,7 @@ go_test( "build_issue_store_test.go", "build_issue_update_test.go", "build_store_test.go", + "fix_report_store_test.go", "issue_log_store_test.go", "issue_repair_store_test.go", "issue_state_list_test.go", diff --git a/stovepipe/extension/storage/mysql/fix_report_store.go b/stovepipe/extension/storage/mysql/fix_report_store.go new file mode 100644 index 000000000..8635550b2 --- /dev/null +++ b/stovepipe/extension/storage/mysql/fix_report_store.go @@ -0,0 +1,101 @@ +// 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 mysql + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + + "github.com/uber/submitqueue/stovepipe/entity" + "github.com/uber/submitqueue/stovepipe/extension/storage" +) + +type fixReportStore struct { + db *sql.DB + queue string +} + +func (s *fixReportStore) Create(ctx context.Context, report entity.FixReport) error { + if report.Queue != s.queue { + return fmt.Errorf("fix report queue %q does not match store queue %q", report.Queue, s.queue) + } + _, err := s.db.ExecContext(ctx, `INSERT INTO fix_report (queue, executor_id, fix_id, payload_json) VALUES (?, ?, ?, ?)`, + s.queue, report.ExecutorID, report.FixID, []byte(report.Payload)) + if isDuplicateEntry(err) { + return storage.ErrAlreadyExists + } + if err != nil { + return fmt.Errorf("create fix report: %w", err) + } + return nil +} + +func (s *fixReportStore) Get(ctx context.Context, executorID, fixID string) (entity.FixReport, error) { + report := entity.FixReport{Queue: s.queue, ExecutorID: executorID, FixID: fixID} + var payload []byte + err := s.db.QueryRowContext(ctx, `SELECT payload_json FROM fix_report WHERE queue=? AND executor_id=? AND fix_id=?`, + s.queue, executorID, fixID).Scan(&payload) + if errors.Is(err, sql.ErrNoRows) { + return entity.FixReport{}, storage.WrapNotFound(err) + } + if err != nil { + return entity.FixReport{}, fmt.Errorf("read fix report: %w", err) + } + report.Payload = payload + return report, nil +} + +func (s *fixReportStore) GetTrackingState(ctx context.Context, executorID, fixID string) (entity.FixTrackingState, error) { + var snapshot entity.FixTrackingState + var encoded []byte + err := s.db.QueryRowContext(ctx, `SELECT tracking_state, tracking_version FROM fix_report WHERE queue=? AND executor_id=? AND fix_id=?`, + s.queue, executorID, fixID).Scan(&encoded, &snapshot.Version) + if errors.Is(err, sql.ErrNoRows) { + return entity.FixTrackingState{}, storage.WrapNotFound(err) + } + if err != nil { + return entity.FixTrackingState{}, fmt.Errorf("read fix progress: %w", err) + } + if len(encoded) > 0 { + if err := json.Unmarshal(encoded, &snapshot); err != nil { + return entity.FixTrackingState{}, fmt.Errorf("decode fix progress: %w", err) + } + } + return snapshot, nil +} + +func (s *fixReportStore) UpdateTrackingState(ctx context.Context, executorID, fixID string, snapshot entity.FixTrackingState, oldVersion, newVersion int32) error { + encoded, err := json.Marshal(snapshot) + if err != nil { + return fmt.Errorf("encode fix progress: %w", err) + } + result, err := s.db.ExecContext(ctx, `UPDATE fix_report SET tracking_state=?, tracking_version=? + WHERE queue=? AND executor_id=? AND fix_id=? AND tracking_version=?`, + encoded, newVersion, s.queue, executorID, fixID, oldVersion) + if err != nil { + return fmt.Errorf("update fix progress: %w", err) + } + affected, err := result.RowsAffected() + if err != nil { + return fmt.Errorf("read updated fix progress count: %w", err) + } + if affected == 0 { + return storage.ErrVersionMismatch + } + return nil +} diff --git a/stovepipe/extension/storage/mysql/fix_report_store_test.go b/stovepipe/extension/storage/mysql/fix_report_store_test.go new file mode 100644 index 000000000..fe2628c95 --- /dev/null +++ b/stovepipe/extension/storage/mysql/fix_report_store_test.go @@ -0,0 +1,53 @@ +// 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 mysql + +import ( + "database/sql" + "encoding/json" + "testing" + + "github.com/DATA-DOG/go-sqlmock" + mysql "github.com/go-sql-driver/mysql" + "github.com/stretchr/testify/require" + "github.com/uber/submitqueue/stovepipe/entity" + "github.com/uber/submitqueue/stovepipe/extension/storage" +) + +func TestFixReportStore(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer db.Close() + backend := &fixReportStore{db: db, queue: "main"} + report := entity.FixReport{Queue: "main", ExecutorID: "repair", FixID: "42", Payload: json.RawMessage(`{"results":[]}`)} + + mock.ExpectExec("INSERT INTO fix_report").WithArgs("main", "repair", "42", []byte(report.Payload)).WillReturnResult(sqlmock.NewResult(0, 1)) + require.NoError(t, backend.Create(t.Context(), report)) + mock.ExpectExec("INSERT INTO fix_report").WithArgs("main", "repair", "42", []byte(report.Payload)).WillReturnError(&mysql.MySQLError{Number: 1062}) + require.ErrorIs(t, backend.Create(t.Context(), report), storage.ErrAlreadyExists) + + query := `SELECT payload_json FROM fix_report WHERE queue=\? AND executor_id=\? AND fix_id=\?` + mock.ExpectQuery(query).WithArgs("main", "repair", "42").WillReturnRows(sqlmock.NewRows([]string{"payload_json"}).AddRow([]byte(report.Payload))) + got, err := backend.Get(t.Context(), "repair", "42") + require.NoError(t, err) + require.Equal(t, report, got) + mock.ExpectQuery(query).WithArgs("main", "repair", "99").WillReturnError(sql.ErrNoRows) + _, err = backend.Get(t.Context(), "repair", "99") + require.ErrorIs(t, err, storage.ErrNotFound) + + report.Queue = "other" + require.Error(t, backend.Create(t.Context(), report)) + require.NoError(t, mock.ExpectationsWereMet()) +} diff --git a/stovepipe/extension/storage/mysql/schema/fix_report.sql b/stovepipe/extension/storage/mysql/schema/fix_report.sql new file mode 100644 index 000000000..8a9cf0106 --- /dev/null +++ b/stovepipe/extension/storage/mysql/schema/fix_report.sql @@ -0,0 +1,9 @@ +CREATE TABLE IF NOT EXISTS fix_report ( + queue VARBINARY(255) NOT NULL, + executor_id VARBINARY(128) NOT NULL, + fix_id VARBINARY(255) NOT NULL, + payload_json MEDIUMBLOB NOT NULL, + tracking_state JSON NULL, + tracking_version INT NOT NULL DEFAULT 0, + PRIMARY KEY (queue, executor_id, fix_id) +) ENGINE=InnoDB; diff --git a/stovepipe/extension/storage/mysql/storage.go b/stovepipe/extension/storage/mysql/storage.go index a38a4877b..70177fad9 100644 --- a/stovepipe/extension/storage/mysql/storage.go +++ b/stovepipe/extension/storage/mysql/storage.go @@ -47,6 +47,7 @@ func (s *Storage) For(queueName string) (storage.Storage, error) { queueScope := s.scope.Tagged(map[string]string{"queue": queueName}) return &mysqlStorage{ issueRepairStore: NewIssueRepairStore(s.db, queueName), + fixReportStore: &fixReportStore{db: s.db, queue: queueName}, requestStore: NewRequestStore(s.db, queueScope.SubScope("request_store"), queueName), requestURIStore: NewRequestURIStore(s.db, queueScope.SubScope("request_uri_store"), queueName), requestLogStore: NewRequestLogStore(s.db, queueScope.SubScope("request_log_store"), queueName), @@ -78,6 +79,7 @@ func (s *Storage) Close() error { // mysqlStorage is the queue-scoped store aggregate returned by For. type mysqlStorage struct { issueRepairStore storage.IssueRepairStore + fixReportStore storage.FixReportStore requestStore storage.RequestStore requestURIStore storage.RequestURIStore requestLogStore storage.RequestLogStore @@ -192,3 +194,7 @@ func (f *mysqlStorage) GetIssueTrackingStore() storage.IssueTrackingStore { func (f *mysqlStorage) GetRequestIssueSummaryStore() storage.RequestIssueSummaryStore { return f.requestIssueSummaryStore } + +func (f *mysqlStorage) GetFixReportStore() storage.FixReportStore { + return f.fixReportStore +} diff --git a/stovepipe/extension/storage/storage.go b/stovepipe/extension/storage/storage.go index 40761c01e..9a2ced90b 100644 --- a/stovepipe/extension/storage/storage.go +++ b/stovepipe/extension/storage/storage.go @@ -72,6 +72,9 @@ type Storage interface { // GetIssueRepairStore returns per-executor repair dispositions. GetIssueRepairStore() IssueRepairStore + // GetFixReportStore returns immutable executor reports. + GetFixReportStore() FixReportStore + // GetRequestStore returns the RequestStore instance. GetRequestStore() RequestStore diff --git a/test/integration/stovepipe/extension/storage/mysql/storage_test.go b/test/integration/stovepipe/extension/storage/mysql/storage_test.go index f6322e6ac..c501e878c 100644 --- a/test/integration/stovepipe/extension/storage/mysql/storage_test.go +++ b/test/integration/stovepipe/extension/storage/mysql/storage_test.go @@ -65,6 +65,50 @@ func TestMySQLStorage(t *testing.T) { return backend.For(config.QueueName) }).AnyTimes() + t.Run("FixReport", func(t *testing.T) { + result := entity.FixReport{Queue: "result/main", ExecutorID: "repair", FixID: "AbC", Payload: json.RawMessage(`{"results":[]}`)} + bound, err := backend.For(result.Queue) + require.NoError(t, err) + results := bound.GetFixReportStore() + require.NoError(t, results.Create(t.Context(), result)) + require.ErrorIs(t, results.Create(t.Context(), result), storage.ErrAlreadyExists) + got, err := results.Get(t.Context(), result.ExecutorID, result.FixID) + require.NoError(t, err) + require.Equal(t, result, got) + + progress, err := results.GetTrackingState(t.Context(), result.ExecutorID, result.FixID) + require.NoError(t, err) + require.Zero(t, progress) + next := entity.FixTrackingState{FixObservation: entity.FixObservation{State: entity.FixStateSucceeded, ChangeURLs: []string{"https://example.org/repo/pull/2"}}} + require.NoError(t, results.UpdateTrackingState(t.Context(), result.ExecutorID, result.FixID, next, 0, 1)) + require.ErrorIs(t, results.UpdateTrackingState(t.Context(), result.ExecutorID, result.FixID, next, 0, 1), storage.ErrVersionMismatch) + progress, err = results.GetTrackingState(t.Context(), result.ExecutorID, result.FixID) + require.NoError(t, err) + next.Version = 1 + require.Equal(t, next, progress) + got, err = results.Get(t.Context(), result.ExecutorID, result.FixID) + require.NoError(t, err) + require.Equal(t, result, got) + + _, err = results.Get(t.Context(), result.ExecutorID, "abc") + require.ErrorIs(t, err, storage.ErrNotFound) + other, err := backend.For("result/other") + require.NoError(t, err) + otherQueue := result + otherQueue.Queue, otherQueue.Payload = "result/other", json.RawMessage(`{"queue":2}`) + require.NoError(t, other.GetFixReportStore().Create(t.Context(), otherQueue)) + otherExecutor := result + otherExecutor.ExecutorID, otherExecutor.Payload = "second", json.RawMessage(`{"executor":2}`) + require.NoError(t, results.Create(t.Context(), otherExecutor)) + for _, row := range []entity.FixReport{result, otherQueue, otherExecutor} { + bound, err := backend.For(row.Queue) + require.NoError(t, err) + got, err := bound.GetFixReportStore().Get(t.Context(), row.ExecutorID, row.FixID) + require.NoError(t, err) + require.Equal(t, row, got) + } + }) + t.Run("ValidationFactBatchRetry", func(t *testing.T) { resetStorage(t, db) testValidationFactBatchRetry(t, ctx, backend)