bensheldon/good_job · error · ArgumentError

All batches must be new (not persisted)

Error message

All batches must be new (not persisted)

What it means

Error "All batches must be new (not persisted)" thrown in bensheldon/good_job.

Source

Thrown at app/models/good_job/batch.rb:81

    # Bulk-enqueue multiple batches with their jobs in minimal DB round-trips.
    #
    # Instead of creating batches one-at-a-time (~7 queries per batch), this method
    # inserts all batch records and jobs in a fixed number of queries:
    #   1. INSERT all BatchRecords  (insert_all!)
    #   2. INSERT all Jobs          (insert_all)
    #   3. NOTIFY per distinct queue/scheduled_at
    #
    # @param batch_job_pairs [Array<Array(GoodJob::Batch, Array<ActiveJob::Base>)>]
    #   Array of [batch, jobs] pairs. Each batch must be new (not yet persisted).
    # @return [Array<GoodJob::Batch>] The enqueued batches
    # @raise [ArgumentError] if any batch is already persisted
    def self.enqueue_all(batch_job_pairs)
      batch_job_pairs = Array(batch_job_pairs)
      return [] if batch_job_pairs.empty?

      batch_job_pairs.each do |(batch, _)|
        raise ArgumentError, "All batches must be new (not persisted)" if batch.persisted?
      end

      Rails.application.executor.wrap do
        current_time = Time.current
        adapter = ActiveJob::Base.queue_adapter
        execute_inline = adapter.respond_to?(:execute_inline?) && adapter.execute_inline?

        # Phase 1: Insert all batch records
        batch_rows = _build_batch_rows(batch_job_pairs, current_time)
        BatchRecord.insert_all!(batch_rows) # rubocop:disable Rails/SkipsModelValidations
        _mark_batches_persisted(batch_job_pairs, batch_rows, current_time)

        # Phase 2: Build and partition jobs by concurrency limits
        build_result = _build_and_partition_jobs(batch_job_pairs, current_time)

        # Phase 3–6: Insert, claim, and execute inline jobs
        lock_strategy = Job.effective_lock_strategy
        tracker_registered = false

View on GitHub (pinned to 5fcde48f87)

Solutions

  1. Only add unpersisted batches; do not save the batch before enqueueing it.
  2. Build the batch with GoodJob::Batch.new instead of create/save.

Example fix

batch = GoodJob::Batch.new
# enqueue without calling batch.save first

When it happens

Trigger: Thrown at app/models/good_job/batch.rb:81 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of bensheldon/good_job@5fcde48f87 (2026-08-23). Data as JSON: /api/errors/fa0f06d75987e7e1. Report an issue: GitHub.