ALTER TABLE attachments DROP CONSTRAINT attachments_status_check; ALTER TABLE attachments ADD CONSTRAINT attachments_status_check CHECK (status IN ('queued', 'processing', 'ready', 'failed')); ALTER TABLE attachments DROP CONSTRAINT IF EXISTS attachments_error_code_check; ALTER TABLE attachments DROP CONSTRAINT IF EXISTS attachments_check; ALTER TABLE attachments ADD CONSTRAINT attachments_error_code_check CHECK ( error_code IS NULL OR error_code IN ('invalid_image', 'processing_failed', 'retry_exhausted') ); ALTER TABLE attachments ADD COLUMN staging_key TEXT UNIQUE; CREATE TABLE image_jobs ( id UUID PRIMARY KEY, attachment_id UUID NOT NULL UNIQUE REFERENCES attachments(id) ON DELETE CASCADE, pipeline_version INTEGER NOT NULL DEFAULT 1 CHECK (pipeline_version >= 1), attempt INTEGER NOT NULL DEFAULT 1 CHECK (attempt BETWEEN 1 AND 20), max_attempts INTEGER NOT NULL DEFAULT 5 CHECK (max_attempts BETWEEN 1 AND 20), published_attempt INTEGER NOT NULL DEFAULT 0 CHECK (published_attempt BETWEEN 0 AND attempt), status TEXT NOT NULL DEFAULT 'queued' CHECK (status IN ('queued', 'processing', 'ready', 'failed')), last_error_code TEXT CHECK ( last_error_code IS NULL OR last_error_code IN ('invalid_image', 'processing_failed', 'retry_exhausted') ), created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX image_jobs_outbox_idx ON image_jobs (created_at, id) WHERE status = 'queued' AND published_attempt < attempt;