-- ScheduleRetry records the transient reason on the job while it waits for the -- next attempt. The original 0004 constraint only allowed error_code on failed -- rows, so a jittered retry update was rejected and the broker redelivery was -- then acknowledged as "busy", leaving the job processing until lease expiry. -- Ready stays clean; failed stays explainable; queued/processing may carry the -- most recent transient reason. ALTER TABLE attachments DROP CONSTRAINT IF EXISTS attachments_error_state; ALTER TABLE attachments ADD CONSTRAINT attachments_error_state CHECK ( (status = 'ready' AND error_code IS NULL) OR (status = 'failed' AND error_code IS NOT NULL) OR (status IN ('queued', 'processing')) ); ALTER TABLE attachment_jobs DROP CONSTRAINT IF EXISTS attachment_jobs_error_state; ALTER TABLE attachment_jobs ADD CONSTRAINT attachment_jobs_error_state CHECK ( (status = 'ready' AND error_code IS NULL) OR (status = 'failed' AND error_code IS NOT NULL) OR (status IN ('queued', 'processing')) );