-- Job row is the durable intention. published_at stays null until a later outbox -- step; lease_until is left for a stuck-worker timeout. Neither is required to finish a job. ALTER TABLE attachments ADD COLUMN error_code TEXT; ALTER TABLE attachments ADD CONSTRAINT attachments_error_code CHECK (error_code IS NULL OR (char_length(error_code) >= 1 AND char_length(error_code) <= 64)); ALTER TABLE attachments ADD COLUMN pipeline_version INTEGER NOT NULL DEFAULT 1; ALTER TABLE attachments ADD CONSTRAINT attachments_pipeline CHECK (pipeline_version >= 1); CREATE TABLE attachment_jobs ( id UUID PRIMARY KEY, attachment_id UUID NOT NULL REFERENCES attachments (id), pipeline_version INTEGER NOT NULL, attempt INTEGER NOT NULL, max_attempts INTEGER NOT NULL, lease_until TIMESTAMPTZ, published_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL, CONSTRAINT attachment_jobs_attempt CHECK (attempt >= 1 AND attempt <= max_attempts), CONSTRAINT attachment_jobs_max CHECK (max_attempts >= 1), CONSTRAINT attachment_jobs_pipeline CHECK (pipeline_version >= 1), CONSTRAINT attachment_jobs_one UNIQUE (attachment_id, pipeline_version) ); CREATE INDEX attachment_jobs_unpublished_idx ON attachment_jobs (created_at) WHERE published_at IS NULL; CREATE TABLE attachment_variants ( attachment_id UUID NOT NULL REFERENCES attachments (id), pipeline_version INTEGER NOT NULL, name TEXT NOT NULL, content_type TEXT NOT NULL, size_bytes INTEGER NOT NULL, width INTEGER NOT NULL, height INTEGER NOT NULL, sha256 TEXT NOT NULL, object_key TEXT NOT NULL, PRIMARY KEY (attachment_id, pipeline_version, name), CONSTRAINT attachment_variants_name CHECK (name IN ('thumbnail', 'crop', 'optimized')), CONSTRAINT attachment_variants_type CHECK (content_type IN ('image/jpeg', 'image/png', 'image/webp')), CONSTRAINT attachment_variants_size CHECK (size_bytes >= 1), CONSTRAINT attachment_variants_dim CHECK (width >= 1 AND height >= 1), CONSTRAINT attachment_variants_sha CHECK (sha256 ~ '^[a-f0-9]{64}$'), CONSTRAINT attachment_variants_key UNIQUE (object_key) );