From a22578a39cdaf4c9dc4e1cbf0a5eac749cb4904e Mon Sep 17 00:00:00 2001 From: Andy Wang Date: Sun, 15 Nov 2026 09:35:10 +0800 Subject: [PATCH 1/5] Claim a pending evaluation run before replaying it EvaluationRunJob checked `run.pending?` and the scenario runner then wrote `running`, as two steps. A job delivered twice, or two workers that both loaded the run as pending, each replayed the whole suite (every replay a billed provider call that may call the agent's tools), or with scenario_evaluation_fan_out on each enqueued a full set of replay jobs. ScenarioEvaluationRunner#call now moves the run from pending to running in one conditional update, as AgentExecutionJob#claim_pending does, and a runner that loses the claim returns without writing to the run. The claim sits in the runner, so ProjectEvaluationJob, which has the same check-then-run shape, is covered as well. It happens before the selection is read, so a selection that raises (an unsupported provider in a re-run's models) now fails the run instead of leaving it pending forever: `run` was still unassigned when the rescue ran. --- CHANGELOG.md | 16 ++ .../jobs/action_agent/evaluation_run_job.rb | 4 +- .../scenario_evaluation_runner.rb | 27 ++- actionagent/test/evaluation_run_claim_test.rb | 211 ++++++++++++++++++ 4 files changed, 255 insertions(+), 3 deletions(-) create mode 100644 actionagent/test/evaluation_run_claim_test.rb 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 From 8551738f5b213901c6ebd2b2b2e716f587bf232c Mon Sep 17 00:00:00 2001 From: Andy Wang Date: Sun, 15 Nov 2026 09:38:14 +0800 Subject: [PATCH 2/5] Refuse catalog YAML that safe loading rejects as an invalid document Catalog.parse rescued only Psych::SyntaxError. YAML.safe_load refuses a tag naming a class outside the permitted list (Psych::DisallowedClass) and an alias to an undefined anchor (Psych::BadAlias) with errors that are not syntax errors, so a document such as `--- !ruby/object:Object {}` escaped ScenarioCatalogImport as a 500 from the catalog import and preview endpoints, and as an internal error from the catalogs_import and catalogs_preview MCP tools. The rescue is now Psych::Exception, their common parent, as ScenarioParser and the CLI credentials reader already do, so these documents get the same "the catalog is not valid YAML" 422 as a syntax error. The permitted classes and aliases are unchanged. --- CHANGELOG.md | 14 +++++++++ actionagent/test/mcp_dashboard_tools_test.rb | 6 ++++ .../test/scenario_catalogs_api_test.rb | 13 ++++++++ lib/active_agent/evals/catalog.rb | 7 +++-- test/evals/catalog_test.rb | 31 +++++++++++++++++++ 5 files changed, 69 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 50e736f6e..69a52ecf8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,20 @@ 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 catalog document YAML refuses to load is an invalid document** + (`activeagent`, `actionagent`). `Catalog.parse` turned only a syntax + error into `Catalog::InvalidDocument`, while safe loading refuses a tag + naming a Ruby class (`!ruby/object:...`) or an alias to an undefined + anchor with other `Psych` errors. Those escaped the dashboard's catalog + import and preview as a 500, and the `catalogs_import` and + `catalogs_preview` tools as an internal error. They are now refused like + any other invalid catalog: 422 with "the catalog is not valid YAML: ...". + What safe loading permits is unchanged. + ## [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/test/mcp_dashboard_tools_test.rb b/actionagent/test/mcp_dashboard_tools_test.rb index c65e5829e..07870d437 100644 --- a/actionagent/test/mcp_dashboard_tools_test.rb +++ b/actionagent/test/mcp_dashboard_tools_test.rb @@ -535,6 +535,12 @@ def structured(body) assert_equal true, body.dig("result", "isError") assert_match(/product has no key/, body.dig("result", "content", 0, "text")) assert_equal(-32602, call_tool("catalogs_import").dig("error", "code")) + + %w[catalogs_import catalogs_preview].each do |tool| + body = call_tool(tool, { document: "--- !ruby/object:Object {}\n" }) + assert_equal true, body.dig("result", "isError"), "#{tool} answers a refused document as a tool error" + assert_match(/not valid YAML/, body.dig("result", "content", 0, "text")) + end end test "catalog_set_run materializes the set as an evaluation and queues its run" do diff --git a/actionagent/test/scenario_catalogs_api_test.rb b/actionagent/test/scenario_catalogs_api_test.rb index ae210c79e..69ddeab04 100644 --- a/actionagent/test/scenario_catalogs_api_test.rb +++ b/actionagent/test/scenario_catalogs_api_test.rb @@ -163,6 +163,19 @@ def body assert_match(/product has no key/, body["errors"].first) end + test "a document naming a Ruby class is refused as invalid YAML, on import and on preview" do + document = "--- !ruby/object:Object {}\n" + + post "/activeagents/api/scenario_catalogs", params: { document: document }, as: :json + assert_response :unprocessable_entity + assert_match(/not valid YAML: Tried to load unspecified class: Object/, body["errors"].first) + + post "/activeagents/api/scenario_catalogs/preview", params: { document: document }, as: :json + assert_response :unprocessable_entity + assert_match(/not valid YAML/, body["errors"].first) + assert_equal 0, ActionAgent::ScenarioCatalog.count + end + test "imports every catalog file of a connected repository at a ref" do ActionAgent::GithubConnection.create!( access_token: "gho_test", github_user_id: 42, login: "octocat", diff --git a/lib/active_agent/evals/catalog.rb b/lib/active_agent/evals/catalog.rb index 4c14ba463..bb0a9a3c6 100644 --- a/lib/active_agent/evals/catalog.rb +++ b/lib/active_agent/evals/catalog.rb @@ -81,13 +81,16 @@ def self.load(*paths, name: nil) end # Parses YAML text. Raises InvalidDocument for YAML that is not a - # document (a list, a scalar) or that YAML cannot read. + # document (a list, a scalar) or that YAML cannot read: a syntax error, + # and what safe loading refuses — a tag naming a Ruby class other than + # Symbol (Psych::DisallowedClass) or an alias to an undefined anchor + # (Psych::BadAlias), which are not Psych::SyntaxError. def self.parse(text, name: nil) document = YAML.safe_load(text.to_s, aliases: true, permitted_classes: [ Symbol ]) raise InvalidDocument, "a scenario catalog is a YAML mapping" unless document.is_a?(Hash) new([ document ], name: name) - rescue Psych::SyntaxError => e + rescue Psych::Exception => e raise InvalidDocument, "the catalog is not valid YAML: #{e.message}" end diff --git a/test/evals/catalog_test.rb b/test/evals/catalog_test.rb index 7648f6d22..59a55caa3 100644 --- a/test/evals/catalog_test.rb +++ b/test/evals/catalog_test.rb @@ -351,6 +351,37 @@ def gated_catalog(*overlays) assert_raises(ActiveAgent::Evals::Catalog::NotFound) { ActiveAgent::Evals::Catalog.load(File.join(FIXTURES, "missing.yml")) } end + # The document is read with YAML.safe_load, which refuses a tag naming a + # Ruby class and an alias to an anchor the document never defines with + # errors of its own, apart from Psych::SyntaxError. + test "refuses YAML that safe loading will not read, as an invalid document" do + { + "--- !ruby/object:Object {}\n" => /Tried to load unspecified class: Object/, + "catalog: x\nproducts: [{ key: p, at: !ruby/object:OpenStruct { a: 1 } }]\n" => /unspecified class: OpenStruct/, + "catalog: x\nproducts: *undefined\n" => /undefined/ + }.each do |document, reason| + error = assert_raises(ActiveAgent::Evals::Catalog::InvalidDocument, document) { ActiveAgent::Evals::Catalog.parse(document) } + assert_match(/\Athe catalog is not valid YAML: /, error.message) + assert_match reason, error.message + end + end + + test "keeps reading the symbols and aliases a catalog may use" do + catalog = ActiveAgent::Evals::Catalog.parse(<<~YAML) + catalog: x + products: + - key: p + judge: :rules + sets: + - key: s + scenarios: + - &first { key: a, prompt: Which tickets are open? } + - *first + YAML + + assert_equal [ "a" ], catalog.scenarios.map(&:key).uniq + end + test "refuses malformed criteria, naming the product or set and the list" do refused = { "catalog: x\nproducts: [{ key: p, criteria: oops }]" => /criteria of product "p" are not a list or a mapping of lists/, From 83354c17fd228dbfa5e62b137c08928d5287a86b Mon Sep 17 00:00:00 2001 From: Andy Wang Date: Sun, 15 Nov 2026 10:02:33 +0800 Subject: [PATCH 3/5] 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", From 7017be83993b0fbd593932afc9b1bb8a87324744 Mon Sep 17 00:00:00 2001 From: Andy Wang Date: Sun, 15 Nov 2026 10:07:11 +0800 Subject: [PATCH 4/5] Say when a run reached only ungated groups instead of "every gate met" An ungated group's gate row is met without being held to a bar. A report whose every result sat in ungated groups therefore had only met rows, and GateCheck#message (what assert_meets_pass_gates and the RSpec matcher print) said "every pass gate met", as did `evals run --wait` ("Gates: every gate met"), even when every answer had failed. The verdict is kept: the docs promise an ungated group never fails the run, and a catalog set marked `gated: false` is tested to report gates_met true. Only the wording changes. GateCheck says every group the run covered is ungated and no answer was held to a bar, and the CLI prints "Gates: every group reached is ungated (N); nothing was held to a bar." The evaluations and CLI guides note it, and point at --min-pass-rate for a run that should still fail CI. --- CHANGELOG.md | 13 +++++++++++++ docs/framework/cli.md | 4 +++- docs/framework/evaluations.md | 4 +++- lib/active_agent/cli/eval_commands.rb | 8 +++++++- lib/active_agent/evals/gate_check.rb | 5 ++++- test/cli/cli_test.rb | 15 +++++++++++++++ test/evals/gate_check_test.rb | 12 ++++++++++++ 7 files changed, 57 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 50e736f6e..2431dd317 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,19 @@ 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 run of only ungated groups no longer reads as "every gate met"** + (`activeagent`). An ungated group's row is met without being held to a + bar, so a report whose every result sat in ungated groups said "every + pass gate met" (`GateCheck`, `assert_meets_pass_gates`, the RSpec + matcher) and `evals run --wait` printed `Gates: every gate met`, even + when every answer had failed. The verdict is unchanged, since an ungated + group never fails the run, but the message now says that every group + covered is ungated and nothing was held to a bar. + ## [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/docs/framework/cli.md b/docs/framework/cli.md index 248eabe31..97e1e3183 100644 --- a/docs/framework/cli.md +++ b/docs/framework/cli.md @@ -129,7 +129,9 @@ FAIL Here the whole run clears 80% and still fails, because the critical group is held to 100%. A group with `gated: false` is reported and never fails -the run. `--json` adds the run's `gates` beside `pass_rate` and `verdict`. +the run; a run that reached only ungated groups prints `Gates: every group +reached is ungated (N); nothing was held to a bar.` in place of `every gate +met`, so add `--min-pass-rate` if such a run should still fail CI. `--json` adds the run's `gates` beside `pass_rate` and `verdict`. A run without gates is gated on its status and pass rate alone, as before, and without `--wait` or `--min-pass-rate` the command returns once the run starts, before any gate exists. diff --git a/docs/framework/evaluations.md b/docs/framework/evaluations.md index 49628854d..3b7eac7c7 100644 --- a/docs/framework/evaluations.md +++ b/docs/framework/evaluations.md @@ -775,7 +775,9 @@ and `pass_rate` (a 0..1 fraction) beside the true when the rate reaches the bar, and always for an ungated group. `Report#passed?` is every gate met, and a report with no gate (a selection that matched nothing, or every scenario dropped as `production_only`) does -not pass. +not pass. A report whose every result sits in an ungated group passes, +since such a group never fails the run, but nothing in it was held to a +bar, and `GateCheck#message` says so rather than "every pass gate met". `Report#failures(group:)` lists the results that did not pass — failed and errored, in run order — and `failures_markdown(group:)` writes them one per line. diff --git a/lib/active_agent/cli/eval_commands.rb b/lib/active_agent/cli/eval_commands.rb index 2cde4d342..e853b53f2 100644 --- a/lib/active_agent/cli/eval_commands.rb +++ b/lib/active_agent/cli/eval_commands.rb @@ -247,7 +247,13 @@ def run_gates(run) def print_gates(gates, missed) unmet = gates.reject { |gate| gate["met"] == true } unless missed - @out.puts "Gates: every gate met (#{gates.size})." + # Ungated rows are met without being held to a bar, so a run that + # reached only those says so rather than "every gate met". + if gates.none? { |gate| gate["gated"] != false } + @out.puts "Gates: every group reached is ungated (#{gates.size}); nothing was held to a bar." + else + @out.puts "Gates: every gate met (#{gates.size})." + end return end diff --git a/lib/active_agent/evals/gate_check.rb b/lib/active_agent/evals/gate_check.rb index 720ebc1a8..752496682 100644 --- a/lib/active_agent/evals/gate_check.rb +++ b/lib/active_agent/evals/gate_check.rb @@ -45,7 +45,9 @@ def unmet end # The text a failing assertion prints. The first line counts the gates - # not met, or is the one line "every pass gate met" when none is; then + # not met, or is the one line "every pass gate met" when none is (a + # report whose every row is an ungated group's says that instead: its + # rows are met because nothing held them to a bar); then # each unmet gate as Gate#to_s; then, after a blank line, the failures # to read: for each group with an unmet gate, in gates order, " # failures:" over Report#failures_markdown for that group. An unmet All @@ -59,6 +61,7 @@ def message return "no result reached a pass gate; the run evaluated nothing" if all.empty? unmet = all.reject(&:met?) + return "every group the run covered is ungated; no answer was held to a bar" if all.none?(&:gated) return "every pass gate met" if unmet.empty? lines = [ "#{unmet.size} of #{all.size} pass gates not met", *unmet.map { |gate| "- #{gate}" } ] diff --git a/test/cli/cli_test.rb b/test/cli/cli_test.rb index 54440b0c5..7f78de9af 100644 --- a/test/cli/cli_test.rb +++ b/test/cli/cli_test.rb @@ -347,6 +347,21 @@ def test_evals_run_trusts_the_dashboards_verdict_on_its_gates assert_includes out, "Gates: no gate was reached." end + # An ungated group never fails the run, so the verdict stands; the line + # under it no longer claims a gate was met when none held anything. + def test_evals_run_says_when_every_group_the_run_reached_is_ungated + stub_tool("evaluations_run", run_payload("pending")) + ungated = [ gate_row("experimental", "Experimental", 0, 2, 0.8, gated: false) ] + stub_tool("evaluation_runs_get", run_payload("complete", passed: 0, evaluated: 2, gates: ungated, gates_met: true)) + + code, out, = cli("evals", "run", "7", "--wait") + + assert_equal CLI::EXIT_SUCCESS, code + assert_includes out, "Gates: every group reached is ungated (1); nothing was held to a bar." + refute_includes out, "every gate met" + assert_match(/PASS$/, out) + end + def test_evals_run_json_adds_the_gates_and_keeps_the_payload stub_tool("evaluations_run", run_payload("pending")) stub_tool("evaluation_runs_get", gated_run) diff --git a/test/evals/gate_check_test.rb b/test/evals/gate_check_test.rb index c0a66a67e..68b05a9ee 100644 --- a/test/evals/gate_check_test.rb +++ b/test/evals/gate_check_test.rb @@ -38,6 +38,18 @@ def test_a_report_with_no_results_is_not_met_and_says_it_evaluated_nothing assert_equal "no result reached a pass gate; the run evaluated nothing", check.message end + # An ungated group never fails the run, so a report of nothing else is + # met; its message says why instead of "every pass gate met". + def test_a_report_with_only_ungated_groups_is_met_and_says_nothing_was_held_to_a_bar + experiment = grouped("exp_1", "Draft a reply in the customer's tone.", "experimental", "Experimental") + report = Report.new(results: [ result(experiment, gpt, replay(answer: "Dear customer."), score: 0.1) ], models: [ gpt ], pass_thresholds: THRESHOLDS) + check = GateCheck.new(report) + + assert check.met? + assert_empty check.unmet + assert_equal "every group the run covered is ungated; no answer was held to a bar", check.message + end + def test_the_message_counts_the_unmet_gates_then_lists_them_and_each_groups_failures report = gated_report check = GateCheck.new(report) From 09f8e9c0a5777cb6faf5d454e05693c68a4aa25d Mon Sep 17 00:00:00 2001 From: Andy Wang Date: Sun, 15 Nov 2026 10:16:40 +0800 Subject: [PATCH 5/5] Refuse media content the RubyLLM provider would drop RubyLLMProvider#extract_content_text kept only `type: "text"` blocks, so a message holding an image (image_url, image, input_image), audio or a file reached RubyLLM as its text alone, or as an empty string when it held only the image, and the reply read as if the model had seen it. The test named "array content filters non-text blocks" asserted only that a response came back. Such a message now raises Errors::InvalidRequest (provider_tag "RubyLLM") naming the block types, before any provider call. MEDIA_BLOCK_TYPES lists the shapes the OpenAI Chat, OpenAI Responses and Anthropic transforms write. Other non-text blocks, such as an earlier turn's reasoning, are still left out, so a history carried over from another provider keeps working. The provider guide gains a Text-Only Content section. Sending images through RubyLLM's attachments is left for a follow-up: it differs between ruby_llm 1.x (Content) and 2.x (Message attachments:), needs data: URLs decoded, and has RubyLLM fetch http(s) image URLs from the application server. --- CHANGELOG.md | 13 ++++++ docs/providers/ruby_llm.md | 10 +++++ .../providers/ruby_llm_provider.rb | 21 ++++++++++ .../ruby_llm/ruby_llm_provider_test.rb | 42 +++++++++++++------ 4 files changed, 74 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 50e736f6e..35d43733e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,19 @@ 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 + +- **The RubyLLM provider refuses media it would drop** (`activeagent`). It + sends RubyLLM the text of each message and silently left out every other + content block, so a message with an image (`image_url`, `image`, + `input_image`), audio or a file reached the model as its text alone, or + as an empty message, and the model answered as if it had seen it. Such + a message now raises `ActiveAgent::Providers::Errors::InvalidRequest`, + naming the block types, before any provider call. Blocks that are not + media (an earlier turn's reasoning) are still left out, as before. + ## [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/docs/providers/ruby_llm.md b/docs/providers/ruby_llm.md index 5e7023a70..c5381e756 100644 --- a/docs/providers/ruby_llm.md +++ b/docs/providers/ruby_llm.md @@ -243,6 +243,15 @@ For interleaved parallel OpenAI tool calls, use ruby_llm 2.x. ruby_llm 1.16 disc See [Streaming](/agents/streaming) for ActionCable integration and real-time updates. +## Text-Only Content + +The provider sends RubyLLM the text of each message. A message whose +content holds an image, audio or file block (`image_url`, `image`, +`input_image`, `input_audio`, `file`, `input_file`, `document`, and the +like) is refused with `ActiveAgent::Providers::Errors::InvalidRequest` +before any provider call, rather than sent without it. Use the OpenAI, +Anthropic or OpenRouter provider for images and files. + ## When to Use RubyLLM vs Direct Providers **Use RubyLLM when:** @@ -253,6 +262,7 @@ See [Streaming](/agents/streaming) for ActionCable integration and real-time upd **Use a direct provider (OpenAI, Anthropic) when:** - You need provider-specific features (MCP servers, extended thinking, JSON schema mode) +- You send images, audio or files (see [Text-Only Content](#text-only-content)) - You want the tightest integration with a provider's gem SDK - You need provider-specific error handling classes diff --git a/lib/active_agent/providers/ruby_llm_provider.rb b/lib/active_agent/providers/ruby_llm_provider.rb index e5e6908ac..3515e6c5c 100644 --- a/lib/active_agent/providers/ruby_llm_provider.rb +++ b/lib/active_agent/providers/ruby_llm_provider.rb @@ -381,6 +381,7 @@ def extract_content_text(content) when String content when Array + refuse_media_blocks!(content) content.select { |block| block.is_a?(Hash) && block[:type] == "text" } .map { |block| block[:text] } .join("\n") @@ -389,6 +390,26 @@ def extract_content_text(content) end end + # Content block types that carry media rather than text, in the shapes + # the OpenAI (Chat and Responses) and Anthropic transforms write. + MEDIA_BLOCK_TYPES = %w[image image_url input_image audio input_audio file input_file document video].freeze + + # This provider sends RubyLLM text only, so an image, audio clip or + # file would be dropped while the model answered as if it had seen + # it. Such a request is refused before any provider call. Other + # blocks that are not text (an earlier turn's reasoning) are still + # left out. + def refuse_media_blocks!(content) + types = content.filter_map { |block| block[:type].to_s if block.is_a?(Hash) && MEDIA_BLOCK_TYPES.include?(block[:type].to_s) }.uniq + return if types.empty? + + raise Errors::InvalidRequest.new( + "The RubyLLM provider sends text only; this message has #{types.join(', ')} content, which it would drop. " \ + "Send it through a provider that accepts it, or as text.", + provider_tag: "RubyLLM" + ) + end + # Converts ActiveAgent tool_calls to RubyLLM's ToolCall format. # # @param tool_calls [Array] ActiveAgent format tool calls diff --git a/test/providers/ruby_llm/ruby_llm_provider_test.rb b/test/providers/ruby_llm/ruby_llm_provider_test.rb index 4d73dea4f..64725a39a 100644 --- a/test/providers/ruby_llm/ruby_llm_provider_test.rb +++ b/test/providers/ruby_llm/ruby_llm_provider_test.rb @@ -637,26 +637,44 @@ def complete(messages, **kwargs) response = provider.prompt assert_not_nil response + assert_equal "Hello\nWorld", @fake_provider.last_messages.find { |message| message.role == :user }.content end - test "array content filters non-text blocks" do + # The provider sends RubyLLM text only. An image, audio clip or file in + # the content would be dropped, and the model would answer as if it had + # seen it, so the request is refused before any provider call. + [ + { type: "image_url", image_url: { url: "data:image/png;base64,iVBORw0KGgo=" } }, + { type: "image", source: { type: "url", url: "https://example.com/cat.png" } }, + { type: "input_audio", input_audio: { data: "UklGRg==", format: "wav" } }, + { type: "file", file: { filename: "report.pdf", file_data: "data:application/pdf;base64,JVBERi0=" } }, + { type: "document", source: { type: "url", url: "https://example.com/report.pdf" } } + ].each do |block| + test "array content with a #{block[:type]} block is refused, not sent as text alone" do + provider = ActiveAgent::Providers::RubyLLMProvider.new( + service: "RubyLLM", + model: "gpt-4o-mini", + messages: [ { role: "user", content: [ block, { type: "text", text: "Describe this" } ] } ] + ) + + error = assert_raises(ActiveAgent::Providers::Errors::InvalidRequest) { provider.prompt } + + assert_match(/sends text only.*#{block[:type]}/, error.message) + assert_equal "RubyLLM", error.provider_tag + assert_nil @fake_provider.last_messages, "nothing reached RubyLLM" + end + end + + test "array content keeps leaving out blocks that are not media" do provider = ActiveAgent::Providers::RubyLLMProvider.new( service: "RubyLLM", model: "gpt-4o-mini", - messages: [ - { - role: "user", - content: [ - { type: "image_url", image_url: { url: "data:image/png;base64,..." } }, - { type: "text", text: "Describe this image" } - ] - } - ] + messages: [ { role: "user", content: [ { type: "thinking", thinking: "Earlier reasoning." }, { type: "text", text: "Describe this" } ] } ] ) - response = provider.prompt + provider.prompt - assert_not_nil response + assert_equal "Describe this", @fake_provider.last_messages.find { |message| message.role == :user }.content end # --- Empty/nil tool_calls ---