ALTER TABLE attachments RENAME COLUMN object_key TO staging_key; ALTER TABLE attachments ADD COLUMN original_key text, ADD COLUMN status text NOT NULL DEFAULT 'queued' CHECK (status IN ('queued', 'processing', 'ready', 'failed')), ADD COLUMN error_code text, ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1, ADD COLUMN processing_started_at timestamptz; CREATE TABLE attachment_variants ( attachment_id uuid NOT NULL REFERENCES attachments(id) ON DELETE CASCADE, pipeline_version integer NOT NULL, 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), width integer NOT NULL CHECK (width > 0), height integer NOT NULL CHECK (height > 0), sha256 char(64) NOT NULL, PRIMARY KEY (attachment_id, pipeline_version, name) ); CREATE TABLE attachment_jobs ( job_id uuid PRIMARY KEY, attachment_id uuid NOT NULL UNIQUE REFERENCES attachments(id) ON DELETE CASCADE, pipeline_version integer NOT NULL DEFAULT 1, attempt integer NOT NULL DEFAULT 1 CHECK (attempt >= 1), status text NOT NULL DEFAULT 'queued' CHECK (status IN ('queued', 'processing', 'ready', 'failed')), last_error text, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now() ); CREATE INDEX attachment_jobs_status_idx ON attachment_jobs(status, updated_at);