ALTER TABLE attachments DROP CONSTRAINT IF EXISTS attachments_status_check; ALTER TABLE attachments ADD CONSTRAINT attachments_status_check CHECK (status IN ('queued','processing','ready','failed')); ALTER TABLE attachments ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1 CHECK (pipeline_version > 0); ALTER TABLE attachments ADD COLUMN variants jsonb NOT NULL DEFAULT '[]'; ALTER TABLE attachments ADD COLUMN stage_key text; CREATE TABLE attachment_jobs ( id uuid PRIMARY KEY, attachment_id uuid NOT NULL REFERENCES attachments(id), pipeline_version integer NOT NULL CHECK (pipeline_version > 0), source_key text, state text NOT NULL CHECK (state IN ('queued','processing','ready','failed','superseded')), attempt integer NOT NULL DEFAULT 0 CHECK (attempt >= 0), attempt_limit integer NOT NULL CHECK (attempt_limit > 0), lease_id uuid, lease_until timestamptz, available_at timestamptz NOT NULL DEFAULT now(), error_code text, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), UNIQUE(attachment_id,pipeline_version) ); CREATE INDEX jobs_recovery_idx ON attachment_jobs(state,lease_until); CREATE TABLE job_outbox ( job_id uuid PRIMARY KEY REFERENCES attachment_jobs(id), published_at timestamptz ); CREATE TABLE job_audit ( id bigserial PRIMARY KEY, job_id uuid NOT NULL REFERENCES attachment_jobs(id), event text NOT NULL, attempt integer NOT NULL, created_at timestamptz NOT NULL DEFAULT now() ); CREATE TABLE failed_jobs ( job_id uuid PRIMARY KEY REFERENCES attachment_jobs(id), error_code text NOT NULL, failed_at timestamptz NOT NULL DEFAULT now(), replay_count integer NOT NULL DEFAULT 0 ); CREATE TABLE test_faults ( id bigserial PRIMARY KEY, point text NOT NULL, attachment_id uuid, action text NOT NULL CHECK (action IN ('crash','pause','error')), reached_at timestamptz, released boolean NOT NULL DEFAULT false );