param( [Parameter(Mandatory = $true)] [string]$JobId, [string]$RequestedBy = $env:USERNAME, [string]$EnvFile = ".env" ) $parsedJobId = [guid]::Empty if (-not [guid]::TryParse($JobId, [ref]$parsedJobId)) { throw "JobId must be a UUID" } if ($RequestedBy -notmatch '^[A-Za-z0-9_.@-]{1,128}$') { throw "RequestedBy contains unsupported characters" } $sql = @" WITH candidate AS ( SELECT j.id, j.attachment_id, j.attempt FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id WHERE j.id = '$parsedJobId'::uuid AND j.status = 'failed' AND a.status = 'failed' AND j.pipeline_version = a.pipeline_version FOR UPDATE OF j, a ), audited AS ( INSERT INTO attachment_job_replays (job_id, requested_by, previous_attempt) SELECT id, '$RequestedBy', attempt FROM candidate RETURNING job_id ), reset_job AS ( UPDATE attachment_jobs j SET status = 'queued', attempt = 1, published = false, last_error_code = NULL, next_attempt_at = clock_timestamp(), lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp() FROM candidate c, audited a WHERE j.id = c.id AND a.job_id = c.id RETURNING j.attachment_id ), reset_attachment AS ( UPDATE attachments a SET status = 'queued', error_code = NULL, updated_at = clock_timestamp() FROM reset_job r WHERE a.id = r.attachment_id AND a.status = 'failed' RETURNING a.id ) SELECT CASE WHEN EXISTS (SELECT 1 FROM reset_attachment) THEN 'replayed' ELSE 'no-op' END; "@ $result = docker compose --env-file $EnvFile exec -T postgres ` psql -v ON_ERROR_STOP=1 -U messenger -d messenger -At -c $sql if ($LASTEXITCODE -ne 0) { throw "Replay transaction failed" } if (($result | Select-Object -Last 1).Trim() -eq "replayed") { Write-Output "Replay requested for failed job $parsedJobId by $RequestedBy" } else { Write-Output "No-op: job $parsedJobId is missing, not failed, or already recovered" }