diff --git a/CHANGELOG.md b/CHANGELOG.md index 50e736f6e..014603cf4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,22 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Fixed + +- **An evaluation run is executed by one job** (`actionagent`). The run job + read a run's status, then the scenario runner wrote `running`, as two + steps, so a job delivered twice, or two workers that both loaded the run + as pending, each replayed the whole suite, or with + `scenario_evaluation_fan_out` on each enqueued a full set of replay jobs. + The runner now moves the run from pending to running in one conditional + update, as the execution job claims an agent run, and replays nothing + unless it was the one to do so; this covers `ProjectEvaluationJob` too. + The claim comes before the selection is read, so a selection that cannot + be resolved (an unsupported provider in a re-run's models) now fails the + run instead of leaving it pending forever. + ## [1.9.8] - 2026-11-12 The dashboard holds a run to its catalog's pass bars: a product's and a diff --git a/actionagent/app/jobs/action_agent/evaluation_run_job.rb b/actionagent/app/jobs/action_agent/evaluation_run_job.rb index 28afa60e5..7ab0a5dd9 100644 --- a/actionagent/app/jobs/action_agent/evaluation_run_job.rb +++ b/actionagent/app/jobs/action_agent/evaluation_run_job.rb @@ -3,7 +3,9 @@ module ActionAgent # Executes an evaluation run created by Evaluation#run_later!. The run # record already exists (pending), so the dashboard can show it while the - # job is queued; the runner marks it running, then complete or failed. + # job is queued; the runner claims it as running, then marks it complete + # or failed. A job delivered again finds the run claimed and replays + # nothing, even when two workers load it as pending at once. class EvaluationRunJob < ApplicationJob queue_as :agents diff --git a/actionagent/app/services/action_agent/scenario_evaluation_runner.rb b/actionagent/app/services/action_agent/scenario_evaluation_runner.rb index d1ffc0705..c4544ccd9 100644 --- a/actionagent/app/services/action_agent/scenario_evaluation_runner.rb +++ b/actionagent/app/services/action_agent/scenario_evaluation_runner.rb @@ -82,10 +82,15 @@ def initialize(evaluation, selection: {}, run: nil) end def call + pending = @run || @evaluation.evaluation_runs.create!(status: :pending) + # Another worker started this run (a job delivered twice, or handed to + # two workers): it is theirs to finish, so nothing here writes to it. + return pending.reload unless claim!(pending) + + run = pending scenarios = selected_scenarios specs = model_specs - run = @run || @evaluation.evaluation_runs.create!(status: :pending) - run.update!(status: :running, selection: selection_summary(scenarios, specs)) + run.update!(selection: selection_summary(scenarios, specs)) record_pass_thresholds!(run) ensure_sandbox_live! @@ -291,6 +296,24 @@ def finish_fan_out!(run) private + # Moves the run from pending to running in one conditional update, as + # AgentExecutionJob#claim_pending claims an agent run, and returns + # whether this runner is the one that did. Of two workers that loaded + # the run as pending, only the first to write replays the suite (or fans + # it out); the other replays nothing and leaves the run alone. The claim + # comes before the selection is read, so a selection that cannot be + # resolved fails the run rather than leaving it pending. Nothing is held + # over the replays. + def claim!(run) + now = Time.current + claimed = EvaluationRun.where(id: run.id, status: EvaluationRun.statuses[:pending]) + .update_all(status: EvaluationRun.statuses[:running], updated_at: now) + return false if claimed.zero? + + run.reload + true + end + def fan_out?(adapter) ActionAgent.scenario_evaluation_fan_out == true && adapter.nil? && !browser_requested? && Evals::Runner.instance_method(:initialize).parameters.any? { |_type, name| name == :refine_gate } diff --git a/actionagent/test/evaluation_run_claim_test.rb b/actionagent/test/evaluation_run_claim_test.rb new file mode 100644 index 000000000..bbb2ce360 --- /dev/null +++ b/actionagent/test/evaluation_run_claim_test.rb @@ -0,0 +1,211 @@ +# frozen_string_literal: true + +require "test_helper" + +# An evaluation run created ahead of time (Evaluation#run_later!) is executed +# by the EvaluationRunJob delivered for it. A job delivered again, or one the +# queue hands to a second worker, must not replay the suite a second time: +# every replay is a billed provider call and may call the agent's tools. +module EvaluationRunClaimHelpers + def build_suite + agent = ActionAgent::Agent.create!(name: "Claim Agent", provider: "mock", model: "mock-model", instructions: "Answer with the data.") + evaluation = agent.evaluations.new( + name: "Support questions", + judge_kind: "rules", + criteria: [ { "key" => "response_present", "type" => "response_present", "config" => {} } ] + ) + evaluation.scenarios.build(key: "tickets_1", group: "Tickets", prompt: "Which open tickets mention a refund?") + evaluation.scenarios.build(key: "tickets_2", group: "Tickets", prompt: "Show me all tickets with no assignee") + evaluation.scenarios.build(key: "history_1", group: "History", prompt: "Who changed the shipping policy last week?") + evaluation.save! + evaluation + end + + # Runs the block with every replay answered without the agent, counting + # the replays in +calls+. + def counting_replays(calls) + klass = ActionAgent::ScenarioEvaluationRunner + original = klass.instance_method(:replay) + klass.define_method(:replay) do |_scenario, _spec| + calls.increment + ActiveAgent::Evals::Replay.new(answer: "The data.", duration_ms: 1) + end + yield + ensure + klass.define_method(:replay, original) + end + + def with_fan_out(value) + previous = ActionAgent.scenario_evaluation_fan_out + ActionAgent.scenario_evaluation_fan_out = value + yield + ensure + ActionAgent.scenario_evaluation_fan_out = previous + end +end + +class EvaluationRunClaimTest < ActiveSupport::TestCase + include ActiveJob::TestHelper + include EvaluationRunClaimHelpers + + def setup + ActionAgent::Agent.delete_all + end + + test "a pending run is executed once and completed" do + evaluation = build_suite + run = evaluation.run_later! + calls = Concurrent::AtomicFixnum.new(0) + + counting_replays(calls) { perform_enqueued_jobs(only: ActionAgent::EvaluationRunJob) } + + assert_equal 3, calls.value + assert_equal "complete", run.reload.status + assert_equal 3, run.scenario_results.count + end + + test "a job delivered again for a run already running replays nothing" do + evaluation = build_suite + run = evaluation.evaluation_runs.create!(status: :running) + calls = Concurrent::AtomicFixnum.new(0) + + counting_replays(calls) { ActionAgent::EvaluationRunJob.perform_now(evaluation.id, run.id, {}) } + + assert_equal 0, calls.value + assert_equal "running", run.reload.status + end + + %w[complete failed].each do |status| + test "a job delivered again for a #{status} run leaves it #{status}" do + evaluation = build_suite + run = evaluation.evaluation_runs.create!(status: status, error_message: "kept", completed_at: 1.hour.ago) + calls = Concurrent::AtomicFixnum.new(0) + + counting_replays(calls) { ActionAgent::EvaluationRunJob.perform_now(evaluation.id, run.id, {}) } + + assert_equal 0, calls.value + run.reload + assert_equal status, run.status + assert_equal "kept", run.error_message + end + end + + # A copy loaded while the run was still pending, as a second worker holds + # it, does not start the run once another worker has claimed it. + test "a runner handed a stale pending copy of a claimed run replays nothing" do + evaluation = build_suite + run = evaluation.evaluation_runs.create!(status: :pending) + stale = evaluation.evaluation_runs.find(run.id) + run.update!(status: :running) + calls = Concurrent::AtomicFixnum.new(0) + + counting_replays(calls) { evaluation.run!(run: stale) } + + assert_equal 0, calls.value + assert_equal "running", run.reload.status + assert_empty run.scenario_results + end + + # The run records the failure instead of staying pending forever: the + # selection is read after the run is claimed, so its error fails the run. + # A model handed back whole (a re-run of a stored spec) keeps the provider + # it names, which is how an unsupported one reaches the runner. + test "a pending run whose models cannot be resolved fails rather than staying pending" do + evaluation = build_suite + run = evaluation.run_later!(models: [ { "provider" => "nowhere", "model" => "model-x" } ]) + + assert_raises(ArgumentError) { perform_enqueued_jobs(only: ActionAgent::EvaluationRunJob) } + + run.reload + assert_equal "failed", run.status + assert_match(/unsupported model provider/, run.error_message) + assert_not_nil run.completed_at + end +end + +# Two workers that receive the same EvaluationRunJob at once have both read +# the run as pending before either writes. Real connections are needed to +# see it, so the test does not run inside a transaction, and it removes the +# rows it commits. Both workers are held right after loading the run until +# each has it, which makes the interleaving certain instead of likely. +class EvaluationRunClaimConcurrencyTest < ActiveSupport::TestCase + include ActiveJob::TestHelper + include EvaluationRunClaimHelpers + + self.use_transactional_tests = false + + def setup + @evaluation = build_suite + end + + # The evaluation, its runs, results and scenarios go with the agent. + def teardown + ActionAgent::Agent.find_by(id: @evaluation&.agent_id)&.destroy! + end + + # Each worker's evaluation hands out its runs through this, which waits + # for the other worker once the run is loaded. + class RunsLoadedTogether < SimpleDelegator + def initialize(runs, barrier) + super(runs) + @barrier = barrier + end + + def find(*args) + __getobj__.find(*args).tap do + @barrier&.wait(10) + @barrier = nil + end + end + end + + def two_workers_at_once(run) + lookup = ActionAgent::Evaluation.method(:find) + barrier = Concurrent::CyclicBarrier.new(2) + loaded_together = lambda do |id| + evaluation = lookup.call(id) + runs = RunsLoadedTogether.new(evaluation.evaluation_runs, barrier) + evaluation.define_singleton_method(:evaluation_runs) { runs } + evaluation + end + errors = Queue.new + + ActionAgent::Evaluation.stub(:find, loaded_together) do + workers = Array.new(2) do + Thread.new do + ActiveRecord::Base.connection_pool.with_connection do + ActionAgent::EvaluationRunJob.perform_now(@evaluation.id, run.id, {}) + end + rescue StandardError => e + errors << e + end + end + workers.each(&:join) + end + assert_empty Array.new(errors.size) { errors.pop }, "a worker raised" + end + + test "two workers that load the same pending run replay the suite once" do + run = @evaluation.evaluation_runs.create!(status: :pending) + calls = Concurrent::AtomicFixnum.new(0) + + with_fan_out(false) do + counting_replays(calls) { two_workers_at_once(run) } + end + + run.reload + assert_equal 3, calls.value, "the suite was replayed by both workers" + assert_equal "complete", run.status + assert_equal 3, run.scenario_results.count + end + + test "two workers that load the same pending fanned-out run enqueue its replays once" do + run = @evaluation.evaluation_runs.create!(status: :pending) + + with_fan_out(true) { two_workers_at_once(run) } + + replays = enqueued_jobs.select { |job| job["job_class"] == "ActionAgent::EvaluationReplayJob" } + assert_equal 3, replays.size, "both workers fanned the run out" + assert_equal "running", run.reload.status + end +end