BEGIN; SELECT plan(6); -- Start from an empty queue and a claim throttle that allows a claim now. DELETE FROM public.updates_cache_purge_pending; UPDATE public.updates_cache_purge_state SET last_claim_at = now() - interval '1 hour' WHERE id; INSERT INTO public.updates_cache_purge_pending (app_id, scope, due_at, initial) VALUES ('com.test.purge.backoff.a', 'app', now() - interval '1 second', true), ('com.test.purge.backoff.b', 'app', now() - interval '1 second', true); CREATE TEMP TABLE claim_result AS SELECT public.claim_updates_cache_purge(1) AS result; SELECT is( (SELECT result->>'status' FROM claim_result), 'ok', 'a claim succeeds while the throttle allows it' ); -- Clear the 1 second throttle the claim set, so only the ack can block the next claim. UPDATE public.updates_cache_purge_state SET last_claim_at = now() - interval '1 hour' WHERE id; SELECT lives_ok( $$ SELECT public.ack_updates_cache_purge((SELECT (result->>'lease_token')::uuid FROM claim_result), false, 30) $$, 'a failed batch is acked with its Retry-After' ); SELECT ok( (SELECT due_at > now() + interval '25 seconds' FROM public.updates_cache_purge_pending WHERE lease_token IS NULL AND app_id = (SELECT result->'apps'->0->>'app_id' FROM claim_result)), 'the failed app is requeued at its Retry-After' ); SELECT ok( (SELECT last_claim_at > now() + interval '25 seconds' FROM public.updates_cache_purge_state WHERE id), 'a failed ack moves the shared claim throttle to the end of the Retry-After window' ); SELECT is( (SELECT public.claim_updates_cache_purge(10)->>'status'), 'throttled', 'no drain can claim another batch (the other app is due) until the window ends' ); -- A successful ack must not pause the queue. UPDATE public.updates_cache_purge_state SET last_claim_at = now() - interval '1 hour' WHERE id; UPDATE public.updates_cache_purge_pending SET due_at = now() - interval '1 second' WHERE app_id LIKE 'com.test.purge.backoff.%'; DROP TABLE claim_result; CREATE TEMP TABLE claim_result AS SELECT public.claim_updates_cache_purge(1) AS result; CREATE TEMP TABLE throttle_before AS SELECT last_claim_at FROM public.updates_cache_purge_state WHERE id; SELECT public.ack_updates_cache_purge((SELECT (result->>'lease_token')::uuid FROM claim_result), true, 30); SELECT is( (SELECT last_claim_at FROM public.updates_cache_purge_state WHERE id), (SELECT last_claim_at FROM throttle_before), 'a successful ack leaves the claim throttle alone' ); SELECT * FROM finish(); ROLLBACK;