From f2000a788305d614afa1c4ab18701216be3263b2 Mon Sep 17 00:00:00 2001 From: kk10 Date: Mon, 16 Nov 2026 16:18:54 +0300 Subject: [PATCH] feat(worker): prepare replay queries and audit schema --- db/migrations/00004_attachment_pipeline.sql | 13 ++ db/queries/attachment_replays.sql | 14 +++ db/queries/attachments.sql | 33 ++++++ internal/db/attachment_replays.sql.go | 47 ++++++++ internal/db/attachments.sql.go | 124 +++++++++++++++++++- internal/db/models.go | 10 ++ internal/worker/retry.go | 8 +- 7 files changed, 239 insertions(+), 10 deletions(-) create mode 100644 db/queries/attachment_replays.sql create mode 100644 internal/db/attachment_replays.sql.go diff --git a/db/migrations/00004_attachment_pipeline.sql b/db/migrations/00004_attachment_pipeline.sql index 6ed6ec50..9bd17b93 100644 --- a/db/migrations/00004_attachment_pipeline.sql +++ b/db/migrations/00004_attachment_pipeline.sql @@ -6,6 +6,7 @@ ALTER TABLE attachments ADD COLUMN job_id uuid UNIQUE, ADD COLUMN pipeline_version int NOT NULL DEFAULT 1 CHECK (pipeline_version > 0), ADD COLUMN attempts int NOT NULL DEFAULT 0 CHECK (attempts >= 0), + ADD COLUMN retry_base int NOT NULL DEFAULT 0 CHECK (retry_base >= 0 AND retry_base <= attempts), ADD COLUMN width int CHECK (width > 0), ADD COLUMN height int CHECK (height > 0), ADD COLUMN lease_until timestamptz; @@ -39,7 +40,18 @@ CREATE TABLE outbox ( CREATE INDEX idx_outbox_pending ON outbox (available_at, id) WHERE published_at IS NULL; +CREATE TABLE attachment_replays ( + attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE CASCADE, + attempt int NOT NULL CHECK (attempt > 0), + previous_error_code text, + operator text NOT NULL, + reason text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (attachment_id, attempt) +); + -- +goose Down +DROP TABLE attachment_replays; DROP TABLE outbox; DROP TABLE attachment_variants; DROP TYPE attachment_variant_name; @@ -48,6 +60,7 @@ ALTER TABLE attachments DROP COLUMN height, DROP COLUMN width, DROP COLUMN lease_until, + DROP COLUMN retry_base, DROP COLUMN attempts, DROP COLUMN pipeline_version, DROP COLUMN job_id, diff --git a/db/queries/attachment_replays.sql b/db/queries/attachment_replays.sql new file mode 100644 index 00000000..60044d17 --- /dev/null +++ b/db/queries/attachment_replays.sql @@ -0,0 +1,14 @@ +-- name: CreateAttachmentReplay :exec +INSERT INTO attachment_replays ( + attachment_id, + attempt, + previous_error_code, + operator, + reason +) VALUES ( + sqlc.arg(attachment_id), + sqlc.arg(attempt), + sqlc.narg(previous_error_code), + sqlc.arg(operator), + sqlc.arg(reason) +); diff --git a/db/queries/attachments.sql b/db/queries/attachments.sql index 8a26c771..94060500 100644 --- a/db/queries/attachments.sql +++ b/db/queries/attachments.sql @@ -77,6 +77,13 @@ ORDER BY message_id, position; SELECT id, s3_key, staging_key, status, size_bytes, updated_at FROM attachments; +-- name: ListFailedAttachments :many +SELECT id, job_id, error_code, attempts, updated_at +FROM attachments +WHERE status = 'failed' +ORDER BY updated_at, id +LIMIT sqlc.arg(batch_size)::int; + -- name: LockAttachmentJob :one SELECT * FROM attachments WHERE id = sqlc.arg(id)::uuid @@ -95,6 +102,17 @@ ORDER BY lease_until, id LIMIT sqlc.arg(batch_size)::int FOR UPDATE SKIP LOCKED; +-- name: LockFailedAttachmentForReplay :one +SELECT * FROM attachments +WHERE id = sqlc.arg(id)::uuid + AND status = 'failed' + AND staging_key IS NOT NULL + AND NOT EXISTS ( + SELECT 1 FROM attachment_variants + WHERE attachment_id = attachments.id + ) +FOR UPDATE; + -- name: ClearAttachmentStagingKey :exec UPDATE attachments SET staging_key = NULL @@ -142,6 +160,21 @@ WHERE id = sqlc.arg(id)::uuid AND attempts = sqlc.arg(attempt)::int AND lease_until > now(); +-- name: ReplayAttachmentJob :execrows +UPDATE attachments +SET status = 'queued', + retry_base = attempts, + error_code = NULL, + lease_until = NULL, + updated_at = now() +WHERE id = sqlc.arg(id)::uuid + AND status = 'failed' + AND staging_key IS NOT NULL + AND NOT EXISTS ( + SELECT 1 FROM attachment_variants + WHERE attachment_id = attachments.id + ); + -- name: FailAttachmentJob :execrows UPDATE attachments SET status = 'failed', diff --git a/internal/db/attachment_replays.sql.go b/internal/db/attachment_replays.sql.go new file mode 100644 index 00000000..7e584479 --- /dev/null +++ b/internal/db/attachment_replays.sql.go @@ -0,0 +1,47 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: attachment_replays.sql + +package db + +import ( + "context" + + "github.com/google/uuid" +) + +const createAttachmentReplay = `-- name: CreateAttachmentReplay :exec +INSERT INTO attachment_replays ( + attachment_id, + attempt, + previous_error_code, + operator, + reason +) VALUES ( + $1, + $2, + $3, + $4, + $5 +) +` + +type CreateAttachmentReplayParams struct { + AttachmentID uuid.UUID + Attempt int + PreviousErrorCode *string + Operator string + Reason string +} + +func (q *Queries) CreateAttachmentReplay(ctx context.Context, arg CreateAttachmentReplayParams) error { + _, err := q.db.Exec(ctx, createAttachmentReplay, + arg.AttachmentID, + arg.Attempt, + arg.PreviousErrorCode, + arg.Operator, + arg.Reason, + ) + return err +} diff --git a/internal/db/attachments.sql.go b/internal/db/attachments.sql.go index 9e2f8da4..b367fe26 100644 --- a/internal/db/attachments.sql.go +++ b/internal/db/attachments.sql.go @@ -23,7 +23,7 @@ WHERE id = $2::uuid AND pipeline_version = $4::int AND status = 'queued' AND attempts + 1 = $5::int -RETURNING id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, width, height, lease_until +RETURNING id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until ` type ClaimAttachmentJobParams struct { @@ -60,6 +60,7 @@ func (q *Queries) ClaimAttachmentJob(ctx context.Context, arg ClaimAttachmentJob &i.JobID, &i.PipelineVersion, &i.Attempts, + &i.RetryBase, &i.Width, &i.Height, &i.LeaseUntil, @@ -138,7 +139,7 @@ WHERE EXISTS ( WHERE chat_id = $2 AND user_id = $3 ) -RETURNING id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, width, height, lease_until +RETURNING id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until ` type CreateAttachmentParams struct { @@ -191,6 +192,7 @@ func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentPara &i.JobID, &i.PipelineVersion, &i.Attempts, + &i.RetryBase, &i.Width, &i.Height, &i.LeaseUntil, @@ -267,7 +269,7 @@ func (q *Queries) FailExpiredAttachmentJob(ctx context.Context, id uuid.UUID) (i } const getAttachmentByID = `-- name: GetAttachmentByID :one -SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, width, height, lease_until FROM attachments +SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until FROM attachments WHERE id = $1::uuid ` @@ -291,6 +293,7 @@ func (q *Queries) GetAttachmentByID(ctx context.Context, dollar_1 uuid.UUID) (At &i.JobID, &i.PipelineVersion, &i.Attempts, + &i.RetryBase, &i.Width, &i.Height, &i.LeaseUntil, @@ -371,6 +374,48 @@ func (q *Queries) ListAttachmentsForReconcile(ctx context.Context) ([]ListAttach return items, nil } +const listFailedAttachments = `-- name: ListFailedAttachments :many +SELECT id, job_id, error_code, attempts, updated_at +FROM attachments +WHERE status = 'failed' +ORDER BY updated_at, id +LIMIT $1::int +` + +type ListFailedAttachmentsRow struct { + ID uuid.UUID + JobID *uuid.UUID + ErrorCode *string + Attempts int + UpdatedAt time.Time +} + +func (q *Queries) ListFailedAttachments(ctx context.Context, batchSize int) ([]ListFailedAttachmentsRow, error) { + rows, err := q.db.Query(ctx, listFailedAttachments, batchSize) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListFailedAttachmentsRow{} + for rows.Next() { + var i ListFailedAttachmentsRow + if err := rows.Scan( + &i.ID, + &i.JobID, + &i.ErrorCode, + &i.Attempts, + &i.UpdatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const listMessageAttachmentIDs = `-- name: ListMessageAttachmentIDs :many SELECT attachment_id FROM message_attachments @@ -431,7 +476,7 @@ func (q *Queries) ListMessageAttachmentsByMessageIDs(ctx context.Context, messag } const lockAttachmentByStagingKey = `-- name: LockAttachmentByStagingKey :one -SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, width, height, lease_until FROM attachments +SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until FROM attachments WHERE staging_key = $1::text FOR UPDATE ` @@ -456,6 +501,7 @@ func (q *Queries) LockAttachmentByStagingKey(ctx context.Context, stagingKey str &i.JobID, &i.PipelineVersion, &i.Attempts, + &i.RetryBase, &i.Width, &i.Height, &i.LeaseUntil, @@ -464,7 +510,7 @@ func (q *Queries) LockAttachmentByStagingKey(ctx context.Context, stagingKey str } const lockAttachmentJob = `-- name: LockAttachmentJob :one -SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, width, height, lease_until FROM attachments +SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until FROM attachments WHERE id = $1::uuid AND status = 'processing' AND job_id = $2::uuid @@ -506,6 +552,7 @@ func (q *Queries) LockAttachmentJob(ctx context.Context, arg LockAttachmentJobPa &i.JobID, &i.PipelineVersion, &i.Attempts, + &i.RetryBase, &i.Width, &i.Height, &i.LeaseUntil, @@ -514,7 +561,7 @@ func (q *Queries) LockAttachmentJob(ctx context.Context, arg LockAttachmentJobPa } const lockExpiredAttachmentJobs = `-- name: LockExpiredAttachmentJobs :many -SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, width, height, lease_until FROM attachments +SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until FROM attachments WHERE status = 'processing' AND lease_until <= now() ORDER BY lease_until, id @@ -548,6 +595,7 @@ func (q *Queries) LockExpiredAttachmentJobs(ctx context.Context, batchSize int) &i.JobID, &i.PipelineVersion, &i.Attempts, + &i.RetryBase, &i.Width, &i.Height, &i.LeaseUntil, @@ -562,6 +610,46 @@ func (q *Queries) LockExpiredAttachmentJobs(ctx context.Context, batchSize int) return items, nil } +const lockFailedAttachmentForReplay = `-- name: LockFailedAttachmentForReplay :one +SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until FROM attachments +WHERE id = $1::uuid + AND status = 'failed' + AND staging_key IS NOT NULL + AND NOT EXISTS ( + SELECT 1 FROM attachment_variants + WHERE attachment_id = attachments.id + ) +FOR UPDATE +` + +func (q *Queries) LockFailedAttachmentForReplay(ctx context.Context, id uuid.UUID) (Attachment, error) { + row := q.db.QueryRow(ctx, lockFailedAttachmentForReplay, id) + var i Attachment + err := row.Scan( + &i.ID, + &i.ChatID, + &i.OwnerID, + &i.S3Key, + &i.Filename, + &i.ContentType, + &i.SizeBytes, + &i.Sha256, + &i.Status, + &i.ErrorCode, + &i.CreatedAt, + &i.UpdatedAt, + &i.StagingKey, + &i.JobID, + &i.PipelineVersion, + &i.Attempts, + &i.RetryBase, + &i.Width, + &i.Height, + &i.LeaseUntil, + ) + return i, err +} + const markAttachmentFailedIfReady = `-- name: MarkAttachmentFailedIfReady :execrows UPDATE attachments SET status = 'failed', @@ -601,6 +689,30 @@ func (q *Queries) RecoverExpiredAttachmentJob(ctx context.Context, id uuid.UUID) return result.RowsAffected(), nil } +const replayAttachmentJob = `-- name: ReplayAttachmentJob :execrows +UPDATE attachments +SET status = 'queued', + retry_base = attempts, + error_code = NULL, + lease_until = NULL, + updated_at = now() +WHERE id = $1::uuid + AND status = 'failed' + AND staging_key IS NOT NULL + AND NOT EXISTS ( + SELECT 1 FROM attachment_variants + WHERE attachment_id = attachments.id + ) +` + +func (q *Queries) ReplayAttachmentJob(ctx context.Context, id uuid.UUID) (int64, error) { + result, err := q.db.Exec(ctx, replayAttachmentJob, id) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + const retryAttachmentJob = `-- name: RetryAttachmentJob :execrows UPDATE attachments SET status = 'queued', diff --git a/internal/db/models.go b/internal/db/models.go index 98dbdaf3..9a74b410 100644 --- a/internal/db/models.go +++ b/internal/db/models.go @@ -158,11 +158,21 @@ type Attachment struct { JobID *uuid.UUID PipelineVersion int Attempts int + RetryBase int Width *int32 Height *int32 LeaseUntil *time.Time } +type AttachmentReplay struct { + AttachmentID uuid.UUID + Attempt int + PreviousErrorCode *string + Operator string + Reason string + CreatedAt time.Time +} + type AttachmentVariant struct { AttachmentID uuid.UUID PipelineVersion int diff --git a/internal/worker/retry.go b/internal/worker/retry.go index b684fa4b..836f188b 100644 --- a/internal/worker/retry.go +++ b/internal/worker/retry.go @@ -39,7 +39,7 @@ func (w *Worker) finishFailure(ctx context.Context, job model.AttachmentJob, cau } var n int64 - if permanent || row.Attempts >= w.cfg.MaxAttempts { + if permanent || row.Attempts-row.RetryBase >= w.cfg.MaxAttempts { if !permanent { code = "retry_exhausted" } @@ -59,7 +59,7 @@ func (w *Worker) finishFailure(ctx context.Context, job model.AttachmentJob, cau _, err = q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{ AttachmentID: row.ID, Attempt: row.Attempts + 1, - AvailableAt: time.Now().Add(retryDelay(row.Attempts)), + AvailableAt: time.Now().Add(retryDelay(row.Attempts - row.RetryBase)), }) } } @@ -119,7 +119,7 @@ func (w *Worker) recoverOne(ctx context.Context) (bool, error) { } row := rows[0] - if row.Attempts >= w.cfg.MaxAttempts { + if row.Attempts-row.RetryBase >= w.cfg.MaxAttempts { _, err = q.FailExpiredAttachmentJob(ctx, row.ID) } else { _, err = q.RecoverExpiredAttachmentJob(ctx, row.ID) @@ -127,7 +127,7 @@ func (w *Worker) recoverOne(ctx context.Context) (bool, error) { _, err = q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{ AttachmentID: row.ID, Attempt: row.Attempts + 1, - AvailableAt: time.Now().Add(retryDelay(row.Attempts)), + AvailableAt: time.Now().Add(retryDelay(row.Attempts - row.RetryBase)), }) } }