ALTER TABLE attachments 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 staging_key text NOT NULL DEFAULT '', ADD COLUMN variants jsonb NOT NULL DEFAULT '[]', ADD COLUMN variant_keys jsonb NOT NULL DEFAULT '{}'; UPDATE attachments SET staging_key=object_key; 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 CHECK(attempt>0), attempt_limit integer NOT NULL, state text NOT NULL, token uuid NOT NULL, lease_until timestamptz, next_attempt_at timestamptz NOT NULL, error_code text, created_at timestamptz NOT NULL, updated_at timestamptz NOT NULL, UNIQUE(attachment_id,pipeline_version) ); CREATE INDEX jobs_recovery ON attachment_jobs(state,lease_until); CREATE TABLE outbox ( id uuid PRIMARY KEY, job_id uuid NOT NULL REFERENCES attachment_jobs(id), payload jsonb NOT NULL, status text NOT NULL, attempts integer NOT NULL DEFAULT 0, max_attempts integer NOT NULL, token uuid NOT NULL, locked_until timestamptz, next_attempt_at timestamptz NOT NULL, last_error text, created_at timestamptz NOT NULL, updated_at timestamptz NOT NULL ); CREATE INDEX outbox_delivery ON outbox(status,next_attempt_at); CREATE TABLE job_audit ( id bigserial PRIMARY KEY, job_id uuid NOT NULL REFERENCES attachment_jobs(id), action text NOT NULL, created_at timestamptz NOT NULL DEFAULT clock_timestamp() ); -- Existing lab4 originals become durable sources for the first asynchronous run. INSERT INTO attachment_jobs SELECT gen_random_uuid(),id,1,1,5,'queued',gen_random_uuid(),NULL,clock_timestamp(),NULL,created_at,clock_timestamp() FROM attachments; INSERT INTO outbox SELECT gen_random_uuid(),id,jsonb_build_object('schema_version',1,'job_id',id,'type','attachment.process.v1','attachment_id',attachment_id,'pipeline_version',1,'attempt',1,'created_at',created_at), 'pending',0,5,gen_random_uuid(),NULL,clock_timestamp(),NULL,clock_timestamp(),clock_timestamp() FROM attachment_jobs; ---- create above / drop below ---- DROP TABLE job_audit; DROP TABLE outbox; DROP TABLE attachment_jobs; ALTER TABLE attachments DROP COLUMN status,DROP COLUMN error_code,DROP COLUMN pipeline_version,DROP COLUMN staging_key,DROP COLUMN variants,DROP COLUMN variant_keys;