StagedJobs.where('id <= ?', job_batch.last).delete
This will end up deleting a job id that was reserved inside a transaction, meanwhile your enqueuer kicks off and fetches the jobs, then your transaction writes the job to staged_jobs table, just in time for enqueuer to delete it without ever queueing it.You need to delete the specifically queued ids and not a numeric range.