-- Variant outputs (thumbnail/crop/optimized) produced by the worker. CREATE TABLE IF NOT EXISTS attachment_variants ( attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE, name TEXT NOT NULL, content_type TEXT NOT NULL, size_bytes BIGINT NOT NULL, width INT NOT NULL, height INT NOT NULL, sha256 TEXT NOT NULL, s3_key TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (attachment_id, name) ); -- Transactional outbox: written in the SAME transaction as the attachments -- INSERT, so a crash between COMMIT and broker publish leaves a recoverable -- row instead of a lost job. A relay (in-process background task) publishes -- unpublished rows and marks them, so publish is retried, not re-created. CREATE TABLE IF NOT EXISTS job_outbox ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE, job_id UUID NOT NULL, pipeline_version INT NOT NULL DEFAULT 1, attempt INT NOT NULL DEFAULT 1, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), published_at TIMESTAMPTZ ); CREATE INDEX IF NOT EXISTS job_outbox_unpublished_idx ON job_outbox (created_at) WHERE published_at IS NULL; -- Durable delayed-retry schedule (Redis Streams has no native delay): a -- failed attempt is parked here with a next_attempt_at instead of sleeping -- in-process, so a worker crash during the backoff window does not lose the -- retry -- any worker's scheduler tick will still publish it on time. CREATE TABLE IF NOT EXISTS job_retry_schedule ( attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE, job_id UUID NOT NULL, attempt INT NOT NULL, next_attempt_at TIMESTAMPTZ NOT NULL, PRIMARY KEY (attachment_id, job_id) ); CREATE INDEX IF NOT EXISTS job_retry_schedule_due_idx ON job_retry_schedule (next_attempt_at); -- Explicit failure record for DLQ-style operator visibility and replay. CREATE TABLE IF NOT EXISTS job_failures ( attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE, job_id UUID NOT NULL, attempt INT NOT NULL, error_code TEXT NOT NULL, failed_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (attachment_id, job_id) );