bitfab 0.78.4 → 0.78.5

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.
@@ -0,0 +1,1434 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "base64"
4
+ require "fileutils"
5
+ require "json"
6
+ require "net/http"
7
+ require "open3"
8
+ require "rbconfig"
9
+ require "securerandom"
10
+ require "tmpdir"
11
+ require "uri"
12
+ require "zlib"
13
+
14
+ module Bitfab
15
+ module CloudExecute
16
+ WORKFLOW = "bitfab-replay.yml"
17
+ WORKFLOW_NAMES = [WORKFLOW, "bitfab-replay.yaml"].freeze
18
+ WORKFLOW_DIRECTORY = ".github/workflows"
19
+ PREFIX = "bitfab-replay/"
20
+ REPLAY_COMMAND_ENV = "BITFAB_REPLAY_COMMAND"
21
+ CHECK_COMMAND_ENV = "BITFAB_REPLAY_CHECK"
22
+ EXECUTION_TARGET_ENV = "BITFAB_REPLAY_EXECUTION_TARGET"
23
+ HOSTED_EXECUTION_TARGET = "hosted"
24
+ API_KEY_ENV = "BITFAB_REPLAY_BITFAB_API_KEY"
25
+ PRINT_API_KEY_FLAG = "--print-api-key"
26
+ API_KEY_LINE = "@@bitfab:api-key "
27
+ KEY_INPUT = "key_id"
28
+ KEY_TOKEN_PREFIX = "bfcr_"
29
+ DEFAULT_SERVICE_URL = "https://bitfab.ai"
30
+ OIDC_AUDIENCE = "bitfab-cloud-replay"
31
+ API_KEY_PROBE_SECONDS = 120
32
+ REQUEST_VERSION = 4
33
+ PLAIN_REQUEST_VERSION = 3
34
+ OLDEST_DISPATCHED_VERSION = 2
35
+ RESULT_LINE = "bitfab-replay-result "
36
+ RESULT_CHUNK = 4000
37
+ OUTPUT_BEGIN = "bitfab-replay-output-begin"
38
+ OUTPUT_END = "bitfab-replay-output-end"
39
+ OUTPUT_LIMIT = 16 * 1024 * 1024
40
+ DISK_LIMIT = 1024 * 1024 * 1024
41
+ ITEM_ERROR_FIELDS = %w[error traceError trace_error replayError replay_error].freeze
42
+ ITEM_ID_FIELDS = %w[originalTraceId original_trace_id traceId trace_id].freeze
43
+ ITEM_ERROR_LINES = 20
44
+ ITEM_ERROR_LENGTH = 500
45
+ SUMMARY_ERROR_ITEMS = 100
46
+ EXPERIMENT_FIELDS = {
47
+ "experimentId" => %w[experimentId experiment_id],
48
+ "experimentUrl" => %w[experimentUrl experiment_url],
49
+ "testRunId" => %w[testRunId test_run_id],
50
+ "testRunUrl" => %w[testRunUrl test_run_url],
51
+ "attempts" => %w[attempts]
52
+ }.freeze
53
+ UUID = /\A[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\z/
54
+ SHA = /\A[0-9a-f]{40}\z/
55
+ EXPERIMENT_LINE = /\A\[replay\] Experiment ([0-9a-f-]{36}):/
56
+ PROGRESS_PREFIX = "@@bitfab:progress "
57
+ PROGRESS_PAYLOAD_FIELDS = %w[input result originalOutput original_output selectiveReplay selective_replay].freeze
58
+ SECRET_REFERENCE = /["']?([A-Za-z_][A-Za-z0-9_]*)["']?[ \t]*:[ \t]*["']?\$\{\{\s*secrets(?:\.([A-Za-z_][A-Za-z0-9_]*)|\[\s*["']([A-Za-z_][A-Za-z0-9_]*)["']\s*\])\s*\}\}/
59
+ BRANCH_NAME = %r{\A[A-Za-z0-9][A-Za-z0-9._/-]*\z}
60
+ ENV_NAME = /\A[A-Za-z_][A-Za-z0-9_]*\z/
61
+ RESERVED_ENV_PREFIXES = %w[GITHUB_ RUNNER_ ACTIONS_ BITFAB_REPLAY_].freeze
62
+ SECRET_ENV_NAME = /(?:^|_)(?:KEY|SECRET|TOKEN|PASSWORD|PASSWD|CREDENTIALS?)(?:_|$)/i
63
+ ENV_FLAG = "--cloud-env"
64
+ URL_PASSWORD = %r{[A-Za-z][A-Za-z0-9+.-]*://[^/\s:@]*:[^/\s@]+@}
65
+ CODE_CHANGE_FLAG = "--code-change"
66
+ CODE_CHANGE_BASE_FLAG = "--code-change-base"
67
+ BRANCH_CODE_CHANGES = %w[last-branch default-branch ref].freeze
68
+ FETCHED_CODE_CHANGES = %w[default-branch ref].freeze
69
+ CHECKOUT_ONLY_CODE_CHANGES = %w[working-tree last-branch].freeze
70
+ GIT_TOKEN_ENV = "BITFAB_REPLAY_GIT_TOKEN"
71
+ FETCH_SECONDS = 600
72
+ DESCRIBED_REF = /\A[^\x00-\x1f\x7f]{1,200}\z/
73
+ CODE_CHANGE_PATH_ENV = "BITFAB_CODE_CHANGE_PATH"
74
+ CODE_CHANGE_MAX_FILES = 60
75
+ CODE_CHANGE_MAX_FILE_BYTES = 500_000
76
+ CODE_CHANGE_MAX_TOTAL_BYTES = 2_000_000
77
+ LINE_BREAKS = /\r\n|[\n\r\v\f\x1c\x1d\x1e\u0085

]/
78
+ REDIRECTS = [301, 302, 303, 307, 308].freeze
79
+ REDIRECT_LIMIT = 20
80
+ ARRAY_INDEX = /\A(?:0|[1-9][0-9]*)\z/
81
+ ARRAY_INDEX_LIMIT = 4_294_967_295
82
+ EXACT_INTEGER_LIMIT = 2**53
83
+ SURROGATE_STAND_IN = 0xF0000
84
+ STAND_INS = /[\u{F0000}-\u{F07FF}]/
85
+ LONE_SURROGATE_HINT = /\\u[dD][89a-fA-F]/
86
+ SURROGATE_ESCAPES = /\\u[dD][89abAB]\h{2}\\u[dD][c-fC-F]\h{2}|\\u([dD][89a-fA-F]\h{2})|\\./m
87
+ JS_ESCAPES = {"\"" => "\\\"", "\\" => "\\\\", "\b" => "\\b", "\f" => "\\f", "\n" => "\\n", "\r" => "\\r", "\t" => "\\t"}.freeze
88
+ JS_ESCAPED = /["\\\x00-\x1f]|[\u{F0000}-\u{F07FF}]/
89
+ JS_WHITESPACE = /\A[\s\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+|[\s\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+\z/
90
+ DECIMAL = /\A[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?\z/
91
+ CANCELLED = "the GitHub run was cancelled"
92
+ DETACHED = "Detached. A GitHub run that already started continues; follow it with --cloud-watch and the printed execution UUID, or stop it with --cloud-cancel and remove its snapshot branch with --cloud-cleanup once it completes"
93
+
94
+ class ValueError < StandardError; end
95
+
96
+ class CommandError < StandardError; end
97
+
98
+ class ProcessError < StandardError; end
99
+
100
+ class CommandTimeout < StandardError; end
101
+
102
+ class UnreachableError < StandardError
103
+ attr_reader :reason
104
+
105
+ def initialize(reason)
106
+ @reason = reason
107
+ super
108
+ end
109
+ end
110
+
111
+ class HttpFailure < StandardError
112
+ attr_reader :code, :body
113
+
114
+ def initialize(code, body)
115
+ @code = code
116
+ @body = body
117
+ super("HTTP Error #{code}")
118
+ end
119
+ end
120
+
121
+ class Cancelled < StandardError; end
122
+
123
+ Child = Struct.new(:pid, :status)
124
+
125
+ module_function
126
+
127
+ def utf8(text)
128
+ text.to_s.dup.force_encoding(Encoding::UTF_8).scrub
129
+ end
130
+
131
+ def env_value(name)
132
+ value = ENV[name]
133
+ value.nil? ? nil : utf8(value)
134
+ end
135
+
136
+ def say(text = "")
137
+ $stdout.write("#{text}\n")
138
+ $stdout.flush
139
+ end
140
+
141
+ def progress(text)
142
+ $stderr.write("[cloud] #{text}\n")
143
+ $stderr.flush
144
+ end
145
+
146
+ def js_value(value)
147
+ case value
148
+ when Hash then value.transform_values { |item| js_value(item) }
149
+ when Array then value.map { |item| js_value(item) }
150
+ when Float
151
+ (value.finite? && value == value.floor && value.abs < EXACT_INTEGER_LIMIT) ? value.to_i : value
152
+ when Integer
153
+ (value.abs < EXACT_INTEGER_LIMIT) ? value : value.to_f
154
+ else value
155
+ end
156
+ end
157
+
158
+ def stand_in_lone_surrogates(text)
159
+ return text unless text.match?(LONE_SURROGATE_HINT)
160
+ text.gsub(SURROGATE_ESCAPES) do |escape|
161
+ lone = Regexp.last_match(1)
162
+ lone ? (SURROGATE_STAND_IN + lone.hex - 0xd800).chr(Encoding::UTF_8) : escape
163
+ end
164
+ end
165
+
166
+ def parse_json(text)
167
+ js_value(JSON.parse(stand_in_lone_surrogates(utf8(text)), max_nesting: false, allow_duplicate_key: true))
168
+ rescue JSON::ParserError => error
169
+ raise ValueError, error.message
170
+ end
171
+
172
+ def js_integer?(value)
173
+ value.is_a?(Integer) || (value.is_a?(Float) && value.finite? && value == value.floor)
174
+ end
175
+
176
+ def js_number(value)
177
+ return "NaN" if value.nan?
178
+ return value.positive? ? "Infinity" : "-Infinity" if value.infinite?
179
+ return "0" if value.zero?
180
+ return value.to_i.to_s if value == value.floor && value.abs < EXACT_INTEGER_LIMIT
181
+ mantissa, exponent = value.abs.to_s.split("e")
182
+ whole, fraction = mantissa.split(".")
183
+ digits = whole + fraction.to_s
184
+ point = whole.length + exponent.to_i
185
+ significant = digits.sub(/\A0+/, "")
186
+ point -= digits.length - significant.length
187
+ digits = significant.sub(/0+\z/, "")
188
+ length = digits.length
189
+ body = if point.between?(length, 21)
190
+ digits + "0" * (point - length)
191
+ elsif point.positive? && point <= 21
192
+ "#{digits[0, point]}.#{digits[point..]}"
193
+ elsif point > -6 && point <= 0
194
+ "0.#{"0" * -point}#{digits}"
195
+ else
196
+ power = point - 1
197
+ suffix = "e#{power.negative? ? "-" : "+"}#{power.abs}"
198
+ (length == 1) ? "#{digits}#{suffix}" : "#{digits[0]}.#{digits[1..]}#{suffix}"
199
+ end
200
+ value.negative? ? "-#{body}" : body
201
+ end
202
+
203
+ def js_quote(text)
204
+ escaped = text.gsub(JS_ESCAPED) do |character|
205
+ code = character.ord
206
+ if code >= SURROGATE_STAND_IN
207
+ format("\\u%04x", code - SURROGATE_STAND_IN + 0xd800)
208
+ else
209
+ JS_ESCAPES[character] || format("\\u%04x", code)
210
+ end
211
+ end
212
+ "\"#{escaped}\""
213
+ end
214
+
215
+ def js_entries(hash)
216
+ indexes = hash.keys.select { |key| key.is_a?(String) && ARRAY_INDEX.match?(key) && key.to_i < ARRAY_INDEX_LIMIT }
217
+ ordered = indexes.sort_by(&:to_i) + (hash.keys - indexes)
218
+ ordered.map { |key| [key, hash[key]] }
219
+ end
220
+
221
+ def js_json(value)
222
+ case value
223
+ when nil then "null"
224
+ when true then "true"
225
+ when false then "false"
226
+ when Integer then value.to_s
227
+ when Float then value.finite? ? js_number(value) : "null"
228
+ when String then js_quote(value)
229
+ when Array then "[#{value.map { |item| js_json(item) }.join(",")}]"
230
+ when Hash then "{#{js_entries(value).map { |key, item| "#{js_quote(key.to_s)}:#{js_json(item)}" }.join(",")}}"
231
+ else js_quote(value.to_s)
232
+ end
233
+ end
234
+
235
+ def string_number(text)
236
+ trimmed = text.gsub(JS_WHITESPACE, "")
237
+ return 0 if trimmed.empty?
238
+ return Float::INFINITY if trimmed == "Infinity" || trimmed == "+Infinity"
239
+ return -Float::INFINITY if trimmed == "-Infinity"
240
+ return trimmed[2..].to_i(16) if trimmed.match?(/\A0[xX]\h+\z/)
241
+ return trimmed[2..].to_i(8) if trimmed.match?(/\A0[oO][0-7]+\z/)
242
+ return trimmed[2..].to_i(2) if trimmed.match?(/\A0[bB][01]+\z/)
243
+ return Float(trimmed.sub(/\A([+-]?)\./, "\\10.").sub(/\.(?=[eE]|\z)/, "")) if trimmed.match?(DECIMAL)
244
+ Float::NAN
245
+ end
246
+
247
+ def js_number_of(value)
248
+ case value
249
+ when true then 1
250
+ when false, nil then 0
251
+ when Numeric then value
252
+ when String then string_number(value)
253
+ when Array then string_number(js_string(value))
254
+ else Float::NAN
255
+ end
256
+ end
257
+
258
+ def parse_json_or_nil(text)
259
+ parse_json(text)
260
+ rescue ValueError
261
+ nil
262
+ end
263
+
264
+ def object?(value)
265
+ value.is_a?(Hash)
266
+ end
267
+
268
+ def truthy?(value)
269
+ !(value.nil? || value == false || value == 0 || value == "" || (value.is_a?(Float) && value.nan?))
270
+ end
271
+
272
+ def js_string(value)
273
+ case value
274
+ when String then value
275
+ when nil then "undefined"
276
+ when Hash then "[object Object]"
277
+ when Array then value.map { |item| item.nil? ? "" : js_string(item) }.join(",")
278
+ when Float then js_number(value)
279
+ else value.to_s
280
+ end
281
+ end
282
+
283
+ def ascii_string(text)
284
+ js_quote(text).each_char.map do |character|
285
+ code = character.ord
286
+ if code < 0x7f
287
+ character
288
+ elsif code > 0xffff
289
+ offset = code - 0x10000
290
+ format("\\u%04x\\u%04x", 0xd800 + (offset >> 10), 0xdc00 + (offset & 0x3ff))
291
+ else
292
+ format("\\u%04x", code)
293
+ end
294
+ end.join
295
+ end
296
+
297
+ def python_json(value)
298
+ case value
299
+ when nil then "null"
300
+ when String then ascii_string(value)
301
+ when Array then "[#{value.map { |item| python_json(item) }.join(", ")}]"
302
+ when Hash then "{#{js_entries(value).map { |key, item| "#{ascii_string(key.to_s)}: #{python_json(item)}" }.join(", ")}}"
303
+ else js_json(value)
304
+ end
305
+ end
306
+
307
+ def python_repr(value)
308
+ case value
309
+ when nil then "None"
310
+ when true then "True"
311
+ when false then "False"
312
+ when String then "'#{value.gsub("\\") { "\\\\" }.gsub("'") { "\\'" }}'"
313
+ else js_json(value)
314
+ end
315
+ end
316
+
317
+ def python_text(value)
318
+ case value
319
+ when true then "True"
320
+ when false then "False"
321
+ when String then value
322
+ else python_json(value)
323
+ end
324
+ end
325
+
326
+ def split_lines(text)
327
+ return [] if text.empty?
328
+ parts = text.split(LINE_BREAKS, -1)
329
+ parts.pop if parts.last == ""
330
+ parts
331
+ end
332
+
333
+ def partition(text, separator)
334
+ at = text.index(separator)
335
+ return [text, "", ""] if at.nil?
336
+ [text[0...at], separator, text[(at + separator.length)..]]
337
+ end
338
+
339
+ def shell_split(text)
340
+ parts = []
341
+ current = +""
342
+ started = false
343
+ quote = nil
344
+ index = 0
345
+ while index < text.length
346
+ character = text[index]
347
+ if quote == "'"
348
+ (character == "'") ? quote = nil : current << character
349
+ elsif quote == "\""
350
+ if character == "\""
351
+ quote = nil
352
+ elsif character == "\\" && index + 1 < text.length && ["\"", "\\"].include?(text[index + 1])
353
+ current << text[index + 1]
354
+ index += 1
355
+ else
356
+ current << character
357
+ end
358
+ elsif character.match?(/\s/)
359
+ if started
360
+ parts << current
361
+ current = +""
362
+ started = false
363
+ end
364
+ else
365
+ started = true
366
+ if character == "'" || character == "\""
367
+ quote = character
368
+ elsif character == "\\"
369
+ raise ValueError, "No escaped character" if index + 1 >= text.length
370
+ current << text[index + 1]
371
+ index += 1
372
+ else
373
+ current << character
374
+ end
375
+ end
376
+ index += 1
377
+ end
378
+ raise ValueError, "No closing quotation" unless quote.nil?
379
+ parts << current if started
380
+ parts
381
+ end
382
+
383
+ def run_process(args, cwd: nil, env: nil, input: nil, timeout: nil)
384
+ options = cwd ? {chdir: cwd} : {}
385
+ Open3.popen3(env || {}, [args[0], args[0]], *args[1..], **options) do |stdin, stdout, stderr, waiter|
386
+ stdout.binmode
387
+ stderr.binmode
388
+ readers = [stdout, stderr].map do |stream|
389
+ Thread.new do
390
+ Thread.current.report_on_exception = false
391
+ stream.read
392
+ rescue IOError
393
+ ""
394
+ end
395
+ end
396
+ begin
397
+ stdin.write(input) if input
398
+ rescue Errno::EPIPE
399
+ nil
400
+ end
401
+ stdin.close
402
+ finished = waiter.join(timeout)
403
+ check_interrupt
404
+ if finished.nil?
405
+ begin
406
+ Process.kill("KILL", waiter.pid)
407
+ rescue Errno::ESRCH
408
+ nil
409
+ end
410
+ waiter.join
411
+ raise CommandTimeout, "Command '#{args.join(" ")}' timed out after #{timeout} seconds"
412
+ end
413
+ status = waiter.value
414
+ code = status.exitstatus || -(status.termsig || 1)
415
+ [code, readers[0].value.to_s, readers[1].value.to_s]
416
+ end
417
+ rescue SystemCallError => error
418
+ raise ProcessError, "#{args[0]}: #{error.message}"
419
+ end
420
+
421
+ def command(args, cwd: nil, env: nil, timeout: 60, input: nil)
422
+ code, stdout, stderr = run_process(args, cwd:, env:, input:, timeout:)
423
+ if code != 0
424
+ status = utf8(stderr)[/\bHTTP (\d{3})\b/, 1]
425
+ raise CommandError, "#{args[0]} #{args[1]} failed (exit #{code}#{", HTTP #{status}" if status}); check authentication and permissions"
426
+ end
427
+ utf8(stdout).strip
428
+ end
429
+
430
+ def git(root, *args, env: nil)
431
+ command(["git", "-C", root, *args], env:)
432
+ end
433
+
434
+ def quiet_git(root, *args)
435
+ git(root, *args)
436
+ rescue CommandError
437
+ ""
438
+ end
439
+
440
+ def resolve_path(value)
441
+ absolute = File.expand_path(value)
442
+ File.realpath(absolute)
443
+ rescue SystemCallError
444
+ parent = File.dirname(absolute)
445
+ return absolute if parent == absolute
446
+ File.join(resolve_path(parent), File.basename(absolute))
447
+ end
448
+
449
+ def root_directory
450
+ resolve_path(command(["git", "rev-parse", "--show-toplevel"]))
451
+ end
452
+
453
+ def relative_path(value)
454
+ if !value.is_a?(String) || value.empty? || value.include?("\\") || value.include?("\x00")
455
+ raise ValueError, "Expected a repository-relative path"
456
+ end
457
+ if value.start_with?("/") || value.split("/").include?("..") || value.start_with?("-")
458
+ raise ValueError, "Paths must stay inside the repository"
459
+ end
460
+ value
461
+ end
462
+
463
+ def within(root, value)
464
+ resolved = resolve_path(File.join(root, relative_path(value)))
465
+ unless resolved == root || resolved.start_with?(root.end_with?("/") ? root : "#{root}/")
466
+ raise ValueError, "#{resolved} is not in the subpath of #{root}"
467
+ end
468
+ resolved
469
+ end
470
+
471
+ def file?(path)
472
+ File.file?(path)
473
+ end
474
+
475
+ def read_text(path)
476
+ utf8(File.binread(path))
477
+ end
478
+
479
+ def replay_command
480
+ configured = ENV[REPLAY_COMMAND_ENV]
481
+ return [RbConfig.ruby, CloudReplayCli::REPLAY_EXECUTABLE] if configured.nil?
482
+ value = parse_json_or_nil(configured)
483
+ unless value.is_a?(Array) && !value.empty? && value.all? { |part| part.is_a?(String) && !part.empty? }
484
+ raise ValueError, "#{REPLAY_COMMAND_ENV} must be a JSON list of the command that starts the replay"
485
+ end
486
+ value
487
+ end
488
+
489
+ def flag_value(args, flag)
490
+ args.each_with_index do |value, index|
491
+ return partition(value, "=")[2] if value.start_with?("#{flag}=")
492
+ return args[index + 1] if value == flag && index + 1 < args.length
493
+ end
494
+ nil
495
+ end
496
+
497
+ def replay_name(args)
498
+ flag_value(args, "--name")
499
+ end
500
+
501
+ def validate_arguments(args)
502
+ unless args.is_a?(Array) && args.all? { |value| value.is_a?(String) }
503
+ raise ValueError, "Replay arguments must be a list of strings"
504
+ end
505
+ args.each do |value|
506
+ raise ValueError, "Replay options must be single-line values" if value.include?("\x00") || value.include?("\n")
507
+ raise ValueError, "The runner replays locally and never dispatches again" if value.start_with?("--cloud")
508
+ end
509
+ raise ValueError, "Replay options exceed 16000 characters" if args.sum(&:length) > 16000
510
+ end
511
+
512
+ def validate_environment(values)
513
+ unless object?(values) && values.values.all? { |value| value.is_a?(String) }
514
+ raise ValueError, "Replay environment must map names to string values"
515
+ end
516
+ js_entries(values).each do |name, value|
517
+ unless ENV_NAME.match?(name)
518
+ raise ValueError, "'#{name}' is not an environment variable name; use letters, digits, and underscores"
519
+ end
520
+ upper = name.upcase
521
+ if RESERVED_ENV_PREFIXES.any? { |prefix| upper.start_with?(prefix) } || upper == "CI"
522
+ raise ValueError, "#{name} belongs to GitHub Actions or the cloud runner and cannot be set per replay"
523
+ end
524
+ if SECRET_ENV_NAME.match?(name)
525
+ raise ValueError, "#{name} looks like a secret, and #{ENV_FLAG} values are stored in the snapshot commit on GitHub. Map it in the workflow's replay step env from a GitHub secret instead, then set it with bitfab-replay --cloud-secrets"
526
+ end
527
+ if value.include?("\x00") || value.include?("\n") || value.include?("\r")
528
+ raise ValueError, "#{name} must be a single-line value"
529
+ end
530
+ if URL_PASSWORD.match?(value)
531
+ raise ValueError, "#{name} holds a URL with a password, and #{ENV_FLAG} values are stored in the snapshot commit on GitHub. Map it in the workflow's replay step env from a GitHub secret instead, then set it with bitfab-replay --cloud-secrets"
532
+ end
533
+ end
534
+ if values.sum { |name, value| name.length + value.length } > 16000
535
+ raise ValueError, "Replay environment exceeds 16000 characters"
536
+ end
537
+ end
538
+
539
+ def refuse_git_code_change(replay, where)
540
+ kind = flag_value(replay, CODE_CHANGE_FLAG)
541
+ if CHECKOUT_ONLY_CODE_CHANGES.include?(kind)
542
+ raise ValueError, "#{where} as it is on GitHub, with no snapshot of a checkout, so --code-change #{kind} has nothing to compare against there; pass --code-change default-branch, --code-change ref with #{CODE_CHANGE_BASE_FLAG}, --code-change skip, or --code-change manual with --code-change-file, or start it with bitfab-replay --cloud and no --cloud-ref, which resolves #{kind} from your checkout before upload"
543
+ end
544
+ if kind == "ref" && !BRANCH_NAME.match?(flag_value(replay, CODE_CHANGE_BASE_FLAG) || "")
545
+ raise ValueError, "#{where} as it is on GitHub, so --code-change ref needs #{CODE_CHANGE_BASE_FLAG} naming a branch or commit SHA on GitHub to fetch there"
546
+ end
547
+ end
548
+
549
+ def find_workflow(root)
550
+ WORKFLOW_NAMES.find { |name| file?(within(root, "#{WORKFLOW_DIRECTORY}/#{name}")) }
551
+ end
552
+
553
+ def running_workflow(root)
554
+ match = (env_value("GITHUB_WORKFLOW_REF") || "").match(%r{(\.github/workflows/[^@]+)@})
555
+ return within(root, match[1]) if match
556
+ within(root, "#{WORKFLOW_DIRECTORY}/#{find_workflow(root) || WORKFLOW}")
557
+ end
558
+
559
+ def workflow_secrets(text)
560
+ text.scan(SECRET_REFERENCE).to_h do |name, dotted, bracketed|
561
+ [name, (dotted.nil? || dotted.empty?) ? bracketed : dotted]
562
+ end
563
+ end
564
+
565
+ def workflow_environment_conflicts(root, values)
566
+ workflow = running_workflow(root)
567
+ mapped = File.exist?(workflow) ? workflow_secrets(read_text(workflow)) : {}
568
+ conflicts = values.keys.select { |name| mapped.key?(name) }.sort
569
+ return if conflicts.empty?
570
+ raise ValueError, "The workflow already reads #{conflicts.join(", ")} from a GitHub secret, so a replay cannot set it; update the secret with bitfab-replay --cloud-secrets"
571
+ end
572
+
573
+ def check_secrets(root)
574
+ workflow = running_workflow(root)
575
+ targets = file?(workflow) ? workflow_secrets(read_text(workflow)) : {}
576
+ empty = targets.keys.select { |name| ENV[name] == "" }
577
+ unless empty.empty?
578
+ listed = empty.map { |name| "#{name} (secret #{targets[name]})" }.join(", ")
579
+ raise ValueError, "These replay environment variables are empty on the runner: #{listed}. GitHub passes a secret that does not exist as an empty string. Create each one under Settings, Secrets and variables, Actions, in the repository or in the job's Environment"
580
+ end
581
+ targets.each_key do |name|
582
+ lines = split_lines(env_value(name) || "").drop(1)
583
+ next unless lines.any? { |line| !line.strip.empty? && line.strip.length < 4 }
584
+ say("::warning title=Bitfab replay::#{name} has a line of three characters or fewer, such as a lone brace in multi-line JSON, and GitHub masks that text everywhere in this log. Store it on one line; bitfab-replay --cloud-secrets does this for JSON")
585
+ end
586
+ end
587
+
588
+ def snapshot_request(root, commit)
589
+ message = git(root, "log", "-1", "--format=%B", commit)
590
+ request = parse_json_or_nil(partition(message, "\n\n")[2])
591
+ unless object?(request) && [PLAIN_REQUEST_VERSION, REQUEST_VERSION].include?(request["version"])
592
+ version = if object?(request)
593
+ request["version"].nil? ? 0 : request["version"]
594
+ else
595
+ 0
596
+ end
597
+ newer = js_integer?(version) && version > REQUEST_VERSION
598
+ raise ValueError, "This replay was submitted by a #{newer ? "newer" : "different"} SDK than the one the snapshot installs; match the SDK you run locally to the one in the lockfile"
599
+ end
600
+ id = request["id"].nil? ? "None" : js_string(request["id"])
601
+ if env_value("GITHUB_REF_NAME") != PREFIX + id
602
+ raise ValueError, "The runner replays only the snapshot branch its request names; start replays with bitfab-replay --cloud"
603
+ end
604
+ validate_arguments(request["args"])
605
+ validate_environment(request["env"]) if request.key?("env")
606
+ request
607
+ end
608
+
609
+ def dispatch_event
610
+ path = ENV["GITHUB_EVENT_PATH"]
611
+ return {} if path.nil? || path.empty? || !file?(path)
612
+ event = parse_json(read_text(path))
613
+ object?(event) ? event : {}
614
+ end
615
+
616
+ def dispatched_inputs
617
+ inputs = dispatch_event["inputs"]
618
+ object?(inputs) ? inputs : {}
619
+ end
620
+
621
+ def event_default_branch
622
+ repository = dispatch_event["repository"]
623
+ branch = object?(repository) ? repository["default_branch"] : nil
624
+ unless branch.is_a?(String) && BRANCH_NAME.match?(branch)
625
+ raise ValueError, "The run's event names no default branch, so --code-change default-branch has nothing to compare against; pass --code-change ref with --code-change-base"
626
+ end
627
+ branch
628
+ end
629
+
630
+ def strict_base64(text)
631
+ if text.length % 4 != 0 || !text.match?(%r{\A[A-Za-z0-9+/]*={0,2}\z})
632
+ raise ValueError, "Invalid base64-encoded string"
633
+ end
634
+ Base64.decode64(text)
635
+ end
636
+
637
+ def decode_request(text)
638
+ begin
639
+ return parse_json(text)
640
+ rescue ValueError
641
+ nil
642
+ end
643
+ begin
644
+ parse_json(strict_base64(text))
645
+ rescue ValueError
646
+ raise ValueError, "The request input is neither JSON nor base64-encoded JSON"
647
+ end
648
+ end
649
+
650
+ def dispatched_request
651
+ branch = env_value("GITHUB_REF_NAME") || ""
652
+ inputs = dispatched_inputs
653
+ text = (truthy?(inputs["request"]) ? js_string(inputs["request"]) : "").strip
654
+ if text == "" || text == "-"
655
+ raise ValueError, "A replay of #{branch} takes its request from the workflow_dispatch request input, and this run has none; start replays with bitfab-replay --cloud, or --cloud --cloud-ref #{branch} to replay the branch as it is"
656
+ end
657
+ request = decode_request(text)
658
+ raise ValueError, "The request input must be a JSON object" unless object?(request)
659
+ version = request.key?("version") ? request["version"] : REQUEST_VERSION
660
+ if !js_integer?(version) || version < OLDEST_DISPATCHED_VERSION
661
+ raise ValueError, "Request version #{python_repr(version)} is not supported; send version #{REQUEST_VERSION}, or leave version out"
662
+ end
663
+ if version > REQUEST_VERSION
664
+ raise ValueError, "This replay was submitted by a newer SDK than the one #{branch} installs; the request is version #{js_string(version)} and this SDK reads up to #{REQUEST_VERSION}"
665
+ end
666
+ execution_id = [request["id"], inputs["execution_id"]].find { |value| truthy?(value) } || SecureRandom.uuid
667
+ raise ValueError, "The request id must be a UUID" unless execution_id.is_a?(String) && UUID.match?(execution_id)
668
+ if truthy?(inputs["execution_id"]) && inputs["execution_id"] != execution_id
669
+ raise ValueError, "The request id does not match the execution_id input"
670
+ end
671
+ args = request["args"]
672
+ validate_arguments(args)
673
+ refuse_git_code_change(args, "A dispatched replay runs #{branch}")
674
+ args = [*args, "--dry-run"] if request["check"] == true && !args.include?("--dry-run")
675
+ normalized = {
676
+ "version" => REQUEST_VERSION,
677
+ "id" => execution_id,
678
+ "cwd" => truthy?(request["cwd"]) ? request["cwd"] : ".",
679
+ "args" => args
680
+ }
681
+ timeout = request["timeoutMinutes"]
682
+ unless timeout.nil?
683
+ raise ValueError, "timeoutMinutes must be 1..7200" unless js_integer?(timeout) && timeout.between?(1, 7200)
684
+ normalized["timeoutMinutes"] = timeout
685
+ end
686
+ normalized["fullOutput"] = true if request["fullOutput"] == true
687
+ environment = request["env"]
688
+ if truthy?(environment) && !(object?(environment) && environment.empty?)
689
+ validate_environment(environment)
690
+ normalized["env"] = environment
691
+ end
692
+ normalized
693
+ end
694
+
695
+ def runner_request(root, commit)
696
+ return snapshot_request(root, commit) if (ENV["GITHUB_REF_NAME"] || "").start_with?(PREFIX)
697
+ dispatched_request
698
+ end
699
+
700
+ def check_out_snapshot_base(root, commit, branch)
701
+ begin
702
+ base = git(root, "rev-parse", "--verify", "-q", "#{commit}^")
703
+ rescue CommandError
704
+ say("This checkout does not include the commit the snapshot was taken on, so the experiment records no code change and the snapshot commit instead of your branch; set fetch-depth: 2 on the workflow's checkout step, or run bitfab-replay --cloud-update")
705
+ return nil
706
+ end
707
+ if branch.is_a?(String) && BRANCH_NAME.match?(branch)
708
+ begin
709
+ git(root, "update-ref", "refs/heads/#{branch}", base)
710
+ git(root, "symbolic-ref", "HEAD", "refs/heads/#{branch}")
711
+ return base
712
+ rescue CommandError
713
+ nil
714
+ end
715
+ end
716
+ git(root, "reset", "-q", "--soft", base)
717
+ base
718
+ end
719
+
720
+ def git_blob(root, ref, file)
721
+ begin
722
+ text = git(root, "cat-file", "-s", "#{ref}:#{file}")
723
+ rescue CommandError
724
+ return nil
725
+ end
726
+ return nil unless text.match?(/\A\s*[+-]?\d+\s*\z/)
727
+ return nil if text.to_i > CODE_CHANGE_MAX_FILE_BYTES
728
+ code, stdout, = run_process(["git", "-C", root, "show", "#{ref}:#{file}"])
729
+ return nil if code != 0 || stdout.byteslice(0, 8000).include?("\x00")
730
+ utf8(stdout).gsub("\r\n", "\n")
731
+ end
732
+
733
+ def changed_paths(root, base, commit)
734
+ raw = git(root, "diff", "--name-status", "--find-renames", "-z", base, commit, "--", ":!.bitfab")
735
+ parts = raw.split("\x00").reject(&:empty?)
736
+ paths = []
737
+ index = 0
738
+ while index + 1 < parts.length
739
+ status = parts[index][0]
740
+ before_path = parts[index + 1]
741
+ index += 2
742
+ file = before_path
743
+ if "RC".include?(status) && index < parts.length
744
+ file = parts[index]
745
+ index += 1
746
+ end
747
+ paths << [status, before_path, file]
748
+ end
749
+ paths
750
+ end
751
+
752
+ def snapshot_code_change(root, base, commit, name, against = "uncommitted (vs HEAD)", subject_ref = nil)
753
+ files = []
754
+ total = 0
755
+ changed_paths(root, base, commit).each do |status, before_path, file|
756
+ break if files.length >= CODE_CHANGE_MAX_FILES
757
+ before = (status == "A") ? "" : git_blob(root, base, before_path)
758
+ after = (status == "D") ? "" : git_blob(root, commit, file)
759
+ next if before.nil? || after.nil? || before == after
760
+ size = before.bytesize + after.bytesize
761
+ next if total + size > CODE_CHANGE_MAX_TOTAL_BYTES
762
+ total += size
763
+ files << {"path" => file, "before" => before, "after" => after}
764
+ end
765
+ return nil if files.empty?
766
+ head = (name || "").strip
767
+ head = git(root, "log", "-1", "--format=%s", subject_ref || base) if head.empty?
768
+ word = (files.length == 1) ? "file" : "files"
769
+ {
770
+ "description" => "#{head.empty? ? "Working-tree change" : head} (#{files.length} #{word} changed #{against})",
771
+ "files" => files
772
+ }
773
+ end
774
+
775
+ def branch_code_change(root, base, commit, request)
776
+ point = request["codeChangeBase"]
777
+ return nil unless object?(point)
778
+ sha = point["sha"]
779
+ ref = point["ref"]
780
+ trusted = sha.is_a?(String) && SHA.match?(sha) && ref.is_a?(String) && DESCRIBED_REF.match?(ref) &&
781
+ (sha == base || quiet_git(root, "rev-parse", "--verify", "-q", "#{commit}^2") == sha)
782
+ return nil unless trusted
783
+ snapshot_code_change(root, sha, commit, replay_name(request["args"]), "vs #{ref}", base)
784
+ end
785
+
786
+ def runner_code_change(root, base, commit, request)
787
+ kind = flag_value(request["args"], CODE_CHANGE_FLAG)
788
+ change = if kind == "working-tree"
789
+ snapshot_code_change(root, base, commit, replay_name(request["args"]))
790
+ elsif BRANCH_CODE_CHANGES.include?(kind)
791
+ branch_code_change(root, base, commit, request)
792
+ else
793
+ return nil
794
+ end
795
+ change || {"files" => []}
796
+ end
797
+
798
+ def git_token_environment(token)
799
+ environment = {"GIT_TERMINAL_PROMPT" => "0"}
800
+ return environment if token.nil? || token.empty?
801
+ basic = Base64.strict_encode64("x-access-token:#{token}")
802
+ environment.merge(
803
+ "GIT_CONFIG_COUNT" => "1",
804
+ "GIT_CONFIG_KEY_0" => "http.https://github.com/.extraheader",
805
+ "GIT_CONFIG_VALUE_0" => "AUTHORIZATION: basic #{basic}"
806
+ )
807
+ end
808
+
809
+ def fetched_base(root, ref, token)
810
+ shallow = quiet_git(root, "rev-parse", "--is-shallow-repository") == "true"
811
+ begin
812
+ command(
813
+ ["git", "-C", root, "fetch", "-q", "--no-tags", *(shallow ? ["--unshallow"] : []), "origin", ref],
814
+ env: git_token_environment(token),
815
+ timeout: FETCH_SECONDS
816
+ )
817
+ rescue CommandError, CommandTimeout => error
818
+ hint = if token.nil? || token.empty?
819
+ "the workflow passes no #{GIT_TOKEN_ENV} to fetch it with, so run bitfab-replay --cloud-update and commit the workflow it updates"
820
+ else
821
+ "check that it exists on GitHub"
822
+ end
823
+ raise ValueError, "Could not fetch #{ref} from origin to compare against (#{error.message}); #{hint}, or pass --code-change skip"
824
+ end
825
+ base = quiet_git(root, "merge-base", "HEAD", "FETCH_HEAD")
826
+ raise ValueError, "This branch shares no history with #{ref}, so there is nothing to compare against" if base.empty?
827
+ base
828
+ end
829
+
830
+ def dispatched_code_change(root, commit, request, token)
831
+ args = request["args"]
832
+ kind = flag_value(args, CODE_CHANGE_FLAG)
833
+ return nil unless FETCHED_CODE_CHANGES.include?(kind)
834
+ ref = (kind == "ref") ? flag_value(args, CODE_CHANGE_BASE_FLAG) : event_default_branch
835
+ say("Fetching #{ref} to record the code change against it")
836
+ base = fetched_base(root, ref, token)
837
+ snapshot_code_change(root, base, commit, replay_name(args), "vs #{ref}", commit) || {"files" => []}
838
+ end
839
+
840
+ def write_code_change(change)
841
+ parent = ENV["RUNNER_TEMP"]
842
+ directory = Dir.mktmpdir("bitfab-code-change-", (parent.nil? || parent.empty?) ? Dir.tmpdir : parent)
843
+ file = File.join(directory, "change.json")
844
+ File.binwrite(file, JSON.generate(change))
845
+ file
846
+ end
847
+
848
+ def runner_warning(message)
849
+ say("::warning title=Bitfab replay::#{message}")
850
+ end
851
+
852
+ def warn_if_workflow_outdated
853
+ problems = []
854
+ if ENV.key?(API_KEY_ENV)
855
+ problems << "still sets #{API_KEY_ENV} from a secret named by the run's inputs, which makes GitHub give this run every secret in the repository"
856
+ end
857
+ if (ENV["ACTIONS_ID_TOKEN_REQUEST_URL"] || "").empty?
858
+ problems << "does not grant id-token: write, so replays use the workflow's BITFAB_API_KEY secret instead of running as the person who started them"
859
+ end
860
+ return if problems.empty?
861
+ runner_warning("This workflow #{problems.join(" and ")}. Run bitfab-replay --cloud-update and commit the workflow it updates")
862
+ end
863
+
864
+ def urlopen(url, method:, headers:, data:, timeout:)
865
+ check_interrupt
866
+ uri = URI(url)
867
+ REDIRECT_LIMIT.succ.times do
868
+ http = Net::HTTP.new(uri.host, uri.port)
869
+ http.use_ssl = uri.scheme == "https"
870
+ http.open_timeout = timeout
871
+ http.read_timeout = timeout
872
+ http.write_timeout = timeout
873
+ request = Net::HTTPGenericRequest.new(method, !data.nil?, true, uri.request_uri, headers)
874
+ request.body = data unless data.nil?
875
+ response = http.request(request)
876
+ check_interrupt
877
+ code = response.code.to_i
878
+ location = response["location"]
879
+ if REDIRECTS.include?(code) && location
880
+ target = URI.join(uri.to_s, location)
881
+ headers = headers.except("Authorization") if target.host != uri.host || target.port != uri.port
882
+ if code == 303 || (code <= 302 && method == "POST")
883
+ method = "GET"
884
+ data = nil
885
+ headers = headers.except("Content-Type")
886
+ end
887
+ uri = target
888
+ next
889
+ end
890
+ raise HttpFailure.new(code, response.body.to_s) if code >= 400
891
+ return response.body.to_s
892
+ end
893
+ raise UnreachableError, "too many redirects"
894
+ rescue HttpFailure, UnreachableError
895
+ raise
896
+ rescue => error
897
+ raise UnreachableError, error.message
898
+ end
899
+
900
+ def local_client(root, request)
901
+ begin
902
+ output = command(
903
+ [*replay_command, *request["args"], PRINT_API_KEY_FLAG],
904
+ cwd: within(root, request["cwd"]),
905
+ timeout: API_KEY_PROBE_SECONDS,
906
+ input: ""
907
+ )
908
+ rescue
909
+ return nil
910
+ end
911
+ split_lines(output).reverse_each do |line|
912
+ next unless line.start_with?(API_KEY_LINE)
913
+ reported = parse_json_or_nil(line.delete_prefix(API_KEY_LINE))
914
+ return nil unless object?(reported)
915
+ key = reported["apiKey"]
916
+ return nil unless key.is_a?(String) && !key.strip.empty?
917
+ url = reported["serviceUrl"]
918
+ url = DEFAULT_SERVICE_URL unless url.is_a?(String) && !url.strip.empty?
919
+ return {"apiKey" => key, "serviceUrl" => url.sub(%r{/+\z}, "")}
920
+ end
921
+ nil
922
+ end
923
+
924
+ def bitfab_api(client, location, method: "POST", payload: nil)
925
+ data = payload.nil? ? nil : js_json(payload)
926
+ headers = {}
927
+ headers["Authorization"] = "Bearer #{client["apiKey"]}" if truthy?(client["apiKey"])
928
+ headers["User-Agent"] = "bitfab-cloud-replay"
929
+ headers["Content-Type"] = "application/json" unless data.nil?
930
+ begin
931
+ body = urlopen("#{client["serviceUrl"]}/api/sdk/#{location}", method:, headers:, data:, timeout: 60)
932
+ rescue HttpFailure => error
933
+ parsed = parse_json_or_nil(error.body)
934
+ reason = object?(parsed) ? parsed["error"] : nil
935
+ raise CommandError, "Bitfab #{method} #{location} failed (HTTP #{error.code})#{": #{js_string(reason)}" if truthy?(reason)}"
936
+ rescue UnreachableError => error
937
+ raise CommandError, "Could not reach #{client["serviceUrl"]}: #{error.reason}"
938
+ end
939
+ text = utf8(body)
940
+ return {} if text.strip.empty?
941
+ begin
942
+ parse_json(text)
943
+ rescue ValueError
944
+ raise CommandError, "Bitfab #{method} #{location} returned a response that is not JSON"
945
+ end
946
+ end
947
+
948
+ def github_run_identity
949
+ url = ENV["ACTIONS_ID_TOKEN_REQUEST_URL"]
950
+ bearer = ENV["ACTIONS_ID_TOKEN_REQUEST_TOKEN"]
951
+ if url.nil? || url.empty? || bearer.nil? || bearer.empty?
952
+ raise CommandError, "The workflow does not grant id-token: write, so this run cannot prove to Bitfab which run it is; run bitfab-replay --cloud-update to add it"
953
+ end
954
+ separator = url.include?("?") ? "&" : "?"
955
+ begin
956
+ body = urlopen(
957
+ "#{url}#{separator}#{URI.encode_www_form(audience: OIDC_AUDIENCE)}",
958
+ method: "GET",
959
+ headers: {"Authorization" => "Bearer #{bearer}", "User-Agent" => "bitfab-cloud-replay"},
960
+ data: nil,
961
+ timeout: 30
962
+ )
963
+ parsed = parse_json(body)
964
+ raise ValueError, "the response is not a JSON object" unless object?(parsed)
965
+ value = parsed["value"]
966
+ rescue UnreachableError => error
967
+ raise CommandError, "GitHub did not issue this run's OIDC token: #{error.reason}"
968
+ rescue => error
969
+ raise CommandError, "GitHub did not issue this run's OIDC token: #{error.message}"
970
+ end
971
+ raise CommandError, "GitHub returned no OIDC token for this run" unless value.is_a?(String) && !value.empty?
972
+ value
973
+ end
974
+
975
+ def starter_key(root, request)
976
+ warn_if_workflow_outdated
977
+ unless (env_value(API_KEY_ENV) || "").strip.empty?
978
+ say("Replaying with the Bitfab API key of the person who started this run")
979
+ return nil
980
+ end
981
+ given = dispatched_inputs[KEY_INPUT]
982
+ token = (truthy?(given) ? js_string(given) : "").strip
983
+ return nil unless token.start_with?(KEY_TOKEN_PREFIX)
984
+ shared = "so this run uses the workflow's BITFAB_API_KEY secret"
985
+ runner = local_client(root, request)
986
+ if runner.nil?
987
+ runner_warning("The replay's Bitfab client resolved no API key on the runner, #{shared}")
988
+ return nil
989
+ end
990
+ begin
991
+ identity = github_run_identity
992
+ rescue CommandError => error
993
+ runner_warning("#{error.message}, #{shared}")
994
+ return nil
995
+ end
996
+ timeout = request["timeoutMinutes"]
997
+ payload = {"token" => token, "oidcToken" => identity}
998
+ payload["minutes"] = timeout if truthy?(timeout)
999
+ begin
1000
+ redeemed = bitfab_api({"serviceUrl" => runner["serviceUrl"]}, "replay/cloudKey/redeem", payload:)
1001
+ rescue CommandError => error
1002
+ runner_warning("#{error.message}, #{shared}")
1003
+ return nil
1004
+ end
1005
+ key = object?(redeemed) ? redeemed["apiKey"] : nil
1006
+ unless key.is_a?(String) && !key.strip.empty?
1007
+ runner_warning("Bitfab returned no key for the replay token, #{shared}")
1008
+ return nil
1009
+ end
1010
+ say("::add-mask::#{key}")
1011
+ ENV[API_KEY_ENV] = key
1012
+ say("Replaying as the person who started this run, with a key that is turned off when the replay ends")
1013
+ {"apiKey" => key, "serviceUrl" => runner["serviceUrl"]}
1014
+ end
1015
+
1016
+ def revoke_starter_key(starter)
1017
+ return if starter.nil?
1018
+ bitfab_api(starter, "replay/cloudKey", method: "DELETE")
1019
+ rescue CommandError => error
1020
+ runner_warning("Could not turn off this replay's key (#{error.message}); it expires on its own 30 minutes after the replay's timeout")
1021
+ end
1022
+
1023
+ def run_check_command(directory, environment)
1024
+ check = (env_value(CHECK_COMMAND_ENV) || "").strip
1025
+ return if check.empty?
1026
+ say("Running #{CHECK_COMMAND_ENV}: #{check}")
1027
+ args = shell_split(check)
1028
+ begin
1029
+ pid = Process.spawn(environment, [args[0], args[0]], *args[1..], chdir: directory, in: File::NULL)
1030
+ rescue SystemCallError => error
1031
+ raise ProcessError, "#{args[0]}: #{error.message}"
1032
+ end
1033
+ _, status = Process.wait2(pid)
1034
+ code = status.exitstatus || 1
1035
+ raise ValueError, "#{CHECK_COMMAND_ENV} exited #{code}; its output is above" if code != 0
1036
+ end
1037
+
1038
+ def item_errored?(item)
1039
+ object?(item) && ITEM_ERROR_FIELDS.any? { |field| !item[field].nil? }
1040
+ end
1041
+
1042
+ def carried_over?(item)
1043
+ object?(item) && (item["carriedOver"] == true || item["carried_over"] == true)
1044
+ end
1045
+
1046
+ def item_errors(items)
1047
+ items.filter_map do |item|
1048
+ next unless item_errored?(item)
1049
+ error = item[ITEM_ERROR_FIELDS.find { |field| !item[field].nil? }]
1050
+ error = truthy?(error["message"]) ? error["message"] : python_json(error) if object?(error)
1051
+ field = ITEM_ID_FIELDS.find { |name| item[name].is_a?(String) }
1052
+ trace = field.nil? ? "unknown trace" : item[field]
1053
+ text = python_text(error).split(/[[:space:]]+/).reject(&:empty?).join(" ")
1054
+ text = "#{text[0, ITEM_ERROR_LENGTH]}..." if text.length > ITEM_ERROR_LENGTH
1055
+ errored = {"originalTraceId" => trace, "error" => text}
1056
+ errored["attempt"] = item["attempt"] if js_integer?(item["attempt"])
1057
+ errored
1058
+ end
1059
+ end
1060
+
1061
+ def item_field(item, camel, snake)
1062
+ item.key?(camel) ? item[camel] : item[snake]
1063
+ end
1064
+
1065
+ def canonical(value)
1066
+ js_json(value)
1067
+ end
1068
+
1069
+ def experiment_fields(parsed)
1070
+ EXPERIMENT_FIELDS.each_with_object({}) do |(name, spellings), fields|
1071
+ key = spellings.find { |spelling| !parsed[spelling].nil? }
1072
+ fields[name] = parsed[key] unless key.nil?
1073
+ end
1074
+ end
1075
+
1076
+ def replay_summary(parsed)
1077
+ items = parsed["items"].select { |item| object?(item) }
1078
+ replayed = items.reject { |item| carried_over?(item) }
1079
+ errors = item_errors(replayed)
1080
+ counts = {
1081
+ "replayed" => replayed.length,
1082
+ "carriedOver" => items.length - replayed.length,
1083
+ "same" => 0,
1084
+ "changed" => 0,
1085
+ "matchedExpected" => 0,
1086
+ "missedExpected" => 0,
1087
+ "errored" => errors.length
1088
+ }
1089
+ replayed.each do |item|
1090
+ next if item_errored?(item)
1091
+ equal = canonical(item["result"]) == canonical(item_field(item, "originalOutput", "original_output"))
1092
+ if item_field(item, "ingestionType", "ingestion_type") == "seeded"
1093
+ counts[equal ? "matchedExpected" : "missedExpected"] += 1
1094
+ else
1095
+ counts[equal ? "same" : "changed"] += 1
1096
+ end
1097
+ end
1098
+ summary = {"cloudSummary" => true, **experiment_fields(parsed), "counts" => counts, "erroredItems" => errors.first(SUMMARY_ERROR_ITEMS)}
1099
+ summary["erroredItemsOmitted"] = errors.length - SUMMARY_ERROR_ITEMS if errors.length > SUMMARY_ERROR_ITEMS
1100
+ summary
1101
+ end
1102
+
1103
+ def trailing_json(text)
1104
+ bytes = text.b
1105
+ offset = 0
1106
+ until offset.nil?
1107
+ if bytes.getbyte(offset) == 0x7b
1108
+ value = parse_json_or_nil(bytes.byteslice(offset..))
1109
+ return [offset, value] if object?(value)
1110
+ end
1111
+ newline = bytes.index("\n".b, offset)
1112
+ offset = newline && newline + 1
1113
+ end
1114
+ [nil, nil]
1115
+ end
1116
+
1117
+ def last_json(text)
1118
+ trailing_json(text)[1]
1119
+ end
1120
+
1121
+ def result_summary(stdout)
1122
+ parsed = last_json(stdout) || {}
1123
+ return parsed if parsed["cloudSummary"] == true
1124
+ return replay_summary(parsed) if parsed["items"].is_a?(Array)
1125
+ nil
1126
+ end
1127
+
1128
+ def summary_markdown(result)
1129
+ summary = result_summary(result["stdout"]) || {}
1130
+ counts = object?(summary["counts"]) ? summary["counts"] : {}
1131
+ test_run = truthy?(result["testRunId"]) ? result["testRunId"] : summary["testRunId"]
1132
+ errors = summary["erroredItems"].is_a?(Array) ? summary["erroredItems"] : []
1133
+ lines = ["Commit: `#{result["commitSha"]}`", "Exit code: #{result["exitCode"]}"]
1134
+ lines.unshift("Test run: `#{js_string(test_run)}`") if truthy?(test_run)
1135
+ if truthy?(result["stoppedEarly"])
1136
+ lines << "Stopped early: #{result["stoppedEarly"]}"
1137
+ elsif truthy?(counts["replayed"]) || truthy?(counts["carriedOver"])
1138
+ lines << "Replayed: #{js_string(counts["replayed"])}, same: #{js_string(counts["same"])}, changed: #{js_string(counts["changed"])}, errored: #{js_string(counts["errored"])}"
1139
+ end
1140
+ text = "### Bitfab replay\n\n#{lines.join("\n\n")}\n"
1141
+ shown = errors.first(ITEM_ERROR_LINES).map do |error|
1142
+ error = {} unless object?(error)
1143
+ "trace #{js_string(error["originalTraceId"])}: #{js_string(error["error"])}"
1144
+ end
1145
+ errored = counts["errored"].nil? ? 0 : counts["errored"]
1146
+ shown << "and #{errored - shown.length} more errored items" if errored.is_a?(Numeric) && errored > shown.length
1147
+ text += "\n#### Errored items\n\n" + shown.map { |line| "- `#{line.tr("`", "'")}`\n" }.join unless errors.empty?
1148
+ text.gsub(STAND_INS, "\u{FFFD}")
1149
+ end
1150
+
1151
+ def write_result(result)
1152
+ encoded = Base64.strict_encode64(Zlib::Deflate.deflate(JSON.generate(result)))
1153
+ (0...encoded.length).step(RESULT_CHUNK) { |start| say(RESULT_LINE + encoded[start, RESULT_CHUNK]) }
1154
+ summary = ENV["GITHUB_STEP_SUMMARY"]
1155
+ File.open(summary, "a") { |file| file.write(summary_markdown(result)) } unless summary.nil? || summary.empty?
1156
+ end
1157
+
1158
+ def annotate(result)
1159
+ message = if truthy?(result["stoppedEarly"])
1160
+ "Replay stopped early: #{result["stoppedEarly"]}"
1161
+ elsif truthy?(result["exitCode"])
1162
+ "Replay exited #{result["exitCode"]}, so this job exits with it too"
1163
+ else
1164
+ return
1165
+ end
1166
+ runner_warning(message)
1167
+ end
1168
+
1169
+ def runner_exit_code(result)
1170
+ return result["exitCode"] unless truthy?(result["stoppedEarly"])
1171
+ truthy?(result["exitCode"]) ? result["exitCode"] : 1
1172
+ end
1173
+
1174
+ def without_item_payload(line)
1175
+ event = parse_json_or_nil(line.byteslice(PROGRESS_PREFIX.bytesize..))
1176
+ item = object?(event) ? event["item"] : nil
1177
+ return line unless object?(item)
1178
+ kept = item.except(*PROGRESS_PAYLOAD_FIELDS)
1179
+ "#{PROGRESS_PREFIX}#{js_json(event.merge("item" => kept))}\n".b
1180
+ end
1181
+
1182
+ def stripped_line(line, summarize)
1183
+ return line unless summarize && line.byteslice(0, PROGRESS_PREFIX.bytesize) == PROGRESS_PREFIX.b
1184
+ without_item_payload(line)
1185
+ rescue
1186
+ line
1187
+ end
1188
+
1189
+ def forward_line(line, experiment, summarize)
1190
+ text = utf8(stripped_line(line, summarize))
1191
+ $stdout.write(text)
1192
+ $stdout.flush
1193
+ return if experiment.key?("id")
1194
+ match = EXPERIMENT_LINE.match(text)
1195
+ experiment["id"] = match[1] if match
1196
+ rescue
1197
+ nil
1198
+ end
1199
+
1200
+ def forward_stderr(stream, experiment, summarize)
1201
+ stream.binmode
1202
+ stream.each_line { |line| forward_line(line.b, experiment, summarize) }
1203
+ rescue IOError
1204
+ nil
1205
+ end
1206
+
1207
+ def last_json_of(output)
1208
+ trailing_json(output)[1]
1209
+ end
1210
+
1211
+ def read_from(path, start)
1212
+ File.open(path, "rb") do |file|
1213
+ file.seek(start)
1214
+ file.read || "".b
1215
+ end
1216
+ end
1217
+
1218
+ def relayed_stdout(path, code, summarize)
1219
+ if summarize
1220
+ parsed = last_json_of(read_from(path, 0))
1221
+ if object?(parsed) && parsed["items"].is_a?(Array)
1222
+ return ["#{js_json(replay_summary(parsed).merge("exitCode" => code))}\n", 0]
1223
+ end
1224
+ end
1225
+ carried_stdout(path)
1226
+ end
1227
+
1228
+ def carried_stdout(path)
1229
+ start = [0, File.size(path) - OUTPUT_LIMIT].max
1230
+ text = utf8(read_from(path, start))
1231
+ return [text, 0] if start.zero?
1232
+ offset = trailing_json(text)[0] || 0
1233
+ [utf8(text.byteslice(offset..)), start + offset]
1234
+ end
1235
+
1236
+ def kill_group(pid, signal)
1237
+ Process.kill(signal, -pid)
1238
+ rescue Errno::ESRCH, Errno::EPERM
1239
+ nil
1240
+ end
1241
+
1242
+ def reap(child)
1243
+ return true unless child.status.nil?
1244
+ _, status = Process.wait2(child.pid, Process::WNOHANG)
1245
+ child.status = status unless status.nil?
1246
+ !child.status.nil?
1247
+ rescue Errno::ECHILD
1248
+ true
1249
+ end
1250
+
1251
+ def wait_child(child, seconds)
1252
+ if seconds.nil?
1253
+ return true unless child.status.nil?
1254
+ begin
1255
+ _, child.status = Process.wait2(child.pid)
1256
+ rescue Errno::ECHILD
1257
+ nil
1258
+ end
1259
+ return true
1260
+ end
1261
+ deadline = monotonic + seconds
1262
+ until reap(child)
1263
+ return false if monotonic >= deadline
1264
+ sleep 0.05
1265
+ end
1266
+ true
1267
+ end
1268
+
1269
+ def stop(child)
1270
+ kill_group(child.pid, "TERM")
1271
+ wait_child(child, 30)
1272
+ kill_group(child.pid, "KILL")
1273
+ wait_child(child, nil)
1274
+ end
1275
+
1276
+ def monotonic
1277
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
1278
+ end
1279
+
1280
+ def interrupt
1281
+ @interrupted = true
1282
+ end
1283
+
1284
+ def interrupted?
1285
+ @interrupted == true
1286
+ end
1287
+
1288
+ def reset_interrupt
1289
+ @interrupted = false
1290
+ end
1291
+
1292
+ def check_interrupt
1293
+ raise Interrupt if interrupted?
1294
+ end
1295
+
1296
+ def deadline_after(timeout)
1297
+ return nil if timeout.nil?
1298
+ minutes = js_number_of(timeout)
1299
+ return nil if minutes.is_a?(Float) && minutes.nan?
1300
+ monotonic + minutes * 60
1301
+ end
1302
+
1303
+ def run_command(directory, args, timeout, experiment, summarize:, environment:)
1304
+ stopped = nil
1305
+ temporary = Dir.mktmpdir("bitfab-replay-stdout-")
1306
+ path = File.join(temporary, "stdout")
1307
+ output = File.open(path, "w+b")
1308
+ reader, writer = IO.pipe
1309
+ begin
1310
+ begin
1311
+ pid = Process.spawn(
1312
+ environment.merge(EXECUTION_TARGET_ENV => HOSTED_EXECUTION_TARGET),
1313
+ [args[0], args[0]], *args[1..],
1314
+ chdir: directory, in: File::NULL, out: output, err: writer, pgroup: true
1315
+ )
1316
+ rescue SystemCallError => error
1317
+ raise ProcessError, "#{args[0]}: #{error.message}"
1318
+ ensure
1319
+ writer.close
1320
+ end
1321
+ child = Child.new(pid, nil)
1322
+ forwarding = Thread.new { forward_stderr(reader, experiment, summarize) }
1323
+ begin
1324
+ deadline = deadline_after(timeout)
1325
+ parent = Process.ppid
1326
+ checked = monotonic
1327
+ until reap(child)
1328
+ raise ValueError, "Replay printed more than 1 GiB to stdout" if File.size(path) > DISK_LIMIT
1329
+ if deadline && monotonic >= deadline
1330
+ stopped = "it reached the #{js_string(timeout)}-minute --cloud-timeout"
1331
+ stop(child)
1332
+ break
1333
+ end
1334
+ if monotonic - checked >= 1
1335
+ checked = monotonic
1336
+ raise Cancelled if Process.ppid != parent
1337
+ end
1338
+ raise Cancelled if interrupted?
1339
+ sleep 0.1
1340
+ end
1341
+ rescue Cancelled, Interrupt
1342
+ reset_interrupt
1343
+ stopped = CANCELLED
1344
+ stop(child)
1345
+ rescue
1346
+ stop(child)
1347
+ raise
1348
+ ensure
1349
+ kill_group(child.pid, "KILL")
1350
+ forwarding.join(5)
1351
+ end
1352
+ returned = child.status&.exitstatus
1353
+ code = returned.nil? ? 1 : returned
1354
+ text, omitted = relayed_stdout(path, code, summarize)
1355
+ [code, text, omitted, stopped]
1356
+ ensure
1357
+ reader.close unless reader.closed?
1358
+ output.close
1359
+ FileUtils.rm_rf(temporary)
1360
+ end
1361
+ end
1362
+
1363
+ def execute
1364
+ raise ValueError, "Submit a new replay instead of rerunning an Actions job" if ENV["GITHUB_RUN_ATTEMPT"] != "1"
1365
+ git_token = ENV.delete(GIT_TOKEN_ENV)
1366
+ root = root_directory
1367
+ commit = ENV["GITHUB_SHA"]
1368
+ raise ValueError, "'GITHUB_SHA'" if commit.nil?
1369
+ raise ValueError, "Runner checkout does not match the dispatched commit" if git(root, "rev-parse", "HEAD") != commit
1370
+ request = runner_request(root, commit)
1371
+ snapshot = (ENV["GITHUB_REF_NAME"] || "").start_with?(PREFIX)
1372
+ base = snapshot ? check_out_snapshot_base(root, commit, request["branch"]) : nil
1373
+ directory = within(root, request["cwd"])
1374
+ check_secrets(root)
1375
+ environment = truthy?(request["env"]) ? request["env"] : {}
1376
+ unless environment.empty?
1377
+ workflow_environment_conflicts(root, environment)
1378
+ say("Setting #{environment.keys.sort.join(", ")} from the request")
1379
+ end
1380
+ change = if snapshot
1381
+ base.nil? ? nil : runner_code_change(root, base, commit, request)
1382
+ else
1383
+ dispatched_code_change(root, commit, request, git_token)
1384
+ end
1385
+ run_environment = environment.dup
1386
+ run_environment[CODE_CHANGE_PATH_ENV] = write_code_change(change) unless change.nil?
1387
+ args = [*replay_command, *request["args"]]
1388
+ run_check_command(directory, environment) if request["args"].include?("--dry-run")
1389
+ experiment = {}
1390
+ starter = starter_key(root, request)
1391
+ previous = Signal.trap("TERM") { interrupt } || "DEFAULT"
1392
+ say(OUTPUT_BEGIN)
1393
+ begin
1394
+ code, stdout, omitted, stopped = run_command(
1395
+ directory, args, request["timeoutMinutes"], experiment,
1396
+ summarize: request["fullOutput"] != true,
1397
+ environment: run_environment
1398
+ )
1399
+ ensure
1400
+ say(OUTPUT_END)
1401
+ Signal.trap("TERM", previous)
1402
+ revoke_starter_key(starter)
1403
+ end
1404
+ result = {"executionId" => request["id"], "commitSha" => commit, "exitCode" => code, "stdout" => stdout}
1405
+ result["stdoutOmittedBytes"] = omitted if omitted.positive?
1406
+ if stopped
1407
+ result["stoppedEarly"] = stopped
1408
+ result["testRunId"] = experiment["id"] if UUID.match?(experiment["id"] || "")
1409
+ end
1410
+ write_result(result)
1411
+ result
1412
+ end
1413
+
1414
+ def main
1415
+ reset_interrupt
1416
+ previous = Signal.trap("INT") { interrupt } || "DEFAULT"
1417
+ begin
1418
+ result = execute
1419
+ annotate(result)
1420
+ runner_exit_code(result)
1421
+ rescue Interrupt
1422
+ progress(DETACHED)
1423
+ 130
1424
+ rescue => error
1425
+ $stdout.flush
1426
+ $stderr.write("Cloud replay: #{error.message}\n")
1427
+ $stderr.flush
1428
+ 1
1429
+ ensure
1430
+ Signal.trap("INT", previous)
1431
+ end
1432
+ end
1433
+ end
1434
+ end