actionagent 1.9.8 → 1.9.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/app/controllers/action_agent/api/agent_runs_controller.rb +3 -0
- data/app/controllers/action_agent/api/traces_controller.rb +111 -9
- data/app/jobs/action_agent/agent_execution_job.rb +8 -4
- data/app/jobs/action_agent/agent_resume_job.rb +7 -4
- data/app/jobs/action_agent/agent_run_expiry_job.rb +23 -0
- data/app/jobs/action_agent/evaluation_replay_job.rb +4 -2
- data/app/jobs/action_agent/evaluation_run_job.rb +3 -1
- data/app/jobs/action_agent/process_telemetry_traces_job.rb +6 -0
- data/app/jobs/action_agent/project_evaluation_job.rb +9 -1
- data/app/models/action_agent/agent.rb +8 -4
- data/app/models/action_agent/agent_run.rb +117 -5
- data/app/models/action_agent/telemetry_trace.rb +101 -21
- data/app/services/action_agent/scenario_evaluation_runner.rb +125 -5
- data/config/routes.rb +5 -0
- data/lib/action_agent/version.rb +1 -1
- data/lib/action_agent.rb +13 -0
- data/lib/generators/action_agent/templates/action_agent.rb.erb +11 -0
- data/lib/generators/action_agent/templates/migrations/036_add_agent_run_execution_leases.rb.erb +10 -0
- metadata +4 -2
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 49930b222cf8e63f63fa43755877aab31c38bd840bd737ad98889f3e40a5a180
|
|
4
|
+
data.tar.gz: 0b4f401bdc7936566270788ab269964bce1b12ada5a464cf9426a4352e2ce212
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: ce39003e9cdac8cd9fd780c8be24d43bd838067af4dffd98f01eb0d3b436e4ae1840a00ab4d0b98c838869eccf4a05ef7f4ce64e77bb775b2faf6bb1e85f6649
|
|
7
|
+
data.tar.gz: 526b15308898d61fb3f846c2b92b59910213d55e490ac227ac30a57b7178b7db1184ab845cb6e6b1ffb4a87e8c22c2f320d981741f74ade6b3c0b058faea353d
|
|
@@ -8,6 +8,7 @@ module ActionAgent
|
|
|
8
8
|
# GET /api/runs/:id
|
|
9
9
|
def show
|
|
10
10
|
@run.expire_overdue_input_requests!
|
|
11
|
+
@run.expire_if_lost!
|
|
11
12
|
render json: {
|
|
12
13
|
run: run_json(@run),
|
|
13
14
|
messages: interaction_messages(@run),
|
|
@@ -29,6 +30,8 @@ module ActionAgent
|
|
|
29
30
|
def index
|
|
30
31
|
# Scoped to the caller's own agents: this listed (and counted) every
|
|
31
32
|
# run in the database regardless of who owned it.
|
|
33
|
+
# A run whose worker was lost is listed as failed, not as running.
|
|
34
|
+
AgentRun.expire_lost!(AgentRun.where(agent: owner_agents))
|
|
32
35
|
scope = AgentRun.includes(:agent, :pending_input_requests).with_attachments.where(agent: owner_agents).recent
|
|
33
36
|
|
|
34
37
|
scope = scope.where(agent_id: params[:agent_id]) if params[:agent_id].present?
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require "stringio"
|
|
4
|
+
require "zlib"
|
|
5
|
+
|
|
3
6
|
module ActionAgent
|
|
4
7
|
module Api
|
|
5
8
|
# Telemetry ingestion endpoint.
|
|
@@ -33,9 +36,29 @@ module ActionAgent
|
|
|
33
36
|
# "sdk": { "name": "activeagent", "version": "0.5.0" }
|
|
34
37
|
# }
|
|
35
38
|
#
|
|
39
|
+
# The same endpoint takes OpenTelemetry's protocol (OTLP over HTTP), so an
|
|
40
|
+
# application in any language can report with its OpenTelemetry exporter
|
|
41
|
+
# and no ActiveAgent gem. A request is read as OTLP when its body is
|
|
42
|
+
# protobuf, or JSON holding "resourceSpans". The path
|
|
43
|
+
# <mount>/api/otlp/v1/traces answers too, for exporters configured with
|
|
44
|
+
# a base endpoint (OTEL_EXPORTER_OTLP_ENDPOINT), which append /v1/traces.
|
|
45
|
+
#
|
|
46
|
+
# @example OpenTelemetry request
|
|
47
|
+
# POST <mount>/api/traces
|
|
48
|
+
# Authorization: Bearer <api_key>
|
|
49
|
+
# Content-Type: application/x-protobuf
|
|
50
|
+
# Content-Encoding: gzip
|
|
51
|
+
#
|
|
52
|
+
# <ExportTraceServiceRequest>
|
|
53
|
+
#
|
|
36
54
|
class TracesController < ActionController::API
|
|
37
55
|
include IngestAuthentication
|
|
38
56
|
|
|
57
|
+
OTLP_PROTOBUF = "application/x-protobuf"
|
|
58
|
+
|
|
59
|
+
# The largest JSON body accepted once inflated.
|
|
60
|
+
MAX_INFLATED_BYTES = 32 * 1024 * 1024
|
|
61
|
+
|
|
39
62
|
before_action :enforce_ingest_quota!
|
|
40
63
|
|
|
41
64
|
# POST <mount>/api/traces (e.g. /activeagents/api/traces)
|
|
@@ -47,11 +70,93 @@ module ActionAgent
|
|
|
47
70
|
# were silently gone. ProcessTelemetryTracesJob bounds its own work by
|
|
48
71
|
# slicing and re-enqueueing the remainder.
|
|
49
72
|
def create
|
|
73
|
+
return create_from_otlp if otlp_request?
|
|
74
|
+
|
|
50
75
|
traces = Array(params[:traces])
|
|
51
76
|
sdk_info = params[:sdk] || {}
|
|
52
77
|
|
|
53
78
|
return head :accepted if traces.empty?
|
|
54
79
|
|
|
80
|
+
store(traces, sdk_info)
|
|
81
|
+
head :accepted
|
|
82
|
+
rescue ActionController::ParameterMissing => e
|
|
83
|
+
render json: { error: e.message }, status: :bad_request
|
|
84
|
+
rescue StandardError => e
|
|
85
|
+
Rails.logger.error("[ActionAgent] Trace ingestion error: #{e.message}")
|
|
86
|
+
render json: { error: "Internal server error" }, status: :internal_server_error
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
private
|
|
90
|
+
|
|
91
|
+
# OpenTelemetry exporters commonly gzip the body. Rails parses a JSON
|
|
92
|
+
# body while it is still logging the request, before any callback,
|
|
93
|
+
# action or rescue_from runs, and a compressed one fails there with a
|
|
94
|
+
# 400. So a gzipped JSON body is inflated before Rails looks at it. A
|
|
95
|
+
# protobuf body needs none of this: Rails does not parse it, and the
|
|
96
|
+
# decoder inflates it.
|
|
97
|
+
def process_action(*)
|
|
98
|
+
inflate_gzipped_json!
|
|
99
|
+
super
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
# Whether the request is an OpenTelemetry export rather than the native
|
|
103
|
+
# envelope. Decided without touching `params` for anything but plain
|
|
104
|
+
# JSON: a protobuf or gzipped body is not something Rails can parse.
|
|
105
|
+
def otlp_request?
|
|
106
|
+
return true if request.media_type == OTLP_PROTOBUF
|
|
107
|
+
|
|
108
|
+
body = request.request_parameters
|
|
109
|
+
body.key?("resourceSpans") || body.key?("resource_spans")
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
# Replaces a gzipped JSON body with its contents. Reads no more than
|
|
113
|
+
# the limit, so a small request cannot expand without bound; a body
|
|
114
|
+
# that is over it, or is not gzip at all, is left for Rails to refuse
|
|
115
|
+
# as unparseable JSON.
|
|
116
|
+
def inflate_gzipped_json!
|
|
117
|
+
return unless request.headers["Content-Encoding"].to_s.strip.casecmp?("gzip")
|
|
118
|
+
return unless request.media_type == "application/json"
|
|
119
|
+
|
|
120
|
+
body = Zlib::GzipReader.new(request.body).read(MAX_INFLATED_BYTES + 1).to_s
|
|
121
|
+
return if body.bytesize > MAX_INFLATED_BYTES
|
|
122
|
+
|
|
123
|
+
request.env["rack.input"] = StringIO.new(body)
|
|
124
|
+
request.env["CONTENT_LENGTH"] = body.bytesize.to_s
|
|
125
|
+
request.env.delete("HTTP_CONTENT_ENCODING")
|
|
126
|
+
rescue Zlib::Error
|
|
127
|
+
nil
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
# POST <mount>/api/traces or <mount>/api/otlp/v1/traces with an OTLP
|
|
131
|
+
# body. Answers 200 with an empty ExportTraceServiceResponse, as the
|
|
132
|
+
# protocol asks, in the encoding the request used.
|
|
133
|
+
def create_from_otlp
|
|
134
|
+
unless defined?(ActiveAgents::Telemetry::OTLP)
|
|
135
|
+
return render json: { error: "OpenTelemetry ingest needs activeagents-telemetry 0.4 or later" },
|
|
136
|
+
status: :unsupported_media_type
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
result = ActiveAgents::Telemetry::OTLP.decode(
|
|
140
|
+
request.raw_post,
|
|
141
|
+
content_type: request.media_type.presence || OTLP_PROTOBUF,
|
|
142
|
+
content_encoding: request.headers["Content-Encoding"]
|
|
143
|
+
)
|
|
144
|
+
store(result.traces, result.sdk) if result.traces.any?
|
|
145
|
+
|
|
146
|
+
if request.media_type == OTLP_PROTOBUF
|
|
147
|
+
send_data "", type: OTLP_PROTOBUF, disposition: "inline", status: :ok
|
|
148
|
+
else
|
|
149
|
+
render json: {}, status: :ok
|
|
150
|
+
end
|
|
151
|
+
rescue ActiveAgents::Telemetry::OTLP::DecodeError => e
|
|
152
|
+
render json: { error: e.message }, status: :bad_request
|
|
153
|
+
rescue StandardError => e
|
|
154
|
+
Rails.logger.error("[ActionAgent] OTLP ingestion error: #{e.class}: #{e.message}")
|
|
155
|
+
render json: { error: "Internal server error" }, status: :internal_server_error
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
# Hands traces in the native format to the job, or stores them now.
|
|
159
|
+
def store(traces, sdk_info)
|
|
55
160
|
if ActionAgent.multi_tenant?
|
|
56
161
|
# Multi-tenant mode: process in background
|
|
57
162
|
ActionAgent::ProcessTelemetryTracesJob.perform_later(
|
|
@@ -64,17 +169,8 @@ module ActionAgent
|
|
|
64
169
|
# Local mode: process synchronously
|
|
65
170
|
process_traces_synchronously(traces, sdk_info)
|
|
66
171
|
end
|
|
67
|
-
|
|
68
|
-
head :accepted
|
|
69
|
-
rescue ActionController::ParameterMissing => e
|
|
70
|
-
render json: { error: e.message }, status: :bad_request
|
|
71
|
-
rescue StandardError => e
|
|
72
|
-
Rails.logger.error("[ActionAgent] Trace ingestion error: #{e.message}")
|
|
73
|
-
render json: { error: "Internal server error" }, status: :internal_server_error
|
|
74
172
|
end
|
|
75
173
|
|
|
76
|
-
private
|
|
77
|
-
|
|
78
174
|
# The host app's quota checker, asked with kind :trace_ingest.
|
|
79
175
|
def enforce_ingest_quota!
|
|
80
176
|
enforce_ingest_quota_for!(:trace_ingest, "Trace ingest limit reached")
|
|
@@ -91,6 +187,12 @@ module ActionAgent
|
|
|
91
187
|
model = ActionAgent.trace_model
|
|
92
188
|
|
|
93
189
|
traces.each do |trace|
|
|
190
|
+
# Spans of an OpenTelemetry trace arrive over several requests.
|
|
191
|
+
if trace["format"] == "otlp" && model.respond_to?(:ingest_otlp)
|
|
192
|
+
model.ingest_otlp(trace, sdk_info)
|
|
193
|
+
next
|
|
194
|
+
end
|
|
195
|
+
|
|
94
196
|
# Skip if trace already exists (idempotency)
|
|
95
197
|
next if model.exists?(trace_id: trace["trace_id"])
|
|
96
198
|
|
|
@@ -12,6 +12,9 @@ module ActionAgent
|
|
|
12
12
|
# retry of a failed run would re-run the generation.
|
|
13
13
|
return unless claim_pending(run)
|
|
14
14
|
|
|
15
|
+
# This worker's lease: only while the run is still running under it is
|
|
16
|
+
# the result recorded.
|
|
17
|
+
token = run.lease_token
|
|
15
18
|
run.add_log("Starting execution", level: :info)
|
|
16
19
|
|
|
17
20
|
begin
|
|
@@ -20,12 +23,12 @@ module ActionAgent
|
|
|
20
23
|
# Build the agent class dynamically based on configuration
|
|
21
24
|
result = execute_agent(agent_record, run)
|
|
22
25
|
|
|
23
|
-
run.unless_cancelled do
|
|
26
|
+
run.unless_cancelled(token: token) do
|
|
24
27
|
run.record_result!(result, segment_started_at: run.started_at)
|
|
25
28
|
run.add_log(result[:input_requests].present? ? "Execution paused for input" : "Execution completed successfully", level: :info)
|
|
26
29
|
end
|
|
27
30
|
rescue => e
|
|
28
|
-
run.unless_cancelled do
|
|
31
|
+
run.unless_cancelled(token: token) do
|
|
29
32
|
run.record_failure!(e)
|
|
30
33
|
run.add_log("Execution failed: #{e.message}", level: :error)
|
|
31
34
|
end
|
|
@@ -46,11 +49,12 @@ module ActionAgent
|
|
|
46
49
|
# with Rails 7.2, whose deferred transactions cannot write once another
|
|
47
50
|
# writer has committed. Nothing is held over the generation, so a cancel
|
|
48
51
|
# never waits for it. The update skips callbacks, so the status change is
|
|
49
|
-
# broadcast here.
|
|
52
|
+
# broadcast here. The claim takes the run's lease (AgentRun.lease_attributes),
|
|
53
|
+
# so the reloaded run carries this worker's token.
|
|
50
54
|
def claim_pending(run)
|
|
51
55
|
now = Time.current
|
|
52
56
|
claimed = AgentRun.where(id: run.id, status: AgentRun.statuses[:pending])
|
|
53
|
-
.update_all(status: AgentRun.statuses[:running], started_at: now, updated_at: now)
|
|
57
|
+
.update_all(status: AgentRun.statuses[:running], started_at: now, updated_at: now, **AgentRun.lease_attributes(now))
|
|
54
58
|
return false if claimed.zero?
|
|
55
59
|
|
|
56
60
|
run.reload
|
|
@@ -24,6 +24,8 @@ module ActionAgent
|
|
|
24
24
|
pause = claim_pause(run, request)
|
|
25
25
|
return unless pause
|
|
26
26
|
|
|
27
|
+
token = run.lease_token
|
|
28
|
+
|
|
27
29
|
segment_started_at = Time.current
|
|
28
30
|
secrets = pause.select { |paused| paused.kind == "secret" }.filter_map(&:answer)
|
|
29
31
|
|
|
@@ -39,13 +41,13 @@ module ActionAgent
|
|
|
39
41
|
}
|
|
40
42
|
)
|
|
41
43
|
|
|
42
|
-
run.unless_cancelled do
|
|
44
|
+
run.unless_cancelled(token: token) do
|
|
43
45
|
run.record_result!(result, segment_started_at: segment_started_at)
|
|
44
46
|
run.add_log(result[:input_requests].present? ? "Execution paused for input" : "Execution completed successfully", level: :info)
|
|
45
47
|
end
|
|
46
48
|
rescue => e
|
|
47
49
|
message = ActiveAgent::InputRequest.scrub(e.message, secrets)
|
|
48
|
-
run.unless_cancelled do
|
|
50
|
+
run.unless_cancelled(token: token) do
|
|
49
51
|
run.record_failure!(e, message: message)
|
|
50
52
|
run.add_log("Execution failed: #{message}", level: :error)
|
|
51
53
|
end
|
|
@@ -60,7 +62,8 @@ module ActionAgent
|
|
|
60
62
|
# Moves the run from awaiting_input to running when every request of the
|
|
61
63
|
# pause is settled, under the run's row lock, and returns the pause's
|
|
62
64
|
# requests in call order; nil when this job is not the one to resume it,
|
|
63
|
-
# or when the request's pause is not the one the run waits on.
|
|
65
|
+
# or when the request's pause is not the one the run waits on. The resumed
|
|
66
|
+
# segment takes a lease of its own, under a new token.
|
|
64
67
|
def claim_pause(run, request)
|
|
65
68
|
run.with_lock do
|
|
66
69
|
next nil unless run.awaiting_input? && request.current_pause?
|
|
@@ -68,7 +71,7 @@ module ActionAgent
|
|
|
68
71
|
pause = request.pause_requests.order(:id).to_a
|
|
69
72
|
next nil unless pause.all? { |paused| paused.answered? || paused.declined? }
|
|
70
73
|
|
|
71
|
-
run.update!(status: :running)
|
|
74
|
+
run.update!(status: :running, **AgentRun.lease_attributes)
|
|
72
75
|
pause
|
|
73
76
|
end
|
|
74
77
|
end
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ActionAgent
|
|
4
|
+
# Fails the runs whose lease ran out (AgentRun.expire_lost!): running, with
|
|
5
|
+
# no claim, renewal or result from their worker within
|
|
6
|
+
# ActionAgent.run_lease_duration. A run's own page and the run list fail
|
|
7
|
+
# the lost runs they reach; this job reaches the rest. It never executes a
|
|
8
|
+
# run again.
|
|
9
|
+
#
|
|
10
|
+
# Not scheduled by default. To schedule it:
|
|
11
|
+
#
|
|
12
|
+
# # config/recurring.yml
|
|
13
|
+
# agent_run_expiry:
|
|
14
|
+
# class: ActionAgent::AgentRunExpiryJob
|
|
15
|
+
# schedule: every 5 minutes
|
|
16
|
+
class AgentRunExpiryJob < ApplicationJob
|
|
17
|
+
queue_as :default
|
|
18
|
+
|
|
19
|
+
def perform
|
|
20
|
+
AgentRun.expire_lost!
|
|
21
|
+
end
|
|
22
|
+
end
|
|
23
|
+
end
|
|
@@ -8,7 +8,9 @@ module ActionAgent
|
|
|
8
8
|
#
|
|
9
9
|
# A failure outside the replay is stored as the pair's errored result
|
|
10
10
|
# rather than raised, so the run still completes; a scenario removed from
|
|
11
|
-
# the suite during the run is left out of it.
|
|
11
|
+
# the suite during the run is left out of it. The same runner records the
|
|
12
|
+
# failure, since it knows whether this delivery claimed the pair and
|
|
13
|
+
# stored its result (see ScenarioEvaluationRunner#fail_result!).
|
|
12
14
|
class EvaluationReplayJob < ApplicationJob
|
|
13
15
|
queue_as :agents
|
|
14
16
|
|
|
@@ -21,7 +23,7 @@ module ActionAgent
|
|
|
21
23
|
runner.replay_scenario!(run, scenario_id, spec)
|
|
22
24
|
rescue StandardError => e
|
|
23
25
|
Rails.logger.warn("[ActionAgent] evaluation run #{run_id}: replay of scenario #{scenario_id} failed: #{e.class}: #{e.message}")
|
|
24
|
-
|
|
26
|
+
runner.fail_result!(run.reload, scenario_id, spec, e)
|
|
25
27
|
end
|
|
26
28
|
end
|
|
27
29
|
end
|
|
@@ -3,7 +3,9 @@
|
|
|
3
3
|
module ActionAgent
|
|
4
4
|
# Executes an evaluation run created by Evaluation#run_later!. The run
|
|
5
5
|
# record already exists (pending), so the dashboard can show it while the
|
|
6
|
-
# job is queued; the runner
|
|
6
|
+
# job is queued; the runner claims it as running, then marks it complete
|
|
7
|
+
# or failed. A job delivered again finds the run claimed and replays
|
|
8
|
+
# nothing, even when two workers load it as pending at once.
|
|
7
9
|
class EvaluationRunJob < ApplicationJob
|
|
8
10
|
queue_as :agents
|
|
9
11
|
|
|
@@ -73,6 +73,12 @@ module ActionAgent
|
|
|
73
73
|
def process_trace(trace, sdk_info, account)
|
|
74
74
|
model = ActionAgent.trace_model
|
|
75
75
|
|
|
76
|
+
# Spans of an OpenTelemetry trace arrive over several requests, so a
|
|
77
|
+
# trace already stored takes the new spans instead of skipping them.
|
|
78
|
+
if trace["format"] == "otlp" && model.respond_to?(:ingest_otlp)
|
|
79
|
+
return model.ingest_otlp(trace, sdk_info, account: account)
|
|
80
|
+
end
|
|
81
|
+
|
|
76
82
|
# Build uniqueness scope
|
|
77
83
|
scope = model.where(trace_id: trace["trace_id"])
|
|
78
84
|
scope = scope.where(account: account) if ActionAgent.multi_tenant? && account
|
|
@@ -15,6 +15,7 @@ module ActionAgent
|
|
|
15
15
|
|
|
16
16
|
POLL_INTERVAL = 10.seconds
|
|
17
17
|
BOOT_WAIT = 1.hour
|
|
18
|
+
SELECTION_KEYS = %w[keys models].freeze
|
|
18
19
|
|
|
19
20
|
def perform(project_id, run_id, mount_url = nil)
|
|
20
21
|
run = EvaluationRun.find_by(id: run_id)
|
|
@@ -49,7 +50,14 @@ module ActionAgent
|
|
|
49
50
|
return fail_run(run, "This install replays scenarios through its own adapter, which cannot reach a project's sandbox")
|
|
50
51
|
end
|
|
51
52
|
|
|
52
|
-
evaluation.run!(run: run, sandbox_id: sandbox.session_id, browser: true, mount_url: mount_url)
|
|
53
|
+
evaluation.run!(run: run, **requested_selection(run), sandbox_id: sandbox.session_id, browser: true, mount_url: mount_url)
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# The scenarios and models the run was started with. A project's own
|
|
57
|
+
# evaluation stores none; a catalog set run against the project
|
|
58
|
+
# (ScenarioSet#run!) stores the keys and models it was asked for.
|
|
59
|
+
def requested_selection(run)
|
|
60
|
+
run.selection.to_h.slice(*SELECTION_KEYS).symbolize_keys
|
|
53
61
|
end
|
|
54
62
|
|
|
55
63
|
def fail_run(run, message)
|
|
@@ -492,22 +492,26 @@ module ActionAgent
|
|
|
492
492
|
|
|
493
493
|
# Quick test execution (synchronous). A run that pauses for input comes
|
|
494
494
|
# back `awaiting_input` with its requests stored, and AgentResumeJob
|
|
495
|
-
# finishes it once they are answered.
|
|
495
|
+
# finishes it once they are answered. The run is created running, under
|
|
496
|
+
# a lease, as a job's claim would leave it, and its result is recorded
|
|
497
|
+
# as a job's is: not over a cancel, nor once the run left its lease.
|
|
496
498
|
def test_execute(input_prompt, action: nil, attachments: [], actor: nil, runtime_sandbox: nil, **params)
|
|
497
499
|
ensure_executable!
|
|
498
500
|
run = create_run(
|
|
499
501
|
input_prompt, action: action, attachments: attachments, params: params,
|
|
500
|
-
actor: actor, runtime_sandbox: runtime_sandbox, status: :running, started_at: Time.current
|
|
502
|
+
actor: actor, runtime_sandbox: runtime_sandbox, status: :running, started_at: Time.current,
|
|
503
|
+
**AgentRun.lease_attributes
|
|
501
504
|
)
|
|
502
505
|
run.actor = actor
|
|
506
|
+
token = run.lease_token
|
|
503
507
|
|
|
504
508
|
begin
|
|
505
509
|
# Build and execute the agent
|
|
506
510
|
result = AgentExecutionService.call(self, run)
|
|
507
511
|
|
|
508
|
-
run.record_result!(result, segment_started_at: run.started_at)
|
|
512
|
+
run.unless_cancelled(token: token) { run.record_result!(result, segment_started_at: run.started_at) }
|
|
509
513
|
rescue => e
|
|
510
|
-
run.record_failure!(e)
|
|
514
|
+
run.unless_cancelled(token: token) { run.record_failure!(e) }
|
|
511
515
|
end
|
|
512
516
|
|
|
513
517
|
run
|
|
@@ -19,6 +19,11 @@ module ActionAgent
|
|
|
19
19
|
end
|
|
20
20
|
end
|
|
21
21
|
|
|
22
|
+
# The error class recorded on a run failed as lost: running past its
|
|
23
|
+
# lease with no news from its worker (see #expire_if_lost!). Never
|
|
24
|
+
# raised; it names the failure, as record_failure! names any other.
|
|
25
|
+
class WorkerLost < StandardError; end
|
|
26
|
+
|
|
22
27
|
# Files uploaded with the run. The execution service delivers them to
|
|
23
28
|
# the model (images and PDFs as data URIs, text inlined) and the
|
|
24
29
|
# persisted user message keeps a manifest of them.
|
|
@@ -165,6 +170,45 @@ module ActionAgent
|
|
|
165
170
|
end
|
|
166
171
|
end
|
|
167
172
|
|
|
173
|
+
# Whether migration 036's lease columns are installed. A host that
|
|
174
|
+
# upgraded the gem without running the generator takes no leases and
|
|
175
|
+
# runs as before, instead of failing every claim on a missing column.
|
|
176
|
+
def self.execution_leases?
|
|
177
|
+
(%w[execution_token execution_expires_at] - column_names).empty?
|
|
178
|
+
end
|
|
179
|
+
|
|
180
|
+
# The attributes a claim writes to take a run for one execution segment:
|
|
181
|
+
# a token of its own, and an expiry ActionAgent.run_lease_duration from
|
|
182
|
+
# +now+. Empty when leases are off (no columns, or no duration).
|
|
183
|
+
# @return [Hash]
|
|
184
|
+
def self.lease_attributes(now = Time.current)
|
|
185
|
+
duration = ActionAgent.run_lease_duration
|
|
186
|
+
return {} unless duration && execution_leases?
|
|
187
|
+
|
|
188
|
+
{ execution_token: SecureRandom.uuid, execution_expires_at: now + duration }
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
# The token of the lease this copy holds, read through the column guard:
|
|
192
|
+
# nil when the lease columns are not installed (no attribute to read) or
|
|
193
|
+
# the run holds no lease. What a worker hands #unless_cancelled.
|
|
194
|
+
# @return [String, nil]
|
|
195
|
+
def lease_token
|
|
196
|
+
execution_token if self.class.execution_leases?
|
|
197
|
+
end
|
|
198
|
+
|
|
199
|
+
# Pushes the lease's expiry out by ActionAgent.run_lease_duration, while
|
|
200
|
+
# the run is still running under this copy's token. A run that finished,
|
|
201
|
+
# paused, or was taken under another token is left alone. Returns
|
|
202
|
+
# whether the lease was renewed.
|
|
203
|
+
# @return [Boolean]
|
|
204
|
+
def renew_lease!(now = Time.current)
|
|
205
|
+
duration = ActionAgent.run_lease_duration
|
|
206
|
+
return false unless duration && lease_token
|
|
207
|
+
|
|
208
|
+
self.class.where(id: id, status: self.class.statuses[:running], execution_token: execution_token)
|
|
209
|
+
.update_all(execution_expires_at: now + duration) == 1
|
|
210
|
+
end
|
|
211
|
+
|
|
168
212
|
# Callbacks
|
|
169
213
|
before_validation :set_trace_id, on: :create
|
|
170
214
|
after_update_commit :broadcast_update, if: :saved_change_to_status?
|
|
@@ -185,6 +229,7 @@ module ActionAgent
|
|
|
185
229
|
# a "started" event is pending until a "done"/"error" with the same eid
|
|
186
230
|
# lands. update_column: no validations/callbacks, safe from the run's own
|
|
187
231
|
# execution thread; reads current DB state so add_log interleaves safely.
|
|
232
|
+
# An event is the run's sign of progress, so it renews the run's lease.
|
|
188
233
|
def append_event(eid:, kind:, label:, status: "done", detail: nil, duration_ms: nil)
|
|
189
234
|
event = {
|
|
190
235
|
"at" => Time.current.iso8601(3),
|
|
@@ -197,6 +242,7 @@ module ActionAgent
|
|
|
197
242
|
event["duration_ms"] = duration_ms if duration_ms
|
|
198
243
|
current = self.class.where(id: id).pick(:logs) || []
|
|
199
244
|
update_column(:logs, current + [ event ])
|
|
245
|
+
renew_lease!
|
|
200
246
|
event
|
|
201
247
|
end
|
|
202
248
|
|
|
@@ -346,6 +392,54 @@ module ActionAgent
|
|
|
346
392
|
cancelled
|
|
347
393
|
end
|
|
348
394
|
|
|
395
|
+
# Running runs whose lease ran out: no claim, renewal or result from
|
|
396
|
+
# their worker within ActionAgent.run_lease_duration. A run without a
|
|
397
|
+
# lease (claimed before migration 036, or with leases off) is never
|
|
398
|
+
# among them. Needs the lease columns (see .execution_leases?).
|
|
399
|
+
scope :lost, ->(now = Time.current) {
|
|
400
|
+
running.where.not(execution_token: nil).where(execution_expires_at: ..now)
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
# Fails every lost run in +relation+ (see #expire_if_lost!) and returns
|
|
404
|
+
# how many it failed. Nothing without the lease columns.
|
|
405
|
+
# @return [Integer]
|
|
406
|
+
def self.expire_lost!(relation = all, now: Time.current)
|
|
407
|
+
return 0 unless execution_leases?
|
|
408
|
+
|
|
409
|
+
relation.lost(now).find_each.count { |run| run.expire_if_lost!(now) }
|
|
410
|
+
end
|
|
411
|
+
|
|
412
|
+
# Fails the run as lost when it is still running under the lease this
|
|
413
|
+
# copy read and that lease has run out, in one conditional update, so a
|
|
414
|
+
# renewal, a result or a cancel that lands first wins and this changes
|
|
415
|
+
# nothing. The run is not executed again: its worker may have died, or
|
|
416
|
+
# may only be slow, and whatever its provider and tool calls did may
|
|
417
|
+
# already have happened; a slow worker's result is then discarded (see
|
|
418
|
+
# #unless_cancelled). Returns whether this call failed the run, which is
|
|
419
|
+
# reloaded either way it touches the database.
|
|
420
|
+
# @return [Boolean]
|
|
421
|
+
def expire_if_lost!(now = Time.current)
|
|
422
|
+
return false unless self.class.execution_leases? && running? && execution_token &&
|
|
423
|
+
execution_expires_at && execution_expires_at <= now
|
|
424
|
+
|
|
425
|
+
message = "The run's worker stopped reporting progress (its lease expired at #{execution_expires_at.iso8601}). " \
|
|
426
|
+
"The run was not executed again; its provider and tool calls may already have taken effect."
|
|
427
|
+
changed = self.class
|
|
428
|
+
.where(id: id, status: self.class.statuses[:running], execution_token: execution_token)
|
|
429
|
+
.where(execution_expires_at: ..now)
|
|
430
|
+
.update_all(
|
|
431
|
+
status: self.class.statuses[:failed], completed_at: now, error_message: message,
|
|
432
|
+
output_metadata: output_metadata.to_h.merge("error_class" => WorkerLost.name),
|
|
433
|
+
execution_token: nil, execution_expires_at: nil, updated_at: now
|
|
434
|
+
)
|
|
435
|
+
reload
|
|
436
|
+
return false if changed.zero?
|
|
437
|
+
|
|
438
|
+
add_log(message, level: :error)
|
|
439
|
+
broadcast_update
|
|
440
|
+
true
|
|
441
|
+
end
|
|
442
|
+
|
|
349
443
|
# Expires the run's overdue requests for input, which fails the run (see
|
|
350
444
|
# InputRequest#expire!). Returns the run, reloaded when a request
|
|
351
445
|
# expired.
|
|
@@ -376,9 +470,9 @@ module ActionAgent
|
|
|
376
470
|
transaction do
|
|
377
471
|
if result[:input_requests].present?
|
|
378
472
|
InputRequest.record_pause!(self, result[:input_requests], checkpoint: result[:checkpoint])
|
|
379
|
-
update!(attributes.merge(status: :awaiting_input))
|
|
473
|
+
update!(attributes.merge(status: :awaiting_input, **lease_release_attributes))
|
|
380
474
|
else
|
|
381
|
-
update!(attributes.merge(output: result[:output], status: :complete, completed_at: Time.current))
|
|
475
|
+
update!(attributes.merge(output: result[:output], status: :complete, completed_at: Time.current, **lease_release_attributes))
|
|
382
476
|
end
|
|
383
477
|
end
|
|
384
478
|
end
|
|
@@ -395,19 +489,31 @@ module ActionAgent
|
|
|
395
489
|
completed_at: Time.current,
|
|
396
490
|
error_message: message,
|
|
397
491
|
error_backtrace: error.backtrace&.first(10)&.join("\n"),
|
|
398
|
-
output_metadata: output_metadata.to_h.merge("error_class" => error.class.name)
|
|
492
|
+
output_metadata: output_metadata.to_h.merge("error_class" => error.class.name),
|
|
493
|
+
**lease_release_attributes
|
|
399
494
|
)
|
|
400
495
|
end
|
|
401
496
|
|
|
402
497
|
# Yields under the run's row lock unless the run was cancelled meanwhile,
|
|
403
498
|
# so a cancel that arrived while the run executed is never overwritten by
|
|
404
|
-
# the result.
|
|
405
|
-
|
|
499
|
+
# the result. Given the +token+ of the worker's lease, it also yields only
|
|
500
|
+
# while the run still holds that token. Every write that ends a segment
|
|
501
|
+
# releases the lease, so a worker whose run was ended under it (failed as
|
|
502
|
+
# lost, say) or taken for another segment has its result discarded.
|
|
503
|
+
# Returns whether it yielded.
|
|
504
|
+
#
|
|
505
|
+
# @param token [String, nil] the lease token the worker's claim took; nil
|
|
506
|
+
# (no lease) checks for a cancel only
|
|
507
|
+
def unless_cancelled(token: nil)
|
|
406
508
|
with_lock do
|
|
407
509
|
if cancelled?
|
|
408
510
|
add_log("Execution finished after cancellation; result discarded", level: :info)
|
|
409
511
|
next false
|
|
410
512
|
end
|
|
513
|
+
if token && lease_token != token
|
|
514
|
+
add_log("Execution finished after its run was ended or taken by another worker; result discarded", level: :warn)
|
|
515
|
+
next false
|
|
516
|
+
end
|
|
411
517
|
|
|
412
518
|
yield
|
|
413
519
|
true
|
|
@@ -416,6 +522,12 @@ module ActionAgent
|
|
|
416
522
|
|
|
417
523
|
private
|
|
418
524
|
|
|
525
|
+
# Ending a segment ends its lease: nothing renews it, and no worker holds
|
|
526
|
+
# the run until the next claim.
|
|
527
|
+
def lease_release_attributes
|
|
528
|
+
self.class.execution_leases? ? { execution_token: nil, execution_expires_at: nil } : {}
|
|
529
|
+
end
|
|
530
|
+
|
|
419
531
|
def add_tokens(recorded, segment)
|
|
420
532
|
return recorded if segment.nil?
|
|
421
533
|
|
|
@@ -229,21 +229,14 @@ module ActionAgent
|
|
|
229
229
|
end
|
|
230
230
|
end
|
|
231
231
|
|
|
232
|
+
# The most spans one OpenTelemetry trace may hold. A trace arrives over
|
|
233
|
+
# many requests and nothing says which is the last, so a span beyond
|
|
234
|
+
# this is dropped rather than letting one runaway trace grow a row
|
|
235
|
+
# without bound.
|
|
236
|
+
MAX_OTLP_SPANS = 2_000
|
|
237
|
+
|
|
232
238
|
def self.create_from_payload(trace, sdk_info = {}, account: nil, agent: nil)
|
|
233
239
|
spans = trace["spans"] || []
|
|
234
|
-
root_span = spans.find { |s| s["parent_span_id"].nil? } || spans.first || {}
|
|
235
|
-
|
|
236
|
-
total_duration = root_span["duration_ms"]
|
|
237
|
-
total_input, total_output, total_thinking = token_totals(spans)
|
|
238
|
-
|
|
239
|
-
# Extract agent info from root span attributes
|
|
240
|
-
attributes = root_span["attributes"] || {}
|
|
241
|
-
agent_class = attributes["agent.class"]
|
|
242
|
-
agent_action = attributes["agent.action"]
|
|
243
|
-
|
|
244
|
-
# Find any error message
|
|
245
|
-
error_span = spans.find { |s| s["status"] == STATUS_ERROR }
|
|
246
|
-
error_message = error_span&.dig("attributes", "error.message")
|
|
247
240
|
|
|
248
241
|
attrs = {
|
|
249
242
|
trace_id: trace["trace_id"],
|
|
@@ -253,14 +246,7 @@ module ActionAgent
|
|
|
253
246
|
spans: spans,
|
|
254
247
|
resource_attributes: trace["resource_attributes"],
|
|
255
248
|
sdk_info: sdk_info,
|
|
256
|
-
|
|
257
|
-
total_input_tokens: total_input,
|
|
258
|
-
total_output_tokens: total_output,
|
|
259
|
-
total_thinking_tokens: total_thinking,
|
|
260
|
-
status: root_span["status"] || STATUS_UNSET,
|
|
261
|
-
agent_class: agent_class,
|
|
262
|
-
agent_action: agent_action,
|
|
263
|
-
error_message: error_message
|
|
249
|
+
**derived_attributes(spans)
|
|
264
250
|
}
|
|
265
251
|
|
|
266
252
|
# Add account if in multi-tenant mode
|
|
@@ -287,6 +273,100 @@ module ActionAgent
|
|
|
287
273
|
end
|
|
288
274
|
|
|
289
275
|
|
|
276
|
+
# The columns a trace derives from its spans: totals, status, the agent
|
|
277
|
+
# it belongs to and the first error.
|
|
278
|
+
#
|
|
279
|
+
# @return [Hash]
|
|
280
|
+
# @api private
|
|
281
|
+
def self.derived_attributes(spans)
|
|
282
|
+
root_span = spans.find { |s| s["parent_span_id"].nil? } || spans.first || {}
|
|
283
|
+
total_input, total_output, total_thinking = token_totals(spans)
|
|
284
|
+
|
|
285
|
+
# Extract agent info from root span attributes
|
|
286
|
+
attributes = root_span["attributes"] || {}
|
|
287
|
+
|
|
288
|
+
# Find any error message
|
|
289
|
+
error_span = spans.find { |s| s["status"] == STATUS_ERROR }
|
|
290
|
+
|
|
291
|
+
{
|
|
292
|
+
total_duration_ms: root_span["duration_ms"],
|
|
293
|
+
total_input_tokens: total_input,
|
|
294
|
+
total_output_tokens: total_output,
|
|
295
|
+
total_thinking_tokens: total_thinking,
|
|
296
|
+
status: root_span["status"] || STATUS_UNSET,
|
|
297
|
+
agent_class: attributes["agent.class"],
|
|
298
|
+
agent_action: attributes["agent.action"],
|
|
299
|
+
error_message: error_span&.dig("attributes", "error.message")
|
|
300
|
+
}
|
|
301
|
+
end
|
|
302
|
+
|
|
303
|
+
# Stores a trace that arrived over OpenTelemetry's protocol (decoded by
|
|
304
|
+
# ActiveAgents::Telemetry::OTLP), or adds its spans to the trace already
|
|
305
|
+
# stored under that id.
|
|
306
|
+
#
|
|
307
|
+
# Unlike the native reporter, which sends a trace once and whole, an
|
|
308
|
+
# OpenTelemetry exporter sends spans as they end: one trace arrives over
|
|
309
|
+
# several requests, children before their parents. So a second arrival
|
|
310
|
+
# is more of the same trace, not a duplicate to skip.
|
|
311
|
+
#
|
|
312
|
+
# @param trace [Hash] one of OTLP.decode's traces
|
|
313
|
+
# @param sdk_info [Hash] the decode result's sdk
|
|
314
|
+
# @param account [Object, nil] the tenant, in multi-tenant mode
|
|
315
|
+
# @return [TelemetryTrace]
|
|
316
|
+
def self.ingest_otlp(trace, sdk_info = {}, account: nil)
|
|
317
|
+
scope = where(trace_id: trace["trace_id"])
|
|
318
|
+
scope = scope.where(account: account) if ActionAgent.multi_tenant? && account
|
|
319
|
+
|
|
320
|
+
existing = scope.first
|
|
321
|
+
existing ||= begin
|
|
322
|
+
return create_from_payload(trace, sdk_info, account: account)
|
|
323
|
+
rescue ActiveRecord::RecordNotUnique
|
|
324
|
+
# Another request carrying spans of this trace stored it first.
|
|
325
|
+
scope.first!
|
|
326
|
+
end
|
|
327
|
+
|
|
328
|
+
# Only a trace that itself arrived over OTLP grows. One the native
|
|
329
|
+
# reporter or a dashboard run stored is complete, and a second arrival
|
|
330
|
+
# under its id is skipped, as native ingest skips it.
|
|
331
|
+
return existing unless existing.otlp?
|
|
332
|
+
|
|
333
|
+
existing.absorb_otlp_spans!(trace["spans"])
|
|
334
|
+
end
|
|
335
|
+
|
|
336
|
+
# Whether this trace arrived over OpenTelemetry's protocol.
|
|
337
|
+
def otlp?
|
|
338
|
+
sdk_info.is_a?(Hash) && sdk_info["protocol"] == "otlp"
|
|
339
|
+
end
|
|
340
|
+
|
|
341
|
+
# Adds later-arriving spans of this OpenTelemetry trace and recomputes
|
|
342
|
+
# everything derived from them. Locks the row: two requests carrying
|
|
343
|
+
# spans of one trace are often processed at the same moment.
|
|
344
|
+
#
|
|
345
|
+
# @param incoming [Array<Hash>] spans in the native format
|
|
346
|
+
# @return [self]
|
|
347
|
+
def absorb_otlp_spans!(incoming)
|
|
348
|
+
with_lock do
|
|
349
|
+
known = Array(spans).to_h { |span| [ span["span_id"], true ] }
|
|
350
|
+
room = [ MAX_OTLP_SPANS - known.size, 0 ].max
|
|
351
|
+
fresh = Array(incoming).reject { |span| known[span["span_id"]] }.first(room)
|
|
352
|
+
replaced = Array(incoming).select { |span| known[span["span_id"]] }
|
|
353
|
+
|
|
354
|
+
merged = ActiveAgents::Telemetry::OTLP::Assembler.merge(
|
|
355
|
+
{ "trace_id" => trace_id, "service_name" => service_name, "spans" => spans },
|
|
356
|
+
replaced + fresh
|
|
357
|
+
)
|
|
358
|
+
update!(
|
|
359
|
+
spans: merged["spans"],
|
|
360
|
+
timestamp: Time.parse(merged["timestamp"]),
|
|
361
|
+
**self.class.derived_attributes(merged["spans"])
|
|
362
|
+
)
|
|
363
|
+
end
|
|
364
|
+
|
|
365
|
+
AgentRegistrar.call(self)
|
|
366
|
+
attach_agent_version!
|
|
367
|
+
self
|
|
368
|
+
end
|
|
369
|
+
|
|
290
370
|
# The input, output and thinking tokens +spans+ add up to.
|
|
291
371
|
#
|
|
292
372
|
# Instrumentation mirrors LLM token usage onto the root span for display,
|
|
@@ -47,6 +47,7 @@ module ActionAgent
|
|
|
47
47
|
class ScenarioEvaluationRunner < EvaluationRunnerService
|
|
48
48
|
Evals = ActiveAgent::Evals
|
|
49
49
|
JUDGE_LEASE_DURATION = 30.minutes
|
|
50
|
+
REPLAY_LEASE_DURATION = 30.minutes
|
|
50
51
|
|
|
51
52
|
# The providers a candidate model name resolves against. `mock` is the
|
|
52
53
|
# framework's test double, accepted so the test suite can compare cohorts
|
|
@@ -82,10 +83,15 @@ module ActionAgent
|
|
|
82
83
|
end
|
|
83
84
|
|
|
84
85
|
def call
|
|
86
|
+
pending = @run || @evaluation.evaluation_runs.create!(status: :pending)
|
|
87
|
+
# Another worker started this run (a job delivered twice, or handed to
|
|
88
|
+
# two workers): it is theirs to finish, so nothing here writes to it.
|
|
89
|
+
return pending.reload unless claim!(pending)
|
|
90
|
+
|
|
91
|
+
run = pending
|
|
85
92
|
scenarios = selected_scenarios
|
|
86
93
|
specs = model_specs
|
|
87
|
-
run
|
|
88
|
-
run.update!(status: :running, selection: selection_summary(scenarios, specs))
|
|
94
|
+
run.update!(selection: selection_summary(scenarios, specs))
|
|
89
95
|
record_pass_thresholds!(run)
|
|
90
96
|
ensure_sandbox_live!
|
|
91
97
|
|
|
@@ -173,6 +179,13 @@ module ActionAgent
|
|
|
173
179
|
# Replays one scenario under one model and stores the answer as a pending
|
|
174
180
|
# result, then enqueues its scoring. A result already stored for the
|
|
175
181
|
# pair (a retried job) is not replayed again.
|
|
182
|
+
#
|
|
183
|
+
# The replay is claimed before the agent runs, so a second delivery of
|
|
184
|
+
# the job (a queue redelivering it, or handing it to two workers) does
|
|
185
|
+
# not call the provider and the agent's tools a second time. A delivery
|
|
186
|
+
# that finds the pair claimed comes back when the claim expires (see
|
|
187
|
+
# #claim_replay!): by then the owner has stored the result, or stopped
|
|
188
|
+
# and left the pair to it.
|
|
176
189
|
def replay_scenario!(run, scenario_id, spec_value)
|
|
177
190
|
return unless run.running?
|
|
178
191
|
|
|
@@ -180,9 +193,21 @@ module ActionAgent
|
|
|
180
193
|
spec = model_spec_from(spec_value)
|
|
181
194
|
row = stored_result(run, scenario, spec)
|
|
182
195
|
unless row
|
|
196
|
+
key = replay_key(scenario, spec)
|
|
197
|
+
held_until = claim_replay!(run, key)
|
|
198
|
+
if held_until
|
|
199
|
+
EvaluationReplayJob.set(wait_until: held_until).perform_later(run.id, scenario.id, spec_value, @selection.to_h)
|
|
200
|
+
return
|
|
201
|
+
end
|
|
202
|
+
return unless @replay_token # the run stopped running
|
|
203
|
+
|
|
183
204
|
task = Evals::Scenario.from_hash(scenario.as_json_summary)
|
|
184
205
|
replay = fan_out_replay(task, spec)
|
|
185
|
-
row = run.with_lock
|
|
206
|
+
row = run.with_lock do
|
|
207
|
+
stored = stored_result(run, scenario, spec) || store_replay(run, scenario, task, spec, replay).tap { |created| @stored_result_id = created.id }
|
|
208
|
+
release_replay!(run, key)
|
|
209
|
+
stored
|
|
210
|
+
end
|
|
186
211
|
end
|
|
187
212
|
EvaluationJudgeJob.perform_later(row.id, @selection.to_h, run.id) if row.pending?
|
|
188
213
|
row
|
|
@@ -227,6 +252,12 @@ module ActionAgent
|
|
|
227
252
|
# replay (which records its own errors), so the run still completes. A
|
|
228
253
|
# scenario removed from the suite during the run has no result to
|
|
229
254
|
# store; the run completes without it (see #finish_fan_out!).
|
|
255
|
+
#
|
|
256
|
+
# Only this delivery's own pair is failed: one with no result yet and
|
|
257
|
+
# no other delivery replaying it, or the result this runner stored. A
|
|
258
|
+
# result another delivery stored is that delivery's to score, and a
|
|
259
|
+
# pair another delivery has claimed is its to store, so a duplicate
|
|
260
|
+
# delivery's failure cannot turn a good replay into an error.
|
|
230
261
|
def fail_result!(run, scenario_id, spec_value, error)
|
|
231
262
|
return unless run.running?
|
|
232
263
|
|
|
@@ -235,8 +266,15 @@ module ActionAgent
|
|
|
235
266
|
spec = model_spec_from(spec_value)
|
|
236
267
|
run.with_lock do
|
|
237
268
|
row = stored_result(run, scenario, spec)
|
|
238
|
-
|
|
239
|
-
|
|
269
|
+
if row.nil?
|
|
270
|
+
next if replay_claimed_elsewhere?(run, replay_key(scenario, spec))
|
|
271
|
+
|
|
272
|
+
task = Evals::Scenario.from_hash(scenario.as_json_summary)
|
|
273
|
+
row = store_replay(run, scenario, task, spec, Evals::Replay.failed(error))
|
|
274
|
+
@stored_result_id = row.id
|
|
275
|
+
end
|
|
276
|
+
next unless row.id == @stored_result_id
|
|
277
|
+
|
|
240
278
|
attributes = { status: :errored, error_message: row.error_message.presence || error_text(error) }
|
|
241
279
|
if scoring_leases?
|
|
242
280
|
# Another replay delivery may fail while this result is being
|
|
@@ -291,6 +329,24 @@ module ActionAgent
|
|
|
291
329
|
|
|
292
330
|
private
|
|
293
331
|
|
|
332
|
+
# Moves the run from pending to running in one conditional update, as
|
|
333
|
+
# AgentExecutionJob#claim_pending claims an agent run, and returns
|
|
334
|
+
# whether this runner is the one that did. Of two workers that loaded
|
|
335
|
+
# the run as pending, only the first to write replays the suite (or fans
|
|
336
|
+
# it out); the other replays nothing and leaves the run alone. The claim
|
|
337
|
+
# comes before the selection is read, so a selection that cannot be
|
|
338
|
+
# resolved fails the run rather than leaving it pending. Nothing is held
|
|
339
|
+
# over the replays.
|
|
340
|
+
def claim!(run)
|
|
341
|
+
now = Time.current
|
|
342
|
+
claimed = EvaluationRun.where(id: run.id, status: EvaluationRun.statuses[:pending])
|
|
343
|
+
.update_all(status: EvaluationRun.statuses[:running], updated_at: now)
|
|
344
|
+
return false if claimed.zero?
|
|
345
|
+
|
|
346
|
+
run.reload
|
|
347
|
+
true
|
|
348
|
+
end
|
|
349
|
+
|
|
294
350
|
def fan_out?(adapter)
|
|
295
351
|
ActionAgent.scenario_evaluation_fan_out == true && adapter.nil? && !browser_requested? &&
|
|
296
352
|
Evals::Runner.instance_method(:initialize).parameters.any? { |_type, name| name == :refine_gate }
|
|
@@ -404,6 +460,70 @@ module ActionAgent
|
|
|
404
460
|
(%w[scoring_token scoring_expires_at] - EvaluationScenarioResult.column_names).empty?
|
|
405
461
|
end
|
|
406
462
|
|
|
463
|
+
# A pair's replay claim, kept with the run's fan-out bookkeeping
|
|
464
|
+
# (scores["_fan_out"]["replays"]) until the replay is stored, so no
|
|
465
|
+
# migration is needed. The result row cannot hold it: the row is
|
|
466
|
+
# created only once there is an answer to store, and nothing makes a
|
|
467
|
+
# pair's row unique to create it earlier.
|
|
468
|
+
def replay_key(scenario, spec)
|
|
469
|
+
"#{scenario.id}:#{spec.provider}/#{spec.model}"
|
|
470
|
+
end
|
|
471
|
+
|
|
472
|
+
# Claims the pair's replay for this runner (its token in @replay_token)
|
|
473
|
+
# and returns nil, or returns when another delivery's live claim
|
|
474
|
+
# expires. An expired claim is taken over: its worker stopped, or is
|
|
475
|
+
# still replaying after REPLAY_LEASE_DURATION, in which case the two
|
|
476
|
+
# replays overlap and the first to store its answer is kept. A run no
|
|
477
|
+
# longer running claims nothing (@replay_token stays nil).
|
|
478
|
+
#
|
|
479
|
+
# This holds one active replay per pair across ordinary duplicate
|
|
480
|
+
# deliveries. It is not exactly once: a worker that stops after the
|
|
481
|
+
# provider answered and before the result is stored is replayed again.
|
|
482
|
+
def claim_replay!(run, key)
|
|
483
|
+
@replay_token = nil
|
|
484
|
+
token = SecureRandom.uuid
|
|
485
|
+
held_until = nil
|
|
486
|
+
update_fan_out_state!(run) do |state|
|
|
487
|
+
now = Time.current
|
|
488
|
+
replays = state["replays"].is_a?(Hash) ? state["replays"] : {}
|
|
489
|
+
expires_at = replay_expiry(replays[key])
|
|
490
|
+
if expires_at && expires_at > now
|
|
491
|
+
held_until = expires_at
|
|
492
|
+
next state
|
|
493
|
+
end
|
|
494
|
+
|
|
495
|
+
@replay_token = token
|
|
496
|
+
state.merge("replays" => replays.merge(key => { "token" => token, "expires_at" => (now + REPLAY_LEASE_DURATION).iso8601(6) }))
|
|
497
|
+
end
|
|
498
|
+
held_until
|
|
499
|
+
end
|
|
500
|
+
|
|
501
|
+
# Drops this runner's claim once its replay is stored. A claim another
|
|
502
|
+
# delivery took over is left to that delivery. Called under the run's
|
|
503
|
+
# lock, after the store.
|
|
504
|
+
def release_replay!(run, key)
|
|
505
|
+
return unless run.running?
|
|
506
|
+
|
|
507
|
+
state = fan_out_state(run)
|
|
508
|
+
replays = state["replays"].is_a?(Hash) ? state["replays"] : {}
|
|
509
|
+
return unless @replay_token && replays.dig(key, "token") == @replay_token
|
|
510
|
+
|
|
511
|
+
scores = run.scores.is_a?(Hash) ? run.scores : {}
|
|
512
|
+
run.update!(scores: scores.merge("_fan_out" => state.merge("replays" => replays.except(key))))
|
|
513
|
+
end
|
|
514
|
+
|
|
515
|
+
def replay_claimed_elsewhere?(run, key)
|
|
516
|
+
claim = fan_out_state(run)["replays"].to_h[key]
|
|
517
|
+
expires_at = replay_expiry(claim)
|
|
518
|
+
expires_at.present? && expires_at > Time.current && claim["token"] != @replay_token
|
|
519
|
+
end
|
|
520
|
+
|
|
521
|
+
def replay_expiry(claim)
|
|
522
|
+
Time.iso8601(claim["expires_at"].to_s) if claim.is_a?(Hash)
|
|
523
|
+
rescue ArgumentError
|
|
524
|
+
nil
|
|
525
|
+
end
|
|
526
|
+
|
|
407
527
|
# What Evals::Runner does with a replay that raises: an errored replay,
|
|
408
528
|
# scored like any other.
|
|
409
529
|
def fan_out_replay(task, spec)
|
data/config/routes.rb
CHANGED
|
@@ -27,6 +27,11 @@ ActionAgent::Engine.routes.draw do
|
|
|
27
27
|
# Authenticated with a bearer token, not a session.
|
|
28
28
|
resources :traces, only: [ :create ]
|
|
29
29
|
|
|
30
|
+
# The same ingest for OpenTelemetry exporters given a base endpoint
|
|
31
|
+
# (OTEL_EXPORTER_OTLP_ENDPOINT=<mount>/api/otlp), which append
|
|
32
|
+
# /v1/traces to it. The controller reads OTLP at either path.
|
|
33
|
+
post "otlp/v1/traces", to: "traces#create"
|
|
34
|
+
|
|
30
35
|
# The collector for evaluation reports an application ran itself
|
|
31
36
|
# (ActiveAgent::Evals::Publisher), at <mount>/api/evaluation_reports.
|
|
32
37
|
# Authenticated like trace ingest, with a bearer token. GET
|
data/lib/action_agent/version.rb
CHANGED
data/lib/action_agent.rb
CHANGED
|
@@ -829,6 +829,18 @@ module ActionAgent
|
|
|
829
829
|
# @return [ActiveSupport::Duration, nil]
|
|
830
830
|
attr_accessor :input_request_ttl
|
|
831
831
|
|
|
832
|
+
# How long a claimed run stays its worker's without news from it. Each
|
|
833
|
+
# claim (the execution job's, the resume job's, a synchronous test run's)
|
|
834
|
+
# takes a lease this long under a token of its own, and each LLM or tool
|
|
835
|
+
# call the run makes renews it. A run whose lease ran out is failed as
|
|
836
|
+
# lost once its page, the run list or AgentRunExpiryJob reaches it, and a
|
|
837
|
+
# worker that finishes after that has its result discarded. Nothing is
|
|
838
|
+
# executed again. 30 minutes by default: one provider call longer than
|
|
839
|
+
# this, with no progress in between, is taken for a lost worker. nil
|
|
840
|
+
# takes no leases, as before migration 036.
|
|
841
|
+
# @return [ActiveSupport::Duration, nil]
|
|
842
|
+
attr_accessor :run_lease_duration
|
|
843
|
+
|
|
832
844
|
# Whether API keys and provider credentials are encrypted at rest with
|
|
833
845
|
# Active Record Encryption. On by default, which requires the host app
|
|
834
846
|
# to have run `rails db:encryption:init`. Turning it off stores those
|
|
@@ -1356,6 +1368,7 @@ module ActionAgent
|
|
|
1356
1368
|
@agent_polymorphic_name = nil
|
|
1357
1369
|
@encrypt_credentials = true
|
|
1358
1370
|
@input_request_ttl = 1.day
|
|
1371
|
+
@run_lease_duration = 30.minutes
|
|
1359
1372
|
@github_client_id = nil
|
|
1360
1373
|
@github_client_secret = nil
|
|
1361
1374
|
@github_oauth_scopes = "repo read:user"
|
|
@@ -169,6 +169,17 @@ ActionAgent.configure do |config|
|
|
|
169
169
|
#
|
|
170
170
|
# config.input_request_ttl = 1.day
|
|
171
171
|
|
|
172
|
+
# ==========================================================================
|
|
173
|
+
# Agent runs
|
|
174
|
+
# ==========================================================================
|
|
175
|
+
#
|
|
176
|
+
# How long a running run stays its worker's without progress (an LLM or
|
|
177
|
+
# tool call) before it is failed as lost. Its result is then discarded if
|
|
178
|
+
# the worker was only slow; nothing is run again. Schedule
|
|
179
|
+
# ActionAgent::AgentRunExpiryJob to fail the lost runs nobody looks at.
|
|
180
|
+
#
|
|
181
|
+
# config.run_lease_duration = 30.minutes
|
|
182
|
+
|
|
172
183
|
# ==========================================================================
|
|
173
184
|
# Host integration
|
|
174
185
|
# ==========================================================================
|
data/lib/generators/action_agent/templates/migrations/036_add_agent_run_execution_leases.rb.erb
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
class AddAgentRunExecutionLeases < ActiveRecord::Migration<%= migration_version %>
|
|
4
|
+
def change
|
|
5
|
+
add_column "#{ActionAgent.table_name_prefix}agent_runs", :execution_token, :string
|
|
6
|
+
add_column "#{ActionAgent.table_name_prefix}agent_runs", :execution_expires_at, :datetime
|
|
7
|
+
add_index "#{ActionAgent.table_name_prefix}agent_runs", [ :status, :execution_expires_at ],
|
|
8
|
+
name: "index_#{ActionAgent.table_name_prefix}agent_runs_on_status_and_lease"
|
|
9
|
+
end
|
|
10
|
+
end
|
metadata
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: actionagent
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 1.9.
|
|
4
|
+
version: 1.9.10
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Justin Bowen
|
|
8
8
|
autorequire:
|
|
9
9
|
bindir: bin
|
|
10
10
|
cert_chain: []
|
|
11
|
-
date: 2026-
|
|
11
|
+
date: 2026-12-04 00:00:00.000000000 Z
|
|
12
12
|
dependencies:
|
|
13
13
|
- !ruby/object:Gem::Dependency
|
|
14
14
|
name: activeagent
|
|
@@ -189,6 +189,7 @@ files:
|
|
|
189
189
|
- app/controllers/concerns/action_agent/api/run_sandbox.rb
|
|
190
190
|
- app/jobs/action_agent/agent_execution_job.rb
|
|
191
191
|
- app/jobs/action_agent/agent_resume_job.rb
|
|
192
|
+
- app/jobs/action_agent/agent_run_expiry_job.rb
|
|
192
193
|
- app/jobs/action_agent/application_job.rb
|
|
193
194
|
- app/jobs/action_agent/code_session_job.rb
|
|
194
195
|
- app/jobs/action_agent/draft_pull_request_job.rb
|
|
@@ -385,6 +386,7 @@ files:
|
|
|
385
386
|
- lib/generators/action_agent/templates/migrations/032_create_active_agent_mcp_server_configs.rb.erb
|
|
386
387
|
- lib/generators/action_agent/templates/migrations/034_add_catalog_product_criteria.rb.erb
|
|
387
388
|
- lib/generators/action_agent/templates/migrations/035_add_catalog_pass_bars.rb.erb
|
|
389
|
+
- lib/generators/action_agent/templates/migrations/036_add_agent_run_execution_leases.rb.erb
|
|
388
390
|
- lib/tasks/action_agent.rake
|
|
389
391
|
- lib/tasks/browser.rake
|
|
390
392
|
- lib/tasks/claude_code.rake
|