bitfab 0.78.1 → 0.78.3

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.
@@ -1,3758 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import argparse
4
- import base64
5
- import calendar
6
- import contextlib
7
- import functools
8
- import json
9
- import os
10
- import re
11
- import shlex
12
- import shutil
13
- import signal
14
- import ssl
15
- import subprocess
16
- import sys
17
- import tempfile
18
- import threading
19
- import time
20
- import urllib.error
21
- import urllib.request
22
- import uuid
23
- import zlib
24
- from pathlib import Path
25
- from urllib.parse import urlencode
26
-
27
- WORKFLOW = "bitfab-replay.yml"
28
- WORKFLOW_NAMES = (WORKFLOW, "bitfab-replay.yaml")
29
- WORKFLOW_DIRECTORY = ".github/workflows"
30
- OLD_CONFIG = ".bitfab/cloud.json"
31
- PREFIX = "bitfab-replay/"
32
- DEFAULT_SECRET_PREFIX = "BITFAB_CLOUD_"
33
- API_VERSION = "2026-03-10"
34
- REPLAY_COMMAND_ENV = "BITFAB_REPLAY_COMMAND"
35
- SDK_LANGUAGE_ENV = "BITFAB_SDK_LANGUAGE"
36
- CHECK_COMMAND_ENV = "BITFAB_REPLAY_CHECK"
37
- EXECUTION_TARGET_ENV = "BITFAB_REPLAY_EXECUTION_TARGET"
38
- HOSTED_EXECUTION_TARGET = "hosted"
39
- API_KEY_ENV = "BITFAB_REPLAY_BITFAB_API_KEY"
40
- PRINT_API_KEY_FLAG = "--print-api-key"
41
- API_KEY_LINE = "@@bitfab:api-key "
42
- KEY_INPUT = "key_id"
43
- KEY_TOKEN_PREFIX = "bfcr_"
44
- LEFTOVER_KEY_SECRET_PREFIX = "BITFAB_REPLAY_KEY_"
45
- SECRETS_PER_PAGE = 100
46
- LEGACY_KEY_SECRET_REFERENCE = re.compile(
47
- r"^[ \t]*\"?"
48
- + API_KEY_ENV
49
- + r"\"?[ \t]*:[ \t]*[\"']?\$\{\{\s*secrets\[\s*format\(.*$"
50
- )
51
- DEFAULT_SERVICE_URL = "https://bitfab.ai"
52
- OIDC_AUDIENCE = "bitfab-cloud-replay"
53
- ID_TOKEN_PERMISSION = re.compile(
54
- r"^[ \t]*(\"?id-token\"?[ \t]*:[ \t]*[\"']?write[\"']?|\"?permissions\"?[ \t]*:[ \t]*[\"']?write-all[\"']?)[ \t]*(#.*)?$",
55
- re.MULTILINE,
56
- )
57
- API_KEY_PROBE_SECONDS = 120
58
- RUN_NAME = "Bitfab replay ${{ inputs.execution_id || github.ref_name }}"
59
- REQUEST_VERSION = 4
60
- PLAIN_REQUEST_VERSION = 3
61
- OLDEST_DISPATCHED_VERSION = 2
62
- RESULT_LINE = "bitfab-replay-result "
63
- RESULT_CHUNK = 4000
64
- OUTPUT_BEGIN = "bitfab-replay-output-begin"
65
- OUTPUT_END = "bitfab-replay-output-end"
66
- LOG_TAIL_LINES = 40
67
- OUTPUT_LIMIT = 16 * 1024 * 1024
68
- DISK_LIMIT = 1024 * 1024 * 1024
69
- NEW_FILES_LIMIT = 20 * 1024 * 1024
70
- POLL_SECONDS = 5
71
- CLEANABLE_STATES = ("completed", "prepared", "dispatch_unknown", "dispatch_rejected")
72
- CLOCK_SKEW_SECONDS = 600
73
- TIMESTAMP = "%Y-%m-%dT%H:%M:%SZ"
74
- ITEM_ERROR_FIELDS = (
75
- "error",
76
- "traceError",
77
- "trace_error",
78
- "replayError",
79
- "replay_error",
80
- )
81
- ITEM_ID_FIELDS = ("originalTraceId", "original_trace_id", "traceId", "trace_id")
82
- ITEM_ERROR_LINES = 20
83
- ITEM_ERROR_LENGTH = 500
84
- SUMMARY_ERROR_ITEMS = 100
85
- EXPERIMENT_FIELDS = {
86
- "experimentId": ("experimentId", "experiment_id"),
87
- "experimentUrl": ("experimentUrl", "experiment_url"),
88
- "testRunId": ("testRunId", "test_run_id"),
89
- "testRunUrl": ("testRunUrl", "test_run_url"),
90
- "attempts": ("attempts",),
91
- }
92
- UUID = re.compile(r"^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$")
93
- SHA = re.compile(r"^[0-9a-f]{40}$")
94
- GITHUB_REMOTE = re.compile(
95
- r"(?:git@github\.com:|https://github\.com/)([\w.-]+/[\w.-]+?)(?:\.git)?"
96
- )
97
- LOG_TIMESTAMP = re.compile(r"^?\d{4}-\d\d-\d\dT[\d:.]+Z ?")
98
- EXPERIMENT_LINE = re.compile(rb"^\[replay\] Experiment ([0-9a-f-]{36}):")
99
- PROGRESS_PREFIX = b"@@bitfab:progress "
100
- PROGRESS_PAYLOAD_FIELDS = (
101
- "input",
102
- "result",
103
- "originalOutput",
104
- "original_output",
105
- "selectiveReplay",
106
- "selective_replay",
107
- )
108
- SECRET_REFERENCE = re.compile(
109
- r"[\"']?([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*\}\}"
110
- )
111
- ENVIRONMENT_SETTING = re.compile(
112
- r"^[ \t]*\"?environment\"?[ \t]*:[ \t]*[\"']?([\w.-]+)[\"']?[ \t]*,?[ \t]*$",
113
- re.MULTILINE,
114
- )
115
- PUSH_TRIGGER = re.compile(
116
- r"^[ \t]*\"?(?:on\"?[ \t]*:.*\bpush\b|push\"?[ \t]*:)", re.MULTILINE
117
- )
118
- DISPATCH_INPUTS = ("execution_id", "request", KEY_INPUT)
119
- PUSH_SUBJECT = "Bitfab replay started on push"
120
- PUSH_CONDITION = f"github.event_name != 'push' || !startsWith(github.ref_name, '{PREFIX}') || startsWith(github.event.head_commit.message, '{PUSH_SUBJECT}')"
121
- BRANCH_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._/-]*")
122
- ENV_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
123
- RESERVED_ENV_PREFIXES = ("GITHUB_", "RUNNER_", "ACTIONS_", "BITFAB_REPLAY_")
124
- SECRET_ENV_NAME = re.compile(
125
- r"(?:^|_)(?:KEY|SECRET|TOKEN|PASSWORD|PASSWD|CREDENTIALS?)(?:_|$)", re.IGNORECASE
126
- )
127
- ENV_FLAG = "--cloud-env"
128
- ALLOW_FLAG = "--cloud-allow-file"
129
- REPEATED_FLAGS = (ENV_FLAG, ALLOW_FLAG)
130
- URL_PASSWORD = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*://[^/\s:@]*:[^/\s@]+@")
131
- FOLLOW_FLAGS = (
132
- "--cloud-status",
133
- "--cloud-watch",
134
- "--cloud-cancel",
135
- "--cloud-cleanup",
136
- )
137
- CLOUD_VALUE_FLAGS = (
138
- *FOLLOW_FLAGS,
139
- "--cloud-request-id",
140
- "--cloud-timeout",
141
- "--cloud-ref",
142
- )
143
- CLOUD_SWITCHES = ("--cloud", "--cloud-preview", "--cloud-detach", "--cloud-full-output")
144
- RENAMED_FLAGS = {
145
- "--cloud-dry-run": "--cloud-preview",
146
- "--cloud-check": "--dry-run",
147
- "--cloud-include": "nothing: new files that git does not ignore are already in the snapshot",
148
- }
149
- SEED_FLAGS = ("--seed", "--cases", "--from-trace", "--run")
150
- PATH_FLAGS = ("--registry", "--params", "--code-change-file")
151
- CODE_CHANGE_FLAG = "--code-change"
152
- CODE_CHANGE_BASE_FLAG = "--code-change-base"
153
- BRANCH_CODE_CHANGES = ("last-branch", "default-branch", "ref")
154
- GIT_CODE_CHANGES = ("working-tree", *BRANCH_CODE_CHANGES)
155
- FETCHED_CODE_CHANGES = ("default-branch", "ref")
156
- CHECKOUT_ONLY_CODE_CHANGES = ("working-tree", "last-branch")
157
- GIT_TOKEN_ENV = "BITFAB_REPLAY_GIT_TOKEN"
158
- GIT_TOKEN_VALUE = "${{ github.token }}"
159
- FETCH_SECONDS = 600
160
- DESCRIBED_REF = re.compile(r"[^\x00-\x1f\x7f]{1,200}")
161
- CHECKOUT_DEPTH = 2
162
- CODE_CHANGE_PATH_ENV = "BITFAB_CODE_CHANGE_PATH"
163
- CODE_CHANGE_MAX_FILES = 60
164
- CODE_CHANGE_MAX_FILE_BYTES = 500_000
165
- CODE_CHANGE_MAX_TOTAL_BYTES = 2_000_000
166
- BRANCH_WALK_LIMIT = 1000
167
- CHECK_ARGUMENTS_SECONDS = 300
168
- CHECK_ARGUMENTS_FLAG = "--check-arguments"
169
- REPLAY_ARGUMENTS_FLAG = "--replay-arguments"
170
- ARGUMENTS_CHECKED_ENV = "BITFAB_REPLAY_ARGUMENTS_CHECKED"
171
- ACTIONS = {
172
- "checkout": "actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1",
173
- "node": "actions/setup-node@820762786026740c76f36085b0efc47a31fe5020",
174
- "pnpm": "pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413",
175
- "bun": "oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6",
176
- "python": "actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97",
177
- "uv": "astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7",
178
- "ruby": "ruby/setup-ruby@14594264cd68ce8a2345dd349bc3d138a4ef85c8",
179
- "go": "actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e",
180
- }
181
- NO_GITHUB = (
182
- "Cloud replay needs access to GitHub. Any one of these works: "
183
- "log in with the GitHub CLI (gh auth login); "
184
- "set GH_TOKEN to a token that can push to the repository and run its Actions; "
185
- "or push to github.com over https once, so git stores a credential for it"
186
- )
187
- HELP = """Cloud replay: run the replay you run locally on GitHub Actions by adding --cloud.
188
-
189
- bitfab-replay --registry scripts/replay.ts classify --trace-ids UUID --cloud
190
-
191
- Every replay option works as it does locally, including --dry-run and --fail-on-error,
192
- and your SDK checks them before anything is uploaded. The runner replays a snapshot of
193
- your working tree (changed files, plus new files git does not ignore) from the same
194
- directory, and this command prints the replay's output and exits with its exit code.
195
- The experiment records your branch, the commit the snapshot was taken on, and the
196
- snapshot's changed files as its code change, as it would for a local replay.
197
- Credential-like files that are not on GitHub yet are refused unless you name them with
198
- --cloud-allow-file. Requires git and Python 3.10+ on macOS or Linux, with a github.com
199
- origin.
200
-
201
- The replay's stderr comes back as it printed it. Its stdout result comes back as a
202
- short summary instead of every item: the experiment ID and URL, how many traces were
203
- replayed, same, changed, and errored, each errored trace with its error, and the exit
204
- code. Every item's input and output are saved in the experiment in Bitfab, where the
205
- Bitfab MCP tools read them, so by default the job log holds no trace data.
206
-
207
- Options added by --cloud:
208
- --cloud-preview List what the snapshot would contain and push nothing.
209
- --cloud-detach Return after dispatch instead of waiting.
210
- --cloud-full-output Print the replay's whole stdout result, every item included,
211
- instead of the summary. The result passes through the
212
- GitHub job log, so it is refused on a public repository,
213
- and large runs can exceed what the log holds.
214
- --cloud-timeout MIN Stop the replay after MIN minutes (1..7200).
215
- --cloud-env NAME=VALUE Set an environment variable for this replay only; repeat it
216
- for more. NAME alone copies the value from your shell. The
217
- value is stored in the snapshot commit on GitHub, so this is
218
- for settings, never secrets: names that look like secrets,
219
- and names the workflow reads from a secret, are refused.
220
- --cloud-allow-file PATH
221
- Upload PATH even though it looks like a credential, such as
222
- a test certificate; repeat it for more. Refused on a public
223
- repository, where anyone can read the snapshot branch.
224
- --cloud-request-id ID Recover a submission whose response was lost.
225
- --cloud-ref BRANCH Replay BRANCH as it is on GitHub, with no snapshot of your
226
- working tree, and record the experiment on BRANCH. Meant for
227
- CI jobs, such as a nightly replay of dev. Runs from a
228
- checkout of the repository, with GitHub access that can
229
- read it and run Actions (a job token needs contents: read
230
- and actions: write, passed as GH_TOKEN), and a workflow on
231
- BRANCH that declares a request input. With no snapshot,
232
- --code-change default-branch and ref fetch their base on
233
- the runner with the run's GitHub token, which the
234
- workflow passes as BITFAB_REPLAY_GIT_TOKEN and the
235
- replay never sees; working-tree and last-branch are
236
- refused, as they are on a dispatched run.
237
-
238
- A workflow can also dispatch bitfab-replay.yml itself on any branch other than a
239
- bitfab-replay/ snapshot branch, passing the replay as JSON in the request input:
240
-
241
- {"args": ["--registry", "scripts/replay.ts", "classify", "--dataset-ids", "UUID"],
242
- "cwd": "web", "timeoutMinutes": 60, "env": {"LOG_LEVEL": "debug"}}
243
-
244
- args are the replay options without --cloud. cwd is the directory to replay from,
245
- relative to the repository root, and defaults to the root. timeoutMinutes and
246
- fullOutput (true) match --cloud-timeout and --cloud-full-output, and env holds the
247
- values --cloud-env sets. version and id are optional: version names the request
248
- format (4 when env is set, otherwise 3; 2 is still accepted), and id is the
249
- execution UUID, which must match an execution_id input when the workflow has one.
250
-
251
- The replay runs as the person who started it, so the experiment is recorded as
252
- yours. Before dispatch, the replay's registry is loaded locally to read its
253
- client's key, which asks Bitfab for a one-time token passed as the key_id input,
254
- tied to the repository, branch, and workflow of the run. The runner trades that
255
- token, together with the GitHub Actions OIDC token of its own run, for a key that
256
- works only until the replay ends, so only that run can use it; the token alone
257
- opens nothing. With no key resolved locally, a token Bitfab will not issue or
258
- trade, or a workflow that declares no key_id input or does not grant
259
- id-token: write, the run uses the workflow's BITFAB_API_KEY secret instead.
260
-
261
- The runner's job exits with the replay's exit code, so the Actions run fails when
262
- the replay does. Traces that errored fail it only under --fail-on-error.
263
-
264
- Follow a replay by the execution UUID it prints:
265
- --cloud-watch ID | --cloud-status ID | --cloud-cancel ID | --cloud-cleanup ID
266
- --cloud-cleanup removes the snapshot branch once the run completed, or when GitHub
267
- shows no run for it, such as after a dispatch that failed.
268
-
269
- Set up once:
270
- --cloud-init [--secret NAME ...] [--environment NAME] [--run COMMAND]
271
- [--runs-on LABEL] [--secret-prefix PREFIX] [--check COMMAND]
272
- Writes .github/workflows/bitfab-replay.yml, the only file cloud replay keeps
273
- in the repository, and lists what is left to do. On an existing workflow it
274
- adds only the lines a newer SDK needs, such as the push trigger that lets a
275
- replay run without GitHub access, and lists what it changed.
276
- --cloud-update [same options] [--remove-old-key-secrets]
277
- The same command as --cloud-init, for bringing an existing setup up to date.
278
- It also lists BITFAB_REPLAY_KEY_* secrets an older SDK left in the
279
- repository, each a copy of someone's Bitfab API key, and with
280
- --remove-old-key-secrets deletes them.
281
- --cloud-secrets --env-file FILE [NAME ...] [--environment NAME] [--dry-run]
282
- Copies local values into the GitHub secrets the workflow reads.
283
-
284
- GitHub access comes from the GitHub CLI when it is logged in, otherwise from GH_TOKEN
285
- or GITHUB_TOKEN, otherwise from the github.com credential git already stores. Without
286
- the GitHub CLI, --cloud-secrets lists the secrets to create by hand and where.
287
-
288
- Without GitHub access, or with access that cannot read or push to the repository, a
289
- replay still runs when git can push the snapshot branch and the workflow also starts
290
- on a push to a bitfab-replay/ branch, as one written or updated by --cloud-init does.
291
- This command then warns, prints where to watch the run, and returns once the branch
292
- is pushed, with no updates and exit code 0. The run uses the workflow's BITFAB_API_KEY
293
- secret, and --cloud-full-output and --cloud-allow-file are refused, since only GitHub
294
- access can confirm the repository is private. Delete the snapshot branch once the run
295
- finishes. With access, a replay starts through the GitHub API as before, and its
296
- snapshot commit asks GitHub not to start any workflow on the push.
297
- """
298
-
299
-
300
- class CommandError(RuntimeError):
301
- def __init__(self, message, http_status=None):
302
- super().__init__(message)
303
- self.http_status = http_status
304
-
305
-
306
- class DispatchRejected(ValueError):
307
- def __init__(self, message, record):
308
- super().__init__(message)
309
- self.record = record
310
-
311
-
312
- class GithubUnreachable(ValueError):
313
- pass
314
-
315
-
316
- class KeepRedirect(urllib.request.HTTPRedirectHandler):
317
- def redirect_request(self, *args, **kwargs):
318
- return None
319
-
320
-
321
- def command(args, *, cwd=None, env=None, timeout=60, input=None):
322
- result = subprocess.run(
323
- args,
324
- cwd=cwd,
325
- env=env,
326
- input=input,
327
- text=True,
328
- check=False,
329
- capture_output=True,
330
- timeout=timeout,
331
- )
332
- if result.returncode:
333
- status = re.search(r"\bHTTP (\d{3})\b", result.stderr or "")
334
- http_status = int(status[1]) if status else None
335
- raise CommandError(
336
- f"{args[0]} {args[1]} failed (exit {result.returncode}"
337
- + (f", HTTP {http_status}" if http_status else "")
338
- + "); check authentication and permissions",
339
- http_status,
340
- )
341
- return result.stdout.strip()
342
-
343
-
344
- def git(root, *args, env=None, input=None):
345
- return command(["git", "-C", str(root), *args], env=env, input=input)
346
-
347
-
348
- def progress(message):
349
- print(f"[cloud] {message}", file=sys.stderr, flush=True)
350
-
351
-
352
- def root_directory():
353
- return Path(command(["git", "rev-parse", "--show-toplevel"])).resolve()
354
-
355
-
356
- def relative_path(value):
357
- if not isinstance(value, str) or not value or "\\" in value or "\x00" in value:
358
- raise ValueError("Expected a repository-relative path")
359
- if Path(value).is_absolute() or ".." in Path(value).parts or value.startswith("-"):
360
- raise ValueError("Paths must stay inside the repository")
361
- return value
362
-
363
-
364
- def within(root, value):
365
- path = (root / relative_path(value)).resolve()
366
- path.relative_to(root)
367
- return path
368
-
369
-
370
- def repository_path(root, path):
371
- try:
372
- return Path(path).resolve().relative_to(root).as_posix()
373
- except ValueError as error:
374
- raise ValueError(f"{path} must be inside the repository") from error
375
-
376
-
377
- def working_directory(root):
378
- try:
379
- relative = Path.cwd().resolve().relative_to(root).as_posix()
380
- except ValueError as error:
381
- raise ValueError("Run cloud replay from inside the repository") from error
382
- return relative or "."
383
-
384
-
385
- def repository(root):
386
- fetch = GITHUB_REMOTE.fullmatch(git(root, "remote", "get-url", "origin"))
387
- if fetch is None:
388
- raise ValueError(
389
- "origin must be a github.com repository without embedded credentials"
390
- )
391
- push = GITHUB_REMOTE.fullmatch(git(root, "remote", "get-url", "--push", "origin"))
392
- if push is None or push[1].lower() != fetch[1].lower():
393
- raise ValueError("origin fetch and push repositories must match")
394
- return fetch[1]
395
-
396
-
397
- def find_workflow(root):
398
- for name in WORKFLOW_NAMES:
399
- if within(root, f"{WORKFLOW_DIRECTORY}/{name}").is_file():
400
- return name
401
- return None
402
-
403
-
404
- def refuse_old_setup(root):
405
- if within(root, OLD_CONFIG).exists():
406
- raise ValueError(
407
- f"This cloud replay setup was made by an older SDK. Delete {OLD_CONFIG} and {WORKFLOW_DIRECTORY}/{WORKFLOW}, then run bitfab-replay --cloud-init"
408
- )
409
-
410
-
411
- def setup_workflow(root):
412
- refuse_old_setup(root)
413
- name = find_workflow(root)
414
- if name is None:
415
- raise ValueError(
416
- f"No {WORKFLOW_DIRECTORY}/{WORKFLOW} yet. Run bitfab-replay --cloud-init, or ask your coding agent for bitfab:setup cloud"
417
- )
418
- return name
419
-
420
-
421
- def workflow_secrets(text):
422
- return {
423
- name: dotted or bracketed
424
- for name, dotted, bracketed in SECRET_REFERENCE.findall(text)
425
- }
426
-
427
-
428
- def secrets_page(repo, environment):
429
- if environment:
430
- return f"https://github.com/{repo}/settings/environments"
431
- return f"https://github.com/{repo}/settings/secrets/actions"
432
-
433
-
434
- ENV_ASSIGNMENT = re.compile(r"[ \t]*(?:export[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*=")
435
-
436
- ENV_ESCAPES = {"n": "\n", "r": "\r", "t": "\t", '"': '"', "\\": "\\"}
437
-
438
-
439
- def read_environment_value(text, assignment_end, name):
440
- start = assignment_end
441
- while start < len(text) and text[start] in " \t":
442
- start += 1
443
- if start < len(text) and text[start] in ("'", '"'):
444
- quote = text[start]
445
- pieces = []
446
- position = start + 1
447
- while position < len(text):
448
- character = text[position]
449
- if character == "\\" and quote == '"' and position + 1 < len(text):
450
- following = text[position + 1]
451
- pieces.append(ENV_ESCAPES.get(following, character + following))
452
- position += 2
453
- continue
454
- if character == quote:
455
- return "".join(pieces), position + 1
456
- pieces.append(character)
457
- position += 1
458
- raise ValueError(f"{name} opens a quote that the file never closes")
459
- end = text.find("\n", assignment_end)
460
- end = len(text) if end == -1 else end
461
- raw = text[assignment_end:end]
462
- comment = re.search(r"\s#", raw)
463
- return (raw if comment is None else raw[: comment.start()]).strip(), end
464
-
465
-
466
- def parse_environment_file(text):
467
- values = {}
468
- position = 0
469
- while position < len(text):
470
- end = text.find("\n", position)
471
- end = len(text) if end == -1 else end
472
- line = text[position:end]
473
- match = ENV_ASSIGNMENT.match(line)
474
- if match is None or line.lstrip().startswith("#"):
475
- position = end + 1
476
- continue
477
- value, consumed = read_environment_value(text, position + match.end(), match[1])
478
- values[match[1]] = value
479
- newline = text.find("\n", consumed)
480
- position = len(text) if newline == -1 else newline + 1
481
- return values
482
-
483
-
484
- def secret_value(value):
485
- if "\n" not in value:
486
- return value
487
- try:
488
- parsed = json.loads(value)
489
- except ValueError:
490
- return value
491
- return json.dumps(parsed, separators=(",", ":"))
492
-
493
-
494
- def ensure_environment(repo, environment):
495
- try:
496
- api(repo, f"environments/{environment}")
497
- return "exists"
498
- except ValueError:
499
- return "unchecked"
500
- except RuntimeError as error:
501
- if getattr(error, "http_status", None) != 404:
502
- return "unchecked"
503
- try:
504
- api(repo, f"environments/{environment}", method="PUT", payload={})
505
- return "created"
506
- except RuntimeError:
507
- return "missing"
508
-
509
-
510
- def configure_secrets(argv):
511
- parser = argparse.ArgumentParser(
512
- prog="bitfab-replay --cloud-secrets",
513
- description="Copy named values from local environment files into the GitHub Actions secrets the cloud replay workflow reads. Values are piped to the GitHub CLI on standard input and never printed, logged, or passed as arguments. Without the GitHub CLI, it lists the secrets to create by hand and where.",
514
- )
515
- parser.add_argument(
516
- "names",
517
- nargs="*",
518
- help="Environment variable names to copy; defaults to every secret the workflow maps",
519
- )
520
- parser.add_argument(
521
- "--env-file",
522
- action="append",
523
- required=True,
524
- help="Repository-relative environment file to read; repeatable, earliest definition wins",
525
- )
526
- parser.add_argument(
527
- "--environment",
528
- help="GitHub Environment to set the secrets in; defaults to the workflow's environment, and is created when it does not exist",
529
- )
530
- parser.add_argument(
531
- "--dry-run",
532
- action="store_true",
533
- help="Report which names were found without writing anything to GitHub",
534
- )
535
- args = parser.parse_args(argv)
536
- root = root_directory()
537
- text = within(root, f"{WORKFLOW_DIRECTORY}/{setup_workflow(root)}").read_text()
538
- targets = workflow_secrets(text)
539
- names = args.names or list(targets)
540
- unknown = [name for name in names if name not in targets]
541
- if unknown:
542
- raise ValueError(
543
- f"The workflow does not read {', '.join(unknown)}. Add each one to the replay step's env as NAME: ${{{{ secrets.{DEFAULT_SECRET_PREFIX}NAME }}}} first"
544
- )
545
- configured = ENVIRONMENT_SETTING.search(text)
546
- environment = args.environment or (configured[1] if configured else None)
547
- values = {}
548
- for path in args.env_file:
549
- for key, value in parse_environment_file(
550
- within(root, path).read_text()
551
- ).items():
552
- values.setdefault(key, value)
553
- repo = repository(root)
554
- found, missing, empty = [], [], []
555
- for name in names:
556
- value = values.get(name, values.get(targets[name]))
557
- if value is None:
558
- missing.append(targets[name])
559
- elif not value:
560
- empty.append(targets[name])
561
- else:
562
- found.append(name)
563
- result = {
564
- "repository": repo,
565
- "environment": environment,
566
- "dryRun": args.dry_run,
567
- "set": [],
568
- "missing": missing,
569
- "empty": empty,
570
- }
571
- if args.dry_run:
572
- return {**result, "wouldSet": [targets[name] for name in found]}
573
- if environment:
574
- result["environmentStatus"] = ensure_environment(repo, environment)
575
- if found and shutil.which("gh") is None:
576
- progress(
577
- "Setting secrets needs the GitHub CLI (https://cli.github.com), which encrypts each value for GitHub; create the ones listed under createByHand instead"
578
- )
579
- return {
580
- **result,
581
- "createByHand": [targets[name] for name in found],
582
- "where": secrets_page(repo, environment),
583
- }
584
- token = github_access()["token"]
585
- for name in found:
586
- command(
587
- [
588
- "gh",
589
- "secret",
590
- "set",
591
- targets[name],
592
- "--repo",
593
- repo,
594
- *(["--env", environment] if environment else []),
595
- ],
596
- input=secret_value(values.get(name, values.get(targets[name]))),
597
- env={**os.environ, "GH_TOKEN": token},
598
- )
599
- result["set"] = [targets[name] for name in found]
600
- if missing or empty:
601
- result["where"] = secrets_page(repo, environment)
602
- return result
603
-
604
-
605
- @functools.cache
606
- def github_access():
607
- if shutil.which("gh") is not None:
608
- with contextlib.suppress(RuntimeError, OSError, subprocess.SubprocessError):
609
- token = command(["gh", "auth", "token", "--hostname", "github.com"])
610
- if token:
611
- return {"source": "the GitHub CLI", "token": token}
612
- for name in ("GH_TOKEN", "GITHUB_TOKEN"):
613
- if os.environ.get(name):
614
- return {"source": name, "token": os.environ[name]}
615
- token = stored_git_credential()
616
- if token:
617
- return {"source": "the github.com credential git stores", "token": token}
618
- raise ValueError(NO_GITHUB)
619
-
620
-
621
- def stored_git_credential():
622
- try:
623
- result = subprocess.run(
624
- ["git", "credential", "fill"],
625
- input="protocol=https\nhost=github.com\n\n",
626
- text=True,
627
- capture_output=True,
628
- check=False,
629
- timeout=15,
630
- env={
631
- **os.environ,
632
- "GIT_TERMINAL_PROMPT": "0",
633
- "GCM_INTERACTIVE": "never",
634
- "GIT_ASKPASS": "",
635
- "SSH_ASKPASS": "",
636
- },
637
- )
638
- except (OSError, subprocess.SubprocessError):
639
- return None
640
- if result.returncode:
641
- return None
642
- for line in result.stdout.splitlines():
643
- if line.startswith("password="):
644
- return line.removeprefix("password=") or None
645
- return None
646
-
647
-
648
- def api(repo, suffix, *, method="GET", payload=None, raw=False):
649
- path = f"repos/{repo}" + (f"/{suffix}" if suffix else "")
650
- access = github_access()
651
- data = None if payload is None else json.dumps(payload)
652
- request = urllib.request.Request(
653
- f"https://api.github.com/{path}",
654
- method=method,
655
- data=None if data is None else data.encode(),
656
- headers={
657
- "Accept": "application/vnd.github+json",
658
- "Authorization": f"Bearer {access['token']}",
659
- "X-GitHub-Api-Version": API_VERSION,
660
- "User-Agent": "bitfab-cloud-replay",
661
- **({"Content-Type": "application/json"} if data is not None else {}),
662
- },
663
- )
664
- try:
665
- body = fetch(request, follow_without_credentials=raw)
666
- except urllib.error.HTTPError as error:
667
- raise CommandError(
668
- f"GitHub {method} {path.split('?')[0]} failed (HTTP {error.code}) using {access['source']}",
669
- error.code,
670
- ) from None
671
- except (urllib.error.URLError, OSError) as error:
672
- reason = getattr(error, "reason", error)
673
- if isinstance(reason, ssl.SSLCertVerificationError):
674
- raise CommandError(
675
- "Python cannot verify GitHub's certificate because it has no certificate store. "
676
- "On a python.org install, run Install Certificates.command from its Applications folder, "
677
- "or set SSL_CERT_FILE to a certificate bundle"
678
- ) from None
679
- raise CommandError(f"Could not reach api.github.com: {reason}") from None
680
- if raw:
681
- return body.decode(errors="replace").strip()
682
- return json.loads(body) if body.strip() else None
683
-
684
-
685
- def fetch(request, *, follow_without_credentials):
686
- if not follow_without_credentials:
687
- with urllib.request.urlopen(request, timeout=60) as response:
688
- return response.read()
689
- try:
690
- with urllib.request.build_opener(KeepRedirect).open(
691
- request, timeout=60
692
- ) as response:
693
- return response.read()
694
- except urllib.error.HTTPError as error:
695
- location = error.headers.get("Location")
696
- if error.code not in (301, 302, 303, 307, 308) or not location:
697
- raise
698
- with urllib.request.urlopen(location, timeout=120) as response:
699
- return response.read()
700
-
701
-
702
- def option_name(token):
703
- return token.split("=", 1)[0]
704
-
705
-
706
- def split_arguments(argv):
707
- cloud, switches, replay = {}, set(), []
708
- index = 0
709
- while index < len(argv):
710
- token = argv[index]
711
- name = option_name(token)
712
- if name in RENAMED_FLAGS:
713
- raise ValueError(f"{name} is gone; use {RENAMED_FLAGS[name]}")
714
- if name in REPEATED_FLAGS:
715
- if "=" in token:
716
- value = token.split("=", 1)[1]
717
- index += 1
718
- elif index + 1 < len(argv):
719
- value = argv[index + 1]
720
- index += 2
721
- else:
722
- raise ValueError(
723
- f"{ENV_FLAG} needs NAME=VALUE or NAME"
724
- if name == ENV_FLAG
725
- else f"{name} needs a path"
726
- )
727
- cloud.setdefault(name, []).append(value)
728
- elif name in CLOUD_VALUE_FLAGS:
729
- if "=" in token:
730
- value = token.split("=", 1)[1]
731
- index += 1
732
- elif index + 1 < len(argv):
733
- value = argv[index + 1]
734
- index += 2
735
- else:
736
- raise ValueError(f"{name} needs a value")
737
- if name in cloud:
738
- raise ValueError(f"{name} was given twice")
739
- cloud[name] = value
740
- elif token in CLOUD_SWITCHES:
741
- switches.add(token)
742
- index += 1
743
- elif name in SEED_FLAGS:
744
- raise ValueError(f"{name} seeds traces; run it locally, without --cloud")
745
- else:
746
- replay.append(token)
747
- index += 1
748
- return cloud, switches, replay
749
-
750
-
751
- def parse(argv):
752
- cloud, switches, replay = split_arguments(argv)
753
- following = [flag for flag in FOLLOW_FLAGS if flag in cloud]
754
- if following:
755
- if len(following) != 1 or len(cloud) != 1 or switches - {"--cloud"} or replay:
756
- raise ValueError("Cloud follow-up commands take only their execution UUID")
757
- operation = following[0].removeprefix("--cloud-")
758
- execution_id = cloud[following[0]]
759
- else:
760
- if not replay:
761
- raise ValueError(
762
- "Add --cloud to the replay command you run locally, such as bitfab-replay --registry scripts/replay.ts classify --trace-ids UUID --cloud"
763
- )
764
- timeout = cloud.get("--cloud-timeout")
765
- if timeout is not None and not (
766
- timeout.isdigit() and 1 <= int(timeout) <= 7200
767
- ):
768
- raise ValueError("--cloud-timeout must be 1..7200 minutes")
769
- branch = cloud.get("--cloud-ref")
770
- if branch is not None and (
771
- not BRANCH_NAME.fullmatch(branch)
772
- or branch.startswith(PREFIX)
773
- or ".." in branch
774
- or branch.endswith((".", "/", ".lock"))
775
- ):
776
- raise ValueError(
777
- f"--cloud-ref takes a branch name such as dev, other than a {PREFIX} snapshot branch"
778
- )
779
- if ENV_FLAG in cloud:
780
- cloud[ENV_FLAG] = replay_environment(cloud[ENV_FLAG])
781
- if ALLOW_FLAG in cloud and "--cloud-ref" in cloud:
782
- raise ValueError(
783
- f"{ALLOW_FLAG} lets a file into the snapshot of your working tree, and --cloud-ref replays the branch on GitHub with no snapshot"
784
- )
785
- operation = "submit"
786
- execution_id = cloud.get("--cloud-request-id") or str(uuid.uuid4())
787
- if not UUID.fullmatch(execution_id):
788
- raise ValueError("Execution ID must be a UUID")
789
- return {
790
- "operation": operation,
791
- "id": execution_id,
792
- "cloud": cloud,
793
- "switches": switches,
794
- "replay": replay,
795
- }
796
-
797
-
798
- def validate_arguments(args):
799
- if not isinstance(args, list) or not all(isinstance(value, str) for value in args):
800
- raise ValueError("Replay arguments must be a list of strings")
801
- for value in args:
802
- if "\x00" in value or "\n" in value:
803
- raise ValueError("Replay options must be single-line values")
804
- if value.startswith("--cloud"):
805
- raise ValueError("The runner replays locally and never dispatches again")
806
- if sum(len(value) for value in args) > 16000:
807
- raise ValueError("Replay options exceed 16000 characters")
808
-
809
-
810
- def replay_environment(assignments):
811
- values = {}
812
- for assignment in assignments:
813
- name, separator, value = assignment.partition("=")
814
- if not separator:
815
- if name not in os.environ:
816
- raise ValueError(
817
- f"{ENV_FLAG} {name} copies {name} from your shell, and it is not set there; pass {ENV_FLAG} {name}=VALUE instead"
818
- )
819
- value = os.environ[name]
820
- if name in values:
821
- raise ValueError(f"{ENV_FLAG} sets {name} twice")
822
- values[name] = value
823
- validate_environment(values)
824
- return values
825
-
826
-
827
- def validate_environment(values):
828
- if not isinstance(values, dict) or not all(
829
- isinstance(name, str) and isinstance(value, str)
830
- for name, value in values.items()
831
- ):
832
- raise ValueError("Replay environment must map names to string values")
833
- for name, value in values.items():
834
- if not ENV_NAME.fullmatch(name):
835
- raise ValueError(
836
- f"{name!r} is not an environment variable name; use letters, digits, and underscores"
837
- )
838
- if name.upper().startswith(RESERVED_ENV_PREFIXES) or name.upper() == "CI":
839
- raise ValueError(
840
- f"{name} belongs to GitHub Actions or the cloud runner and cannot be set per replay"
841
- )
842
- if SECRET_ENV_NAME.search(name):
843
- raise ValueError(
844
- f"{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"
845
- )
846
- if "\x00" in value or "\n" in value or "\r" in value:
847
- raise ValueError(f"{name} must be a single-line value")
848
- if URL_PASSWORD.search(value):
849
- raise ValueError(
850
- f"{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"
851
- )
852
- if sum(len(name) + len(value) for name, value in values.items()) > 16000:
853
- raise ValueError("Replay environment exceeds 16000 characters")
854
-
855
-
856
- def workflow_environment_conflicts(root, values):
857
- path = running_workflow(root)
858
- mapped = workflow_secrets(path.read_text()) if path.is_file() else {}
859
- conflicts = sorted(name for name in values if name in mapped)
860
- if conflicts:
861
- raise ValueError(
862
- f"The workflow already reads {', '.join(conflicts)} from a GitHub secret, so a replay cannot set it; update the secret with bitfab-replay --cloud-secrets"
863
- )
864
-
865
-
866
- def dry_run(args):
867
- return "--dry-run" in args
868
-
869
-
870
- def replay_arguments(argv):
871
- try:
872
- parsed = parse(argv)
873
- except ValueError:
874
- return None
875
- return parsed["replay"] if parsed["operation"] == "submit" else None
876
-
877
-
878
- def check_arguments(replay):
879
- if os.environ.get(ARGUMENTS_CHECKED_ENV) == "1":
880
- return
881
- try:
882
- result = subprocess.run(
883
- [*replay_command(), CHECK_ARGUMENTS_FLAG, *replay],
884
- text=True,
885
- capture_output=True,
886
- stdin=subprocess.DEVNULL,
887
- check=False,
888
- timeout=CHECK_ARGUMENTS_SECONDS,
889
- )
890
- except subprocess.TimeoutExpired:
891
- raise ValueError(
892
- f"The replay command took more than {CHECK_ARGUMENTS_SECONDS} seconds to check these options, so nothing was uploaded; make sure it reaches the Bitfab replay entry point without waiting on input or a slow setup step"
893
- ) from None
894
- if result.returncode:
895
- message = (result.stderr or result.stdout).strip()
896
- raise ValueError(
897
- message
898
- or f"The replay command refused these options (exit {result.returncode})"
899
- )
900
-
901
-
902
- def replay_request(root, parsed):
903
- cwd = Path.cwd().resolve()
904
- args, files = [], []
905
-
906
- def snapshot_path(value):
907
- path = cwd / value
908
- files.append(repository_path(root, path))
909
- return (
910
- os.path.relpath(path.resolve(), cwd) if Path(value).is_absolute() else value
911
- )
912
-
913
- replay = parsed["replay"]
914
- index = 0
915
- while index < len(replay):
916
- token = replay[index]
917
- name, separator, value = token.partition("=")
918
- if name in PATH_FLAGS and separator:
919
- args.append(f"{name}={snapshot_path(value)}")
920
- elif name in PATH_FLAGS and index + 1 < len(replay):
921
- args += [token, snapshot_path(replay[index + 1])]
922
- index += 1
923
- else:
924
- args.append(token)
925
- index += 1
926
- validate_arguments(args)
927
- request = {
928
- "version": REQUEST_VERSION
929
- if parsed["cloud"].get(ENV_FLAG)
930
- else PLAIN_REQUEST_VERSION,
931
- "id": parsed["id"],
932
- "cwd": working_directory(root),
933
- "args": args,
934
- }
935
- if "--cloud-timeout" in parsed["cloud"]:
936
- request["timeoutMinutes"] = int(parsed["cloud"]["--cloud-timeout"])
937
- if "--cloud-full-output" in parsed["switches"]:
938
- request["fullOutput"] = True
939
- if parsed["cloud"].get(ENV_FLAG):
940
- request["env"] = parsed["cloud"][ENV_FLAG]
941
- return request, files
942
-
943
-
944
- def current_branch(root):
945
- try:
946
- return git(root, "symbolic-ref", "--short", "-q", "HEAD") or None
947
- except CommandError:
948
- return None
949
-
950
-
951
- def quiet_git(root, *args):
952
- try:
953
- return git(root, *args)
954
- except CommandError:
955
- return ""
956
-
957
-
958
- def default_branch(root):
959
- origin_head = quiet_git(root, "rev-parse", "--abbrev-ref", "origin/HEAD")
960
- candidates = [
961
- origin_head if origin_head and origin_head != "origin/HEAD" else None,
962
- "origin/main",
963
- "origin/master",
964
- "main",
965
- "master",
966
- ]
967
- return next(
968
- (
969
- ref
970
- for ref in dict.fromkeys(filter(None, candidates))
971
- if quiet_git(root, "rev-parse", "--verify", "-q", f"{ref}^{{commit}}")
972
- ),
973
- None,
974
- )
975
-
976
-
977
- def current_branch_refs(root):
978
- branch = current_branch(root)
979
- if not branch:
980
- return set()
981
- return {f"refs/heads/{branch}"} | {
982
- f"refs/remotes/{remote}/{branch}"
983
- for remote in quiet_git(root, "remote").split()
984
- }
985
-
986
-
987
- def own_branch_refs(root):
988
- upstream = quiet_git(root, "rev-parse", "--symbolic-full-name", "@{upstream}")
989
- own = current_branch_refs(root)
990
- if upstream:
991
- own.add(upstream)
992
- return own
993
-
994
-
995
- def on_default_branch(root, default):
996
- full_name = quiet_git(root, "rev-parse", "--symbolic-full-name", default)
997
- return bool(full_name) and full_name in current_branch_refs(root)
998
-
999
-
1000
- def branch_tips(root):
1001
- own = own_branch_refs(root)
1002
- listing = quiet_git(
1003
- root,
1004
- "for-each-ref",
1005
- "--format=%(objectname) %(refname)",
1006
- "refs/heads",
1007
- "refs/remotes",
1008
- )
1009
- tips = {}
1010
- for line in listing.splitlines():
1011
- sha, _, ref = line.partition(" ")
1012
- if ref and ref not in own and not ref.endswith("/HEAD"):
1013
- tips.setdefault(
1014
- sha, ref.removeprefix("refs/heads/").removeprefix("refs/remotes/")
1015
- )
1016
- return tips
1017
-
1018
-
1019
- def branch_point(root):
1020
- head = quiet_git(root, "rev-parse", "HEAD")
1021
- if not head:
1022
- return None
1023
- default = default_branch(root)
1024
- if default and on_default_branch(root, default):
1025
- return None
1026
- default_base = quiet_git(root, "merge-base", "HEAD", default) if default else ""
1027
- walk = ["rev-list", "--first-parent", f"--max-count={BRANCH_WALK_LIMIT}", "HEAD"]
1028
- if default_base:
1029
- walk.append(f"^{default_base}")
1030
- tips = branch_tips(root)
1031
- for sha in quiet_git(root, *walk).split()[1:]:
1032
- if sha in tips:
1033
- return {"sha": sha, "ref": tips[sha]}
1034
- if default_base and default_base != head:
1035
- return {"sha": default_base, "ref": default}
1036
- return None
1037
-
1038
-
1039
- def default_branch_point(root):
1040
- default = default_branch(root)
1041
- sha = quiet_git(root, "merge-base", "HEAD", default) if default else ""
1042
- return {"sha": sha, "ref": default} if sha else None
1043
-
1044
-
1045
- def chosen_base_point(root, chosen):
1046
- if not chosen or chosen.startswith("-"):
1047
- return None
1048
- for ref in (chosen, f"origin/{chosen}"):
1049
- if quiet_git(root, "rev-parse", "--verify", "-q", f"{ref}^{{commit}}"):
1050
- sha = quiet_git(root, "merge-base", "HEAD", ref)
1051
- return {"sha": sha, "ref": chosen} if sha else None
1052
- raise ValueError(
1053
- f"{CODE_CHANGE_BASE_FLAG} {chosen} names no branch or commit in this repository; pass a branch name or a commit SHA, and fetch it first if it only exists on the remote"
1054
- )
1055
-
1056
-
1057
- def refuse_git_code_change(replay, where):
1058
- kind = flag_value(replay, CODE_CHANGE_FLAG)
1059
- if kind in CHECKOUT_ONLY_CODE_CHANGES:
1060
- raise ValueError(
1061
- f"{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"
1062
- )
1063
- if kind == "ref" and not BRANCH_NAME.fullmatch(
1064
- flag_value(replay, CODE_CHANGE_BASE_FLAG) or ""
1065
- ):
1066
- raise ValueError(
1067
- f"{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"
1068
- )
1069
-
1070
-
1071
- def code_change_base(root, replay):
1072
- kind = flag_value(replay, CODE_CHANGE_FLAG)
1073
- if kind == "ref":
1074
- return chosen_base_point(root, flag_value(replay, CODE_CHANGE_BASE_FLAG))
1075
- if kind == "last-branch":
1076
- return branch_point(root)
1077
- if kind == "default-branch":
1078
- return default_branch_point(root)
1079
- return None
1080
-
1081
-
1082
- def replay_artifact(path):
1083
- return path == ".bitfab" or path.startswith(".bitfab/")
1084
-
1085
-
1086
- def sensitive(path):
1087
- parts = Path(path).parts
1088
- name = Path(path).name.lower()
1089
- return (
1090
- any(part in (".git", ".ssh", ".aws") for part in parts)
1091
- or name == ".env"
1092
- or (
1093
- name.startswith(".env.")
1094
- and name not in (".env.example", ".env.sample", ".env.template")
1095
- )
1096
- or name in (".npmrc", ".pypirc", ".netrc", "id_rsa", "id_ed25519")
1097
- or name.endswith((".pem", ".key", ".p12", ".pfx", ".local.json"))
1098
- or name
1099
- in (
1100
- "credentials",
1101
- "credentials.json",
1102
- "secrets.json",
1103
- "secrets.yml",
1104
- "secrets.yaml",
1105
- )
1106
- )
1107
-
1108
-
1109
- def snapshot_subject(execution_id, on_push):
1110
- if on_push:
1111
- return f"{PUSH_SUBJECT} {execution_id}"
1112
- return f"Bitfab replay {execution_id} [skip actions]"
1113
-
1114
-
1115
- def snapshot(
1116
- root, workflow, files, request, *, preview=False, allowed=(), on_push=False
1117
- ):
1118
- if git(root, "ls-files", "-u"):
1119
- raise ValueError("Resolve merge conflicts before snapshotting")
1120
- head = git(root, "rev-parse", "HEAD")
1121
- with tempfile.TemporaryDirectory(prefix="bitfab-cloud-index-") as directory:
1122
- env = {**os.environ, "GIT_INDEX_FILE": str(Path(directory) / "index")}
1123
- git(root, "read-tree", head, env=env)
1124
- git(root, "add", "-A", "--", ".", env=env)
1125
- entries = git(root, "ls-files", "--stage", "-z", env=env).split("\x00")
1126
- tracked = set()
1127
- for entry in filter(None, entries):
1128
- metadata, path = entry.split("\t", 1)
1129
- tracked.add(path)
1130
- if metadata.startswith("160000"):
1131
- raise ValueError(
1132
- f"{path} is a submodule or nested repository, which cloud snapshots do not support"
1133
- )
1134
- ignored = [
1135
- path
1136
- for path in [f"{WORKFLOW_DIRECTORY}/{workflow}", *files]
1137
- if path not in tracked
1138
- ]
1139
- if ignored:
1140
- raise ValueError(
1141
- "Git ignores "
1142
- + ", ".join(ignored)
1143
- + ", so the snapshot cannot include it; stop ignoring it or move it"
1144
- )
1145
- tree = git(root, "write-tree", env=env)
1146
- changes = [
1147
- line.split("\t", 1)
1148
- for line in git(
1149
- root, "diff", "--name-status", "--no-renames", head, tree
1150
- ).splitlines()
1151
- ]
1152
- new_files = sorted(path for status, path in changes if status == "A")
1153
- changed_files = sorted(path for status, path in changes if status != "A")
1154
- unpushed = git(
1155
- root,
1156
- "log",
1157
- "--format=",
1158
- "--name-only",
1159
- "--no-renames",
1160
- "--diff-filter=AM",
1161
- head,
1162
- "--not",
1163
- "--remotes",
1164
- ).splitlines()
1165
- uploaded = ({*new_files, *changed_files} & tracked) | set(unpushed)
1166
- for path in sorted(uploaded - set(allowed)):
1167
- if sensitive(path):
1168
- raise ValueError(
1169
- f"Refusing to upload {path}, which looks like a credential and is not on GitHub yet; add it to .gitignore and take it out of any commit you have not pushed, or pass {ALLOW_FLAG} {path} if it is safe to upload. If it is already on GitHub, run git fetch so this check can see it"
1170
- )
1171
- sizes = {path: (root / path).lstat().st_size for path in new_files}
1172
- size = sum(sizes.values())
1173
- if size > NEW_FILES_LIMIT:
1174
- largest = sorted(new_files, key=lambda path: -sizes[path])
1175
- raise ValueError(
1176
- f"New files add {size // (1024 * 1024)} MiB to the snapshot, more than {NEW_FILES_LIMIT // (1024 * 1024)} MiB; add large outputs to .gitignore, such as "
1177
- + ", ".join(largest[:5])
1178
- )
1179
- summary = {
1180
- "baseSha": head,
1181
- "changedFiles": changed_files,
1182
- "newFiles": new_files,
1183
- }
1184
- if preview:
1185
- return summary
1186
- branch_base = str((request.get("codeChangeBase") or {}).get("sha", ""))
1187
- extra_parent = (
1188
- ["-p", branch_base]
1189
- if SHA.fullmatch(branch_base) and branch_base != head
1190
- else []
1191
- )
1192
- sha = git(
1193
- root,
1194
- "commit-tree",
1195
- tree,
1196
- "-p",
1197
- head,
1198
- *extra_parent,
1199
- input=f"{snapshot_subject(request['id'], on_push)}\n\n{json.dumps(request)}\n",
1200
- )
1201
- return {**summary, "sha": sha}
1202
-
1203
-
1204
- def state_directory(root):
1205
- path = Path(git(root, "rev-parse", "--absolute-git-dir")) / "bitfab-cloud"
1206
- path.mkdir(mode=0o700, exist_ok=True)
1207
- return path
1208
-
1209
-
1210
- def save(path, record):
1211
- with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, delete=False) as file:
1212
- json.dump(record, file)
1213
- file.write("\n")
1214
- name = file.name
1215
- os.replace(name, path)
1216
-
1217
-
1218
- @contextlib.contextmanager
1219
- def execution_lock(directory, execution_id):
1220
- import fcntl
1221
-
1222
- with (directory / f"{execution_id}.lock").open("a") as lock:
1223
- try:
1224
- fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
1225
- except BlockingIOError as error:
1226
- raise ValueError(
1227
- "Another command is operating on this cloud execution"
1228
- ) from error
1229
- yield
1230
-
1231
-
1232
- def find_run(record):
1233
- if record.get("snapshot") is False:
1234
- return find_branch_run(record)
1235
- event = "push" if record.get("startedOnPush") else "workflow_dispatch"
1236
- query = urlencode({"event": event, "branch": record["branch"], "per_page": 100})
1237
- runs = api(
1238
- record["repository"], f"actions/workflows/{record['workflow']}/runs?{query}"
1239
- )
1240
- matches = [
1241
- run
1242
- for run in runs["workflow_runs"]
1243
- if run["head_sha"] == record["sha"] and run["head_branch"] == record["branch"]
1244
- ]
1245
- if len(matches) > 1:
1246
- raise ValueError(
1247
- "Multiple matching GitHub runs; inspect Actions before cleanup"
1248
- )
1249
- return matches[0] if matches else None
1250
-
1251
-
1252
- def find_branch_run(record):
1253
- dispatched = calendar.timegm(time.strptime(record["dispatchedAt"], TIMESTAMP))
1254
- query = urlencode(
1255
- {
1256
- "event": "workflow_dispatch",
1257
- "branch": record["branch"],
1258
- "created": ">=" + timestamp(dispatched - CLOCK_SKEW_SECONDS),
1259
- "per_page": 100,
1260
- }
1261
- )
1262
- runs = api(
1263
- record["repository"], f"actions/workflows/{record['workflow']}/runs?{query}"
1264
- )
1265
- on_branch = [
1266
- run for run in runs["workflow_runs"] if run["head_branch"] == record["branch"]
1267
- ]
1268
- named = [run for run in on_branch if record["id"] in run.get("display_title", "")]
1269
- matches = named or [
1270
- run for run in on_branch if run.get("created_at", "") >= record["dispatchedAt"]
1271
- ]
1272
- if len(matches) > 1:
1273
- raise ValueError(
1274
- f"Several runs were dispatched on {record['branch']} at about the same time, so this execution cannot tell which is its own; find it in the Actions tab"
1275
- )
1276
- return matches[0] if matches else None
1277
-
1278
-
1279
- def timestamp(seconds):
1280
- return time.strftime(TIMESTAMP, time.gmtime(seconds))
1281
-
1282
-
1283
- def status(record, *, fetch_result=True):
1284
- if record["state"] in ("prepared", "dispatch_rejected"):
1285
- return record
1286
- run = (
1287
- api(record["repository"], f"actions/runs/{record['runId']}")
1288
- if record.get("runId")
1289
- else find_run(record)
1290
- )
1291
- if run is None:
1292
- record["state"] = "dispatch_unknown"
1293
- return record
1294
- if record.get("snapshot") is False and run["head_branch"] == record["branch"]:
1295
- record["sha"] = run["head_sha"]
1296
- if run["head_sha"] != record["sha"] or run["head_branch"] != record["branch"]:
1297
- raise ValueError("GitHub run does not match the recorded execution")
1298
- record.update(
1299
- runId=run["id"],
1300
- url=run["html_url"],
1301
- state=run["status"],
1302
- conclusion=run.get("conclusion"),
1303
- )
1304
- if fetch_result and record["state"] == "completed" and "exitCode" not in record:
1305
- outcome(record)
1306
- return record
1307
-
1308
-
1309
- def replay_job(record):
1310
- jobs = api(
1311
- record["repository"], f"actions/runs/{record['runId']}/jobs?per_page=100"
1312
- )
1313
- jobs = (jobs or {}).get("jobs", [])
1314
- named = [job for job in jobs if job.get("name") == "replay"]
1315
- return (named or jobs or [None])[0]
1316
-
1317
-
1318
- def job_log(record):
1319
- job = replay_job(record)
1320
- if job is None:
1321
- return []
1322
- for attempt in range(6):
1323
- try:
1324
- text = api(record["repository"], f"actions/jobs/{job['id']}/logs", raw=True)
1325
- return [LOG_TIMESTAMP.sub("", line) for line in text.splitlines()]
1326
- except RuntimeError:
1327
- if attempt == 5:
1328
- raise
1329
- time.sleep(POLL_SECONDS)
1330
- return []
1331
-
1332
-
1333
- def read_result(lines):
1334
- chunks = [
1335
- line[len(RESULT_LINE) :] for line in lines if line.startswith(RESULT_LINE)
1336
- ]
1337
- if not chunks:
1338
- return None
1339
- try:
1340
- return json.loads(
1341
- zlib.decompress(base64.b64decode("".join(chunks), validate=True))
1342
- )
1343
- except ValueError as error:
1344
- raise ValueError("The runner left an unreadable replay result") from error
1345
-
1346
-
1347
- def replay_output(lines):
1348
- if OUTPUT_BEGIN not in lines:
1349
- return None
1350
- start = lines.index(OUTPUT_BEGIN) + 1
1351
- end = lines.index(OUTPUT_END, start) if OUTPUT_END in lines[start:] else len(lines)
1352
- return lines[start:end]
1353
-
1354
-
1355
- def outcome(record):
1356
- lines = job_log(record)
1357
- result = read_result(lines)
1358
- if result is None:
1359
- record["exitCode"] = 1
1360
- return {"record": record, "lines": lines, "result": None}
1361
- if (
1362
- result.get("executionId") != record["id"]
1363
- or result.get("commitSha") != record["sha"]
1364
- ):
1365
- raise ValueError("Replay result does not match this execution")
1366
- record["exitCode"] = result["exitCode"]
1367
- parsed = last_json(result.get("stdout", "")) or {}
1368
- test_run = result.get("testRunId") or experiment_fields(parsed).get("testRunId")
1369
- if isinstance(test_run, str) and UUID.fullmatch(test_run):
1370
- record["testRunId"] = test_run
1371
- if result.get("stoppedEarly"):
1372
- record["stoppedEarly"] = result["stoppedEarly"]
1373
- return {"record": record, "lines": lines, "result": result}
1374
-
1375
-
1376
- def print_outcome(found):
1377
- record, lines, result = found["record"], found["lines"], found["result"]
1378
- if result is None:
1379
- errors = [
1380
- index for index, line in enumerate(lines) if line.startswith("##[error]")
1381
- ]
1382
- shown = lines[: errors[0] + 1] if errors else lines
1383
- tail = [line for line in shown if line.strip()][-LOG_TAIL_LINES:]
1384
- for line in tail:
1385
- print(line, file=sys.stderr)
1386
- progress(
1387
- f"The run stopped before the replay finished ({record.get('conclusion')}); the end of its log is above. Full log: {record.get('url')}"
1388
- )
1389
- return 1
1390
- for line in replay_output(lines) or []:
1391
- print(line, file=sys.stderr)
1392
- sys.stderr.flush()
1393
- if result.get("stdoutOmittedBytes"):
1394
- progress(
1395
- f"The replay also printed {result['stdoutOmittedBytes'] // (1024 * 1024)} MiB to stdout before its result, such as a library's logging; only the end was kept"
1396
- )
1397
- print(result.get("stdout", ""), end="", flush=True)
1398
- summary = last_json(result.get("stdout", "")) or {}
1399
- if summary.get("cloudSummary") is True:
1400
- progress(
1401
- "Printed a summary of the result; every item's input and output are in the experiment"
1402
- + (
1403
- f" at {summary['experimentUrl']}"
1404
- if summary.get("experimentUrl")
1405
- else ""
1406
- )
1407
- + "; the Bitfab MCP tools read them. Add --cloud-full-output to print every item here instead"
1408
- )
1409
- if record.get("stoppedEarly"):
1410
- progress(
1411
- f"Replay stopped early: {record['stoppedEarly']}. Traces that finished are saved"
1412
- + (
1413
- f" in experiment {record['testRunId']}"
1414
- if record.get("testRunId")
1415
- else ""
1416
- )
1417
- )
1418
- return result["exitCode"] or 1
1419
- return result["exitCode"]
1420
-
1421
-
1422
- def cleanup(root, record):
1423
- remove_key(record)
1424
- if record.get("cleaned"):
1425
- return
1426
- if record.get("snapshot") is False:
1427
- record["cleaned"] = True
1428
- return
1429
- if record.get("state") not in CLEANABLE_STATES:
1430
- raise ValueError(
1431
- "Cleanup requires a confirmed completed GitHub run; cancel and wait first"
1432
- )
1433
- if record["branch"] != PREFIX + record["id"] or not SHA.fullmatch(record["sha"]):
1434
- raise ValueError("Refusing cleanup of an unowned branch")
1435
- ref = "refs/heads/" + record["branch"]
1436
- remote = git(root, "ls-remote", "--heads", "origin", ref)
1437
- if remote:
1438
- if remote.split()[0] != record["sha"]:
1439
- raise ValueError(
1440
- "Snapshot branch moved; refusing to delete someone else's changes"
1441
- )
1442
- git(
1443
- root,
1444
- "push",
1445
- f"--force-with-lease={ref}:{record['sha']}",
1446
- "origin",
1447
- f":{ref}",
1448
- )
1449
- record["cleaned"] = True
1450
-
1451
-
1452
- def http_status(error):
1453
- status = getattr(error, "http_status", None)
1454
- return f" (HTTP {status})" if status else ""
1455
-
1456
-
1457
- def preflight(repo, workflow, *, pushes=True, full_output=False, allows_files=False):
1458
- try:
1459
- access = github_access()
1460
- except ValueError as error:
1461
- raise GithubUnreachable(str(error)) from error
1462
- try:
1463
- details = api(repo, "")
1464
- except RuntimeError as error:
1465
- refused = getattr(error, "http_status", None) in (401, 403, 404)
1466
- raise (GithubUnreachable if refused else ValueError)(
1467
- f"GitHub access from {access['source']} cannot read {repo}{http_status(error)}; use an account or token with write access to it"
1468
- ) from error
1469
- if pushes and (details or {}).get("permissions", {}).get("push") is False:
1470
- raise GithubUnreachable(
1471
- f"GitHub access from {access['source']} cannot push to {repo}; use an account or token with write access to it"
1472
- )
1473
- if full_output and (details or {}).get("private") is False:
1474
- raise ValueError(
1475
- f"--cloud-full-output writes every trace's input and output into the Actions job log, and anyone can read the logs of {repo} because it is public; leave it off and read the items in the experiment with the Bitfab MCP tools"
1476
- )
1477
- if allows_files and (details or {}).get("private") is False:
1478
- raise ValueError(
1479
- f"{ALLOW_FLAG} uploads a credential-like file to a snapshot branch, and anyone can read the branches of {repo} because it is public"
1480
- )
1481
- path = f"{WORKFLOW_DIRECTORY}/{workflow}"
1482
- try:
1483
- registered = api(repo, f"actions/workflows/{workflow}")
1484
- except RuntimeError as error:
1485
- raise ValueError(
1486
- f"GitHub Actions has not registered {path}{http_status(error)}; merging it to the default branch once registers it, and after that each replay runs the copy in its own snapshot"
1487
- ) from error
1488
- if registered.get("state") != "active":
1489
- raise ValueError(
1490
- f"{path} is {registered.get('state')}; enable it in the repository's Actions tab"
1491
- )
1492
-
1493
-
1494
- def describe_snapshot(source):
1495
- changed, new = len(source["changedFiles"]), len(source["newFiles"])
1496
- progress(
1497
- f"Snapshot of {source['baseSha'][:12]} with {changed} changed and {new} new files"
1498
- + (
1499
- f" ({', '.join(source['newFiles'][:5])}{', ...' if new > 5 else ''})"
1500
- if new
1501
- else ""
1502
- )
1503
- )
1504
-
1505
-
1506
- def allowed_files(root, parsed):
1507
- cwd = Path.cwd().resolve()
1508
- return [
1509
- repository_path(root, cwd / value)
1510
- for value in parsed["cloud"].get(ALLOW_FLAG, [])
1511
- ]
1512
-
1513
-
1514
- def submit(root, repo, workflow, parsed, path):
1515
- execution_id = parsed["id"]
1516
- request, files = replay_request(root, parsed)
1517
- branch = current_branch(root)
1518
- if branch:
1519
- request["branch"] = branch
1520
- base = code_change_base(root, parsed["replay"])
1521
- if base:
1522
- request["codeChangeBase"] = base
1523
- check_arguments(parsed["replay"])
1524
- allowed = allowed_files(root, parsed)
1525
- if "--cloud-preview" in parsed["switches"]:
1526
- return {
1527
- "preview": True,
1528
- "repository": repo,
1529
- **snapshot(root, workflow, files, request, preview=True, allowed=allowed),
1530
- }
1531
- if path.exists():
1532
- record = json.loads(path.read_text())
1533
- if record["request"] != request or record["repository"].lower() != repo.lower():
1534
- raise ValueError("Execution ID already belongs to a different request")
1535
- if record.get("startedOnPush") and record["state"] != "prepared":
1536
- try:
1537
- github_access()
1538
- except ValueError as error:
1539
- record["unfollowed"] = str(error)
1540
- return record
1541
- status(record, fetch_result=False)
1542
- if record["state"] == "prepared":
1543
- raise ValueError(
1544
- "Submission stopped before dispatch. Use --cloud-cleanup, then submit a new execution UUID"
1545
- )
1546
- refuse_rejected(record)
1547
- return record
1548
- unfollowed = None
1549
- try:
1550
- preflight(
1551
- repo,
1552
- workflow,
1553
- full_output=request.get("fullOutput") is True,
1554
- allows_files=bool(allowed),
1555
- )
1556
- except GithubUnreachable as error:
1557
- unfollowed = str(error)
1558
- refuse_unfollowed(root, repo, workflow, request, allowed, unfollowed)
1559
- if dry_run(request["args"]):
1560
- progress(
1561
- "--dry-run dispatches a GitHub run that checks secrets and resolves the traces without replaying; it receives the workflow's secrets"
1562
- )
1563
- source = snapshot(
1564
- root, workflow, files, request, allowed=allowed, on_push=bool(unfollowed)
1565
- )
1566
- describe_snapshot(source)
1567
- record = {
1568
- "id": execution_id,
1569
- "repository": repo,
1570
- "workflow": workflow,
1571
- "branch": PREFIX + execution_id,
1572
- "request": request,
1573
- "state": "prepared",
1574
- **({"startedOnPush": True} if unfollowed else {}),
1575
- **source,
1576
- }
1577
- save(path, record)
1578
- progress(f"Execution {execution_id}; resume with --cloud-watch {execution_id}")
1579
- ref = "refs/heads/" + record["branch"]
1580
- try:
1581
- git(
1582
- root,
1583
- "push",
1584
- f"--force-with-lease={ref}:",
1585
- "origin",
1586
- f"{record['sha']}:{ref}",
1587
- )
1588
- except RuntimeError as error:
1589
- raise ValueError(
1590
- f"Pushing the snapshot branch {record['branch']} to origin failed; check that git can push to {repo}"
1591
- ) from error
1592
- record["state"] = "dispatch_unknown"
1593
- save(path, record)
1594
- if unfollowed:
1595
- record["unfollowed"] = unfollowed
1596
- return record
1597
- text = within(root, f"{WORKFLOW_DIRECTORY}/{workflow}").read_text()
1598
- declared = declared_inputs(text)
1599
- key_inputs = issue_key_token(root, record, text)
1600
- save(path, record)
1601
- return dispatch(
1602
- record,
1603
- {"execution_id": execution_id, "request": "-", **key_inputs},
1604
- declared,
1605
- )
1606
-
1607
-
1608
- def push_trigger(lines):
1609
- for index, line in enumerate(lines):
1610
- if re.fullmatch(r'"?on"?[ \t]*:[ \t]*(#.*)?', line):
1611
- end = block_end(lines, index, 0)
1612
- step = child_indent(lines, index, end, " ")
1613
- row = next(
1614
- (
1615
- row
1616
- for row in range(index + 1, end)
1617
- if re.fullmatch(rf'{step}"?push"?[ \t]*:.*', lines[row])
1618
- ),
1619
- None,
1620
- )
1621
- if row is None:
1622
- return None
1623
- return lines[row : block_end(lines, row, len(step))]
1624
- if re.match(r'"?on"?[ \t]*:', line):
1625
- return [line] if re.search(r"\bpush\b", line) else None
1626
- return None
1627
-
1628
-
1629
- def starts_on_push(text):
1630
- trigger = push_trigger(text.splitlines()) or []
1631
- return any(PREFIX in line for line in trigger) and not any(
1632
- "branches-ignore" in line for line in trigger
1633
- )
1634
-
1635
-
1636
- def refuse_unfollowed(root, repo, workflow, request, allowed, reason):
1637
- path = f"{WORKFLOW_DIRECTORY}/{workflow}"
1638
- if not starts_on_push(within(root, path).read_text()):
1639
- raise ValueError(
1640
- f"{reason}. Without it a replay can still run, with no updates here, once {path} also starts on a push to a {PREFIX} branch: run bitfab-replay --cloud-update and commit the workflow it updates"
1641
- )
1642
- if request.get("fullOutput") is True:
1643
- raise ValueError(
1644
- f"--cloud-full-output writes every trace's input and output into the Actions job log, so it needs GitHub access that confirms {repo} is private: {reason}"
1645
- )
1646
- if allowed:
1647
- raise ValueError(
1648
- f"{ALLOW_FLAG} uploads a credential-like file to a snapshot branch, so it needs GitHub access that confirms {repo} is private: {reason}"
1649
- )
1650
-
1651
-
1652
- def report_unfollowed(record, reason):
1653
- progress(
1654
- f"Warning: the replay started on GitHub, but this command gets no updates on it: {reason}"
1655
- )
1656
- progress(
1657
- f"It runs with the workflow's BITFAB_API_KEY secret, since replaying as you needs GitHub access. Watch it at https://github.com/{record['repository']}/actions/workflows/{record['workflow']}; its experiment appears in Bitfab when it finishes"
1658
- )
1659
- progress(
1660
- f"Once it finishes, delete its snapshot branch with git push origin --delete {record['branch']}, or with --cloud-cleanup {record['id']} from a machine with GitHub access"
1661
- )
1662
-
1663
-
1664
- def local_client(root, request):
1665
- try:
1666
- output = command(
1667
- [*replay_command(), *request["args"], PRINT_API_KEY_FLAG],
1668
- cwd=within(root, request["cwd"]),
1669
- timeout=API_KEY_PROBE_SECONDS,
1670
- input="",
1671
- )
1672
- except (ValueError, RuntimeError, OSError, subprocess.SubprocessError):
1673
- return None
1674
- for line in reversed(output.splitlines()):
1675
- if not line.startswith(API_KEY_LINE):
1676
- continue
1677
- try:
1678
- reported = json.loads(line.removeprefix(API_KEY_LINE))
1679
- except ValueError:
1680
- return None
1681
- if not isinstance(reported, dict):
1682
- return None
1683
- key = reported.get("apiKey")
1684
- if not isinstance(key, str) or not key.strip():
1685
- return None
1686
- url = reported.get("serviceUrl")
1687
- if not isinstance(url, str) or not url.strip():
1688
- url = DEFAULT_SERVICE_URL
1689
- return {"apiKey": key, "serviceUrl": url.rstrip("/")}
1690
- return None
1691
-
1692
-
1693
- def bitfab_api(client, path, *, method="POST", payload=None):
1694
- data = None if payload is None else json.dumps(payload).encode()
1695
- request = urllib.request.Request(
1696
- f"{client['serviceUrl']}/api/sdk/{path}",
1697
- method=method,
1698
- data=data,
1699
- headers={
1700
- **(
1701
- {"Authorization": f"Bearer {client['apiKey']}"}
1702
- if client.get("apiKey")
1703
- else {}
1704
- ),
1705
- "User-Agent": "bitfab-cloud-replay",
1706
- **({"Content-Type": "application/json"} if data is not None else {}),
1707
- },
1708
- )
1709
- try:
1710
- with urllib.request.urlopen(request, timeout=60) as response:
1711
- body = response.read()
1712
- except urllib.error.HTTPError as error:
1713
- try:
1714
- reason = json.loads(error.read()).get("error")
1715
- except (ValueError, AttributeError, OSError):
1716
- reason = None
1717
- raise CommandError(
1718
- f"Bitfab {method} {path} failed (HTTP {error.code})"
1719
- + (f": {reason}" if reason else ""),
1720
- error.code,
1721
- ) from None
1722
- except (urllib.error.URLError, OSError) as error:
1723
- raise CommandError(
1724
- f"Could not reach {client['serviceUrl']}: {getattr(error, 'reason', error)}"
1725
- ) from None
1726
- return json.loads(body) if body.strip() else {}
1727
-
1728
-
1729
- def grants_id_token(text):
1730
- return ID_TOKEN_PERMISSION.search(text) is not None
1731
-
1732
-
1733
- def issue_key_token(root, record, text):
1734
- shared = "so the run uses the workflow's BITFAB_API_KEY secret"
1735
- if KEY_INPUT not in declared_inputs(text):
1736
- progress(
1737
- f"The workflow takes no {KEY_INPUT} input, {shared}. To replay as yourself, run bitfab-replay --cloud-update, which adds the {KEY_INPUT} input to the workflow"
1738
- )
1739
- return {}
1740
- if not grants_id_token(text):
1741
- progress(
1742
- f"The workflow does not grant id-token: write, so its run cannot prove to Bitfab which run it is, {shared}. To replay as yourself, run bitfab-replay --cloud-update, which adds it"
1743
- )
1744
- return {}
1745
- client = local_client(root, record["request"])
1746
- if client is None:
1747
- progress(
1748
- f"The replay's Bitfab client resolved no API key on this machine, {shared}"
1749
- )
1750
- return {}
1751
- try:
1752
- issued = bitfab_api(
1753
- client,
1754
- "replay/cloudKey",
1755
- payload={
1756
- "executionId": record["id"],
1757
- "repository": record["repository"],
1758
- "ref": "refs/heads/" + record["branch"],
1759
- "workflow": record["workflow"],
1760
- },
1761
- )
1762
- except CommandError as error:
1763
- progress(f"{error}, {shared}")
1764
- return {}
1765
- token = issued.get("token")
1766
- if not isinstance(token, str) or not token.startswith(KEY_TOKEN_PREFIX):
1767
- progress(f"Bitfab issued no replay token, {shared}")
1768
- return {}
1769
- progress(
1770
- f"Replaying as you: the run gets a one-time token that only {record['workflow']} running on {record['branch']} in {record['repository']} can use"
1771
- )
1772
- return {KEY_INPUT: token}
1773
-
1774
-
1775
- def remove_key(record):
1776
- secret = record.get("keySecret")
1777
- if not secret or secret.get("removed"):
1778
- return
1779
- try:
1780
- command(
1781
- [
1782
- "gh",
1783
- "secret",
1784
- "delete",
1785
- secret["name"],
1786
- "--repo",
1787
- record["repository"],
1788
- *(["--env", secret["environment"]] if secret["environment"] else []),
1789
- ],
1790
- env={**os.environ, "GH_TOKEN": github_access()["token"]},
1791
- )
1792
- except (ValueError, RuntimeError, OSError, subprocess.SubprocessError) as error:
1793
- if getattr(error, "http_status", None) != 404:
1794
- progress(
1795
- f"Could not delete the GitHub secret {secret['name']}; delete it at {secrets_page(record['repository'], secret['environment'])}"
1796
- )
1797
- return
1798
- secret["removed"] = True
1799
-
1800
-
1801
- def declared_inputs(text):
1802
- return {
1803
- name
1804
- for name in DISPATCH_INPUTS
1805
- if re.search(rf"^[ \t]*\"?{name}\"?[ \t]*:", text, re.MULTILINE)
1806
- }
1807
-
1808
-
1809
- def dispatch(record, inputs, declared, *, run_details=False):
1810
- payload = {"ref": record["branch"]}
1811
- sent = {name: value for name, value in inputs.items() if name in declared}
1812
- if sent:
1813
- payload["inputs"] = sent
1814
- path = f"actions/workflows/{record['workflow']}/dispatches"
1815
- try:
1816
- try:
1817
- response = api(
1818
- record["repository"],
1819
- path,
1820
- method="POST",
1821
- payload={**payload, "return_run_details": True}
1822
- if run_details
1823
- else payload,
1824
- )
1825
- except RuntimeError as error:
1826
- if not run_details or getattr(error, "http_status", None) != 422:
1827
- raise
1828
- response = api(record["repository"], path, method="POST", payload=payload)
1829
- except RuntimeError as error:
1830
- code = getattr(error, "http_status", None)
1831
- problem = f"Dispatching {record['workflow']} on {record['branch']} failed{http_status(error)}"
1832
- if code is not None and 400 <= code < 500 and code != 429:
1833
- record["state"] = "dispatch_rejected"
1834
- raise DispatchRejected(
1835
- f"{problem}, so no run started"
1836
- + (
1837
- ""
1838
- if record.get("snapshot") is False
1839
- else " and the snapshot branch was removed"
1840
- )
1841
- + ". The GitHub account needs write access to Actions, and the registered workflow must accept workflow_dispatch",
1842
- record,
1843
- ) from error
1844
- raise ValueError(
1845
- f"{problem}, and GitHub may still have started it. Follow it with --cloud-watch {record['id']}, or once --cloud-status {record['id']} shows no run, remove it with --cloud-cleanup {record['id']}"
1846
- ) from error
1847
- if isinstance(response, dict) and response.get("workflow_run_id"):
1848
- record["runId"] = response["workflow_run_id"]
1849
- record["url"] = response.get("html_url")
1850
- record["state"] = "queued"
1851
- return record
1852
-
1853
-
1854
- def branch_head(repo, branch):
1855
- try:
1856
- found = api(repo, f"git/ref/heads/{branch}")
1857
- except RuntimeError as error:
1858
- if getattr(error, "http_status", None) == 404:
1859
- raise ValueError(f"{repo} has no branch {branch}") from error
1860
- raise
1861
- sha = ((found or {}).get("object") or {}).get("sha", "")
1862
- if not SHA.fullmatch(sha):
1863
- raise ValueError(f"GitHub gave no commit for branch {branch}")
1864
- return sha
1865
-
1866
-
1867
- def branch_workflow(repo, workflow, sha):
1868
- path = f"{WORKFLOW_DIRECTORY}/{workflow}"
1869
- try:
1870
- found = api(repo, f"contents/{path}?ref={sha}")
1871
- except RuntimeError as error:
1872
- raise ValueError(
1873
- f"Could not read {path} at {sha[:12]}{http_status(error)}; the branch needs the workflow"
1874
- ) from error
1875
- return base64.b64decode((found or {}).get("content", "")).decode(errors="replace")
1876
-
1877
-
1878
- def submit_as_is(root, repo, workflow, parsed, path):
1879
- execution_id = parsed["id"]
1880
- branch = parsed["cloud"]["--cloud-ref"]
1881
- request, _ = replay_request(root, parsed)
1882
- check_arguments(parsed["replay"])
1883
- refuse_git_code_change(parsed["replay"], f"--cloud-ref replays {branch}")
1884
- sha = branch_head(repo, branch)
1885
- if "--cloud-preview" in parsed["switches"]:
1886
- return {
1887
- "preview": True,
1888
- "repository": repo,
1889
- "branch": branch,
1890
- "sha": sha,
1891
- "request": request,
1892
- }
1893
- if path.exists():
1894
- record = json.loads(path.read_text())
1895
- if (
1896
- record["request"] != request
1897
- or record["repository"].lower() != repo.lower()
1898
- or record["branch"] != branch
1899
- ):
1900
- raise ValueError("Execution ID already belongs to a different request")
1901
- status(record, fetch_result=False)
1902
- refuse_rejected(record)
1903
- return record
1904
- preflight(
1905
- repo, workflow, pushes=False, full_output=request.get("fullOutput") is True
1906
- )
1907
- text = branch_workflow(repo, workflow, sha)
1908
- declared = declared_inputs(text)
1909
- if "request" not in declared:
1910
- raise ValueError(
1911
- f"{WORKFLOW_DIRECTORY}/{workflow} on {branch} declares no request input, so it cannot take a replay; add request (type: string, required: false) under on.workflow_dispatch.inputs and land it on {branch}"
1912
- )
1913
- record = {
1914
- "id": execution_id,
1915
- "repository": repo,
1916
- "workflow": workflow,
1917
- "branch": branch,
1918
- "snapshot": False,
1919
- "request": request,
1920
- "state": "dispatch_unknown",
1921
- "sha": sha,
1922
- "dispatchedAt": timestamp(time.time() - 5),
1923
- }
1924
- save(path, record)
1925
- progress(
1926
- f"Replaying {branch} at {sha[:12]} as it is on GitHub, without local changes. Execution {execution_id}; resume with --cloud-watch {execution_id}"
1927
- )
1928
- key_inputs = issue_key_token(root, record, text)
1929
- save(path, record)
1930
- return dispatch(
1931
- record,
1932
- {"execution_id": execution_id, "request": json.dumps(request), **key_inputs},
1933
- declared,
1934
- run_details=True,
1935
- )
1936
-
1937
-
1938
- def report_steps(record, shown):
1939
- job = replay_job(record)
1940
- for step in (job or {}).get("steps", []):
1941
- if step.get("status") not in ("in_progress", "completed"):
1942
- continue
1943
- if "--cloud-execute" in (step.get("name") or ""):
1944
- remove_key(record)
1945
- if step.get("name") not in shown:
1946
- shown.add(step.get("name"))
1947
- progress(step.get("name"))
1948
-
1949
-
1950
- def refuse_rejected(record):
1951
- if record["state"] == "dispatch_rejected":
1952
- raise ValueError(
1953
- "GitHub refused this execution's dispatch, so no run exists; submit the replay again without --cloud-request-id"
1954
- )
1955
-
1956
-
1957
- def wait(record, path):
1958
- started = time.monotonic()
1959
- announced, steps = None, set()
1960
- while record["state"] != "completed":
1961
- status(record, fetch_result=False)
1962
- save(path, record)
1963
- refuse_rejected(record)
1964
- if record["state"] != announced and record.get("url"):
1965
- announced = record["state"]
1966
- progress(f"{announced.replace('_', ' ').capitalize()}: {record['url']}")
1967
- if record["state"] == "in_progress":
1968
- report_steps(record, steps)
1969
- if (
1970
- record["state"] == "dispatch_unknown"
1971
- and time.monotonic() - started >= 10 * 60
1972
- ):
1973
- raise ValueError(
1974
- f"GitHub has shown no run for this dispatch after 10 minutes. Check Actions, then resume with --cloud-watch {record['id']} or remove the snapshot branch with --cloud-cleanup {record['id']}"
1975
- )
1976
- if record["state"] != "completed":
1977
- time.sleep(POLL_SECONDS)
1978
-
1979
-
1980
- def run_cli(argv):
1981
- parsed = parse(argv)
1982
- operation, execution_id = parsed["operation"], parsed["id"]
1983
- if os.name != "posix" or sys.version_info < (3, 10):
1984
- raise ValueError("Cloud replay currently requires macOS/Linux and Python 3.10+")
1985
- root = root_directory()
1986
- workflow = setup_workflow(root) if operation == "submit" else None
1987
- repo = repository(root)
1988
- directory = state_directory(root)
1989
- path = directory / f"{execution_id}.json"
1990
- with execution_lock(directory, execution_id):
1991
- if operation == "submit":
1992
- submitter = submit_as_is if "--cloud-ref" in parsed["cloud"] else submit
1993
- try:
1994
- record = submitter(root, repo, workflow, parsed, path)
1995
- except DispatchRejected as error:
1996
- cleanup(root, error.record)
1997
- save(path, error.record)
1998
- raise
1999
- if record.get("preview"):
2000
- return record, None
2001
- reason = record.pop("unfollowed", None)
2002
- if reason:
2003
- report_unfollowed(record, reason)
2004
- save(path, record)
2005
- return record, None
2006
- else:
2007
- if not path.exists():
2008
- raise ValueError(
2009
- "No local execution record for this UUID in this worktree"
2010
- )
2011
- record = json.loads(path.read_text())
2012
- if record["repository"].lower() != repo.lower():
2013
- raise ValueError("origin no longer matches the execution repository")
2014
- status(record, fetch_result=operation == "status")
2015
- if operation == "cancel" and record["state"] != "completed":
2016
- if not record.get("runId"):
2017
- raise ValueError(
2018
- "Run not yet found; inspect Actions and retry status before cancelling"
2019
- )
2020
- api(repo, f"actions/runs/{record['runId']}/cancel", method="POST")
2021
- record["state"] = "cancel_requested"
2022
- save(path, record)
2023
- attached = operation == "watch" or (
2024
- operation == "submit" and "--cloud-detach" not in parsed["switches"]
2025
- )
2026
- found = None
2027
- if attached and record["state"] != "prepared":
2028
- wait(record, path)
2029
- found = outcome(record)
2030
- if record["state"] == "completed" or (
2031
- operation == "cleanup" and record["state"] in CLEANABLE_STATES
2032
- ):
2033
- cleanup(root, record)
2034
- elif operation == "cleanup":
2035
- raise ValueError(
2036
- f"The GitHub run is {record['state'].replace('_', ' ')}; cancel it with --cloud-cancel {record['id']} and clean up once it completes. No branch was deleted"
2037
- )
2038
- save(path, record)
2039
- return record, found
2040
-
2041
-
2042
- def replay_command():
2043
- try:
2044
- value = json.loads(os.environ.get(REPLAY_COMMAND_ENV, ""))
2045
- except ValueError:
2046
- value = None
2047
- if (
2048
- not isinstance(value, list)
2049
- or not value
2050
- or not all(isinstance(part, str) and part for part in value)
2051
- ):
2052
- raise ValueError(
2053
- "Start the replay step with the SDK's bitfab-replay command and --cloud-execute, so the runner knows how to start the replay"
2054
- )
2055
- return value
2056
-
2057
-
2058
- def snapshot_request(root, commit):
2059
- message = git(root, "log", "-1", "--format=%B", commit)
2060
- _, _, body = message.partition("\n\n")
2061
- try:
2062
- request = json.loads(body)
2063
- except ValueError:
2064
- request = None
2065
- if not isinstance(request, dict) or request.get("version") not in (
2066
- PLAIN_REQUEST_VERSION,
2067
- REQUEST_VERSION,
2068
- ):
2069
- version = request.get("version", 0) if isinstance(request, dict) else 0
2070
- newer = isinstance(version, int) and version > REQUEST_VERSION
2071
- raise ValueError(
2072
- "This replay was submitted by a "
2073
- + ("newer" if newer else "different")
2074
- + " SDK than the one the snapshot installs; match the SDK you run locally to the one in the lockfile"
2075
- )
2076
- if os.environ.get("GITHUB_REF_NAME") != PREFIX + str(request.get("id")):
2077
- raise ValueError(
2078
- "The runner replays only the snapshot branch its request names; start replays with bitfab-replay --cloud"
2079
- )
2080
- validate_arguments(request["args"])
2081
- if "env" in request:
2082
- validate_environment(request["env"])
2083
- return request
2084
-
2085
-
2086
- def dispatch_event():
2087
- path = os.environ.get("GITHUB_EVENT_PATH")
2088
- if not path or not Path(path).is_file():
2089
- return {}
2090
- event = json.loads(Path(path).read_text())
2091
- return event if isinstance(event, dict) else {}
2092
-
2093
-
2094
- def dispatched_inputs():
2095
- inputs = dispatch_event().get("inputs")
2096
- return inputs if isinstance(inputs, dict) else {}
2097
-
2098
-
2099
- def event_default_branch():
2100
- repository = dispatch_event().get("repository")
2101
- branch = repository.get("default_branch") if isinstance(repository, dict) else None
2102
- if not isinstance(branch, str) or not BRANCH_NAME.fullmatch(branch):
2103
- raise ValueError(
2104
- "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"
2105
- )
2106
- return branch
2107
-
2108
-
2109
- def decode_request(text):
2110
- try:
2111
- return json.loads(text)
2112
- except ValueError:
2113
- pass
2114
- try:
2115
- return json.loads(base64.b64decode(text, validate=True))
2116
- except ValueError as error:
2117
- raise ValueError(
2118
- "The request input is neither JSON nor base64-encoded JSON"
2119
- ) from error
2120
-
2121
-
2122
- def dispatched_request():
2123
- branch = os.environ.get("GITHUB_REF_NAME", "")
2124
- inputs = dispatched_inputs()
2125
- text = str(inputs.get("request") or "").strip()
2126
- if text in ("", "-"):
2127
- raise ValueError(
2128
- f"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"
2129
- )
2130
- request = decode_request(text)
2131
- if not isinstance(request, dict):
2132
- raise ValueError("The request input must be a JSON object")
2133
- version = request.get("version", REQUEST_VERSION)
2134
- if not isinstance(version, int) or version < OLDEST_DISPATCHED_VERSION:
2135
- raise ValueError(
2136
- f"Request version {version!r} is not supported; send version {REQUEST_VERSION}, or leave version out"
2137
- )
2138
- if version > REQUEST_VERSION:
2139
- raise ValueError(
2140
- f"This replay was submitted by a newer SDK than the one {branch} installs; the request is version {version} and this SDK reads up to {REQUEST_VERSION}"
2141
- )
2142
- execution_id = request.get("id") or inputs.get("execution_id") or str(uuid.uuid4())
2143
- if not isinstance(execution_id, str) or not UUID.fullmatch(execution_id):
2144
- raise ValueError("The request id must be a UUID")
2145
- if inputs.get("execution_id") and inputs["execution_id"] != execution_id:
2146
- raise ValueError("The request id does not match the execution_id input")
2147
- args = request.get("args")
2148
- validate_arguments(args)
2149
- refuse_git_code_change(args, f"A dispatched replay runs {branch}")
2150
- if request.get("check") is True and "--dry-run" not in args:
2151
- args = [*args, "--dry-run"]
2152
- normalized = {
2153
- "version": REQUEST_VERSION,
2154
- "id": execution_id,
2155
- "cwd": request.get("cwd") or ".",
2156
- "args": args,
2157
- }
2158
- timeout = request.get("timeoutMinutes")
2159
- if timeout is not None:
2160
- if not isinstance(timeout, int) or not 1 <= timeout <= 7200:
2161
- raise ValueError("timeoutMinutes must be 1..7200")
2162
- normalized["timeoutMinutes"] = timeout
2163
- if request.get("fullOutput") is True:
2164
- normalized["fullOutput"] = True
2165
- if request.get("env"):
2166
- validate_environment(request["env"])
2167
- normalized["env"] = request["env"]
2168
- return normalized
2169
-
2170
-
2171
- def runner_request(root, commit):
2172
- if os.environ.get("GITHUB_REF_NAME", "").startswith(PREFIX):
2173
- return snapshot_request(root, commit)
2174
- return dispatched_request()
2175
-
2176
-
2177
- def check_out_snapshot_base(root, commit, branch):
2178
- try:
2179
- base = git(root, "rev-parse", "--verify", "-q", f"{commit}^")
2180
- except CommandError:
2181
- print(
2182
- "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",
2183
- flush=True,
2184
- )
2185
- return None
2186
- if isinstance(branch, str) and BRANCH_NAME.fullmatch(branch):
2187
- try:
2188
- git(root, "update-ref", f"refs/heads/{branch}", base)
2189
- git(root, "symbolic-ref", "HEAD", f"refs/heads/{branch}")
2190
- return base
2191
- except CommandError:
2192
- pass
2193
- git(root, "reset", "-q", "--soft", base)
2194
- return base
2195
-
2196
-
2197
- def flag_value(args, flag):
2198
- for index, value in enumerate(args):
2199
- if value.startswith(f"{flag}="):
2200
- return value.partition("=")[2]
2201
- if value == flag and index + 1 < len(args):
2202
- return args[index + 1]
2203
- return None
2204
-
2205
-
2206
- def replay_name(args):
2207
- return flag_value(args, "--name")
2208
-
2209
-
2210
- def git_blob(root, ref, path):
2211
- try:
2212
- size = int(git(root, "cat-file", "-s", f"{ref}:{path}"))
2213
- except (CommandError, ValueError):
2214
- return None
2215
- if size > CODE_CHANGE_MAX_FILE_BYTES:
2216
- return None
2217
- result = subprocess.run(
2218
- ["git", "-C", str(root), "show", f"{ref}:{path}"],
2219
- capture_output=True,
2220
- check=False,
2221
- )
2222
- if result.returncode or b"\x00" in result.stdout[:8000]:
2223
- return None
2224
- return result.stdout.decode("utf-8", "replace").replace("\r\n", "\n")
2225
-
2226
-
2227
- def changed_paths(root, base, commit):
2228
- raw = git(
2229
- root,
2230
- "diff",
2231
- "--name-status",
2232
- "--find-renames",
2233
- "-z",
2234
- base,
2235
- commit,
2236
- "--",
2237
- ":!.bitfab",
2238
- )
2239
- parts = [part for part in raw.split("\x00") if part]
2240
- index = 0
2241
- while index + 1 < len(parts):
2242
- status, before_path = parts[index][0], parts[index + 1]
2243
- index += 2
2244
- path = before_path
2245
- if status in "RC" and index < len(parts):
2246
- path = parts[index]
2247
- index += 1
2248
- yield status, before_path, path
2249
-
2250
-
2251
- def snapshot_code_change(
2252
- root, base, commit, name, against="uncommitted (vs HEAD)", subject_ref=None
2253
- ):
2254
- files, total = [], 0
2255
- for status, before_path, path in changed_paths(root, base, commit):
2256
- if len(files) >= CODE_CHANGE_MAX_FILES:
2257
- break
2258
- before = "" if status == "A" else git_blob(root, base, before_path)
2259
- after = "" if status == "D" else git_blob(root, commit, path)
2260
- if before is None or after is None or before == after:
2261
- continue
2262
- size = len(before.encode()) + len(after.encode())
2263
- if total + size > CODE_CHANGE_MAX_TOTAL_BYTES:
2264
- continue
2265
- total += size
2266
- files.append({"path": path, "before": before, "after": after})
2267
- if not files:
2268
- return None
2269
- head = (name or "").strip() or git(
2270
- root, "log", "-1", "--format=%s", subject_ref or base
2271
- )
2272
- word = "file" if len(files) == 1 else "files"
2273
- return {
2274
- "description": f"{head or 'Working-tree change'} ({len(files)} {word} changed {against})",
2275
- "files": files,
2276
- }
2277
-
2278
-
2279
- def branch_code_change(root, base, commit, request):
2280
- code_change_base = request.get("codeChangeBase")
2281
- if not isinstance(code_change_base, dict):
2282
- return None
2283
- sha, ref = code_change_base.get("sha"), code_change_base.get("ref")
2284
- if not (
2285
- isinstance(sha, str)
2286
- and SHA.fullmatch(sha)
2287
- and isinstance(ref, str)
2288
- and DESCRIBED_REF.fullmatch(ref)
2289
- and (
2290
- sha == base
2291
- or quiet_git(root, "rev-parse", "--verify", "-q", f"{commit}^2") == sha
2292
- )
2293
- ):
2294
- return None
2295
- return snapshot_code_change(
2296
- root, sha, commit, replay_name(request["args"]), f"vs {ref}", base
2297
- )
2298
-
2299
-
2300
- def runner_code_change(root, base, commit, request):
2301
- kind = flag_value(request["args"], CODE_CHANGE_FLAG)
2302
- if kind == "working-tree":
2303
- change = snapshot_code_change(root, base, commit, replay_name(request["args"]))
2304
- elif kind in BRANCH_CODE_CHANGES:
2305
- change = branch_code_change(root, base, commit, request)
2306
- else:
2307
- return None
2308
- return change or {"files": []}
2309
-
2310
-
2311
- def git_token_environment(token):
2312
- environment = {**os.environ, "GIT_TERMINAL_PROMPT": "0"}
2313
- if not token:
2314
- return environment
2315
- basic = base64.b64encode(f"x-access-token:{token}".encode()).decode()
2316
- return {
2317
- **environment,
2318
- "GIT_CONFIG_COUNT": "1",
2319
- "GIT_CONFIG_KEY_0": "http.https://github.com/.extraheader",
2320
- "GIT_CONFIG_VALUE_0": f"AUTHORIZATION: basic {basic}",
2321
- }
2322
-
2323
-
2324
- def fetched_base(root, ref, token):
2325
- shallow = quiet_git(root, "rev-parse", "--is-shallow-repository") == "true"
2326
- try:
2327
- command(
2328
- [
2329
- "git",
2330
- "-C",
2331
- str(root),
2332
- "fetch",
2333
- "-q",
2334
- "--no-tags",
2335
- *(["--unshallow"] if shallow else []),
2336
- "origin",
2337
- ref,
2338
- ],
2339
- env=git_token_environment(token),
2340
- timeout=FETCH_SECONDS,
2341
- )
2342
- except (CommandError, subprocess.TimeoutExpired) as error:
2343
- hint = (
2344
- "check that it exists on GitHub"
2345
- if token
2346
- else f"the workflow passes no {GIT_TOKEN_ENV} to fetch it with, so run bitfab-replay --cloud-update and commit the workflow it updates"
2347
- )
2348
- raise ValueError(
2349
- f"Could not fetch {ref} from origin to compare against ({error}); {hint}, or pass --code-change skip"
2350
- ) from None
2351
- base = quiet_git(root, "merge-base", "HEAD", "FETCH_HEAD")
2352
- if not base:
2353
- raise ValueError(
2354
- f"This branch shares no history with {ref}, so there is nothing to compare against"
2355
- )
2356
- return base
2357
-
2358
-
2359
- def dispatched_code_change(root, commit, request, token):
2360
- args = request["args"]
2361
- kind = flag_value(args, CODE_CHANGE_FLAG)
2362
- if kind not in FETCHED_CODE_CHANGES:
2363
- return None
2364
- ref = (
2365
- flag_value(args, CODE_CHANGE_BASE_FLAG)
2366
- if kind == "ref"
2367
- else event_default_branch()
2368
- )
2369
- print(f"Fetching {ref} to record the code change against it", flush=True)
2370
- base = fetched_base(root, ref, token)
2371
- change = snapshot_code_change(
2372
- root, base, commit, replay_name(args), f"vs {ref}", commit
2373
- )
2374
- return change or {"files": []}
2375
-
2376
-
2377
- def write_code_change(change):
2378
- handle, path = tempfile.mkstemp(
2379
- prefix="bitfab-code-change-",
2380
- suffix=".json",
2381
- dir=os.environ.get("RUNNER_TEMP") or None,
2382
- )
2383
- with os.fdopen(handle, "w") as out:
2384
- json.dump(change, out)
2385
- return path
2386
-
2387
-
2388
- def execute():
2389
- if os.environ.get("GITHUB_RUN_ATTEMPT") != "1":
2390
- raise ValueError("Submit a new replay instead of rerunning an Actions job")
2391
- git_token = os.environ.pop(GIT_TOKEN_ENV, None)
2392
- root = root_directory()
2393
- commit = os.environ["GITHUB_SHA"]
2394
- if git(root, "rev-parse", "HEAD") != commit:
2395
- raise ValueError("Runner checkout does not match the dispatched commit")
2396
- request = runner_request(root, commit)
2397
- snapshot = os.environ.get("GITHUB_REF_NAME", "").startswith(PREFIX)
2398
- base = (
2399
- check_out_snapshot_base(root, commit, request.get("branch"))
2400
- if snapshot
2401
- else None
2402
- )
2403
- directory = within(root, request["cwd"])
2404
- check_secrets(root)
2405
- environment = request.get("env") or {}
2406
- if environment:
2407
- workflow_environment_conflicts(root, environment)
2408
- print(f"Setting {', '.join(sorted(environment))} from the request", flush=True)
2409
- if snapshot:
2410
- change = (
2411
- None if base is None else runner_code_change(root, base, commit, request)
2412
- )
2413
- else:
2414
- change = dispatched_code_change(root, commit, request, git_token)
2415
- run_environment = dict(environment)
2416
- if change is not None:
2417
- run_environment[CODE_CHANGE_PATH_ENV] = write_code_change(change)
2418
- args = [*replay_command(), *request["args"]]
2419
- if dry_run(request["args"]):
2420
- run_check_command(directory, environment)
2421
- experiment = {}
2422
- starter = starter_key(root, request)
2423
- previous = signal.signal(signal.SIGTERM, raise_interrupt)
2424
- print(OUTPUT_BEGIN, flush=True)
2425
- try:
2426
- code, stdout, omitted, stopped = run_command(
2427
- directory,
2428
- args,
2429
- request.get("timeoutMinutes"),
2430
- experiment,
2431
- summarize=request.get("fullOutput") is not True,
2432
- environment=run_environment,
2433
- )
2434
- finally:
2435
- print(OUTPUT_END, flush=True)
2436
- signal.signal(signal.SIGTERM, previous)
2437
- revoke_starter_key(starter)
2438
- result = {
2439
- "executionId": request["id"],
2440
- "commitSha": commit,
2441
- "exitCode": code,
2442
- "stdout": stdout,
2443
- }
2444
- if omitted:
2445
- result["stdoutOmittedBytes"] = omitted
2446
- if stopped:
2447
- result["stoppedEarly"] = stopped
2448
- if UUID.fullmatch(experiment.get("id", "")):
2449
- result["testRunId"] = experiment["id"]
2450
- write_result(result)
2451
- return result
2452
-
2453
-
2454
- def runner_warning(message):
2455
- print(f"::warning title=Bitfab replay::{message}", flush=True)
2456
-
2457
-
2458
- def warn_if_workflow_outdated():
2459
- problems = []
2460
- if API_KEY_ENV in os.environ:
2461
- problems.append(
2462
- f"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"
2463
- )
2464
- if not os.environ.get("ACTIONS_ID_TOKEN_REQUEST_URL"):
2465
- problems.append(
2466
- "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"
2467
- )
2468
- if problems:
2469
- runner_warning(
2470
- f"This workflow {' and '.join(problems)}. Run bitfab-replay --cloud-update and commit the workflow it updates"
2471
- )
2472
-
2473
-
2474
- def starter_key(root, request):
2475
- warn_if_workflow_outdated()
2476
- if os.environ.get(API_KEY_ENV, "").strip():
2477
- print(
2478
- "Replaying with the Bitfab API key of the person who started this run",
2479
- flush=True,
2480
- )
2481
- return None
2482
- token = str(dispatched_inputs().get(KEY_INPUT) or "").strip()
2483
- if not token.startswith(KEY_TOKEN_PREFIX):
2484
- return None
2485
- shared = "so this run uses the workflow's BITFAB_API_KEY secret"
2486
- runner = local_client(root, request)
2487
- if runner is None:
2488
- runner_warning(
2489
- f"The replay's Bitfab client resolved no API key on the runner, {shared}"
2490
- )
2491
- return None
2492
- try:
2493
- identity = github_run_identity()
2494
- except CommandError as error:
2495
- runner_warning(f"{error}, {shared}")
2496
- return None
2497
- timeout = request.get("timeoutMinutes")
2498
- try:
2499
- redeemed = bitfab_api(
2500
- {"serviceUrl": runner["serviceUrl"]},
2501
- "replay/cloudKey/redeem",
2502
- payload={
2503
- "token": token,
2504
- "oidcToken": identity,
2505
- **({"minutes": timeout} if timeout else {}),
2506
- },
2507
- )
2508
- except CommandError as error:
2509
- runner_warning(f"{error}, {shared}")
2510
- return None
2511
- key = redeemed.get("apiKey")
2512
- if not isinstance(key, str) or not key.strip():
2513
- runner_warning(f"Bitfab returned no key for the replay token, {shared}")
2514
- return None
2515
- print(f"::add-mask::{key}", flush=True)
2516
- os.environ[API_KEY_ENV] = key
2517
- print(
2518
- "Replaying as the person who started this run, with a key that is turned off when the replay ends",
2519
- flush=True,
2520
- )
2521
- return {"apiKey": key, "serviceUrl": runner["serviceUrl"]}
2522
-
2523
-
2524
- def github_run_identity():
2525
- url = os.environ.get("ACTIONS_ID_TOKEN_REQUEST_URL")
2526
- bearer = os.environ.get("ACTIONS_ID_TOKEN_REQUEST_TOKEN")
2527
- if not url or not bearer:
2528
- raise CommandError(
2529
- "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"
2530
- )
2531
- separator = "&" if "?" in url else "?"
2532
- request = urllib.request.Request(
2533
- f"{url}{separator}{urlencode({'audience': OIDC_AUDIENCE})}",
2534
- headers={
2535
- "Authorization": f"Bearer {bearer}",
2536
- "User-Agent": "bitfab-cloud-replay",
2537
- },
2538
- )
2539
- try:
2540
- with urllib.request.urlopen(request, timeout=30) as response:
2541
- value = json.loads(response.read()).get("value")
2542
- except (urllib.error.URLError, OSError, ValueError, AttributeError) as error:
2543
- raise CommandError(
2544
- f"GitHub did not issue this run's OIDC token: {getattr(error, 'reason', error)}"
2545
- ) from None
2546
- if not isinstance(value, str) or not value:
2547
- raise CommandError("GitHub returned no OIDC token for this run")
2548
- return value
2549
-
2550
-
2551
- def revoke_starter_key(starter):
2552
- if starter is None:
2553
- return
2554
- try:
2555
- bitfab_api(starter, "replay/cloudKey", method="DELETE")
2556
- except CommandError as error:
2557
- runner_warning(
2558
- f"Could not turn off this replay's key ({error}); it expires on its own 30 minutes after the replay's timeout"
2559
- )
2560
-
2561
-
2562
- def running_workflow(root):
2563
- reference = os.environ.get("GITHUB_WORKFLOW_REF", "")
2564
- match = re.search(r"(\.github/workflows/[^@]+)@", reference)
2565
- if match:
2566
- return within(root, match[1])
2567
- return within(root, f"{WORKFLOW_DIRECTORY}/{find_workflow(root) or WORKFLOW}")
2568
-
2569
-
2570
- def check_secrets(root):
2571
- path = running_workflow(root)
2572
- targets = workflow_secrets(path.read_text()) if path.is_file() else {}
2573
- empty = [name for name in targets if os.environ.get(name) == ""]
2574
- if empty:
2575
- raise ValueError(
2576
- "These replay environment variables are empty on the runner: "
2577
- + ", ".join(f"{name} (secret {targets[name]})" for name in empty)
2578
- + ". 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"
2579
- )
2580
- for name in targets:
2581
- if any(
2582
- 0 < len(line.strip()) < 4
2583
- for line in os.environ.get(name, "").splitlines()[1:]
2584
- ):
2585
- print(
2586
- f"::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",
2587
- flush=True,
2588
- )
2589
-
2590
-
2591
- def run_check_command(directory, environment=None):
2592
- check = os.environ.get(CHECK_COMMAND_ENV, "").strip()
2593
- if not check:
2594
- return
2595
- print(f"Running {CHECK_COMMAND_ENV}: {check}", flush=True)
2596
- code = subprocess.run(
2597
- shlex.split(check),
2598
- cwd=directory,
2599
- env={**os.environ, **(environment or {})},
2600
- stdin=subprocess.DEVNULL,
2601
- check=False,
2602
- ).returncode
2603
- if code:
2604
- raise ValueError(f"{CHECK_COMMAND_ENV} exited {code}; its output is above")
2605
-
2606
-
2607
- def item_errors(items):
2608
- errors = []
2609
- for item in items:
2610
- if not item_errored(item):
2611
- continue
2612
- error = next(
2613
- item[field] for field in ITEM_ERROR_FIELDS if item.get(field) is not None
2614
- )
2615
- if isinstance(error, dict):
2616
- error = error.get("message") or json.dumps(error)
2617
- trace = next(
2618
- (
2619
- item[field]
2620
- for field in ITEM_ID_FIELDS
2621
- if isinstance(item.get(field), str)
2622
- ),
2623
- "unknown trace",
2624
- )
2625
- text = " ".join(str(error).split())
2626
- if len(text) > ITEM_ERROR_LENGTH:
2627
- text = text[:ITEM_ERROR_LENGTH] + "..."
2628
- errored = {"originalTraceId": trace, "error": text}
2629
- if isinstance(item.get("attempt"), int):
2630
- errored["attempt"] = item["attempt"]
2631
- errors.append(errored)
2632
- return errors
2633
-
2634
-
2635
- def item_field(item, camel, snake):
2636
- return item[camel] if camel in item else item.get(snake)
2637
-
2638
-
2639
- def canonical(value):
2640
- return json.dumps(value, separators=(",", ":"))
2641
-
2642
-
2643
- def experiment_fields(parsed):
2644
- fields = {}
2645
- for name, spellings in EXPERIMENT_FIELDS.items():
2646
- value = next(
2647
- (parsed[key] for key in spellings if parsed.get(key) is not None), None
2648
- )
2649
- if value is not None:
2650
- fields[name] = value
2651
- return fields
2652
-
2653
-
2654
- def replay_summary(parsed):
2655
- items = [item for item in parsed["items"] if isinstance(item, dict)]
2656
- replayed = [item for item in items if not carried_over(item)]
2657
- errors = item_errors(replayed)
2658
- counts = {
2659
- "replayed": len(replayed),
2660
- "carriedOver": len(items) - len(replayed),
2661
- "same": 0,
2662
- "changed": 0,
2663
- "matchedExpected": 0,
2664
- "missedExpected": 0,
2665
- "errored": len(errors),
2666
- }
2667
- for item in replayed:
2668
- if item_errored(item):
2669
- continue
2670
- equal = canonical(item.get("result")) == canonical(
2671
- item_field(item, "originalOutput", "original_output")
2672
- )
2673
- if item_field(item, "ingestionType", "ingestion_type") == "seeded":
2674
- counts["matchedExpected" if equal else "missedExpected"] += 1
2675
- else:
2676
- counts["same" if equal else "changed"] += 1
2677
- summary = {
2678
- "cloudSummary": True,
2679
- **experiment_fields(parsed),
2680
- "counts": counts,
2681
- "erroredItems": errors[:SUMMARY_ERROR_ITEMS],
2682
- }
2683
- if len(errors) > SUMMARY_ERROR_ITEMS:
2684
- summary["erroredItemsOmitted"] = len(errors) - SUMMARY_ERROR_ITEMS
2685
- return summary
2686
-
2687
-
2688
- def result_summary(stdout):
2689
- parsed = last_json(stdout) or {}
2690
- if parsed.get("cloudSummary") is True:
2691
- return parsed
2692
- if isinstance(parsed.get("items"), list):
2693
- return replay_summary(parsed)
2694
- return None
2695
-
2696
-
2697
- def item_errored(item):
2698
- return isinstance(item, dict) and any(
2699
- item.get(field) is not None for field in ITEM_ERROR_FIELDS
2700
- )
2701
-
2702
-
2703
- def carried_over(item):
2704
- return isinstance(item, dict) and (
2705
- item.get("carriedOver") is True or item.get("carried_over") is True
2706
- )
2707
-
2708
-
2709
- def raise_interrupt(signum, frame):
2710
- raise KeyboardInterrupt
2711
-
2712
-
2713
- def without_item_payload(line):
2714
- try:
2715
- event = json.loads(line[len(PROGRESS_PREFIX) :])
2716
- except ValueError:
2717
- return line
2718
- item = event.get("item") if isinstance(event, dict) else None
2719
- if not isinstance(item, dict):
2720
- return line
2721
- event["item"] = {
2722
- key: value for key, value in item.items() if key not in PROGRESS_PAYLOAD_FIELDS
2723
- }
2724
- return PROGRESS_PREFIX + json.dumps(event).encode() + b"\n"
2725
-
2726
-
2727
- def forward_stderr(stream, experiment, summarize):
2728
- for line in iter(stream.readline, b""):
2729
- if summarize and line.startswith(PROGRESS_PREFIX):
2730
- line = without_item_payload(line)
2731
- sys.stdout.write(line.decode(errors="replace"))
2732
- sys.stdout.flush()
2733
- if "id" not in experiment:
2734
- match = EXPERIMENT_LINE.match(line)
2735
- if match:
2736
- experiment["id"] = match[1].decode()
2737
-
2738
-
2739
- def trailing_json(text):
2740
- decoder = json.JSONDecoder()
2741
- for offset in [0, *[i + 1 for i, value in enumerate(text) if value == "\n"]]:
2742
- if text.startswith("{", offset):
2743
- try:
2744
- value, end = decoder.raw_decode(text, offset)
2745
- except json.JSONDecodeError:
2746
- continue
2747
- if not text[end:].strip() and isinstance(value, dict):
2748
- return offset, value
2749
- return None, None
2750
-
2751
-
2752
- def last_json(text):
2753
- return trailing_json(text)[1]
2754
-
2755
-
2756
- def relayed_stdout(output, code, summarize):
2757
- if summarize:
2758
- output.seek(0)
2759
- parsed = last_json(output.read().decode(errors="replace"))
2760
- if isinstance(parsed, dict) and isinstance(parsed.get("items"), list):
2761
- return json.dumps({**replay_summary(parsed), "exitCode": code}) + "\n", 0
2762
- return carried_stdout(output)
2763
-
2764
-
2765
- def carried_stdout(output):
2766
- start = max(0, os.fstat(output.fileno()).st_size - OUTPUT_LIMIT)
2767
- output.seek(start)
2768
- text = output.read().decode(errors="replace")
2769
- if not start:
2770
- return text, 0
2771
- offset = trailing_json(text)[0] or 0
2772
- return text[offset:], start + len(text[:offset].encode())
2773
-
2774
-
2775
- def write_result(result):
2776
- encoded = base64.b64encode(zlib.compress(json.dumps(result).encode())).decode()
2777
- for start in range(0, len(encoded), RESULT_CHUNK):
2778
- print(RESULT_LINE + encoded[start : start + RESULT_CHUNK])
2779
- sys.stdout.flush()
2780
- summary = os.environ.get("GITHUB_STEP_SUMMARY")
2781
- if summary:
2782
- with Path(summary).open("a") as file:
2783
- file.write(summary_markdown(result))
2784
-
2785
-
2786
- def annotate(result):
2787
- if result.get("stoppedEarly"):
2788
- message = f"Replay stopped early: {result['stoppedEarly']}"
2789
- elif result["exitCode"]:
2790
- message = f"Replay exited {result['exitCode']}, so this job exits with it too"
2791
- else:
2792
- return
2793
- print(f"::warning title=Bitfab replay::{message}", flush=True)
2794
-
2795
-
2796
- def runner_exit_code(result):
2797
- if result.get("stoppedEarly"):
2798
- return result["exitCode"] or 1
2799
- return result["exitCode"]
2800
-
2801
-
2802
- def summary_markdown(result):
2803
- summary = result_summary(result["stdout"]) or {}
2804
- counts = summary.get("counts", {})
2805
- test_run = result.get("testRunId") or summary.get("testRunId")
2806
- errors = summary.get("erroredItems", [])
2807
- lines = [f"Commit: `{result['commitSha']}`", f"Exit code: {result['exitCode']}"]
2808
- if test_run:
2809
- lines.insert(0, f"Test run: `{test_run}`")
2810
- if result.get("stoppedEarly"):
2811
- lines.append(f"Stopped early: {result['stoppedEarly']}")
2812
- elif counts.get("replayed") or counts.get("carriedOver"):
2813
- lines.append(
2814
- f"Replayed: {counts['replayed']}, same: {counts['same']}, changed: {counts['changed']}, errored: {counts['errored']}"
2815
- )
2816
- text = "### Bitfab replay\n\n" + "\n\n".join(lines) + "\n"
2817
- if errors:
2818
- shown = [
2819
- f"trace {error['originalTraceId']}: {error['error']}"
2820
- for error in errors[:ITEM_ERROR_LINES]
2821
- ]
2822
- if counts.get("errored", 0) > len(shown):
2823
- shown.append(f"and {counts['errored'] - len(shown)} more errored items")
2824
- text += "\n#### Errored items\n\n" + "".join(
2825
- f"- `{line.replace('`', chr(39))}`\n" for line in shown
2826
- )
2827
- return text
2828
-
2829
-
2830
- def run_command(
2831
- directory, args, timeout, experiment, *, summarize=True, environment=None
2832
- ):
2833
- stopped = None
2834
- with tempfile.TemporaryFile() as output:
2835
- with subprocess.Popen(
2836
- args,
2837
- cwd=directory,
2838
- env={
2839
- **os.environ,
2840
- **(environment or {}),
2841
- EXECUTION_TARGET_ENV: HOSTED_EXECUTION_TARGET,
2842
- },
2843
- stdout=output,
2844
- stderr=subprocess.PIPE,
2845
- stdin=subprocess.DEVNULL,
2846
- start_new_session=True,
2847
- ) as child:
2848
- reader = threading.Thread(
2849
- target=forward_stderr,
2850
- args=(child.stderr, experiment, summarize),
2851
- daemon=True,
2852
- )
2853
- reader.start()
2854
- try:
2855
- deadline = None if timeout is None else time.monotonic() + timeout * 60
2856
- parent = os.getppid()
2857
- checked = time.monotonic()
2858
- while child.poll() is None:
2859
- if os.fstat(output.fileno()).st_size > DISK_LIMIT:
2860
- raise ValueError("Replay printed more than 1 GiB to stdout")
2861
- if deadline is not None and time.monotonic() >= deadline:
2862
- stopped = f"it reached the {timeout}-minute --cloud-timeout"
2863
- stop(child)
2864
- break
2865
- if time.monotonic() - checked >= 1:
2866
- checked = time.monotonic()
2867
- if os.getppid() != parent:
2868
- raise KeyboardInterrupt
2869
- time.sleep(0.1)
2870
- except KeyboardInterrupt:
2871
- stopped = "the GitHub run was cancelled"
2872
- stop(child)
2873
- except BaseException:
2874
- stop(child)
2875
- raise
2876
- finally:
2877
- with contextlib.suppress(ProcessLookupError, PermissionError):
2878
- os.killpg(child.pid, signal.SIGKILL)
2879
- reader.join(timeout=5)
2880
- code = child.returncode if child.returncode >= 0 else 1
2881
- text, omitted = relayed_stdout(output, code, summarize)
2882
- return code, text, omitted, stopped
2883
-
2884
-
2885
- def stop(child):
2886
- with contextlib.suppress(ProcessLookupError):
2887
- os.killpg(child.pid, signal.SIGTERM)
2888
- with contextlib.suppress(subprocess.TimeoutExpired):
2889
- child.wait(timeout=30)
2890
- with contextlib.suppress(ProcessLookupError):
2891
- os.killpg(child.pid, signal.SIGKILL)
2892
- child.wait()
2893
-
2894
-
2895
- PNPM_FOR_LOCKFILE = {"9": "10", "6": "8", "5": "7"}
2896
- DEFAULT_PNPM = "10"
2897
- RUBY_VERSION_FILES = [".ruby-version", ".tool-versions"]
2898
- PLAIN_SCALAR = re.compile(r"[A-Za-z0-9_./][A-Za-z0-9_ ./@*+=,()-]*")
2899
- YAML_WORDS = {"true", "false", "yes", "no", "on", "off", "null", "~", "y", "n"}
2900
-
2901
-
2902
- def yaml_scalar(value):
2903
- if isinstance(value, (dict, list)):
2904
- return "{}" if isinstance(value, dict) else "[]"
2905
- if isinstance(value, bool):
2906
- return "true" if value else "false"
2907
- if isinstance(value, int):
2908
- return str(value)
2909
- text = str(value)
2910
- if (
2911
- PLAIN_SCALAR.fullmatch(text)
2912
- and text == text.strip()
2913
- and text.lower() not in YAML_WORDS
2914
- and not re.fullmatch(r"[\d._+-]+", text)
2915
- ):
2916
- return text
2917
- return json.dumps(text)
2918
-
2919
-
2920
- def yaml_key(key):
2921
- return "on" if key == "on" else yaml_scalar(str(key))
2922
-
2923
-
2924
- def yaml_lines(value, indent=0):
2925
- pad = " " * indent
2926
- lines = []
2927
- if isinstance(value, dict):
2928
- for key, item in value.items():
2929
- if isinstance(item, (dict, list)) and item:
2930
- lines.append(f"{pad}{yaml_key(key)}:")
2931
- lines += yaml_lines(item, indent + 1)
2932
- else:
2933
- lines.append(f"{pad}{yaml_key(key)}: {yaml_scalar(item)}")
2934
- else:
2935
- for item in value:
2936
- if isinstance(item, dict) and item:
2937
- nested = yaml_lines(item, indent + 1)
2938
- lines.append(f"{pad}- {nested[0].lstrip()}")
2939
- lines += nested[1:]
2940
- else:
2941
- lines.append(f"{pad}- {yaml_scalar(item)}")
2942
- return lines
2943
-
2944
-
2945
- def to_yaml(document):
2946
- return "\n".join(yaml_lines(document)) + "\n"
2947
-
2948
-
2949
- def find_upward(root, start, names):
2950
- directory = start
2951
- while True:
2952
- for name in names:
2953
- if (directory / name).is_file():
2954
- return directory, name
2955
- if directory == root:
2956
- return None, None
2957
- directory = directory.parent
2958
-
2959
-
2960
- def step_directory(root, directory):
2961
- relative = directory.relative_to(root).as_posix()
2962
- return {} if relative in ("", ".") else {"working-directory": relative}
2963
-
2964
-
2965
- def detect_language(root, start):
2966
- markers = {
2967
- "package.json": "typescript",
2968
- "pyproject.toml": "python",
2969
- "requirements.txt": "python",
2970
- "Gemfile": "ruby",
2971
- "go.mod": "go",
2972
- }
2973
- _, found = find_upward(root, start, list(markers))
2974
- if found is None:
2975
- raise ValueError(
2976
- "Could not tell which Bitfab SDK this project uses; run --cloud-init through your SDK's bitfab-replay command"
2977
- )
2978
- return markers[found]
2979
-
2980
-
2981
- def version_input(root, start, key, names, default):
2982
- directory, name = find_upward(root, start, names)
2983
- if name is None:
2984
- return {f"{key}-version": default}
2985
- return {f"{key}-version-file": (directory / name).relative_to(root).as_posix()}
2986
-
2987
-
2988
- def typescript_project(root, start):
2989
- directory, lockfile = find_upward(
2990
- root,
2991
- start,
2992
- ["pnpm-lock.yaml", "bun.lock", "bun.lockb", "yarn.lock", "package-lock.json"],
2993
- )
2994
- manager = {
2995
- "pnpm-lock.yaml": "pnpm",
2996
- "bun.lock": "bun",
2997
- "bun.lockb": "bun",
2998
- "yarn.lock": "yarn",
2999
- }.get(lockfile, "npm")
3000
- install = {
3001
- "pnpm": "pnpm install --frozen-lockfile",
3002
- "bun": "bun install --frozen-lockfile",
3003
- "yarn": "yarn install --frozen-lockfile",
3004
- "npm": "npm ci" if lockfile else "npm install",
3005
- }[manager]
3006
- steps = []
3007
- if manager == "pnpm":
3008
- steps.append(pnpm_setup(root, directory, lockfile))
3009
- if manager == "bun":
3010
- steps.append({"uses": ACTIONS["bun"]})
3011
- cache = {}
3012
- if manager in ("pnpm", "yarn", "npm") and lockfile:
3013
- cache["cache"] = manager
3014
- if directory != root:
3015
- cache["cache-dependency-path"] = (
3016
- (directory / lockfile).relative_to(root).as_posix()
3017
- )
3018
- steps += [
3019
- {
3020
- "uses": ACTIONS["node"],
3021
- "with": {
3022
- **version_input(
3023
- root, start, "node", [".nvmrc", ".node-version"], "lts/*"
3024
- ),
3025
- **cache,
3026
- },
3027
- },
3028
- {**step_directory(root, directory or start), "run": install},
3029
- ]
3030
- run = {
3031
- "pnpm": "pnpm exec bitfab-replay",
3032
- "bun": "bunx bitfab-replay",
3033
- "yarn": "yarn bitfab-replay",
3034
- "npm": "npx --no-install bitfab-replay",
3035
- }[manager]
3036
- return steps, run
3037
-
3038
-
3039
- def pnpm_setup(root, directory, lockfile):
3040
- package = directory / "package.json"
3041
- try:
3042
- declared = json.loads(package.read_text()).get("packageManager", "")
3043
- except (OSError, ValueError, AttributeError):
3044
- declared = ""
3045
- if isinstance(declared, str) and declared.startswith("pnpm@"):
3046
- if directory == root:
3047
- return {"uses": ACTIONS["pnpm"]}
3048
- return {
3049
- "uses": ACTIONS["pnpm"],
3050
- "with": {"package_json_file": package.relative_to(root).as_posix()},
3051
- }
3052
- found = re.search(
3053
- r"^lockfileVersion:\s*['\"]?(\d+)",
3054
- (directory / lockfile).read_text(errors="replace"),
3055
- re.MULTILINE,
3056
- )
3057
- version = PNPM_FOR_LOCKFILE.get(found[1] if found else "", DEFAULT_PNPM)
3058
- return {"uses": ACTIONS["pnpm"], "with": {"version": version}}
3059
-
3060
-
3061
- def python_project(root, start):
3062
- directory, lockfile = find_upward(
3063
- root, start, ["uv.lock", "poetry.lock", "requirements.txt", "pyproject.toml"]
3064
- )
3065
- location = step_directory(root, directory or start)
3066
- python = {
3067
- "uses": ACTIONS["python"],
3068
- "with": version_input(root, start, "python", [".python-version"], "3.12"),
3069
- }
3070
- if lockfile == "uv.lock":
3071
- return [
3072
- {"uses": ACTIONS["uv"]},
3073
- {**location, "run": "uv sync --frozen"},
3074
- ], "uv run bitfab-replay"
3075
- if lockfile == "poetry.lock":
3076
- return [
3077
- python,
3078
- {
3079
- **location,
3080
- "run": "pipx install poetry && poetry install --no-interaction",
3081
- },
3082
- ], "poetry run bitfab-replay"
3083
- install = (
3084
- "pip install -r requirements.txt"
3085
- if lockfile == "requirements.txt"
3086
- else "pip install ."
3087
- )
3088
- return [python, {**location, "run": install}], "bitfab-replay"
3089
-
3090
-
3091
- def ruby_project(root, start):
3092
- directory, _ = find_upward(root, start, ["Gemfile"])
3093
- directory = directory or start
3094
- found, name = find_upward(root, directory, RUBY_VERSION_FILES)
3095
- version = (
3096
- {}
3097
- if found == directory
3098
- else {"ruby-version": (name and ruby_version(found / name)) or "ruby"}
3099
- )
3100
- return [
3101
- {
3102
- "uses": ACTIONS["ruby"],
3103
- "with": {
3104
- **version,
3105
- "bundler-cache": True,
3106
- **step_directory(root, directory),
3107
- },
3108
- }
3109
- ], "bundle exec bitfab-replay"
3110
-
3111
-
3112
- def ruby_version(path):
3113
- text = path.read_text(errors="replace")
3114
- if path.name == ".tool-versions":
3115
- found = re.search(r"^ruby\s+(\S+)", text, re.MULTILINE)
3116
- return found[1] if found else None
3117
- return text.strip() or None
3118
-
3119
-
3120
- def go_project(root, start):
3121
- directory, name = find_upward(root, start, ["go.mod"])
3122
- version = (
3123
- {"go-version-file": (directory / name).relative_to(root).as_posix()}
3124
- if name
3125
- else {"go-version": "stable"}
3126
- )
3127
- return [{"uses": ACTIONS["go"], "with": version}], go_registry_command(root, start)
3128
-
3129
-
3130
- def go_registry_command(root, start):
3131
- programs = set()
3132
- for directory, folders, names in os.walk(root):
3133
- folders[:] = [
3134
- folder
3135
- for folder in folders
3136
- if not folder.startswith(".")
3137
- and folder not in ("node_modules", "vendor", "testdata")
3138
- ]
3139
- for name in names:
3140
- if not name.endswith(".go") or name.endswith("_test.go"):
3141
- continue
3142
- text = (Path(directory) / name).read_text(errors="replace")
3143
- if "RunCloudReplayCLI(" in text and re.search(
3144
- r"^package main\b", text, re.MULTILINE
3145
- ):
3146
- programs.add(Path(directory))
3147
- if len(programs) != 1:
3148
- return None
3149
- relative = os.path.relpath(programs.pop(), start)
3150
- return f"go run {relative if relative.startswith('..') else './' + relative}"
3151
-
3152
-
3153
- PROJECTS = {
3154
- "typescript": typescript_project,
3155
- "python": python_project,
3156
- "ruby": ruby_project,
3157
- "go": go_project,
3158
- }
3159
-
3160
-
3161
- def push_triggers(root, workflow):
3162
- found = []
3163
- directory = root / WORKFLOW_DIRECTORY
3164
- for path in sorted(directory.glob("*.y*ml")) if directory.is_dir() else []:
3165
- text = path.read_text(errors="replace")
3166
- if path.name != workflow and PUSH_TRIGGER.search(text) and PREFIX not in text:
3167
- found.append(path.relative_to(root).as_posix())
3168
- for path in (root / "vercel.json", Path.cwd() / "vercel.json"):
3169
- relative = path.resolve().relative_to(root).as_posix()
3170
- if (
3171
- path.is_file()
3172
- and PREFIX not in path.read_text(errors="replace")
3173
- and relative not in found
3174
- ):
3175
- found.append(relative)
3176
- return found
3177
-
3178
-
3179
- def workflow_document(steps, run, directory, env, *, runs_on, environment):
3180
- job = {"if": PUSH_CONDITION, "runs-on": runs_on}
3181
- if environment:
3182
- job["environment"] = environment
3183
- job["steps"] = [
3184
- {
3185
- "uses": ACTIONS["checkout"],
3186
- "with": {"persist-credentials": False, "fetch-depth": CHECKOUT_DEPTH},
3187
- },
3188
- *steps,
3189
- {
3190
- **({} if directory == "." else {"working-directory": directory}),
3191
- "run": f"{run} --cloud-execute",
3192
- "env": {**env, GIT_TOKEN_ENV: GIT_TOKEN_VALUE},
3193
- },
3194
- ]
3195
- return {
3196
- "name": "Bitfab replay",
3197
- "run-name": RUN_NAME,
3198
- "on": {
3199
- "workflow_dispatch": {
3200
- "inputs": {
3201
- "execution_id": {"type": "string", "required": False},
3202
- "request": {"type": "string", "required": False},
3203
- KEY_INPUT: {"type": "string", "required": False},
3204
- }
3205
- },
3206
- "push": {"branches": [PREFIX + "**"]},
3207
- },
3208
- "permissions": {"contents": "read", "id-token": "write"},
3209
- "jobs": {"replay": job},
3210
- }
3211
-
3212
-
3213
- def indentation(line):
3214
- return len(line) - len(line.lstrip(" \t"))
3215
-
3216
-
3217
- def block_end(lines, start, indent):
3218
- end = start + 1
3219
- while end < len(lines) and (
3220
- not lines[end].strip()
3221
- or lines[end].lstrip().startswith("#")
3222
- or indentation(lines[end]) > indent
3223
- ):
3224
- end += 1
3225
- while end > start + 1 and (
3226
- not lines[end - 1].strip()
3227
- or (
3228
- lines[end - 1].lstrip().startswith("#")
3229
- and indentation(lines[end - 1]) <= indent
3230
- )
3231
- ):
3232
- end -= 1
3233
- return end
3234
-
3235
-
3236
- def add_input(lines, name):
3237
- for index, line in enumerate(lines):
3238
- if not re.fullmatch(r'[ \t]*"?request"?[ \t]*:[ \t]*', line):
3239
- continue
3240
- indent = indentation(line)
3241
- child = " " * (
3242
- indentation(lines[index + 1])
3243
- if block_end(lines, index, indent) > index + 1
3244
- else indent + 2
3245
- )
3246
- end = block_end(lines, index, indent - 1)
3247
- lines[end:end] = [
3248
- f"{line[:indent]}{name}:",
3249
- f"{child}type: string",
3250
- f"{child}required: false",
3251
- ]
3252
- return True
3253
- return False
3254
-
3255
-
3256
- def add_run_name(lines):
3257
- named = next(
3258
- (
3259
- index
3260
- for index, line in enumerate(lines)
3261
- if re.match(r'"?name"?[ \t]*:', line)
3262
- ),
3263
- -1,
3264
- )
3265
- lines.insert(named + 1, f"run-name: {json.dumps(RUN_NAME)}")
3266
-
3267
-
3268
- def without_yaml_comment(line):
3269
- return re.sub(r"(^|\s)#.*", "", line)
3270
-
3271
-
3272
- def remove_legacy_key_env(lines):
3273
- kept = [line for line in lines if not LEGACY_KEY_SECRET_REFERENCE.match(line)]
3274
- if len(kept) == len(lines):
3275
- return False
3276
- lines[:] = kept
3277
- return True
3278
-
3279
-
3280
- def raise_checkout_depth(lines, start, end):
3281
- for at in range(start, end):
3282
- if not re.match(r'[ \t]*"?fetch-depth"?[ \t]*:', lines[at]):
3283
- continue
3284
- depth = re.match(
3285
- r'([ \t]*"?fetch-depth"?[ \t]*:[ \t]*)["\']?(\d+)["\']?(.*)',
3286
- lines[at],
3287
- )
3288
- if depth is None or int(depth[2]) == 0 or int(depth[2]) >= CHECKOUT_DEPTH:
3289
- return False
3290
- lines[at] = f"{depth[1]}{CHECKOUT_DEPTH}{depth[3]}"
3291
- return True
3292
- return None
3293
-
3294
-
3295
- def add_checkout_depth(lines):
3296
- for index, line in enumerate(lines):
3297
- match = re.match(
3298
- r'([ \t]*)(- +)?"?uses"?[ \t]*:[ \t]*"?[\w.-]+/checkout@',
3299
- without_yaml_comment(line),
3300
- )
3301
- if not match:
3302
- continue
3303
- key = len(match[1]) + len(match[2] or "")
3304
- start = index
3305
- while start > 0 and not re.match(r"[ \t]*- ", lines[start]):
3306
- start -= 1
3307
- end = block_end(lines, start, key - 1)
3308
- raised = raise_checkout_depth(lines, start, end)
3309
- if raised is not None:
3310
- return "updated" if raised else "unchanged"
3311
- entry = f"fetch-depth: {CHECKOUT_DEPTH}"
3312
- for at in range(start, end):
3313
- with_key = re.fullmatch(
3314
- r"[ \t]*(- +)?with[ \t]*:(.*)", without_yaml_comment(lines[at])
3315
- )
3316
- if not with_key:
3317
- continue
3318
- if len(lines[at]) - len(lines[at].lstrip(" \t-")) != key:
3319
- continue
3320
- if with_key[2].strip():
3321
- return "by hand"
3322
- entries = block_end(lines, at, key)
3323
- child = indentation(lines[at + 1]) if entries > at + 1 else key + 2
3324
- lines.insert(entries, " " * child + entry)
3325
- return "updated"
3326
- lines[end:end] = [" " * key + "with:", " " * (key + 2) + entry]
3327
- return "updated"
3328
- return "unchanged"
3329
-
3330
-
3331
- def has_git_token_env(lines):
3332
- return any(
3333
- re.match(rf'[ \t]*(- +)?"?{GIT_TOKEN_ENV}"?[ \t]*:', without_yaml_comment(line))
3334
- for line in lines
3335
- )
3336
-
3337
-
3338
- def add_git_token_env(lines):
3339
- execute = next(
3340
- (
3341
- index
3342
- for index in range(len(lines) - 1, -1, -1)
3343
- if "--cloud-execute" in without_yaml_comment(lines[index])
3344
- ),
3345
- None,
3346
- )
3347
- if execute is None:
3348
- return False
3349
- start = execute
3350
- while start > 0 and not re.match(r"[ \t]*- ", lines[start]):
3351
- start -= 1
3352
- key = len(lines[start]) - len(lines[start].lstrip(" \t-"))
3353
- end = block_end(lines, start, key - 1)
3354
- entry = f"{GIT_TOKEN_ENV}: {json.dumps(GIT_TOKEN_VALUE)}"
3355
- for at in range(start, end):
3356
- env_key = re.fullmatch(
3357
- r"[ \t]*(- +)?\"?env\"?[ \t]*:(.*)", without_yaml_comment(lines[at])
3358
- )
3359
- if not env_key or len(lines[at]) - len(lines[at].lstrip(" \t-")) != key:
3360
- continue
3361
- if env_key[2].strip():
3362
- return False
3363
- entries = block_end(lines, at, key)
3364
- child = indentation(lines[at + 1]) if entries > at + 1 else key + 2
3365
- lines.insert(entries, " " * child + entry)
3366
- return True
3367
- lines[end:end] = [" " * key + "env:", " " * (key + 2) + entry]
3368
- return True
3369
-
3370
-
3371
- def add_id_token_permission(lines):
3372
- for index, line in enumerate(lines):
3373
- if not re.fullmatch(r'"?permissions"?[ \t]*:[ \t]*(#.*)?', line):
3374
- continue
3375
- end = block_end(lines, index, 0)
3376
- lines.insert(end, f"{child_indent(lines, index, end, ' ')}id-token: write")
3377
- return True
3378
- return False
3379
-
3380
-
3381
- def holds_yaml(line):
3382
- return bool(line.strip()) and not line.lstrip().startswith("#")
3383
-
3384
-
3385
- def child_indent(lines, index, end, fallback):
3386
- return next(
3387
- (
3388
- lines[row][: indentation(lines[row])]
3389
- for row in range(index + 1, end)
3390
- if holds_yaml(lines[row])
3391
- ),
3392
- fallback,
3393
- )
3394
-
3395
-
3396
- def add_push_trigger(lines):
3397
- for index, line in enumerate(lines):
3398
- if not re.fullmatch(r'"?on"?[ \t]*:[ \t]*(#.*)?', line):
3399
- continue
3400
- end = block_end(lines, index, 0)
3401
- step = child_indent(lines, index, end, " ")
3402
- lines[end:end] = [
3403
- f"{step}push:",
3404
- f"{step * 2}branches:",
3405
- f"{step * 3}- {PREFIX}**",
3406
- ]
3407
- return True
3408
- return False
3409
-
3410
-
3411
- def add_push_condition(lines):
3412
- jobs = next(
3413
- (
3414
- index
3415
- for index, line in enumerate(lines)
3416
- if re.fullmatch(r'"?jobs"?[ \t]*:[ \t]*(#.*)?', line)
3417
- ),
3418
- None,
3419
- )
3420
- if jobs is None:
3421
- return False
3422
- end = block_end(lines, jobs, 0)
3423
- job = next((row for row in range(jobs + 1, end) if holds_yaml(lines[row])), None)
3424
- if job is None or not lines[job].rstrip().endswith(":"):
3425
- return False
3426
- job_end = block_end(lines, job, indentation(lines[job]))
3427
- step = child_indent(lines, job, job_end, " " * (indentation(lines[job]) + 2))
3428
- if any(
3429
- re.fullmatch(rf'{step}"?if"?[ \t]*:.*', lines[row])
3430
- for row in range(job + 1, job_end)
3431
- ):
3432
- return False
3433
- lines.insert(job + 1, f"{step}if: {json.dumps(PUSH_CONDITION)}")
3434
- return True
3435
-
3436
-
3437
- def secret_scope(environment):
3438
- return f"environments/{environment}/" if environment else "actions/"
3439
-
3440
-
3441
- def secret_names(repo, environment):
3442
- names, page = [], 1
3443
- while True:
3444
- listed = (
3445
- api(
3446
- repo,
3447
- f"{secret_scope(environment)}secrets?per_page={SECRETS_PER_PAGE}&page={page}",
3448
- )
3449
- or {}
3450
- )
3451
- batch = [secret["name"] for secret in listed.get("secrets", [])]
3452
- names.extend(batch)
3453
- if len(batch) < SECRETS_PER_PAGE:
3454
- return names
3455
- page += 1
3456
-
3457
-
3458
- def leftover_key_secrets(repo, environment):
3459
- return [
3460
- {"name": name, "environment": scope}
3461
- for scope in dict.fromkeys([None, environment])
3462
- for name in secret_names(repo, scope)
3463
- if name.startswith(LEFTOVER_KEY_SECRET_PREFIX)
3464
- ]
3465
-
3466
-
3467
- def delete_secret(repo, secret):
3468
- try:
3469
- api(
3470
- repo,
3471
- f"{secret_scope(secret['environment'])}secrets/{secret['name']}",
3472
- method="DELETE",
3473
- )
3474
- except CommandError as error:
3475
- if error.http_status != 404:
3476
- return False
3477
- return True
3478
-
3479
-
3480
- def leftover_key_secret_report(root, text, remove):
3481
- try:
3482
- repo = repository(root)
3483
- except ValueError:
3484
- return {}, []
3485
- configured = ENVIRONMENT_SETTING.search(text)
3486
- environment = configured[1] if configured else None
3487
- pages = " and ".join(
3488
- dict.fromkeys(secrets_page(repo, scope) for scope in (None, environment))
3489
- )
3490
- try:
3491
- found = leftover_key_secrets(repo, environment)
3492
- except (ValueError, RuntimeError):
3493
- return {}, [
3494
- f"Could not list the repository's secrets to look for {LEFTOVER_KEY_SECRET_PREFIX}* secrets an older SDK left behind, each a copy of someone's Bitfab API key; delete any at {pages}"
3495
- ]
3496
- if not found:
3497
- return {}, []
3498
- if not remove:
3499
- return {"oldKeySecrets": [secret["name"] for secret in found]}, [
3500
- f"Delete {len(found)} {LEFTOVER_KEY_SECRET_PREFIX}* secret{'s' if len(found) != 1 else ''} an older SDK left behind when a replay could not remove {'them' if len(found) != 1 else 'it'}. Each holds a copy of the Bitfab API key of the person who started that replay, and nothing reads them now. Run bitfab-replay --cloud-update --remove-old-key-secrets, or delete them at {pages}"
3501
- ]
3502
- removed = [secret for secret in found if delete_secret(repo, secret)]
3503
- failed = [secret["name"] for secret in found if secret not in removed]
3504
- report = {"removedOldKeySecrets": [secret["name"] for secret in removed]}
3505
- if not failed:
3506
- return report, []
3507
- return {**report, "oldKeySecrets": failed}, [
3508
- f"Could not delete {', '.join(failed)}, which needs permission to manage the repository's Actions secrets; delete them at {pages}"
3509
- ]
3510
-
3511
-
3512
- def update_workflow(root, path, *, remove_old_key_secrets=False):
3513
- target = within(root, path)
3514
- text = target.read_text()
3515
- lines = text.split("\n")
3516
- updated, by_hand = [], []
3517
- declared = declared_inputs(text)
3518
- for name in ("execution_id", KEY_INPUT):
3519
- if name in declared:
3520
- continue
3521
- if add_input(lines, name):
3522
- updated.append(f"Added the {name} input")
3523
- else:
3524
- by_hand.append(
3525
- f"{name} (type: string, required: false) under on.workflow_dispatch.inputs"
3526
- )
3527
- if not starts_on_push(text):
3528
- if push_trigger(lines) is None and add_push_trigger(lines):
3529
- updated.append(
3530
- f"Started the workflow on a push to a {PREFIX} branch too, so a replay runs without GitHub access, with no updates on it"
3531
- )
3532
- else:
3533
- by_hand.append(f"{PREFIX}** in on.push.branches")
3534
- if push_trigger(lines) is not None and PUSH_SUBJECT not in text:
3535
- if add_push_condition(lines):
3536
- updated.append(
3537
- "Skipped the push run of a replay started through the GitHub API, so each replay runs once"
3538
- )
3539
- else:
3540
- by_hand.append(f"if: {json.dumps(PUSH_CONDITION)} on the replay job")
3541
- if not re.search(r'^"?run-name"?[ \t]*:', text, re.MULTILINE):
3542
- add_run_name(lines)
3543
- updated.append("Named each run after its execution")
3544
- if not grants_id_token(text):
3545
- if add_id_token_permission(lines):
3546
- updated.append(
3547
- "Granted id-token: write, so a run can prove to Bitfab which run it is and get the key of the person who started it"
3548
- )
3549
- else:
3550
- by_hand.append(
3551
- "id-token: write under the workflow's top-level permissions block"
3552
- )
3553
- if remove_legacy_key_env(lines):
3554
- updated.append(
3555
- f"Removed the {API_KEY_ENV} line, which read a secret by a name built from the run's inputs and so gave the runner every secret in the repository; the runner now gets the key from Bitfab"
3556
- )
3557
- if not has_git_token_env(lines):
3558
- if add_git_token_env(lines):
3559
- updated.append(
3560
- f"Passed the run's GitHub token to the replay step as {GIT_TOKEN_ENV}, so a --cloud-ref or dispatched replay can fetch the branch it compares against for --code-change default-branch or ref; the replay itself never sees it"
3561
- )
3562
- else:
3563
- by_hand.append(
3564
- f"{GIT_TOKEN_ENV}: {json.dumps(GIT_TOKEN_VALUE)} in the env of the step that runs --cloud-execute"
3565
- )
3566
- depth = add_checkout_depth(lines)
3567
- if depth == "updated":
3568
- updated.append(
3569
- "Checked out the commit each snapshot is taken on, so experiments record the code change"
3570
- )
3571
- elif depth == "by hand":
3572
- by_hand.append(f"fetch-depth: {CHECKOUT_DEPTH} in the checkout step's with")
3573
- if updated:
3574
- target.write_text("\n".join(lines))
3575
- steps = []
3576
- if updated:
3577
- steps.append(
3578
- f"Commit {path}. A --cloud replay runs the workflow in its own snapshot, so the next one uses it; --cloud-ref replays need it on the branch they replay"
3579
- )
3580
- if by_hand:
3581
- steps.append(
3582
- "Cloud replay could not place these lines, so add them by hand: "
3583
- + "; ".join(by_hand)
3584
- )
3585
- if not steps:
3586
- steps.append(
3587
- "Already set up. Edit the workflow directly to change its install steps, secrets, runner, or Environment"
3588
- )
3589
- leftovers, leftover_steps = leftover_key_secret_report(
3590
- root, text, remove_old_key_secrets
3591
- )
3592
- return {
3593
- "files": [path] if updated else [],
3594
- "workflow": path,
3595
- "updated": updated,
3596
- **leftovers,
3597
- "next": [*steps, *leftover_steps],
3598
- }
3599
-
3600
-
3601
- def initialize(argv, name="--cloud-init"):
3602
- parser = argparse.ArgumentParser(
3603
- prog=f"bitfab-replay {name}",
3604
- description="Write .github/workflows/bitfab-replay.yml, the only file cloud replay keeps in the repository, and list what is left to do. It detects the runtime, package manager, install command, and replay command from the directory you run it in. On an existing workflow it only adds what a newer SDK needs (the execution_id and key_id inputs, the push trigger and the condition that skips a duplicate push run, the run name, the id-token: write permission, and the BITFAB_REPLAY_GIT_TOKEN line that lets a --cloud-ref or dispatched replay fetch the branch it compares against), removes the BITFAB_REPLAY_BITFAB_API_KEY line older SDKs wrote, lists what it changed, and lists the BITFAB_REPLAY_KEY_* secrets older SDKs left in the repository; edit it directly for anything else.",
3605
- )
3606
- parser.add_argument(
3607
- "--secret",
3608
- action="append",
3609
- default=[],
3610
- metavar="NAME",
3611
- help="Environment variable the replay reads from a GitHub secret, such as OPENAI_API_KEY; repeatable. BITFAB_API_KEY is always included",
3612
- )
3613
- parser.add_argument(
3614
- "--secret-prefix",
3615
- default=DEFAULT_SECRET_PREFIX,
3616
- help=f"Prefix of the GitHub secret each value is read from (default {DEFAULT_SECRET_PREFIX}, so OPENAI_API_KEY reads {DEFAULT_SECRET_PREFIX}OPENAI_API_KEY); pass an empty string to reuse secrets under their own names",
3617
- )
3618
- parser.add_argument(
3619
- "--environment",
3620
- help="GitHub Environment that holds the secrets, such as bitfab-replay; add required reviewers to it so no run gets credentials until someone approves",
3621
- )
3622
- parser.add_argument(
3623
- "--run",
3624
- help='Command that starts the SDK\'s bitfab-replay on the runner, such as "pnpm exec bitfab-replay"; detected for every SDK, including the Go program that calls RunCloudReplayCLI',
3625
- )
3626
- parser.add_argument("--runs-on", default="ubuntu-24.04", help="Runner label")
3627
- parser.add_argument(
3628
- "--remove-old-key-secrets",
3629
- action="store_true",
3630
- help=f"On an existing workflow, also delete the {LEFTOVER_KEY_SECRET_PREFIX}* GitHub secrets an older SDK left behind, each a copy of the Bitfab API key of the person who started a replay",
3631
- )
3632
- parser.add_argument(
3633
- "--check",
3634
- help='Command the runner also runs on a --cloud --dry-run, such as "node scripts/checkBucket.js"',
3635
- )
3636
- args = parser.parse_args(argv)
3637
- root = root_directory()
3638
- refuse_old_setup(root)
3639
- existing = find_workflow(root)
3640
- if existing is not None:
3641
- return update_workflow(
3642
- root,
3643
- f"{WORKFLOW_DIRECTORY}/{existing}",
3644
- remove_old_key_secrets=args.remove_old_key_secrets,
3645
- )
3646
- prefix = args.secret_prefix
3647
- if prefix and not re.fullmatch(r"[A-Z][A-Z0-9_]*_", prefix):
3648
- raise ValueError(
3649
- "--secret-prefix must be uppercase and end with an underscore, such as BITFAB_CLOUD_"
3650
- )
3651
- names = list(dict.fromkeys(["BITFAB_API_KEY", *args.secret]))
3652
- if not all(re.fullmatch(r"[A-Z_][A-Z0-9_]*", name) for name in names):
3653
- raise ValueError("Secret names must be uppercase environment variable names")
3654
- start = Path.cwd().resolve()
3655
- directory = working_directory(root)
3656
- language = os.environ.get(SDK_LANGUAGE_ENV) or detect_language(root, start)
3657
- steps, run = PROJECTS[language](root, start)
3658
- run = args.run or run
3659
- if not run:
3660
- raise ValueError(
3661
- 'Pass --run with the command that starts your registry program on the runner, such as --run "go run ./cmd/registry"'
3662
- )
3663
- env = {name: "${{ secrets." + prefix + name + " }}" for name in names}
3664
- if args.check:
3665
- env[CHECK_COMMAND_ENV] = args.check
3666
- path = f"{WORKFLOW_DIRECTORY}/{WORKFLOW}"
3667
- target = within(root, path)
3668
- target.parent.mkdir(parents=True, exist_ok=True)
3669
- with target.open("x") as file:
3670
- file.write(
3671
- to_yaml(
3672
- workflow_document(
3673
- steps,
3674
- run,
3675
- directory,
3676
- env,
3677
- runs_on=args.runs_on,
3678
- environment=args.environment,
3679
- )
3680
- )
3681
- )
3682
- secrets = sorted(prefix + name for name in names)
3683
- triggers = push_triggers(root, WORKFLOW)
3684
- try:
3685
- where = secrets_page(repository(root), args.environment)
3686
- except (ValueError, RuntimeError):
3687
- where = "the repository's Settings, Secrets and variables, Actions"
3688
- return {
3689
- "files": [path],
3690
- "detected": {
3691
- "language": language,
3692
- "install": [step.get("run") or step["uses"] for step in steps],
3693
- "replay": f"{run} --cloud-execute",
3694
- },
3695
- "secrets": secrets,
3696
- "reviewPushTriggers": triggers,
3697
- "next": [
3698
- "Compare the install steps with your CI and add anything detection missed, such as a build or code-generation step",
3699
- f"Create the secrets {', '.join(secrets)} at {where}, or copy them from a local file with bitfab-replay --cloud-secrets --env-file .env",
3700
- *(
3701
- [
3702
- f"Keep bitfab-replay/** branches from triggering {', '.join(triggers)}"
3703
- ]
3704
- if triggers
3705
- else []
3706
- ),
3707
- f"Commit {path} and merge it to the default branch once, so GitHub registers it",
3708
- "Add --cloud --dry-run to your replay command to check the runner, then replay with --cloud",
3709
- ],
3710
- }
3711
-
3712
-
3713
- def print_json(value):
3714
- print(json.dumps(value, indent=2), flush=True)
3715
-
3716
-
3717
- def main():
3718
- argv = sys.argv[1:]
3719
- try:
3720
- if argv[:1] in (["--cloud-init"], ["--cloud-update"]):
3721
- print_json(initialize(argv[1:], argv[0]))
3722
- return 0
3723
- if argv[:1] == ["--cloud-secrets"]:
3724
- print_json(configure_secrets(argv[1:]))
3725
- return 0
3726
- if argv[:1] == [REPLAY_ARGUMENTS_FLAG]:
3727
- print_json(replay_arguments(argv[1:]))
3728
- return 0
3729
- if argv == ["--cloud-execute"]:
3730
- result = execute()
3731
- annotate(result)
3732
- return runner_exit_code(result)
3733
- if "-h" in argv or "--help" in argv:
3734
- print(HELP, end="")
3735
- return 0
3736
- record, found = run_cli(argv)
3737
- if found is not None:
3738
- return print_outcome(found)
3739
- print_json(record)
3740
- return record.get("exitCode", 0) if record.get("state") == "completed" else 0
3741
- except KeyboardInterrupt:
3742
- progress(
3743
- "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"
3744
- )
3745
- return 130
3746
- except (
3747
- ValueError,
3748
- RuntimeError,
3749
- OSError,
3750
- subprocess.SubprocessError,
3751
- KeyError,
3752
- ) as error:
3753
- print(f"Cloud replay: {error}", file=sys.stderr)
3754
- return 1
3755
-
3756
-
3757
- if __name__ == "__main__":
3758
- raise SystemExit(main())