ALTER TABLE attachments DROP CONSTRAINT attachments_state_check; UPDATE attachments SET state = 'failed' WHERE state = 'missing'; ALTER TABLE attachments ADD COLUMN error_code text; UPDATE attachments SET error_code = 'original_unavailable' WHERE state = 'failed'; ALTER TABLE attachments ADD CONSTRAINT attachments_pipeline_state CHECK ( state IN ('queued', 'processing', 'ready', 'failed') AND ((state = 'failed') = (error_code IS NOT NULL)) ); CREATE TABLE attachment_jobs ( id uuid PRIMARY KEY, attachment_id uuid NOT NULL UNIQUE REFERENCES attachments(id), staging_key text NOT NULL UNIQUE, created_at timestamptz NOT NULL DEFAULT clock_timestamp(), attempt integer NOT NULL DEFAULT 1 CHECK (attempt >= 1), attempt_limit integer NOT NULL CHECK (attempt_limit >= 1), state text NOT NULL DEFAULT 'queued' CHECK (state IN ('queued', 'processing', 'ready', 'failed')), next_publish_at timestamptz, published_at timestamptz, publish_failures integer NOT NULL DEFAULT 0, lease_until timestamptz, lease_token uuid, last_error text, CHECK ((lease_until IS NULL) = (lease_token IS NULL)) ); CREATE INDEX attachment_jobs_outbox ON attachment_jobs(next_publish_at) WHERE next_publish_at IS NOT NULL; CREATE INDEX attachment_jobs_leases ON attachment_jobs(lease_until) WHERE lease_until IS NOT NULL; CREATE TABLE attachment_variants ( attachment_id uuid NOT NULL REFERENCES attachments(id), name text NOT NULL CHECK (name IN ('thumbnail', 'crop', 'optimized')), object_key text NOT NULL UNIQUE, content_type text NOT NULL, size_bytes integer NOT NULL CHECK (size_bytes > 0), sha256 char(64) NOT NULL, width integer NOT NULL CHECK (width > 0), height integer NOT NULL CHECK (height > 0), PRIMARY KEY (attachment_id, name) ); CREATE TABLE attachment_replays ( job_id uuid NOT NULL REFERENCES attachment_jobs(id), attempt integer NOT NULL, reason text NOT NULL, created_at timestamptz NOT NULL DEFAULT clock_timestamp(), PRIMARY KEY (job_id, attempt) );