-- V29: durable per-outbound attempt history, pinned retry policy and cancellation (Story 4.4). -- An accepted Task keeps the retry snapshot it was admitted with; legacy Tasks get a single attempt. alter table tasks add column if not exists max_attempts integer not null default 1; alter table tasks add column if not exists retry_backoff_step_ms bigint not null default 0; alter table tasks add column if not exists next_attempt_at timestamptz; alter table tasks add column if not exists cancel_requested_at timestamptz; alter table tasks add column if not exists cancel_reason text; alter table tasks add constraint tasks_max_attempts_check check (max_attempts between 1 and 5); alter table tasks add constraint tasks_retry_backoff_step_check check (retry_backoff_step_ms between 0 and 1000); alter table tasks add constraint tasks_cancel_reason_check check ( cancel_reason is null or octet_length(cancel_reason) between 1 and 160 ); -- One row per committed outbound attempt. The authoritative outcome of a Task stays on `tasks`; -- this history only records what was attempted and how each attempt resolved. create table if not exists task_attempts ( attempt_id text primary key, task_id uuid not null references tasks (task_id) on delete cascade, ordinal integer not null, owner text not null, fence bigint not null default 0, input_fingerprint text not null, upstream_key_digest text, retry_allowed boolean not null default false, checkpoint_at timestamptz not null default now(), resolved_at timestamptz, outcome text, certainty text, phase text, constraint task_attempts_task_ordinal_unique unique (task_id, ordinal), constraint task_attempts_ordinal_check check (ordinal between 1 and 5), constraint task_attempts_outcome_check check ( outcome is null or outcome in ('completed', 'failed', 'retry_scheduled', 'outcome_unknown') ), constraint task_attempts_certainty_check check ( certainty is null or certainty in ('known', 'unknown') ), constraint task_attempts_phase_check check ( phase is null or phase in ('before_dispatch', 'dispatched') ), -- A resolved attempt is complete: an unresolved row carries no resolution at all, so a stale -- writer can never append a second outcome to the same attempt. constraint task_attempts_resolution_check check ( (resolved_at is null and outcome is null and certainty is null and phase is null) or (resolved_at is not null and outcome is not null and certainty is not null) ) ); create index if not exists task_attempts_task_id_idx on task_attempts (task_id, ordinal);