From 83354c17fd228dbfa5e62b137c08928d5287a86b Mon Sep 17 00:00:00 2001 From: Andy Wang Date: Sun, 15 Nov 2026 10:02:33 +0800 Subject: [PATCH] Claim a fanned-out replay before the agent runs ScenarioEvaluationRunner#replay_scenario! checked for a stored result, replayed, and only then took the run's lock to store, so the lock guarded the store and not the provider call. Two deliveries of one EvaluationReplayJob both ran the agent (a billed call that may call its tools) and the second answer was dropped. #fail_result! marked any pending, unscored result errored, so a duplicate delivery that failed (an enqueue error, say) turned the other delivery's good replay into its own error. The replay now takes a claim before the agent runs: a token and expiry per scenario/provider/model in the run's fan-out bookkeeping (scores["_fan_out"]["replays"]), taken under the run lock the bookkeeping already uses, so no migration. The result row cannot carry it, since it is created only once there is an answer, and nothing makes a pair's row unique. A delivery that finds a live claim re-enqueues itself for when the claim expires, as a judge job does inside a scoring lease, and then replays only if nothing was stored, which covers a worker that stopped mid-replay. The owner drops its claim with the store, fenced on its token. #fail_result! now writes only for this delivery's pair: no result yet and no live claim held elsewhere, or the result this runner stored. EvaluationReplayJob hands the failure to the same runner so it knows which that is. This is one active replay per pair across duplicate deliveries, not exactly once: a worker that stops after the provider answered and before the store is replayed after its claim expires. --- CHANGELOG.md | 18 +++ .../action_agent/evaluation_replay_job.rb | 6 +- .../scenario_evaluation_runner.rb | 103 ++++++++++++- .../test/scenario_evaluation_fan_out_test.rb | 145 ++++++++++++++++++ 4 files changed, 267 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 50e736f6e..38d1eacca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,24 @@ 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 + +- **A fanned-out replay is claimed before the agent runs** (`actionagent`). + `EvaluationReplayJob` checked for a stored result, replayed, and only + then took the run's lock to store, so two deliveries of one replay job + both called the provider (and the agent's tools) and the second answer + was dropped. A delivery that failed after another had stored the pair's + replay also marked that good result errored. The replay now takes a + claim, kept with the run's fan-out bookkeeping (no migration), before + the agent runs. A delivery that finds the pair claimed comes back when + the claim expires (30 minutes) and replays only if nothing was stored, + so a worker that stopped mid-replay is still covered. A failure is + stored only over the delivery's own pair. A worker that stops after the + provider answered and before the result is stored is still replayed + again: this is one active replay per pair, not exactly once. + ## [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_replay_job.rb b/actionagent/app/jobs/action_agent/evaluation_replay_job.rb index 30df2043c..7cb088d19 100644 --- a/actionagent/app/jobs/action_agent/evaluation_replay_job.rb +++ b/actionagent/app/jobs/action_agent/evaluation_replay_job.rb @@ -8,7 +8,9 @@ module ActionAgent # # A failure outside the replay is stored as the pair's errored result # rather than raised, so the run still completes; a scenario removed from - # the suite during the run is left out of it. + # the suite during the run is left out of it. The same runner records the + # failure, since it knows whether this delivery claimed the pair and + # stored its result (see ScenarioEvaluationRunner#fail_result!). class EvaluationReplayJob < ApplicationJob queue_as :agents @@ -21,7 +23,7 @@ def perform(run_id, scenario_id, spec, selection = {}) runner.replay_scenario!(run, scenario_id, spec) rescue StandardError => e Rails.logger.warn("[ActionAgent] evaluation run #{run_id}: replay of scenario #{scenario_id} failed: #{e.class}: #{e.message}") - ScenarioEvaluationRunner.new(run.evaluation, selection: selection, run: run).fail_result!(run.reload, scenario_id, spec, e) + runner.fail_result!(run.reload, scenario_id, spec, e) end end end diff --git a/actionagent/app/services/action_agent/scenario_evaluation_runner.rb b/actionagent/app/services/action_agent/scenario_evaluation_runner.rb index d1ffc0705..5c0b05d4f 100644 --- a/actionagent/app/services/action_agent/scenario_evaluation_runner.rb +++ b/actionagent/app/services/action_agent/scenario_evaluation_runner.rb @@ -47,6 +47,7 @@ module ActionAgent class ScenarioEvaluationRunner < EvaluationRunnerService Evals = ActiveAgent::Evals JUDGE_LEASE_DURATION = 30.minutes + REPLAY_LEASE_DURATION = 30.minutes # The providers a candidate model name resolves against. `mock` is the # framework's test double, accepted so the test suite can compare cohorts @@ -173,6 +174,13 @@ def call # Replays one scenario under one model and stores the answer as a pending # result, then enqueues its scoring. A result already stored for the # pair (a retried job) is not replayed again. + # + # The replay is claimed before the agent runs, so a second delivery of + # the job (a queue redelivering it, or handing it to two workers) does + # not call the provider and the agent's tools a second time. A delivery + # that finds the pair claimed comes back when the claim expires (see + # #claim_replay!): by then the owner has stored the result, or stopped + # and left the pair to it. def replay_scenario!(run, scenario_id, spec_value) return unless run.running? @@ -180,9 +188,21 @@ def replay_scenario!(run, scenario_id, spec_value) spec = model_spec_from(spec_value) row = stored_result(run, scenario, spec) unless row + key = replay_key(scenario, spec) + held_until = claim_replay!(run, key) + if held_until + EvaluationReplayJob.set(wait_until: held_until).perform_later(run.id, scenario.id, spec_value, @selection.to_h) + return + end + return unless @replay_token # the run stopped running + task = Evals::Scenario.from_hash(scenario.as_json_summary) replay = fan_out_replay(task, spec) - row = run.with_lock { stored_result(run, scenario, spec) || store_replay(run, scenario, task, spec, replay) } + row = run.with_lock do + stored = stored_result(run, scenario, spec) || store_replay(run, scenario, task, spec, replay).tap { |created| @stored_result_id = created.id } + release_replay!(run, key) + stored + end end EvaluationJudgeJob.perform_later(row.id, @selection.to_h, run.id) if row.pending? row @@ -227,6 +247,12 @@ def judge_result!(row) # replay (which records its own errors), so the run still completes. A # scenario removed from the suite during the run has no result to # store; the run completes without it (see #finish_fan_out!). + # + # Only this delivery's own pair is failed: one with no result yet and + # no other delivery replaying it, or the result this runner stored. A + # result another delivery stored is that delivery's to score, and a + # pair another delivery has claimed is its to store, so a duplicate + # delivery's failure cannot turn a good replay into an error. def fail_result!(run, scenario_id, spec_value, error) return unless run.running? @@ -235,8 +261,15 @@ def fail_result!(run, scenario_id, spec_value, error) spec = model_spec_from(spec_value) run.with_lock do row = stored_result(run, scenario, spec) - task = Evals::Scenario.from_hash(scenario.as_json_summary) - row ||= store_replay(run, scenario, task, spec, Evals::Replay.failed(error)) + if row.nil? + next if replay_claimed_elsewhere?(run, replay_key(scenario, spec)) + + task = Evals::Scenario.from_hash(scenario.as_json_summary) + row = store_replay(run, scenario, task, spec, Evals::Replay.failed(error)) + @stored_result_id = row.id + end + next unless row.id == @stored_result_id + attributes = { status: :errored, error_message: row.error_message.presence || error_text(error) } if scoring_leases? # Another replay delivery may fail while this result is being @@ -404,6 +437,70 @@ def scoring_leases? (%w[scoring_token scoring_expires_at] - EvaluationScenarioResult.column_names).empty? end + # A pair's replay claim, kept with the run's fan-out bookkeeping + # (scores["_fan_out"]["replays"]) until the replay is stored, so no + # migration is needed. The result row cannot hold it: the row is + # created only once there is an answer to store, and nothing makes a + # pair's row unique to create it earlier. + def replay_key(scenario, spec) + "#{scenario.id}:#{spec.provider}/#{spec.model}" + end + + # Claims the pair's replay for this runner (its token in @replay_token) + # and returns nil, or returns when another delivery's live claim + # expires. An expired claim is taken over: its worker stopped, or is + # still replaying after REPLAY_LEASE_DURATION, in which case the two + # replays overlap and the first to store its answer is kept. A run no + # longer running claims nothing (@replay_token stays nil). + # + # This holds one active replay per pair across ordinary duplicate + # deliveries. It is not exactly once: a worker that stops after the + # provider answered and before the result is stored is replayed again. + def claim_replay!(run, key) + @replay_token = nil + token = SecureRandom.uuid + held_until = nil + update_fan_out_state!(run) do |state| + now = Time.current + replays = state["replays"].is_a?(Hash) ? state["replays"] : {} + expires_at = replay_expiry(replays[key]) + if expires_at && expires_at > now + held_until = expires_at + next state + end + + @replay_token = token + state.merge("replays" => replays.merge(key => { "token" => token, "expires_at" => (now + REPLAY_LEASE_DURATION).iso8601(6) })) + end + held_until + end + + # Drops this runner's claim once its replay is stored. A claim another + # delivery took over is left to that delivery. Called under the run's + # lock, after the store. + def release_replay!(run, key) + return unless run.running? + + state = fan_out_state(run) + replays = state["replays"].is_a?(Hash) ? state["replays"] : {} + return unless @replay_token && replays.dig(key, "token") == @replay_token + + scores = run.scores.is_a?(Hash) ? run.scores : {} + run.update!(scores: scores.merge("_fan_out" => state.merge("replays" => replays.except(key)))) + end + + def replay_claimed_elsewhere?(run, key) + claim = fan_out_state(run)["replays"].to_h[key] + expires_at = replay_expiry(claim) + expires_at.present? && expires_at > Time.current && claim["token"] != @replay_token + end + + def replay_expiry(claim) + Time.iso8601(claim["expires_at"].to_s) if claim.is_a?(Hash) + rescue ArgumentError + nil + end + # What Evals::Runner does with a replay that raises: an errored replay, # scored like any other. def fan_out_replay(task, spec) diff --git a/actionagent/test/scenario_evaluation_fan_out_test.rb b/actionagent/test/scenario_evaluation_fan_out_test.rb index d84755d72..a5cf30212 100644 --- a/actionagent/test/scenario_evaluation_fan_out_test.rb +++ b/actionagent/test/scenario_evaluation_fan_out_test.rb @@ -603,6 +603,151 @@ def with_method(klass, method_name, body) end end + # The replay job of +run+'s one pair, as the run job enqueued it. + def replay_job_arguments + job = enqueued_jobs.find { |entry| entry["job_class"] == "ActionAgent::EvaluationReplayJob" } + ActiveJob::Arguments.deserialize(job["arguments"]) + end + + # Runs the block with every replay counted in +calls+ and answered by + # +answer+ (a proc given the call's number), without the agent. + def counting_replays(calls, answer = ->(_number) { }) + with_method(ActionAgent::ScenarioEvaluationRunner, :replay, proc { |_task, _spec| + calls << :replay + answer.call(calls.size) + ActiveAgent::Evals::Replay.new(answer: "The data.", duration_ms: 1) + }) { yield } + end + + test "a delivery that arrives while another is replaying the pair does not replay it again" do + evaluation = build_suite + run = evaluation.run_later!(keys: [ "tickets_1" ]) + perform_enqueued_jobs(only: ActionAgent::EvaluationRunJob) + args = replay_job_arguments + clear_enqueued_jobs + calls = [] + # The duplicate is delivered while the first delivery's provider call + # is still out. + duplicate = ->(number) { ActionAgent::EvaluationReplayJob.perform_now(*args) if number == 1 } + + counting_replays(calls, duplicate) { ActionAgent::EvaluationReplayJob.perform_now(*args) } + + assert_equal 1, calls.size, "the provider was called by both deliveries" + assert_equal 1, run.scenario_results.count + deferred = enqueued_jobs.find { |job| job["job_class"] == "ActionAgent::EvaluationReplayJob" } + assert deferred, "the duplicate comes back for when the claim expires" + assert_in_delta ActionAgent::ScenarioEvaluationRunner::REPLAY_LEASE_DURATION.from_now.to_f, + Time.iso8601(deferred["scheduled_at"]).to_f, 5 + assert_empty run.reload.scores.dig("_fan_out", "replays"), "the stored replay released its claim" + + counting_replays(calls) do + travel(ActionAgent::ScenarioEvaluationRunner::REPLAY_LEASE_DURATION + 1.second) { drain } + end + + assert_equal 1, calls.size, "the deferred duplicate finds the result stored" + assert_equal "complete", run.reload.status + end + + test "a redelivery inside a stopped worker's live replay claim replays the pair once the claim expires" do + evaluation = build_suite + run = evaluation.run_later!(keys: [ "tickets_1" ]) + perform_enqueued_jobs(only: ActionAgent::EvaluationRunJob) + args = replay_job_arguments + clear_enqueued_jobs + # The first delivery claims the pair, then its worker dies mid-replay. + stopped = ActionAgent::ScenarioEvaluationRunner.new(evaluation, run: run) + scenario = evaluation.scenarios.find(args[1]) + assert_nil stopped.send(:claim_replay!, run.reload, stopped.send(:replay_key, scenario, stopped.send(:model_spec_from, args[2]))) + calls = [] + + counting_replays(calls) { ActionAgent::EvaluationReplayJob.perform_now(*args) } + + assert_empty calls, "a live claim is not replayed over" + assert_equal 0, run.scenario_results.count + retry_job = enqueued_jobs.sole + assert_equal "ActionAgent::EvaluationReplayJob", retry_job["job_class"] + + counting_replays(calls) do + travel_to(Time.iso8601(retry_job["scheduled_at"]) + 1.second) { drain } + end + + assert_equal 1, calls.size + assert_equal 1, run.scenario_results.count + assert_equal "complete", run.reload.status + end + + test "a late replay from a worker whose claim was taken over does not release its successor's claim" do + evaluation = build_suite + run = evaluation.run_later!(keys: [ "tickets_1" ]) + perform_enqueued_jobs(only: ActionAgent::EvaluationRunJob) + args = replay_job_arguments + scenario = evaluation.scenarios.find(args[1]) + old_owner = ActionAgent::ScenarioEvaluationRunner.new(evaluation, run: run) + key = old_owner.send(:replay_key, scenario, old_owner.send(:model_spec_from, args[2])) + old_owner.send(:claim_replay!, run.reload, key) + successor = ActionAgent::ScenarioEvaluationRunner.new(evaluation, run: run) + + travel(ActionAgent::ScenarioEvaluationRunner::REPLAY_LEASE_DURATION + 1.second) do + assert_nil successor.send(:claim_replay!, run.reload, key), "an expired claim is taken over" + run.with_lock { old_owner.send(:release_replay!, run, key) } + end + + assert_equal successor.instance_variable_get(:@replay_token), run.reload.scores.dig("_fan_out", "replays", key, "token") + end + + test "a duplicate delivery's failure leaves the replay another delivery stored" do + evaluation = build_suite + run = evaluation.run_later!(keys: [ "tickets_1" ]) + perform_enqueued_jobs(only: ActionAgent::EvaluationRunJob) + args = replay_job_arguments + ActionAgent::EvaluationReplayJob.perform_now(*args) + row = run.scenario_results.sole + assert_predicate row, :pending? + + # A second delivery finds the stored replay, and enqueuing its judge fails. + ActionAgent::EvaluationJudgeJob.stub(:perform_later, ->(*) { raise ActiveJob::EnqueueError, "queue unavailable" }) do + ActionAgent::EvaluationReplayJob.perform_now(*args) + end + + row.reload + assert_predicate row, :pending?, "the stored replay was turned into the duplicate's error" + assert_nil row.error_message + drain + assert_equal "passed", row.reload.status + assert_equal "complete", run.reload.status + end + + test "a delivery whose own judge cannot be enqueued stores its replay errored, and the run completes" do + evaluation = build_suite + run = evaluation.run_later!(keys: [ "tickets_1" ]) + perform_enqueued_jobs(only: ActionAgent::EvaluationRunJob) + args = replay_job_arguments + + ActionAgent::EvaluationJudgeJob.stub(:perform_later, ->(*) { raise ActiveJob::EnqueueError, "queue unavailable" }) do + ActionAgent::EvaluationReplayJob.perform_now(*args) + end + + row = run.scenario_results.sole + assert_equal "errored", row.status + assert_match(/queue unavailable/, row.error_message) + assert_equal "complete", run.reload.status + end + + test "a failure while another delivery holds the pair's replay claim stores nothing over it" do + evaluation = build_suite + run = evaluation.run_later!(keys: [ "tickets_1" ]) + perform_enqueued_jobs(only: ActionAgent::EvaluationRunJob) + args = replay_job_arguments + scenario = evaluation.scenarios.find(args[1]) + owner = ActionAgent::ScenarioEvaluationRunner.new(evaluation, run: run) + owner.send(:claim_replay!, run.reload, owner.send(:replay_key, scenario, owner.send(:model_spec_from, args[2]))) + + ActionAgent::ScenarioEvaluationRunner.new(evaluation, run: run).fail_result!(run.reload, args[1], args[2], RuntimeError.new("duplicate failed")) + + assert_equal 0, run.scenario_results.count, "the owner stores the pair's result" + assert_equal "running", run.reload.status + end + test "a duplicate replay failure cannot interrupt an active scoring owner" do evaluation = build_suite evaluation.update!(judge_kind: "llm", judge_model: "claude-opus-5",