Module: Bitfab::Replay

Defined in:
lib/bitfab/replay.rb

Overview

Replay historical traces through a traced method and create a test run.

Class Method Summary collapse

Class Method Details

.build_mock_tree(root) ⇒ Object

Walk the children of a root span tree node depth-first and build a lookup keyed by “#trace_function_key:#span_name:#call_index”.

The root node itself is excluded — at replay time the runtime root span never queries the mock tree.

The compound (key, name) match disambiguates same-key spans that come from the fluent ‘client.get_function(key).wrap(…)` pattern: every wrapped method shares trace_function_key but differs in span_name. The counter is per-(key, name) pair so repeated same-name calls (including recursion) still order by occurrence. Mirrors the Python and TypeScript SDKs after HVT-2078 — keying by trace_function_key alone caused the wrong historical output for fluent-API span sets.



221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/bitfab/replay.rb', line 221

def build_mock_tree(root)
  spans = {}
  counters = {}

  walk = lambda do |node|
    key = node["traceFunctionKey"]
    if key && !key.empty?
      name = node["spanName"]
      name = key if name.nil? || name.empty?
      counter_key = "#{key}:#{name}"
      index = counters[counter_key] || 0
      counters[counter_key] = index + 1
      spans["#{counter_key}:#{index}"] = {
        source_span_id: node["sourceSpanId"],
        output: node["output"],
        output_meta: node["outputMeta"]
      }
    end
    (node["children"] || []).each { |child| walk.call(child) }
  end

  (root["children"] || []).each { |child| walk.call(child) }

  spans
end

.execute_item(item, receiver, method_name, test_run_id, input_source_span_id = nil, metrics = {}, input_source_trace_id: nil, mock_strategy: "none", mock_tree: nil) ⇒ Object

Execute a single replay item: deserialize inputs, call method with replay context.



282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/bitfab/replay.rb', line 282

def execute_item(item, receiver, method_name, test_run_id, input_source_span_id = nil, metrics = {},
  input_source_trace_id: nil, mock_strategy: "none", mock_tree: nil)
  args, kwargs = Serialize.deserialize_inputs(item)

  fn_result = nil
  fn_error = nil
  sdk_trace_id = SecureRandom.uuid

  ReplayContext.with_context(
    test_run_id:,
    input_source_span_id:,
    input_source_trace_id:,
    trace_id: sdk_trace_id,
    mock_tree:,
    mock_strategy:
  ) do
    fn_result = if kwargs.empty?
      receiver.send(method_name, *args)
    else
      receiver.send(method_name, *args, **kwargs)
    end
  rescue => e
    fn_error = e.message
  end

  {
    input: args,
    result: fn_result,
    original_output: item["output"],
    error: fn_error,
    duration_ms: metrics[:duration_ms],
    tokens: metrics[:tokens],
    model: metrics[:model],
    trace_id: sdk_trace_id
  }
end

.extract_server_item_metrics(server_item) ⇒ Object

Pull durationMs / tokens / model from the start-replay server item. Normalizes to symbol-keyed tokens hash and nil-safe defaults so older servers without these fields still produce a consistent shape.



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/bitfab/replay.rb', line 263

def extract_server_item_metrics(server_item)
  raw_tokens = server_item["tokens"]
  tokens = if raw_tokens.is_a?(Hash)
    {
      input: raw_tokens["input"],
      output: raw_tokens["output"],
      cached: raw_tokens["cached"],
      total: raw_tokens["total"]
    }
  end

  {
    duration_ms: server_item["durationMs"],
    tokens:,
    model: server_item["model"]
  }
end

.extract_span_data(span) ⇒ Object

Extract input/output data from an external span’s rawData.



248
249
250
251
252
253
254
255
256
257
258
# File 'lib/bitfab/replay.rb', line 248

def extract_span_data(span)
  raw_data = span["rawData"] || {}
  span_data = raw_data["span_data"] || {}

  {
    "input" => span_data["input"],
    "output" => span_data["output"],
    "inputSerialized" => span_data["input_serialized"],
    "outputSerialized" => span_data["output_serialized"]
  }
end

.process_items(http_client, server_items, receiver, method_name, test_run_id, max_concurrency, mock_strategy) ⇒ Object

Process all replay items, optionally in parallel using threads.



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/bitfab/replay.rb', line 135

def process_items(http_client, server_items, receiver, method_name, test_run_id, max_concurrency, mock_strategy)
  concurrency = max_concurrency || server_items.length

  if concurrency <= 1
    server_items.map do |item|
      process_single_item(http_client, item, receiver, method_name, test_run_id, mock_strategy)
    end
  else
    results_mutex = Mutex.new
    results = []
    work_queue = server_items.each_with_index.to_a
    work_mutex = Mutex.new

    workers = [concurrency, server_items.length].min.times.map do
      Thread.new do
        loop do
          item, idx = work_mutex.synchronize { work_queue.shift }
          break unless item

          result = process_single_item(http_client, item, receiver, method_name, test_run_id, mock_strategy)
          results_mutex.synchronize { results[idx] = result }
        end
      end
    end

    workers.each(&:join)
    results.compact
  end
end

.process_single_item(http_client, server_item, receiver, method_name, test_run_id, mock_strategy) ⇒ Object

Fetch span data and execute a single replay item.

Any error while fetching the span, building the mock tree, or deserializing inputs is captured on the returned item’s :error rather than propagated, so one bad trace never aborts the whole replay run (mirrors the TypeScript and Python SDKs’ per-item rescue).



171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/bitfab/replay.rb', line 171

def process_single_item(http_client, server_item, receiver, method_name, test_run_id, mock_strategy)
  metrics = extract_server_item_metrics(server_item)

  span = http_client.get_external_span(server_item["externalSpanId"])
  item_data = extract_span_data(span)

  mock_tree = nil
  if mock_strategy == "all" || mock_strategy == "marked"
    tree = http_client.get_span_tree(server_item["externalSpanId"])
    mock_tree = build_mock_tree(tree["root"] || {})
  end

  execute_item(
    item_data,
    receiver,
    method_name,
    test_run_id,
    span["id"],
    metrics,
    input_source_trace_id: span["externalTraceId"],
    mock_strategy:,
    mock_tree:
  )
rescue => e
  warn "Bitfab: replay item for span #{server_item["externalSpanId"]} failed before execution: #{e.message}"
  {
    input: [],
    result: nil,
    original_output: nil,
    error: e.message,
    duration_ms: metrics&.dig(:duration_ms),
    tokens: metrics&.dig(:tokens),
    model: metrics&.dig(:model),
    trace_id: nil
  }
end

.run(client, receiver, method_name, trace_function_key:, limit: nil, trace_ids: nil, max_concurrency: 10, code_change_description: nil, code_change_files: nil, experiment_group_id: nil, mock: "none") ⇒ Hash

Replay historical traces through a method and create a test run.

Fetches the last N traces for the given trace function key, re-runs each through the provided receiver and method, and returns comparison data.

Parameters:

  • client (Bitfab::Client)

    the Bitfab client instance

  • receiver (Object, Class)

    an instance for instance methods, or a Class for class methods

  • method_name (Symbol)

    the method to replay

  • trace_function_key (String)

    the trace function key for this method

  • limit (Integer, nil) (defaults to: nil)

    maximum number of traces to replay (default: 5). Mutually exclusive with trace_ids: an explicit ID list already determines how many traces replay, so passing both raises.

  • trace_ids (Array<String>, nil) (defaults to: nil)

    optional list of trace IDs to replay (max 100)

  • max_concurrency (Integer, nil) (defaults to: 10)

    max threads for parallel replay (default: 10)

  • code_change_description (String, nil) (defaults to: nil)

    optional rationale for the code change being tested in this replay (stored on the experiment)

  • code_change_files (Array<Hash>, nil) (defaults to: nil)

    optional list of edited files, each as { path:, before:, after: } (empty string for new/deleted files)

  • experiment_group_id (String, nil) (defaults to: nil)

    optional UUID grouping multiple replay runs into a single experiment batch

  • mock (String) (defaults to: "none")

    mock strategy for child spans: “none” (default), “all”, or “marked”. “all” mocks every child span; “marked” only mocks spans declared with mock_on_replay: true.

Returns:

  • (Hash)

    with :items, :test_run_id, :test_run_url



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/bitfab/replay.rb', line 74

def run(client, receiver, method_name, trace_function_key:, limit: nil, trace_ids: nil, max_concurrency: 10,
  code_change_description: nil, code_change_files: nil, experiment_group_id: nil, mock: "none")
  unless MOCK_STRATEGIES.include?(mock.to_s)
    raise ArgumentError, "Invalid mock strategy '#{mock}'. Must be one of: #{MOCK_STRATEGIES.join(", ")}"
  end
  if trace_ids
    raise ArgumentError, "trace_ids must contain at least one trace ID." if trace_ids.empty?
    if trace_ids.length > 100
      raise ArgumentError, "trace_ids supports at most 100 trace IDs per replay (got #{trace_ids.length})."
    end
  end
  if limit && trace_ids
    raise ArgumentError,
      "Pass either limit or trace_ids, not both: an explicit trace ID list already determines how many traces replay."
  end

  http_client = client.instance_variable_get(:@http_client)

  # limit is meaningless with explicit trace_ids (the ID list determines
  # the count), so it's omitted from the request entirely.
  effective_limit = trace_ids ? nil : (limit || 5)

  replay_data = http_client.start_replay(
    trace_function_key,
    effective_limit,
    trace_ids:,
    code_change_description:,
    code_change_files:,
    experiment_group_id:
  )
  test_run_id = replay_data["testRunId"]
  test_run_url = replay_data["testRunUrl"]
  server_items = replay_data["items"] || []

  result_items = if server_items.any?
    process_items(http_client, server_items, receiver, method_name, test_run_id, max_concurrency, mock.to_s)
  else
    []
  end

  Bitfab.flush_traces

  begin
    complete_response = http_client.complete_replay(test_run_id)
    trace_id_map = complete_response&.dig("traceIds") || {}
    result_items.each do |item|
      item[:trace_id] = trace_id_map[item[:trace_id]]
    end
  rescue => e
    warn "Bitfab: Failed to complete replay: #{e.message}"
    result_items.each { |item| item[:trace_id] = nil }
  end

  {
    items: result_items,
    test_run_id:,
    test_run_url: "#{client.service_url}#{test_run_url}"
  }
end