diff --git a/internal/contracts/state/v1/state.pb.go b/internal/contracts/state/v1/state.pb.go index b4a939385..6a448273f 100644 --- a/internal/contracts/state/v1/state.pb.go +++ b/internal/contracts/state/v1/state.pb.go @@ -5566,6 +5566,8 @@ func (*BeginRemediationResponse) Descriptor() ([]byte, []int) { return file_state_v1_state_proto_rawDescGZIP(), []int{86} } +// UpdateReviewPayloadRequest merges payload's comments into the unclaimed +// review unit with the same review id, active or pending. type UpdateReviewPayloadRequest struct { state protoimpl.MessageState `protogen:"open.v1"` TaskId int64 `protobuf:"varint,1,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"` diff --git a/internal/daemon/reactions.go b/internal/daemon/reactions.go index a041ccc1c..419b2737f 100644 --- a/internal/daemon/reactions.go +++ b/internal/daemon/reactions.go @@ -173,38 +173,15 @@ func (c *reactionConsumer) handleComment(ctx context.Context, msg eventbus.Messa return } - // A comment with a parent review is collected into that review's pending - // unit, never dispatched alone. Once the unit has been claimed, its input - // is frozen: a late comment is dropped, and the round cap bounds the - // exchange if the reviewer re-reviews. - if task.Status != workflow.StatusQueued || task.Workflow != "remediate" { - c.drop(msg, "parent review's unit is no longer pending") - return - } - unit, err := workflow.DecodeReviewUnit(task.ReviewPayload) - if err != nil { - if errors.Is(err, workflow.ErrNoReviewPayload) { - c.drop(msg, "queued remediation carries no review unit") - return - } - c.log.Error("review payload decode failed", "task", task.ID, "err", err) - _ = msg.Nak() - return - } - if unit.ReviewID != e.ReviewID { - c.drop(msg, "comment's parent review is not the pending unit") - return - } - for _, existing := range unit.Comments { - if existing.CommentID == e.CommentID { - _ = msg.Ack() // re-delivery of an already-collected comment - return - } - } - unit.Comments = append(unit.Comments, workflow.ReviewUnitComment{ - CommentID: e.CommentID, Path: e.Path, Line: e.Line, Body: e.Body, + // A comment with a parent review is collected into that review's unit + // while the unit is unclaimed: the queued active unit, or one waiting + // behind a running remediation. A claimed unit's input is frozen, so a + // late comment is dropped and the round cap bounds the exchange if the + // reviewer re-reviews. + payload, err := workflow.EncodeReviewUnit(workflow.ReviewUnit{ + ReviewID: e.ReviewID, + Comments: []workflow.ReviewUnitComment{{CommentID: e.CommentID, Path: e.Path, Line: e.Line, Body: e.Body}}, }) - payload, err := workflow.EncodeReviewUnit(unit) if err != nil { c.log.Error("review unit encode failed", "task", task.ID, "err", err) _ = msg.Nak() @@ -212,8 +189,7 @@ func (c *reactionConsumer) handleComment(ctx context.Context, msg eventbus.Messa } if err := c.remediations.UpdateReviewPayload(ctx, task.ID, payload); err != nil { if errors.Is(err, storecontract.ErrStaleTransition) { - // Claimed between the read and the write: the unit is frozen. - _ = msg.Ack() + c.drop(msg, "parent review's unit is no longer pending") return } c.log.Error("UpdateReviewPayload failed", "task", task.ID, "err", err) diff --git a/internal/domain/storecontract/storecontract.go b/internal/domain/storecontract/storecontract.go index 04212b5c0..7c34ec3f8 100644 --- a/internal/domain/storecontract/storecontract.go +++ b/internal/domain/storecontract/storecontract.go @@ -106,7 +106,8 @@ type ReviewGateResponder interface { // for one task are serialised, so a distinct review that arrives while a // remediation owns the task is queued behind it and remediated once that run // finishes; a re-delivered unit is absorbed, not queued twice. -// UpdateReviewPayload appends late-arriving comments to a still-queued unit. +// UpdateReviewPayload merges late-arriving comments into the unclaimed unit +// for the same review, active or queued behind a running remediation. type RemediationStarter interface { BeginRemediation(ctx context.Context, taskID int64, payload string) error UpdateReviewPayload(ctx context.Context, taskID int64, payload string) error diff --git a/internal/infrastructure/postgres/postgresdb/tasks.sql.go b/internal/infrastructure/postgres/postgresdb/tasks.sql.go index ce310cb0a..1ae404b70 100644 --- a/internal/infrastructure/postgres/postgresdb/tasks.sql.go +++ b/internal/infrastructure/postgres/postgresdb/tasks.sql.go @@ -581,6 +581,32 @@ func (q *Queries) ListTaskSummaries(ctx context.Context, arg ListTaskSummariesPa return items, nil } +const lockReviewUnits = `-- name: LockReviewUnits :one +SELECT status, workflow, review_payload, pending_reviews::text AS pending_reviews +FROM tasks WHERE id = $1 FOR UPDATE +` + +type LockReviewUnitsRow struct { + Status string + Workflow string + ReviewPayload string + PendingReviews string +} + +// The remediation's review units, locked so a comment merge cannot race the +// claim that freezes the active unit or the promotion of a pending one. +func (q *Queries) LockReviewUnits(ctx context.Context, id int64) (LockReviewUnitsRow, error) { + row := q.db.QueryRow(ctx, lockReviewUnits, id) + var i LockReviewUnitsRow + err := row.Scan( + &i.Status, + &i.Workflow, + &i.ReviewPayload, + &i.PendingReviews, + ) + return i, err +} + const lockTaskStatus = `-- name: LockTaskStatus :one SELECT status FROM tasks WHERE id = $1 FOR UPDATE ` @@ -778,6 +804,22 @@ func (q *Queries) SetReviewCursors(ctx context.Context, arg SetReviewCursorsPara return result.RowsAffected(), nil } +const setReviewUnits = `-- name: SetReviewUnits :exec +UPDATE tasks SET review_payload = $2, pending_reviews = CAST(CAST($3 AS text) AS jsonb), updated_at = now() +WHERE id = $1 +` + +type SetReviewUnitsParams struct { + ID int64 + ReviewPayload string + PendingReviews string +} + +func (q *Queries) SetReviewUnits(ctx context.Context, arg SetReviewUnitsParams) error { + _, err := q.db.Exec(ctx, setReviewUnits, arg.ID, arg.ReviewPayload, arg.PendingReviews) + return err +} + const stampTaskBinding = `-- name: StampTaskBinding :exec UPDATE tasks SET binding_id = $2, binding_version = $3 WHERE id = $1 ` @@ -1015,24 +1057,6 @@ func (q *Queries) TransitionTask(ctx context.Context, arg TransitionTaskParams) return result.RowsAffected(), nil } -const updateReviewPayloadTask = `-- name: UpdateReviewPayloadTask :execrows -UPDATE tasks SET review_payload = $2, updated_at = now() -WHERE id = $1 AND status = 'queued' AND workflow = 'remediate' -` - -type UpdateReviewPayloadTaskParams struct { - ID int64 - ReviewPayload string -} - -func (q *Queries) UpdateReviewPayloadTask(ctx context.Context, arg UpdateReviewPayloadTaskParams) (int64, error) { - result, err := q.db.Exec(ctx, updateReviewPayloadTask, arg.ID, arg.ReviewPayload) - if err != nil { - return 0, err - } - return result.RowsAffected(), nil -} - const updateTask = `-- name: UpdateTask :exec UPDATE tasks SET workflow = $2, branch = $3, plan = $4, notes = $5, pr_number = $6, tokens_used = $7, iterations = $8, park_reason = $9, diff --git a/internal/infrastructure/postgres/queries/tasks.sql b/internal/infrastructure/postgres/queries/tasks.sql index 05ec9dd60..ea497ad5c 100644 --- a/internal/infrastructure/postgres/queries/tasks.sql +++ b/internal/infrastructure/postgres/queries/tasks.sql @@ -188,9 +188,15 @@ UPDATE tasks SET status = 'queued', workflow = 'remediate', park_reason = '', WHERE id = $1 AND status = 'pr_open' AND workflow = 'remediate' AND jsonb_array_length(pending_reviews) > 0; --- name: UpdateReviewPayloadTask :execrows -UPDATE tasks SET review_payload = $2, updated_at = now() -WHERE id = $1 AND status = 'queued' AND workflow = 'remediate'; +-- name: LockReviewUnits :one +-- The remediation's review units, locked so a comment merge cannot race the +-- claim that freezes the active unit or the promotion of a pending one. +SELECT status, workflow, review_payload, pending_reviews::text AS pending_reviews +FROM tasks WHERE id = $1 FOR UPDATE; + +-- name: SetReviewUnits :exec +UPDATE tasks SET review_payload = $2, pending_reviews = CAST(CAST(sqlc.arg(pending_reviews) AS text) AS jsonb), updated_at = now() +WHERE id = $1; -- name: SetReviewCursors :execrows UPDATE tasks SET review_cursor = $2, watch_comment_id = $3, updated_at = now() diff --git a/internal/infrastructure/postgres/review_queue_test.go b/internal/infrastructure/postgres/review_queue_test.go index 5015e6fee..4789a386d 100644 --- a/internal/infrastructure/postgres/review_queue_test.go +++ b/internal/infrastructure/postgres/review_queue_test.go @@ -29,10 +29,20 @@ func TestSecondReviewDuringRemediationIsQueued(t *testing.T) { } assertActiveReview(t, db, id, first) + // An inline comment on the waiting review is collected into its queued + // unit rather than dropped, and travels with it when it is promoted. + comment := workflow.ReviewUnitComment{CommentID: 5, Path: "main.go", Line: 3, Body: "rename this"} + if err := db.UpdateReviewPayload(ctx, id, reviewUnitWith(t, 22, comment)); err != nil { + t.Fatalf("comment on the queued review was refused: %v", err) + } + if err := db.UpdateReviewPayload(ctx, id, reviewUnitWith(t, 22, comment)); err != nil { + t.Fatalf("re-delivered comment was refused: %v", err) + } + // The first round runs and finishes; the second, still waiting, is - // promoted behind it. + // promoted behind it with its comment. runRemediationRound(t, db, id) - assertActiveReview(t, db, id, second) + assertActiveReview(t, db, id, withComment(t, second, comment)) // The second round runs and finds nothing left waiting. runRemediationRound(t, db, id) @@ -104,3 +114,26 @@ func reviewUnit(t *testing.T, reviewID int64) string { } return payload } + +func reviewUnitWith(t *testing.T, reviewID int64, comment workflow.ReviewUnitComment) string { + t.Helper() + payload, err := workflow.EncodeReviewUnit(workflow.ReviewUnit{ReviewID: reviewID, Comments: []workflow.ReviewUnitComment{comment}}) + if err != nil { + t.Fatal(err) + } + return payload +} + +func withComment(t *testing.T, payload string, comment workflow.ReviewUnitComment) string { + t.Helper() + unit, err := workflow.DecodeReviewUnit(payload) + if err != nil { + t.Fatal(err) + } + unit.Comments = append(unit.Comments, comment) + encoded, err := workflow.EncodeReviewUnit(unit) + if err != nil { + t.Fatal(err) + } + return encoded +} diff --git a/internal/infrastructure/postgres/store.go b/internal/infrastructure/postgres/store.go index ef3f33692..ce968e8f0 100644 --- a/internal/infrastructure/postgres/store.go +++ b/internal/infrastructure/postgres/store.go @@ -3,8 +3,10 @@ package postgres import ( "context" + "encoding/json" "errors" "fmt" + "slices" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" @@ -379,18 +381,79 @@ func (s *Store) BeginRemediation(ctx context.Context, taskID int64, payload stri return tx.Commit(ctx) } -// UpdateReviewPayload replaces a queued remediation's review unit. +// UpdateReviewPayload merges payload's comments into the not-yet-claimed unit +// for the same review: the active unit while the remediation is still queued, +// or a unit waiting in pending_reviews behind a running one. A unit already +// claimed is frozen, so a comment for it is ErrStaleTransition. func (s *Store) UpdateReviewPayload(ctx context.Context, taskID int64, payload string) error { - n, err := s.queries().UpdateReviewPayloadTask(ctx, postgresdb.UpdateReviewPayloadTaskParams{ - ID: taskID, ReviewPayload: clip(payload, 4000), - }) + incoming, err := workflow.DecodeReviewUnit(payload) if err != nil { return err } - if n == 0 { + tx, err := s.pool.Begin(ctx) + if err != nil { + return err + } + defer func() { _ = tx.Rollback(ctx) }() + q := postgresdb.New(tx) + row, err := q.LockReviewUnits(ctx, taskID) + if errors.Is(err, pgx.ErrNoRows) { return storecontract.ErrStaleTransition } - return nil + if err != nil { + return err + } + if row.Workflow != "remediate" { + return storecontract.ErrStaleTransition + } + var pending []string + if err := json.Unmarshal([]byte(row.PendingReviews), &pending); err != nil { + return fmt.Errorf("decode pending reviews: %w", err) + } + active := row.ReviewPayload + merged := false + if row.Status == workflow.StatusQueued { + active, merged = mergeReviewComments(active, incoming) + } + for i := range pending { + if merged { + break + } + pending[i], merged = mergeReviewComments(pending[i], incoming) + } + if !merged { + return storecontract.ErrStaleTransition + } + encoded, err := json.Marshal(pending) + if err != nil { + return err + } + if err := q.SetReviewUnits(ctx, postgresdb.SetReviewUnitsParams{ + ID: taskID, ReviewPayload: clip(active, 4000), PendingReviews: string(encoded), + }); err != nil { + return err + } + return tx.Commit(ctx) +} + +// mergeReviewComments adds incoming's comments to the unit encoded in payload +// when both are the same review, skipping comments it already holds. It +// reports whether payload was that review's unit. +func mergeReviewComments(payload string, incoming workflow.ReviewUnit) (string, bool) { + unit, err := workflow.DecodeReviewUnit(payload) + if err != nil || unit.ReviewID != incoming.ReviewID { + return payload, false + } + for _, c := range incoming.Comments { + if !slices.ContainsFunc(unit.Comments, func(e workflow.ReviewUnitComment) bool { return e.CommentID == c.CommentID }) { + unit.Comments = append(unit.Comments, c) + } + } + encoded, err := workflow.EncodeReviewUnit(unit) + if err != nil { + return payload, false + } + return encoded, true } // SetReviewCursors persists the poll backstop's per-task review and comment diff --git a/proto/state/v1/state.proto b/proto/state/v1/state.proto index f3aeb3742..ee0839051 100644 --- a/proto/state/v1/state.proto +++ b/proto/state/v1/state.proto @@ -788,6 +788,8 @@ message BeginRemediationRequest { } message BeginRemediationResponse {} +// UpdateReviewPayloadRequest merges payload's comments into the unclaimed +// review unit with the same review id, active or pending. message UpdateReviewPayloadRequest { int64 task_id = 1; string payload = 2;