actionagent 1.9.9 → 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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 5f8ad45415f0faa3e84cd38c32ceeb8f1b59a2240b5a9bbcced702a2ddd6d246
4
- data.tar.gz: 5e8315eca89021eb8a54abb1282f6c74721eff39c380e14bcadd8904930c70b2
3
+ metadata.gz: 49930b222cf8e63f63fa43755877aab31c38bd840bd737ad98889f3e40a5a180
4
+ data.tar.gz: 0b4f401bdc7936566270788ab269964bce1b12ada5a464cf9426a4352e2ce212
5
5
  SHA512:
6
- metadata.gz: 65b3d15741034542a8f72a99022da4bc79bd0c6ef510a75482453b02c069f96b6085d20a1c27aa0a14eaa77b1a9c629d4d53752974664aa60e12beff90fb7c33
7
- data.tar.gz: a6bc5006b281eaed9717ce3dbb6225b6e005ef81b3e6a37b29463a9b55f963c526fb5ab8734d6f5961d99aeaa07eef23fde6d37c11a0ce2f1c59b48daabe8055
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
@@ -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. Returns whether it yielded.
405
- def unless_cancelled
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
- total_duration_ms: total_duration,
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,
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
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module ActionAgent
4
- VERSION = "1.9.9"
4
+ VERSION = "1.9.10"
5
5
  end
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
  # ==========================================================================
@@ -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.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-19 00:00:00.000000000 Z
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