ALTER TABLE attachments DROP CONSTRAINT attachments_status_check; UPDATE attachments SET status='failed' WHERE status='missing'; ALTER TABLE attachments ADD CONSTRAINT attachments_status_check CHECK(status IN ('queued','processing','ready','failed')); ALTER TABLE attachments ADD COLUMN variants jsonb NOT NULL DEFAULT '[]'; ALTER TABLE attachments ADD COLUMN error_code text; UPDATE attachments SET error_code='original_missing' WHERE status='failed'; CREATE TABLE attachment_jobs ( id uuid PRIMARY KEY, attachment_id uuid NOT NULL UNIQUE REFERENCES attachments(id), pipeline_version int NOT NULL DEFAULT 1, staging_key text NOT NULL UNIQUE, state text NOT NULL CHECK(state IN ('queued','processing','ready','failed')), attempts int NOT NULL DEFAULT 0, next_at timestamptz NOT NULL DEFAULT now(), lease_token uuid, lease_until timestamptz, error_code text, created_at timestamptz NOT NULL DEFAULT now(), completed_at timestamptz, staging_deleted_at timestamptz, replay_count int NOT NULL DEFAULT 0 ); CREATE INDEX attachment_jobs_active_idx ON attachment_jobs(state,next_at); CREATE TABLE attachment_outbox ( job_id uuid PRIMARY KEY REFERENCES attachment_jobs(id), available_at timestamptz NOT NULL DEFAULT now(), published_at timestamptz ); CREATE INDEX attachment_outbox_pending_idx ON attachment_outbox(available_at) WHERE published_at IS NULL; CREATE TABLE attachment_job_events ( id bigserial PRIMARY KEY, job_id uuid NOT NULL REFERENCES attachment_jobs(id), event text NOT NULL, attempt int NOT NULL, created_at timestamptz NOT NULL DEFAULT now() );