diff --git a/PLAN.md b/PLAN.md index aa47d399..cba5c06f 100644 --- a/PLAN.md +++ b/PLAN.md @@ -165,6 +165,12 @@ Actions visibility and runner evaluation. - `docs/bugs/fixed/runners-registering-together-lose-their-tokens.md` - `docs/bugs/fixed/github-context-identity-values-are-empty.md` - `docs/bugs/fixed/rendered-github-context-differs-from-github.md` +- `docs/bugs/fixed/container-and-services-jobs-run-on-the-host.md` +- `docs/bugs/fixed/unresolved-reusable-workflow-call-passes.md` +- `docs/bugs/fixed/skipped-reusable-workflow-caller-lists-the-called-jobs.md` +- `docs/bugs/fixed/job-needing-a-reusable-workflow-caller-waits-forever.md` +- `docs/bugs/fixed/actions-in-emulator-repositories-are-fetched-upstream.md` +- `docs/bugs/fixed/jobs-list-shows-jobs-waiting-on-needs.md` ## Decisions diff --git a/docs/bugs/fixed/actions-in-emulator-repositories-are-fetched-upstream.md b/docs/bugs/fixed/actions-in-emulator-repositories-are-fetched-upstream.md new file mode 100644 index 00000000..0860947a --- /dev/null +++ b/docs/bugs/fixed/actions-in-emulator-repositories-are-fetched-upstream.md @@ -0,0 +1,39 @@ +# Bug: an action in a repository on the emulator is fetched upstream + +Status: fixed 2026-11-14. + +## Summary + +The emulator resolved and fetched every `uses: owner/repo@ref` from +github.com. An action pushed to a repository on the emulator therefore +failed with "does not exist upstream". GitHub Enterprise Server resolves an +action against a repository it holds, and goes to github.com only for a +repository it lacks. A test stack that pushes its own actions needs the same. + +## Fix + +- `actionsdownloadinfo` resolves `owner/repo@ref` against a repository on the + emulator first. A name the emulator does not hold goes upstream. +- Unlike GHES, a public repository here that lacks the ref also goes + upstream, so a partial local copy of a public action (one pushed without + all its tags) still works. +- A private or internal repository here that lacks the ref is unresolvable + (`404` `UnresolvableActionDownloadInfoException`), and the archive URL for a + commit it lacks is `404`. Neither is looked up upstream under the same name, + so a private action's name never resolves to a different upstream + repository's code. +- A job may use a repository here as an action only when it is public or is + the job's own repository. GitHub lets other repositories use a private or + internal repository's actions only when its owner enables that access, and + the emulator has no such setting yet, so it allows only these two. Any + other private or internal repository, the same owner's included, is + unresolvable (`404` `UnresolvableActionDownloadInfoException`) and its name + is not looked up upstream. The archive URL applies the same rule (`404`), + since a job can request it directly. +- The name is matched case-insensitively; when two repositories differ only + in case, the first created is used. +- The archive is built with `git archive`, with one top-level directory as in + GitHub's archives, and cached apart from upstream archives + (`action_download_service`). + +Tests: `tests/actions/test_emulator_hosted_actions.py`. diff --git a/docs/bugs/fixed/container-and-services-jobs-run-on-the-host.md b/docs/bugs/fixed/container-and-services-jobs-run-on-the-host.md new file mode 100644 index 00000000..1466b3ae --- /dev/null +++ b/docs/bugs/fixed/container-and-services-jobs-run-on-the-host.md @@ -0,0 +1,28 @@ +# Bug: container and services jobs run their steps on the runner host + +Status: fixed 2026-11-14. + +## Summary + +On GitHub, a job with `container:` runs its steps inside that container, and +`services:` starts service containers beside the job. Neither runner path in +the emulator starts job or service containers. A job with either key ran its +steps on the runner host instead: + +- a step that checked the container (`grep Alpine /etc/os-release`) failed; +- a step that needed only a shell passed. + +Either way the outcome described the runner host, not the workflow. + +## Fix + +`workflow_service.build_job_graph` replaces the steps of a job with +`container:` or `services:` with one step that fails with: + +`::error::container: not supported by this emulator's runners; the job's steps were NOT run` + +The message names whichever keys are present. This follows the existing +refusal for `docker://` actions (`_unsupported_uses_script`). An empty +`container:` is not a container, and a job without either key is unchanged. + +Tests: `tests/actions/test_container_jobs.py`. diff --git a/docs/bugs/fixed/job-needing-a-reusable-workflow-caller-waits-forever.md b/docs/bugs/fixed/job-needing-a-reusable-workflow-caller-waits-forever.md new file mode 100644 index 00000000..2bbf57bd --- /dev/null +++ b/docs/bugs/fixed/job-needing-a-reusable-workflow-caller-waits-forever.md @@ -0,0 +1,112 @@ +# Bug: a job that needs a reusable-workflow caller waits forever + +Status: fixed 2026-11-14. + +## Summary + +On GitHub, a job can name a reusable-workflow caller in `needs:` and read +`needs..result` and `needs..outputs`; the outputs are the +callee's `on.workflow_call.outputs`. + +The emulator inlines a caller as its called jobs, so the caller is no job in +the run. A job with `needs: `: + +- waited for a job that never existed, and stayed `waiting`; +- had nothing to read in `needs..outputs`. + +## Fix + +- A need on a caller becomes a need on every job the call inlined. +- The dependent carries the caller's called-job keys and the callee's + `on.workflow_call.outputs`. At promotion the scheduler builds + `needs.` from them: the result is the worst of the called jobs' + results, and the outputs are evaluated with a `jobs` context of the called + jobs. +- The dependent waits for every called job, but its implicit `success()`, + and `success()`/`failure()` in its `if:`, read the call's result, not each + called job's. On GitHub a call whose jobs succeeded except one skipped by + its own `if:` succeeds, and a `needs: ` dependent with no `if:` + runs. Before, the scheduler saw the skipped called job as an unsuccessful + need and skipped the dependent. A call with a failed or cancelled job is + still unsuccessful, so its dependent is still skipped. Plain needs are + judged as before. +- The same holds further down a chain. `success()` and `failure()` answer + for every ancestor, and a called job reached through another job is + counted as its caller, with the call's result (the worst of its called + jobs' results). The caller is found from the key: called jobs are keyed + ` / `, and a job id cannot hold ` / `. For `call -> middle -> + final`, with `final` on `if: success()` and the call holding one + successful job and one skipped by its own `if:`, `final` now runs. Before, + only `final`'s own needs were read through the call's alias, so `success()` + saw the skipped called job and `final` was skipped. Inside a called + workflow, `deploy / final` counts `deploy / call / *` as the + `deploy / call` call. A failed called job still skips `middle` and makes + `success()` false and `failure()` true for `final`, as behind a plain + failed job. +- Nested calls re-prefix those keys at each level. +- A caller inside a called workflow keeps its own alias inside the outer + caller's alias (`callers`). The outer call's outputs can then read + `jobs..outputs`: that entry is built the same way, from the + nested caller's called jobs and its own `on.workflow_call.outputs`. Before, + the outer `jobs` context held only the flattened called jobs + (` / `), so such an output rendered as `""`. +- A skipped caller is one skipped job under its own key + (`skipped-reusable-workflow-caller-lists-the-called-jobs.md`), so a need on + it points at that job. Its `needs.` is then that job's own entry + (`result: skipped`); the entry built from called jobs, which were never + created, is dropped. Before, it overwrote the real entry with `result: ''`. +- Only needs on the run's own (top-level) callers are pointed at a skipped + caller's job (`_caller_needs`). A caller in a called workflow can share a + top-level caller's key; a need on it used to be pointed at the skipped + top-level job instead. +- A call's outputs are evaluated with the contexts GitHub allows in + `on.workflow_call.outputs..value`: `github`, `jobs`, `vars` and + `inputs` ([contexts reference, context availability][contexts]). The alias + carries the call's resolved inputs (the caller's `with:` plus the callee's + declared defaults), nested callers' aliases included, and the scheduler + passes the run's `github` and `vars`. Before, only `jobs` was there, so + `${{ inputs.version }}` rendered as `""` even when the caller passed it or + it had a default. `with:` values still holding an expression are rendered + at promotion against `github`, `vars`, `needs` and the calling workflow's + inputs. `secrets` is not in that context, as on GitHub. +- For the run's own (top-level) callers, "the calling workflow's inputs" are + the run's inputs (`inputs` in the run's expression context, from the + `workflow_dispatch` or `workflow_call` payload), the same values the called + jobs render their `with:` against. Before, the alias used `{}` there, so a + compound expression such as `${{ format('{0}-x', inputs.ver) }}` gave the + called job `1.0-x` but `needs..outputs` `-x`. For a caller inside + a called workflow, they are that workflow's inputs, not the run's. +- Calls nested at any depth resolve each `with:` in the terms of the + workflow it is written in. The alias keeps the `with:` of every enclosing + call (`parent_inputs_chain`, outermost first), and each called job keeps + the same chain (`_call_inputs_chain`). Both are rendered one level at a + time: the rendered inputs of one level are the `inputs` context of the + next, starting from the run's inputs. Before, the alias kept only the + innermost calling workflow's inputs and rendered them against the run's, + and the called jobs rendered all levels' merged inputs in one pass against + the run's. With the run's `ver=run`, `outer` called with `ver=2`, `mid` + with `ver=${{ format('{0}-mid', inputs.ver) }}` and `inner` with + `tag=${{ format('v{0}', inputs.ver) }}`, a job in `mid` read `run-mid` + for `inputs.ver` and `vrun-mid` for `needs.inner.outputs.tag`; they are now + `2-mid` and `v2-mid`. +- A bare `${{ inputs.x }}` in a called workflow is substituted at + materialization only when the passed value is a literal. A value that is + itself an expression is in the calling workflow's terms, so the reference + is kept and reads the job's rendered inputs. Before, the expression was + copied in and then rendered against the called workflow's inputs: with + `ver=${{ format('{0}-mid', inputs.ver) }}`, `${{ inputs.ver }}` in `mid` + became `2-mid-mid`. +- A caller that needs another caller (A → B → C, B with + `x: ${{ needs.A.outputs.o }}`) keeps the aliases of the callers it needs + (`needs_aliases`, in any job order; a needs cycle is cut). Its `with:` is + rendered with `needs.A` built from A's called jobs, the entry a plain + dependent of A reads. Before, C's called jobs read `needs.B` from B's + alias, which rendered `needs.A` against plain job rows only, so + `needs.B.outputs` was `""`, C's jobs received an empty input, and + `needs.C.outputs` was empty too. B's own called jobs already rendered + `inputs.x` correctly from their own `needs.A` entry. + +[contexts]: https://docs.github.com/en/actions/reference/workflows-and-actions/contexts#context-availability + +Tests: `tests/actions/test_reusable_caller_needs.py`, +`tests/actions/test_skipped_reusable_caller.py`. diff --git a/docs/bugs/fixed/jobs-list-shows-jobs-waiting-on-needs.md b/docs/bugs/fixed/jobs-list-shows-jobs-waiting-on-needs.md new file mode 100644 index 00000000..ace66c14 --- /dev/null +++ b/docs/bugs/fixed/jobs-list-shows-jobs-waiting-on-needs.md @@ -0,0 +1,22 @@ +# Bug: a run's jobs list shows jobs still waiting on needs + +Status: fixed 2026-11-14. + +## Summary + +Probed side by side with GitHub, with a workflow where jobs `b` and `c` need +job `a`. While `a` ran, GitHub's `GET /repos/{owner}/{repo}/actions/runs/{id}/jobs` +listed only `a` (`total_count` 1). `b` and `c` appeared once they were +queued. + +The emulator listed `b` and `c` with status `waiting`. GitHub uses `waiting` +for a job held for an environment approval. A stage that had not started +looked like part of the run, and a client that checks once that a job is not +going to run read it as pending. + +## Fix + +The jobs list leaves out jobs that are still blocked on `needs:`. A job is +listed from when it is queued. + +Tests: `tests/actions/test_jobs_list_unstarted.py`. diff --git a/docs/bugs/fixed/skipped-reusable-workflow-caller-lists-the-called-jobs.md b/docs/bugs/fixed/skipped-reusable-workflow-caller-lists-the-called-jobs.md new file mode 100644 index 00000000..1fd13cc2 --- /dev/null +++ b/docs/bugs/fixed/skipped-reusable-workflow-caller-lists-the-called-jobs.md @@ -0,0 +1,51 @@ +# Bug: a skipped reusable-workflow caller lists the called jobs, and the run succeeds + +Status: fixed 2026-11-14. + +## Summary + +On GitHub, a job that calls a reusable workflow +(`uses: ./.github/workflows/reusable-dispatch.yml`) and is skipped by its own +`if:` is never expanded. The run lists one job, named after the caller job +(its `name:`, or its key), concluded `skipped`. A run whose jobs were all +skipped concludes `skipped`. + +The emulator inlined the called jobs at run creation and ANDed the caller's +condition into each of them. For Fullsend's `fullsend.yaml`, whose `dispatch` +job runs only for `issues` events labelled `go`, an `issues: opened` event +produced a run that: + +- listed every called job (`dispatch / route`, `Triage`, `Code` and two + `Harness run (${{ matrix.agent }})` jobs), each `skipped`; +- concluded `success`, because the run conclusion treated "all skipped" as + success. + +Fullsend's behaviour tests skip runs that concluded `skipped` or `cancelled`. +They read a `success` run whose "Harness run" job was skipped as a failed +dispatch. + +A job that `needs:` the caller key (`needs: dispatch`) also never resolved, +because no row carried that key, so it stayed waiting. + +## Fix + +- `workflow_service._materialize_reusable_jobs` marks each job inlined from + a top-level call with its caller (`_caller`: key, name, condition, needs). + `build_job_graph` carries the mark. +- `create_workflow_run` evaluates a caller's `if:` once, when the caller has + no `needs:`. When it is false, the run gets one skipped row, named after + the caller and keyed by the caller's key, and none of the called jobs. + Jobs that need the caller are skipped through it as usual; one that runs + anyway (`if: always()`) reads `needs..result` as `skipped`. +- `workflow_scheduler.check_run_completion` concludes a run `skipped` when + every job concluded `skipped`. Runs where some jobs ran keep their + `success` or `failure` conclusion. + +When the caller runs, the called jobs and their names are unchanged. + +Not covered: a caller with `needs:` is still decided at promotion, where its +condition is ANDed into each called job, so a skip there still lists the +called jobs. The emulator does not mirror check suites or send `workflow_run` +webhooks, so there is no other conclusion to update. + +Tests: `tests/actions/test_skipped_reusable_caller.py`. diff --git a/docs/bugs/fixed/unresolved-reusable-workflow-call-passes.md b/docs/bugs/fixed/unresolved-reusable-workflow-call-passes.md new file mode 100644 index 00000000..00dd01da --- /dev/null +++ b/docs/bugs/fixed/unresolved-reusable-workflow-call-passes.md @@ -0,0 +1,37 @@ +# Bug: a reusable-workflow call that cannot be inlined passes + +Status: fixed 2026-11-14. + +## Summary + +The emulator inlines a reusable-workflow call into the called jobs. When it +could not, it left a placeholder job with no steps, and a job with no steps +passes. That happened for: + +- a cross-repository call (`owner/repo/.github/workflows/x.yml@ref`) to a + repository the emulator does not store; +- a call nested deeper than the limit; +- a call that loops back to itself. + +A run whose whole pipeline was one such call looked green. On GitHub the +same run fails. + +## Fix + +`workflow_service._materialize_reusable_jobs` builds the placeholder with +`_reusable_placeholder`, which gives it one step that fails with an +`::error::` saying why. For a missing repository the message says the call +resolves only against repositories stored in the emulator, and that the +repository has to be pushed first. The placeholder no longer carries `uses`, +`with` or `secrets`. + +GitHub fails such a run without assigning a runner. The placeholder is +therefore never queued: `create_workflow_run` concludes it `failure` when +the run is created, or, for a placeholder with `needs:`, the scheduler +concludes it when its needs finish and its `if:` holds +(`workflow_service.fail_refused_job`). Its one step is recorded as the +failed step, and the reason is written to the job's log. Queued, it waited +forever on a stack whose runners do not offer its `runs-on` labels +(`ubuntu-latest` by default). + +Tests: `tests/actions/test_reusable_unresolved.py`. diff --git a/src/app/api/actions.py b/src/app/api/actions.py index ae89b42a..583c6c2a 100644 --- a/src/app/api/actions.py +++ b/src/app/api/actions.py @@ -710,7 +710,12 @@ async def list_jobs( if run_result.scalar_one_or_none() is None: raise HTTPException(status_code=404, detail="Not Found") - query = select(WorkflowJob).where(WorkflowJob.run_id == run_id) + # A job still waiting on its `needs` is not listed: GitHub lists a job + # once it is queued (or decided, e.g. skipped). Its "waiting" status is + # for a job held for an environment approval, which this emulator does + # not have; listing blocked jobs as waiting made a not-yet-started stage + # look like one that ran. + query = select(WorkflowJob).where(WorkflowJob.run_id == run_id, WorkflowJob.status != "waiting") jobs = (await db.execute(query)).scalars().all() items = [_job_json(j, owner, repo) for j in jobs] return {"total_count": len(items), "jobs": items} diff --git a/src/app/api/actions_distributed_task.py b/src/app/api/actions_distributed_task.py index 51ca7733..3a410a61 100644 --- a/src/app/api/actions_distributed_task.py +++ b/src/app/api/actions_distributed_task.py @@ -18,7 +18,7 @@ from fastapi import APIRouter, HTTPException, Query, Request from fastapi.responses import FileResponse, JSONResponse, Response -from sqlalchemy import and_, exists, or_, select, update +from sqlalchemy import and_, exists, func, or_, select, update from sqlalchemy.orm.attributes import flag_modified from app.api.actions_dispatch import _claim_queued_job @@ -49,9 +49,11 @@ from app.models.repository import Repository from app.services.action_download_service import ( UpstreamActionError, + build_local_action_archive, fetch_action_archive, parse_uses, resolve_action_sha, + resolve_local_action_sha, ) from app.services.auth_service import hash_token from app.services.job_token_service import validate_job_token @@ -1928,7 +1930,7 @@ async def dt_resolve_action_download_info( here: the runner downloads it with the job token as a Basic credential, which GitHub would reject and this service can verify. """ - await _job_for_plan(request, db, plan_id) + job = await _job_for_plan(request, db, plan_id) body = await request.json() references = body.get("actions") or body.get("Actions") or [] base = _runner_reachable_base_url(_request_base(request)) @@ -1942,14 +1944,35 @@ async def dt_resolve_action_download_info( 400, "NonRetryableActionDownloadInfoException", f"action reference needs nameWithOwner and ref: {reference!r}", ) - try: - sha = await resolve_action_sha(name, ref) - except UpstreamActionError as exc: - if exc.not_found: - return _wrapped_exception( - 404, "UnresolvableActionDownloadInfoException", str(exc) - ) - return _wrapped_exception(502, "DistributedTaskException", str(exc)) + # A repository on this emulator first, then upstream. GHES resolves a + # repository it holds locally and goes to github.com only for one it + # lacks; this emulator also goes upstream when a public repository is + # here but lacks the ref, so a partial local copy of a public action + # works. A private or internal repository here that lacks the ref is + # unresolvable, and its name is not looked up upstream. + held, local = await _local_action_repository(name, job, db) + if held and local is None: + # Here, but not usable by this job's repository: as unresolvable as + # on GitHub, and not looked up upstream under the same name. + return _wrapped_exception( + 404, "UnresolvableActionDownloadInfoException", + f"Unable to resolve action {name}@{ref}, repository not found", + ) + sha = await resolve_local_action_sha(local.disk_path, ref) if local else None + if sha is None and local is not None and not _is_public(local): + return _wrapped_exception( + 404, "UnresolvableActionDownloadInfoException", + f"Unable to resolve action {name}@{ref}, unable to find version {ref}", + ) + if sha is None: + try: + sha = await resolve_action_sha(name, ref) + except UpstreamActionError as exc: + if exc.not_found: + return _wrapped_exception( + 404, "UnresolvableActionDownloadInfoException", str(exc) + ) + return _wrapped_exception(502, "DistributedTaskException", str(exc)) archive = f"{base}/_apis/distributedtask/actions/archives/{name}/{sha}/archive" resolved[f"{name}@{ref}"] = { "nameWithOwner": name, @@ -1962,15 +1985,63 @@ async def dt_resolve_action_download_info( return {"actions": resolved} +async def _local_action_repository( + name_with_owner: str, job: WorkflowJob, db, +) -> tuple[bool, Repository | None]: + """Whether this emulator holds the repository a `uses:` reference names, + and that repository when the job may use it as an action. + + As GitHub does by default, a workflow may use an action from a public + repository or from its own repository. GitHub lets other repositories use + a private or internal repository's actions only when its owner enables + that access; this emulator has no such setting, so any other private or + internal repository, the same owner's included, is not usable. + """ + repository = (await db.execute( + select(Repository) + .where(func.lower(Repository.full_name) == name_with_owner.lower()) + .order_by(Repository.id) + )).scalars().first() + if repository is None or not repository.disk_path: + return False, None + if _is_public(repository): + return True, repository + job_repository = (await db.execute( + select(Repository) + .join(WorkflowRun, WorkflowRun.repo_id == Repository.id) + .where(WorkflowRun.id == job.run_id) + )).scalars().first() + if job_repository is not None and job_repository.id == repository.id: + return True, repository + return True, None + + +def _is_public(repository: Repository) -> bool: + return not repository.private and (repository.visibility or "public") == "public" + + @router.get("/_apis/distributedtask/actions/archives/{owner}/{repo}/{sha}/archive.{fmt}") @router.get("/{owner_}/{repo_}/_apis/distributedtask/actions/archives/{owner}/{repo}/{sha}/archive.{fmt}") async def dt_action_archive( owner: str, repo: str, sha: str, fmt: str, request: Request, db: DbSession, ): - """Serve an action archive, fetched from upstream once per SHA.""" - await _get_job_from_download_credential(request, db) + """Serve an action archive: built from a repository here when it holds the + commit, else fetched from upstream once per SHA. A private or internal + repository here that lacks the commit is 404, not fetched upstream.""" + job = await _get_job_from_download_credential(request, db) + name = f"{owner}/{repo}" + held, local = await _local_action_repository(name, job, db) + if held and local is None: + # The same rule as when the download was resolved, since a job can + # also request this URL directly, without resolving it first. + raise HTTPException(status_code=404, detail="Not Found") try: - path = await fetch_action_archive(f"{owner}/{repo}", sha, fmt) + if local and await resolve_local_action_sha(local.disk_path, sha) == sha: + path = await build_local_action_archive(local.disk_path, name, sha, fmt) + elif local is not None and not _is_public(local): + raise HTTPException(status_code=404, detail="Not Found") + else: + path = await fetch_action_archive(name, sha, fmt) except UpstreamActionError as exc: raise HTTPException(status_code=404 if exc.not_found else 502, detail=str(exc)) from exc media = "application/gzip" if fmt == "tar.gz" else "application/zip" diff --git a/src/app/services/action_download_service.py b/src/app/services/action_download_service.py index c3d07054..0a2df229 100644 --- a/src/app/services/action_download_service.py +++ b/src/app/services/action_download_service.py @@ -19,6 +19,7 @@ from __future__ import annotations +import asyncio import os import re import tempfile @@ -181,3 +182,62 @@ async def fetch_action_archive(name_with_owner: str, sha: str, fmt: str) -> str: if os.path.exists(tmp): os.unlink(tmp) return path + + +# --- actions hosted on this emulator ------------------------------------------ +# +# GHES resolves `uses: owner/repo@ref` against a repository it holds, and +# goes to github.com only for a repository it lacks. This emulator does the +# same, and also goes upstream when the repository is here but lacks the ref, +# so a partial local copy of a public action still works. Without this, an +# action pushed to a repository here was looked up upstream and failed with +# "does not exist upstream". Which local repositories a job may use is decided +# by the caller (see actions_distributed_task._local_action_repository). + + +async def _git(disk_path: str, *args: str) -> tuple[int, bytes]: + proc = await asyncio.create_subprocess_exec( + "git", *args, + stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL, + env={**os.environ, "GIT_DIR": disk_path}, + ) + stdout, _ = await proc.communicate() + return proc.returncode or 0, stdout + + +async def resolve_local_action_sha(disk_path: str, ref: str) -> str | None: + """The commit `ref` (branch, tag or SHA) names in a local repository, if any.""" + code, out = await _git(disk_path, "rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}") + return out.decode().strip() if code == 0 and out.strip() else None + + +def local_archive_cache_path(name_with_owner: str, sha: str, fmt: str) -> str: + # Apart from the upstream cache: a repository here may share its name + # with one on github.com. + owner, repo = name_with_owner.split("/", 1) + return os.path.join(settings.DATA_DIR, "actions-archives-local", owner, repo, f"{sha}.{fmt}") + + +async def build_local_action_archive(disk_path: str, name_with_owner: str, sha: str, fmt: str) -> str: + """Path of a `git archive` of `sha`, shaped like GitHub's: one top directory.""" + if fmt not in ("tar.gz", "zip"): + raise UpstreamActionError(f"unsupported archive format {fmt!r}", not_found=True) + path = local_archive_cache_path(name_with_owner, sha, fmt) + if os.path.exists(path): + return path + os.makedirs(os.path.dirname(path), exist_ok=True) + owner, repo = name_with_owner.split("/", 1) + fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".partial-") + os.close(fd) + try: + code, _ = await _git( + disk_path, "archive", f"--format={fmt}", f"--prefix={owner}-{repo}-{sha[:7]}/", + f"--output={tmp}", sha, + ) + if code != 0: + raise UpstreamActionError(f"no commit {sha} in {name_with_owner}", not_found=True) + os.replace(tmp, path) + finally: + if os.path.exists(tmp): + os.unlink(tmp) + return path diff --git a/src/app/services/workflow_expressions.py b/src/app/services/workflow_expressions.py index 841945f9..5a6e0851 100644 --- a/src/app/services/workflow_expressions.py +++ b/src/app/services/workflow_expressions.py @@ -292,6 +292,9 @@ def _object_filter(value: object) -> "_Filtered": # ``needs:`` keys and whether the run was cancelled. JOB_NEEDS_KEY = "__job_needs__" RUN_CANCELLED_KEY = "__run_cancelled__" +# Results of ancestors the job has no ``needs`` entry for: a reusable-workflow +# caller reached through another job, judged by the call's result. +JOB_ANCESTOR_RESULTS_KEY = "__job_ancestor_results__" def uses_status_function(condition: object) -> bool: @@ -311,7 +314,11 @@ def job_status(name: str, context: dict) -> bool: keys = context.get(JOB_NEEDS_KEY) if keys is None: keys = list(needs) - results = [str((needs.get(key) or {}).get("result") or "") for key in keys] + ancestor_results = context.get(JOB_ANCESTOR_RESULTS_KEY) or {} + results = [ + str(ancestor_results[key] if key in ancestor_results else (needs.get(key) or {}).get("result") or "") + for key in keys + ] if name == "failure": return any(result == "failure" for result in results) return not cancelled and all(result == "success" for result in results) diff --git a/src/app/services/workflow_scheduler.py b/src/app/services/workflow_scheduler.py index 4c39968d..dcd873d5 100644 --- a/src/app/services/workflow_scheduler.py +++ b/src/app/services/workflow_scheduler.py @@ -7,6 +7,7 @@ from app.models.actions import WorkflowJob, WorkflowRun + def _runs_after_unsuccessful_needs(job: WorkflowJob) -> bool: """Whether a job is still evaluated when a job it needs failed, was skipped or was cancelled: on GitHub, when its condition names a status @@ -18,20 +19,112 @@ def _runs_after_unsuccessful_needs(job: WorkflowJob) -> bool: return uses_status_function(pending.get("if")) -def _ancestors(job: WorkflowJob, all_jobs) -> list[str]: +def _called_jobs(job: WorkflowJob) -> dict[str, str]: + """The jobs a need on a reusable-workflow caller became, each mapped to + that caller's key.""" + aliases = (job.pending_render or {}).get("_needs_aliases") or {} + called: dict[str, str] = {} + for caller, alias in aliases.items(): + for outer in alias.get("jobs", {}).values(): + called.setdefault(outer, caller) + return called + + +def _caller_of(key: str, prefix: str) -> str | None: + """The caller, in the workflow whose jobs are keyed ````, + whose call inlined job ``key``; None when ``key`` is a job of that + workflow itself or of another one. Called jobs are keyed + `` / ``, and a job id cannot hold `` / ``.""" + if not key.startswith(prefix): + return None + rest = key[len(prefix):] + if " / " not in rest: + return None + return prefix + rest.split(" / ", 1)[0] + + +def _ancestors( + job: WorkflowJob, all_jobs, key_results: dict | None = None, +) -> tuple[list[str], dict[str, str]]: """Every job ``job`` depends on, directly or through others: the jobs ``success()`` and ``failure()`` answer for, as on GitHub, so a cleanup - job behind a skipped one still sees the failure that skipped it.""" + job behind a skipped one still sees the failure that skipped it. + + A called job of a caller ``job`` needs is listed as that caller, whose + ``needs`` entry carries the call's result: a called job skipped by its + own condition does not make ``success()`` false when the call succeeded. + A called job reached through another job is listed as its caller too, + with the call's result (``alias_result``: the worst of its called jobs' + results) returned alongside, since ``job`` has no ``needs`` entry for + that caller. + """ + from app.services.workflow_service import _combined_result + + key_results = key_results or {} needs_by_key = {(j.job_key or j.name): list(j.needs or []) for j in all_jobs} + own_key = job.job_key or job.name + prefix = own_key.rsplit(" / ", 1)[0] + " / " if " / " in own_key else "" + called = _called_jobs(job) seen: list[str] = [] + results: dict[str, str] = {} + visited: set[str] = set() pending = list(job.needs or []) while pending: key = pending.pop() - if key in seen: + if key in visited: continue - seen.append(key) + visited.add(key) + name = called.get(key) + if name is None: + name = _caller_of(key, prefix) or key + if name != key and name not in results: + result = "" + for other, other_result in key_results.items(): + if other.startswith(name + " / "): + result = _combined_result(result, other_result) + results[name] = result + if name not in seen: + seen.append(name) pending.extend(needs_by_key.get(key, [])) - return seen + return seen, results + + +def _needs_state( + job: WorkflowJob, completed_keys: set, unsuccessful_keys: set, key_results: dict, +) -> tuple[bool, bool]: + """Whether every need of ``job`` has finished, and whether one did not + succeed. + + A plain need is unsuccessful when any of its rows did not succeed. The + jobs a need on a reusable-workflow caller became are judged together, by + the call's result (``alias_result``): the call is finished when all of + them are, and unsuccessful when that result is not ``success``. On + GitHub a call with one job skipped by its own condition and none failed + or cancelled succeeds. + """ + from app.services.workflow_service import alias_result + + needs = list(job.needs or []) + aliases = (job.pending_render or {}).get("_needs_aliases") or {} + finished, unsuccessful = True, False + covered: set[str] = set() + for alias in aliases.values(): + keys = [key for key in alias.get("jobs", {}).values() if key in needs] + if not keys: + continue + covered.update(keys) + if not all(key in key_results for key in keys): + finished = False + elif alias_result({"jobs": {key: key for key in keys}}, key_results) != "success": + unsuccessful = True + for need in needs: + if need in covered: + continue + if need in unsuccessful_keys: + unsuccessful = True + elif need not in completed_keys: + finished = False + return finished, unsuccessful async def dispatch_ready_jobs(db: AsyncSession, run_id: int) -> list[WorkflowJob]: @@ -41,19 +134,24 @@ async def dispatch_ready_jobs(db: AsyncSession, run_id: int) -> list[WorkflowJob creation when it declares dependencies, because they may read ``needs..outputs.*``, which only exist once those jobs have finished. """ + from app.services.workflow_expressions import ( + JOB_ANCESTOR_RESULTS_KEY, + JOB_NEEDS_KEY, + RUN_CANCELLED_KEY, + evaluate_job_if, + render_expressions, + ) from app.services.workflow_service import ( + _combined_result, build_needs_context, build_run_expression_context, build_steps_data, + call_inputs_context, + fail_refused_job, + needs_alias_entries, render_job_labels, strategy_context, ) - from app.services.workflow_expressions import ( - JOB_NEEDS_KEY, - RUN_CANCELLED_KEY, - evaluate_job_if, - render_expressions, - ) result = await db.execute( select(WorkflowJob).where(WorkflowJob.run_id == run_id) @@ -76,6 +174,15 @@ async def dispatch_ready_jobs(db: AsyncSession, run_id: int) -> list[WorkflowJob completed_keys.add(key) else: unsuccessful_keys.add(key) + # Each finished key's result, worst of its rows, for judging the jobs a + # need on a reusable-workflow caller became by the call's result. + key_results: dict[str, str] = {} + for key, rows in rows_by_key.items(): + if all(row.status == "completed" for row in rows): + key_result = "" + for row in rows: + key_result = _combined_result(key_result, row.conclusion or "") + key_results[key] = key_result promoted = [] ready = [] @@ -89,10 +196,13 @@ async def dispatch_ready_jobs(db: AsyncSession, run_id: int) -> list[WorkflowJob for job in all_jobs: if job.status != "waiting" or job in ready: continue - needs = job.needs or [] - if any(n in unsuccessful_keys for n in needs) and not _runs_after_unsuccessful_needs(job): + finished, unsuccessful = _needs_state( + job, completed_keys, unsuccessful_keys, key_results, + ) + if unsuccessful and not _runs_after_unsuccessful_needs(job): job.status = "completed" job.conclusion = "skipped" + key_results[job.job_key or job.name] = "skipped" job.completed_at = datetime.now(timezone.utc) job.steps = [ {**step, "status": "completed", "conclusion": "skipped"} @@ -100,7 +210,7 @@ async def dispatch_ready_jobs(db: AsyncSession, run_id: int) -> list[WorkflowJob ] unsuccessful_keys.add(job.job_key or job.name) changed = True - elif all(n in completed_keys or n in unsuccessful_keys for n in needs): + elif finished: # Every need has finished. Either all succeeded, or the job's # condition names a status function and decides for itself. ready.append(job) @@ -121,10 +231,19 @@ async def dispatch_ready_jobs(db: AsyncSession, run_id: int) -> list[WorkflowJob [j for j in all_jobs if j.status == "completed"] ) github_ctx = base_context.get("github") or {} + ancestors, ancestor_results = _ancestors(job, all_jobs, key_results) context = { **base_context, - "needs": needs_context, - JOB_NEEDS_KEY: _ancestors(job, all_jobs), + # A reusable-workflow caller this job needs is not a job + # in the run; answer needs. from its called jobs. + "needs": { + **needs_context, + **needs_alias_entries( + pending.get("_needs_aliases"), needs_context, base_context, + ), + }, + JOB_NEEDS_KEY: ancestors, + JOB_ANCESTOR_RESULTS_KEY: ancestor_results, RUN_CANCELLED_KEY: bool(base_context.get(RUN_CANCELLED_KEY)), "matrix": pending.get("matrix") or {}, "strategy": pending.get("strategy") or strategy_context(None), @@ -135,13 +254,10 @@ async def dispatch_ready_jobs(db: AsyncSession, run_id: int) -> list[WorkflowJob or github_ctx.get("sha", ""), }, } - call_inputs = pending.get("_call_inputs") or {} call_secrets = pending.get("_call_secrets") or {} - if call_inputs: - context["inputs"] = { - **(base_context.get("inputs") or {}), - **render_expressions(call_inputs, context), - } + inputs = call_inputs_context(pending, base_context.get("inputs") or {}, context) + if inputs is not None: + context["inputs"] = inputs if call_secrets: context["secrets"] = { **(base_context.get("secrets") or {}), @@ -157,6 +273,12 @@ async def dispatch_ready_jobs(db: AsyncSession, run_id: int) -> list[WorkflowJob ] job.pending_render = None continue + if pending.get("refused"): + # A reusable call that could not be inlined: failed here, + # without a runner, and its dependents decided next pass. + fail_refused_job(job, pending["refused"]) + expansion_failed = True + continue instances = [(job, context)] if pending.get("dynamic_matrix") is not None: instances = await _expand_dynamic_matrix(db, job, pending, context) @@ -187,8 +309,8 @@ async def dispatch_ready_jobs(db: AsyncSession, run_id: int) -> list[WorkflowJob await db.flush() if expansion_failed: - # A job that failed to expand is a finished, unsuccessful need: the - # jobs behind it (a cleanup with always(), or ones to skip) are + # A job that failed to expand, or was refused, is a finished, + # unsuccessful need: the jobs behind it (a cleanup with always(), or ones to skip) are # decided now, since no job will complete to trigger another pass. promoted.extend(await dispatch_ready_jobs(db, run_id)) @@ -211,14 +333,13 @@ async def _expand_dynamic_matrix( GitHub ("Matrix vector 'include' does not contain any values"). Returns the instances with their expression contexts, or [] when the job failed. """ - from app.services.workflow_expressions import evaluate_expression_value + from app.services.workflow_expressions import evaluate_expression_value, render_expressions from app.services.workflow_service import ( _job_concurrency, matrix_combinations, matrix_job_name, strategy_context, ) - from app.services.workflow_expressions import render_expressions combos = matrix_combinations( evaluate_expression_value(pending["dynamic_matrix"], context) @@ -327,6 +448,9 @@ def stranded(j) -> bool: run.conclusion = "failure" elif "cancelled" in conclusions: run.conclusion = "cancelled" + elif conclusions and all(c == "skipped" for c in conclusions): + # GitHub concludes a run whose every job was skipped as skipped. + run.conclusion = "skipped" elif all(c in ("success", "skipped") for c in conclusions): run.conclusion = "success" else: diff --git a/src/app/services/workflow_service.py b/src/app/services/workflow_service.py index 2bdc4e1b..47023272 100644 --- a/src/app/services/workflow_service.py +++ b/src/app/services/workflow_service.py @@ -4,6 +4,7 @@ import copy import itertools import logging +import os import re import uuid from dataclasses import dataclass @@ -227,6 +228,52 @@ def expand_matrix(job_config: dict) -> list[dict]: return expanded +def _refusal_steps(name: str, why: str) -> list[dict]: + """One step that fails with ``why`` in place of a job this emulator cannot run. + + The `::error::` line becomes an annotation on the run, so the refusal is + visible from the UI and not only from the step log. The message is one + single-quoted shell word, so nothing in it is read by the shell. + """ + quoted = "'" + f"::error::{why}".replace("'", "'\\''") + "'" + return [{"name": name, "run": f"echo {quoted} >&2\nexit 1"}] + + +def _reusable_placeholder(key: str, config: dict, why: str) -> dict: + """A job standing in for a reusable-workflow call that could not be inlined.""" + placeholder = { + name: value for name, value in copy.deepcopy(config).items() + if name not in ("uses", "with", "secrets") + } + placeholder["steps"] = _refusal_steps("Resolve reusable workflow", why) + placeholder["name"] = placeholder.get("name", f"{key} (reusable workflow)") + # Failed when it would start, with no runner: GitHub fails a run whose + # reusable workflow cannot be resolved without assigning a runner, and a + # placeholder sent to one waits forever on a stack that lacks its labels. + placeholder["_refused"] = why + return placeholder + + +def fail_refused_job(job: WorkflowJob, why: str) -> None: + """Conclude a job that is not run as failed, the reason in its log. + + Its one step, the refusal, is recorded as the failed one; the reason is + also the job's log, which is where GitHub shows it for such a run. + """ + job.status = "completed" + job.conclusion = "failure" + job.completed_at = datetime.now(timezone.utc) + job.steps = [ + {**step, "status": "completed", "conclusion": "failure"} + for step in (job.steps or []) + ] + job.pending_render = None + log_dir = os.path.join(settings.DATA_DIR, "logs", "jobs") + os.makedirs(log_dir, exist_ok=True) + with open(os.path.join(log_dir, f"{job.id}.log"), "w", encoding="utf-8") as log: + log.write(f"##[error]{why}\n") + + def build_job_graph(workflow_yaml: dict) -> list[dict]: """Parse jobs section into a dependency-ordered list.""" jobs_config = workflow_yaml.get("jobs", {}) @@ -256,6 +303,17 @@ def build_job_graph(workflow_yaml: dict) -> list[dict]: needs = [needs] steps = config.get("steps", []) + unsupported = [key_name for key_name in ("container", "services") if config.get(key_name)] + if unsupported: + # Neither runner here starts job or service containers. Running + # the steps anyway puts them on the runner host, where they pass + # or fail for reasons unrelated to the workflow: a false result + # either way. Refuse the job instead. + steps = _refusal_steps( + "Unsupported job keys", + f"{' and '.join(f'{k}:' for k in unsupported)} not supported by this " + "emulator's runners; the job's steps were NOT run", + ) jobs.append({ "key": key, @@ -278,10 +336,15 @@ def build_job_graph(workflow_yaml: dict) -> list[dict]: "concurrency": config.get("concurrency"), "outputs": config.get("outputs", {}), "_call_inputs": config.get("_call_inputs", {}), + "_call_inputs_chain": config.get("_call_inputs_chain") or [], "_call_secrets": config.get("_call_secrets", {}), "_workflow_repository": config.get("_workflow_repository", ""), "_workflow_sha": config.get("_workflow_sha", ""), "_workflow_ref": config.get("_workflow_ref", ""), + "_caller": config.get("_caller"), + "_refused": config.get("_refused"), + "_needs_aliases": config.get("_needs_aliases") or {}, + "_caller_needs": config.get("_caller_needs") or {}, "timeout_minutes": config.get("timeout-minutes", 360), }) @@ -358,6 +421,13 @@ def replace(match): if not _BARE_CONTEXT_PATH_RE.fullmatch(expression): return match.group(0) if expression.startswith("inputs."): + # An input that is itself an unrendered expression is in the + # calling workflow's terms. Substituted here, it would be + # rendered against this workflow's inputs instead; kept, it + # reads this workflow's rendered inputs (``_call_inputs_chain``). + passed = inputs.get(expression.split(".", 2)[1]) + if isinstance(passed, str) and "${{" in passed: + return match.group(0) return _lookup_context({"inputs": inputs}, expression) if expression.startswith("secrets."): if secrets is None: @@ -461,6 +531,167 @@ async def _resolve_ref_sha(repo_disk_path: str, ref: str) -> str: return stdout.decode().strip() +def _declared_call_outputs(called: dict) -> dict[str, str]: + """``on.workflow_call.outputs`` as name -> value expression.""" + on = called.get("on") or called.get(True) or {} + call = on.get("workflow_call") if isinstance(on, dict) else None + declared = call.get("outputs") if isinstance(call, dict) else None + if not isinstance(declared, dict): + return {} + return { + str(name): str(spec.get("value", "")) if isinstance(spec, dict) else str(spec) + for name, spec in declared.items() + } + + +def needs_alias_entries(aliases: dict, needs_context: dict, run_context: dict | None = None) -> dict: + """needs. for each reusable-workflow caller a job needs. + + The result is the worst of the called jobs' results, as for a matrix; + outputs are the call's workflow_call outputs, evaluated with the contexts + GitHub allows there: ``jobs`` (the called jobs by their own keys), + ``inputs`` (the call's resolved inputs), and the run's ``github`` and + ``vars`` from ``run_context``. A caller inside the called workflow + (``callers``) is in ``jobs`` under its own key, its entry built the same + way, so an output can read ``jobs..outputs``. + + A ``with:`` expression on ``inputs`` reads the calling workflow's + inputs: for the run's own callers, the run's (``run_context['inputs']``), + as the called jobs' ``_job_context`` does; for a caller inside a called + workflow, that workflow's, resolved from the inputs of each enclosing + call (``parent_inputs_chain``, kept at materialization). + """ + run_context = run_context or {} + return { + caller: _alias_entry( + alias, needs_context, run_context, _alias_parent_inputs(alias, needs_context, run_context), + ) + for caller, alias in (aliases or {}).items() + } + + +def resolve_call_inputs_chain(chain: list, inputs: dict, context: dict) -> list[dict]: + """Render the inputs of nested calls, outermost first. + + ``chain[k]`` is the ``with:`` of the call at level k+1, written in the + terms of the workflow at level k. Each level is rendered with ``inputs`` + set to the level before it, starting from ``inputs`` (the run's), and the + rendered levels are returned in the same order. Rendering every level + against the run's inputs read a nested ``with:`` in the wrong workflow's + terms once calls nested more than one level. + """ + resolved: list[dict] = [] + for level in chain or []: + rendered = render_expressions(level or {}, {**context, "inputs": inputs}) + inputs = rendered if isinstance(rendered, dict) else {} + resolved.append(inputs) + return resolved + + +def _alias_parent_inputs(alias: dict, needs_context: dict, run_context: dict) -> dict: + run_inputs = run_context.get("inputs") or {} + chain = alias.get("parent_inputs_chain") or [] + if not chain: + return run_inputs + # The inputs of the workflow holding the caller, each enclosing call's + # ``with:`` rendered in its own calling workflow's terms. + return resolve_call_inputs_chain(chain, run_inputs, { + "github": run_context.get("github") or {}, + "vars": run_context.get("vars") or {}, + "needs": needs_context, + })[-1] + + +def alias_result(alias: dict, results: dict) -> str: + """The result of a call from its called jobs' results, by the rule + ``needs_alias_entries`` uses: ``failure`` or ``cancelled`` if a job had + it, else ``success`` if one succeeded; ``skipped`` only when all were.""" + result = "" + for outer in alias.get("jobs", {}).values(): + result = _combined_result(result, results.get(outer) or "") + return result + + +def _alias_entry(alias: dict, needs_context: dict, run_context: dict, parent_inputs: dict) -> dict: + # The call's ``with:`` values may still hold expressions in the calling + # workflow's terms (``${{ github.ref_name }}``, ``${{ needs.x.outputs.y }}``, + # or a compound one on the caller's own inputs), rendered here as + # ``_job_context`` renders them for the called jobs. A need on another + # caller (``needs_aliases``) reads that caller's entry, as the called + # jobs' own needs. does. A run's caller skipped by its own + # ``if:`` has none of its called jobs in the run, only one skipped job + # under its key: that job's entry stands, as run creation keeps it for + # the caller's direct dependents. + needs = {**needs_context} + for name, upstream in (alias.get("needs_aliases") or {}).items(): + if name in needs_context and not any( + outer in needs_context for outer in upstream.get("jobs", {}).values() + ): + continue + needs[name] = _alias_entry(upstream, needs_context, run_context, parent_inputs) + inputs = render_expressions(alias.get("inputs") or {}, { + "github": run_context.get("github") or {}, + "vars": run_context.get("vars") or {}, + "needs": needs, + "inputs": parent_inputs, + }) + if not isinstance(inputs, dict): + inputs = {} + jobs_context = { + inner: needs_context.get(outer) or {"outputs": {}, "result": ""} + for inner, outer in alias.get("jobs", {}).items() + } + result = alias_result(alias, { + outer: (needs_context.get(outer) or {}).get("result") or "" + for outer in alias.get("jobs", {}).values() + }) + for name, nested in (alias.get("callers") or {}).items(): + jobs_context[name] = _alias_entry(nested, needs_context, run_context, inputs) + output_context = { + "jobs": jobs_context, + "inputs": inputs, + "github": run_context.get("github") or {}, + "vars": run_context.get("vars") or {}, + } + outputs = { + name: str(render_expressions(expression, output_context) or "") + for name, expression in (alias.get("outputs") or {}).items() + } + return {"result": result, "outputs": outputs} + + +def _prefix_alias(alias: dict, prefix: str, keys: set, call_inputs: dict | None = None) -> dict: + """An alias from a called workflow with its job keys as this level names + them, its own nested callers included. + + ``call_inputs`` is the ``with:`` of the call this level makes into that + workflow. It goes in front of the alias's ``parent_inputs_chain``, so at + the run's level the chain holds the inputs of every enclosing call, + outermost first. A nested caller in ``callers`` or ``needs_aliases`` gets + its inputs from the entry built around it, so it needs no chain. + """ + prefixed = { + **alias, + "jobs": { + inner: f"{prefix}{outer}" if outer in keys else outer + for inner, outer in alias.get("jobs", {}).items() + }, + "callers": { + name: _prefix_alias(nested, prefix, keys) + for name, nested in (alias.get("callers") or {}).items() + }, + "needs_aliases": { + name: _prefix_alias(upstream, prefix, keys) + for name, upstream in (alias.get("needs_aliases") or {}).items() + }, + } + if call_inputs is not None: + prefixed["parent_inputs_chain"] = [ + copy.deepcopy(call_inputs), *(alias.get("parent_inputs_chain") or []), + ] + return prefixed + + def _declared_call_inputs(called: dict) -> dict: """Return the `on.workflow_call.inputs` declaration of a called workflow.""" on = called.get("on") or called.get(True) or {} @@ -565,6 +796,11 @@ async def _materialize_reusable_jobs( result = copy.deepcopy(workflow_yaml) expanded: dict[str, dict] = {} + # Each inlined caller at this level: its called jobs by their own key and + # by the key they get here, its ``on.workflow_call.outputs`` and its inputs. + callers: dict[str, dict] = {} + # Each caller's own needs, for the callers among them (below). + caller_needs: dict[str, list] = {} for key, config in jobs.items(): if not isinstance(config, dict) or not config.get("uses"): expanded[key] = _render_reusable_call_context(config, inputs, secrets) @@ -572,22 +808,27 @@ async def _materialize_reusable_jobs( uses = str(config["uses"]) if depth >= _MAX_REUSABLE_WORKFLOW_DEPTH or uses in ancestry: - placeholder = copy.deepcopy(config) - placeholder["steps"] = [] - placeholder["name"] = placeholder.get("name", f"{key} (reusable workflow)") - expanded[key] = placeholder + expanded[key] = _reusable_placeholder( + key, config, + f"reusable workflow {uses} was not run: calls nest deeper than " + f"{_MAX_REUSABLE_WORKFLOW_DEPTH} levels or call themselves", + ) continue called, called_repo_path, called_ref, _, called_full_name = ( await _resolve_reusable_workflow(uses, repo_disk_path, ref, db) ) if called is None or not isinstance(called.get("jobs"), dict): - # Keep unresolved calls inspectable and non-successful rather than - # silently dropping them from the run graph. - placeholder = copy.deepcopy(config) - placeholder["steps"] = [] - placeholder["name"] = placeholder.get("name", f"{key} (reusable workflow)") - expanded[key] = placeholder + # Keep unresolved calls inspectable and failing rather than + # silently dropping them from the run graph. A placeholder with no + # steps used to pass, so a run whose whole pipeline was a call to + # a repository this emulator did not hold looked green. + expanded[key] = _reusable_placeholder( + key, config, + f"reusable workflow {uses} was not found on this emulator; it " + "resolves only against repositories stored here, so push the " + "repository that holds it at that ref first", + ) continue call_inputs = _render_reusable_call_context( @@ -634,9 +875,30 @@ async def _materialize_reusable_jobs( called_jobs = materialized.get("jobs", {}) called_keys = set(called_jobs) prefix = f"{key} / " + # The called workflow's own callers stay in this caller's alias, so + # its outputs can read jobs..outputs. + nested_callers = materialized.pop("_callers", None) or {} + callers[key] = { + "jobs": {called_key: f"{prefix}{called_key}" for called_key in called_jobs}, + "outputs": _declared_call_outputs(called), + # The call's inputs, declared defaults included, which its outputs + # may read as ``inputs.``. + "inputs": copy.deepcopy(call_inputs), + "callers": { + name: _prefix_alias(nested, prefix, called_keys) + for name, nested in nested_callers.items() + }, + } + declared_needs = config.get("needs") or [] + caller_needs[key] = [declared_needs] if isinstance(declared_needs, str) else list(declared_needs) for called_key, called_config in called_jobs.items(): child = copy.deepcopy(called_config) child["name"] = child.get("name", f"{key} / {called_key}") + # Aliases a nested level gave this job name its jobs by their keys + # there; this level prefixes those keys, so prefix them here too. + aliases = child.get("_needs_aliases") or {} + for name, alias in aliases.items(): + aliases[name] = _prefix_alias(alias, prefix, called_keys, call_inputs) caller_condition = config.get("if") child_condition = child.get("if") if caller_condition is not None: @@ -649,6 +911,12 @@ async def _materialize_reusable_jobs( # substituted lexically, so the called workflow's inputs and # secrets travel with the job and enter its expression context. child["_call_inputs"] = {**call_inputs, **(child.get("_call_inputs") or {})} + # The same inputs by level, outermost first: a nested call's + # ``with:`` is in its own calling workflow's terms, so the job's + # inputs are rendered one level at a time (``call_inputs_context``). + child["_call_inputs_chain"] = [ + copy.deepcopy(call_inputs), *(child.get("_call_inputs_chain") or []), + ] child["_call_secrets"] = { **(call_secrets or {}), **(child.get("_call_secrets") or {}), } @@ -670,14 +938,70 @@ async def _materialize_reusable_jobs( f"{prefix}{dependency}" if dependency in called_keys else dependency for dependency in child_needs ] - if config.get("needs"): - outer_needs = config["needs"] - if isinstance(outer_needs, str): - outer_needs = [outer_needs] + outer_needs = config.get("needs") or [] + if isinstance(outer_needs, str): + outer_needs = [outer_needs] + if outer_needs: child["needs"] = [*outer_needs, *child["needs"]] + if depth == 0: + # The run's own caller job. When its ``if:`` is false, GitHub + # never expands the call and lists only this job, skipped. + child["_caller"] = { + "key": key, + "name": config.get("name", key), + "if": caller_condition, + "needs": list(outer_needs), + } expanded[f"{prefix}{called_key}"] = child + # A job that needs a caller needs every job the call inlined: the caller + # itself is no job in the run. needs. still has to answer, with + # the call's result and its workflow_call outputs, so the job carries + # what the scheduler needs to build that entry (_needs_aliases). + # A caller's ``with:`` may read needs..outputs, so each + # alias also holds the aliases of the callers it needs (``needs_aliases``), + # in any job order; a cycle in needs is cut rather than followed. + def linked(key: str, seen: frozenset) -> dict: + return { + **callers[key], + "needs_aliases": { + need: linked(need, seen | {need}) + for need in caller_needs.get(key, []) + if need in callers and need not in seen + }, + } + + callers = {key: linked(key, frozenset({key})) for key in callers} + for job in expanded.values(): + if not isinstance(job, dict): + continue + needs = job.get("needs") or [] + if isinstance(needs, str): + needs = [needs] + if not any(need in callers for need in needs): + continue + remapped: list[str] = [] + for need in needs: + if need in callers: + remapped.extend(callers[need]["jobs"].values()) + # A called job already holding an alias under this key got it + # from its own workflow, where the key names that workflow's + # caller: keep it, since that is the job its needs. reads. + job.setdefault("_needs_aliases", {}).setdefault(need, copy.deepcopy(callers[need])) + if depth == 0: + # The run's own callers, by key, and the called jobs a + # need on each became. Only these are decided at run + # creation, so only these can be pointed back at a + # skipped caller's job; a key from a nested workflow may + # coincide with one of them and must not be. + job.setdefault("_caller_needs", {})[need] = list(callers[need]["jobs"].values()) + else: + remapped.append(need) + job["needs"] = list(dict.fromkeys(remapped)) + result["jobs"] = expanded + # For the calling level, which keeps them in its own caller's alias. + result["_callers"] = callers return result @@ -699,7 +1023,7 @@ async def materialize_reusable_workflows( those lexical contexts and remaps dependencies so nested calls behave like their GitHub counterparts. """ - return await _materialize_reusable_jobs( + materialized = await _materialize_reusable_jobs( workflow_yaml, repo_disk_path, ref, @@ -709,6 +1033,8 @@ async def materialize_reusable_workflows( depth=0, ancestry=(), ) + materialized.pop("_callers", None) + return materialized def _instance_strategy(job_config: dict, context: dict) -> dict: @@ -721,6 +1047,28 @@ def _instance_strategy(job_config: dict, context: dict) -> dict: return strategy_context(job_config.get("strategy"), context=context) +def call_inputs_context(job_config: dict, run_inputs: dict, context: dict) -> dict | None: + """The ``inputs`` context of a job an inlined reusable workflow defined. + + Each enclosing call's ``with:`` (``_call_inputs_chain``, outermost first) + is rendered against the inputs of the workflow it is written in, as + ``needs_alias_entries`` renders them for needs.. Keys of outer + levels stay visible under inner ones, as the merged ``_call_inputs`` has + them. A job with only ``_call_inputs`` has it rendered in one pass. None + when the job carries no call inputs. + """ + chain = job_config.get("_call_inputs_chain") or [] + if chain: + merged = dict(run_inputs) + for level in resolve_call_inputs_chain(chain, run_inputs, context): + merged.update(level) + return merged + call_inputs = job_config.get("_call_inputs") or {} + if call_inputs: + return {**run_inputs, **render_expressions(call_inputs, context)} + return None + + def _job_context(base_context: dict, job_config: dict) -> dict: """Build a job's expression context, layering any reusable-call values. @@ -743,11 +1091,10 @@ def _job_context(base_context: dict, job_config: dict) -> dict: "workflow_sha": job_config.get("_workflow_sha") or github.get("sha", ""), }, } - call_inputs = job_config.get("_call_inputs") or {} call_secrets = job_config.get("_call_secrets") or {} - if call_inputs: - rendered_inputs = render_expressions(call_inputs, context) - context["inputs"] = {**(base_context.get("inputs") or {}), **rendered_inputs} + inputs = call_inputs_context(job_config, base_context.get("inputs") or {}, context) + if inputs is not None: + context["inputs"] = inputs if call_secrets: rendered_secrets = render_expressions(call_secrets, context) context["secrets"] = {**(base_context.get("secrets") or {}), **rendered_secrets} @@ -1173,8 +1520,64 @@ async def create_workflow_run( job_list = build_job_graph(workflow_yaml) skipped_job_created = False + # Placeholders for reusable calls that could not be inlined, failed once + # the run is flushed and their rows have ids for a log. + refused_jobs: list[tuple[WorkflowJob, str]] = [] + # Caller jobs of reusable workflows, by key: True when the call runs. + caller_runs: dict[str, bool] = {} for job_def in job_list: + # A need on a caller became a need on its called jobs. A skipped + # caller creates none of them, only one skipped job under its own + # key, so point the need back at that job. Its needs. is then + # that job's own entry (result "skipped"), not one built from called + # jobs that were never created, so the alias for it is dropped. + for top_caller, called_jobs in (job_def.get("_caller_needs") or {}).items(): + if caller_runs.get(top_caller) is not False: + continue + called = set(called_jobs) + kept = [need for need in job_def.get("needs", []) if need not in called] + job_def["needs"] = [*kept, top_caller] + aliases = job_def.get("_needs_aliases") or {} + alias = aliases.get(top_caller) + if alias is not None and set(alias.get("jobs", {}).values()) == called: + job_def["_needs_aliases"] = { + name: value for name, value in aliases.items() if name != top_caller + } + caller = job_def.get("_caller") + # A caller with needs is decided at promotion; its called jobs carry + # its condition and are skipped one by one there. + if caller and not caller.get("needs"): + caller_key = caller["key"] + if caller_key in caller_runs: + if not caller_runs[caller_key]: + continue + else: + caller_context = _job_context(expression_context, {}) + caller_runs[caller_key] = evaluate_job_if(caller.get("if"), caller_context) + if not caller_runs[caller_key]: + # GitHub never expands a skipped call: the run lists the + # caller job alone, named after it. Listing every called + # job as skipped instead named jobs that never existed. + db.add(WorkflowJob( + run_id=run.id, + name=str(render_expressions(caller["name"], caller_context)), + workflow_name=workflow.name, + status="completed", + conclusion="skipped", + completed_at=datetime.now(timezone.utc), + steps=[], + labels=[], + run_attempt=1, + needs=[], + permissions={}, + job_key=caller_key, + outputs_config={}, + outputs={}, + )) + skipped_job_created = True + continue + dynamic_matrix = dynamic_matrix_expression(job_def) if dynamic_matrix is not None and not job_def.get("needs"): # Nothing to wait for: the matrix reads only the event and the @@ -1224,10 +1627,15 @@ async def create_workflow_run( "matrix": job_config.get("_matrix", {}), "strategy": job_expression_context["strategy"], "_call_inputs": job_config.get("_call_inputs") or {}, + "_call_inputs_chain": job_config.get("_call_inputs_chain") or [], "_call_secrets": job_config.get("_call_secrets") or {}, "_workflow_repository": job_config.get("_workflow_repository") or "", "_workflow_sha": job_config.get("_workflow_sha") or "", + "_needs_aliases": job_config.get("_needs_aliases") or {}, } + if job_config.get("_refused"): + # Failed at promotion, once its condition is known. + pending_render["refused"] = job_config["_refused"] if dynamic_matrix is not None: # Expanded at promotion, once needs.*.outputs exist. The # name and concurrency group read matrix.*, so they are @@ -1305,10 +1713,16 @@ async def create_workflow_run( workflow_ref=job_config.get("_workflow_ref") or None, ) db.add(job) + if job_config.get("_refused") and not needs and conclusion is None: + refused_jobs.append((job, job_config["_refused"])) await db.flush() - # A run containing only skipped jobs should finish immediately. Also - # propagate skipped dependencies before the first runner poll. + for job, why in refused_jobs: + fail_refused_job(job, why) + skipped_job_created = True + # A run containing only skipped (or refused) jobs should finish + # immediately. Also propagate those to dependents before the first + # runner poll. if skipped_job_created: await dispatch_ready_jobs(db, run.id) await check_run_completion(db, run.id) diff --git a/tests/actions/test_container_jobs.py b/tests/actions/test_container_jobs.py new file mode 100644 index 00000000..0b361b54 --- /dev/null +++ b/tests/actions/test_container_jobs.py @@ -0,0 +1,46 @@ +"""Jobs that need containers fail loudly instead of running on the host. + +Neither the Python runner nor the upstream-runner path starts a job container +or service containers. Running such a job's steps anyway put them on the +runner host, where a check like "is this Alpine?" failed and a check that +only needed a shell passed: a result about the host, not the workflow. +""" + +import subprocess + +import pytest + +from app.services.workflow_service import build_job_graph + + +def _job(config: dict) -> dict: + [job] = build_job_graph({"on": "push", "jobs": {"j": config}}) + return job + + +@pytest.mark.parametrize("config, named", [ + ({"container": "alpine:3.20"}, "container:"), + ({"container": {"image": "alpine:3.20"}}, "container:"), + ({"services": {"db": {"image": "postgres:16"}}}, "services:"), + ({"container": "alpine:3.20", "services": {"db": {"image": "postgres:16"}}}, + "container: and services:"), +]) +def test_a_container_job_is_refused_not_run_on_the_host(config, named): + job = _job({"runs-on": "ubuntu-latest", **config, "steps": [{"run": "echo would-run"}]}) + [step] = job["steps"] + assert "would-run" not in step["run"] + assert f"::error::{named} not supported" in step["run"] + # The refusal really fails, and says why on stderr. + result = subprocess.run(["bash", "-c", step["run"]], capture_output=True, text=True) + assert result.returncode == 1 + assert "were NOT run" in result.stderr + + +def test_a_job_without_containers_keeps_its_steps(): + job = _job({"runs-on": "ubuntu-latest", "steps": [{"run": "echo would-run"}]}) + assert job["steps"] == [{"run": "echo would-run"}] + + +def test_an_empty_container_key_is_not_a_container(): + job = _job({"runs-on": "ubuntu-latest", "container": "", "steps": [{"run": "echo ok"}]}) + assert job["steps"] == [{"run": "echo ok"}] diff --git a/tests/actions/test_emulator_hosted_actions.py b/tests/actions/test_emulator_hosted_actions.py new file mode 100644 index 00000000..10e4b8fb --- /dev/null +++ b/tests/actions/test_emulator_hosted_actions.py @@ -0,0 +1,242 @@ +"""`uses: owner/repo@ref` resolves against repositories on this emulator first. + +As on GHES, an action pushed to a repository here is used from here, and a +name the emulator does not hold goes upstream. GHES goes upstream only for a +repository it lacks; this emulator also does when a public repository is here +but lacks the ref. A private repository here that lacks the ref or commit is +unresolvable, and is not looked up upstream. Before, every reference was resolved upstream, so an action in +a repository here failed with "does not exist upstream". + +A job may use an action from a public repository or from its own repository. +GitHub lets other repositories use a private repository's actions only when +its owner enables that access; this emulator has no such setting, so any +other private or internal repository, the same owner's included, is not +resolvable, and its name is not looked up upstream. +""" + +import base64 +import io +import tarfile + +import pytest + +from app.api import actions_distributed_task as dt +from app.services.action_download_service import UpstreamActionError +from tests.actions.test_uses_steps import SHA, _claim_job, uses_workflow # noqa: F401 +from tests.conftest import API, auth_headers + + +async def _download_info(client, body, token, name, ref): + return await client.post( + f"/_apis/distributedtask/hubs/Build/plans/{body['plan']['planId']}/actionsdownloadinfo", + json={"actions": [{"nameWithOwner": name, "ref": ref}]}, + headers={"Authorization": f"Bearer {token}"}, + ) + + +@pytest.mark.asyncio +async def test_an_action_in_a_repository_here_is_served_from_here( + client, uses_workflow, test_token, monkeypatch # noqa: F811 +): + resp = await client.post( + f"{API}/user/repos", json={"name": "my-action", "auto_init": True}, + headers=auth_headers(test_token), + ) + assert resp.status_code == 201 + + async def no_upstream(name, ref): + raise AssertionError(f"looked up {name}@{ref} upstream") + monkeypatch.setattr(dt, "resolve_action_sha", no_upstream) + + body = await _claim_job(client, test_token) + token = body["variables"]["system.github.token"]["Value"] + resp = await _download_info(client, body, token, "testuser/my-action", "main") + assert resp.status_code == 200, resp.text + info = resp.json()["actions"]["testuser/my-action@main"] + sha = info["resolvedSha"] + assert len(sha) == 40 + + basic = base64.b64encode(f"x-access-token:{token}".encode()).decode() + path = info["tarballUrl"].split("://", 1)[1].split("/", 1)[1] + archive = await client.get(f"/{path}", headers={"Authorization": f"Basic {basic}"}) + assert archive.status_code == 200, archive.text + with tarfile.open(fileobj=io.BytesIO(archive.content), mode="r:gz") as tar: + names = tar.getnames() + assert f"testuser-my-action-{sha[:7]}/README.md" in names + + +@pytest.mark.asyncio +async def test_a_name_not_held_here_still_goes_upstream( + client, uses_workflow, test_token, monkeypatch # noqa: F811 +): + looked_up = [] + + async def upstream(name, ref): + looked_up.append((name, ref)) + return SHA + monkeypatch.setattr(dt, "resolve_action_sha", upstream) + + body = await _claim_job(client, test_token) + token = body["variables"]["system.github.token"]["Value"] + resp = await _download_info(client, body, token, "actions/checkout", "v4") + assert resp.status_code == 200 + assert looked_up == [("actions/checkout", "v4")] + assert resp.json()["actions"]["actions/checkout@v4"]["resolvedSha"] == SHA + + +@pytest.mark.asyncio +async def test_a_ref_missing_here_falls_back_upstream( + client, uses_workflow, test_token, monkeypatch # noqa: F811 +): + await client.post( + f"{API}/user/repos", json={"name": "my-action", "auto_init": True}, + headers=auth_headers(test_token), + ) + + async def upstream(name, ref): + raise UpstreamActionError(f"{name}@{ref} does not exist upstream", not_found=True) + monkeypatch.setattr(dt, "resolve_action_sha", upstream) + + body = await _claim_job(client, test_token) + token = body["variables"]["system.github.token"]["Value"] + resp = await _download_info(client, body, token, "testuser/my-action", "no-such-tag") + assert resp.status_code == 404 + assert resp.json()["typeKey"] == "UnresolvableActionDownloadInfoException" + + +async def _private_repository(client, token, name): + resp = await client.post( + f"{API}/user/repos", json={"name": name, "auto_init": True, "private": True}, + headers=auth_headers(token), + ) + assert resp.status_code == 201, resp.text + + +def _no_upstream(monkeypatch): + async def resolve(name, ref): + raise AssertionError(f"looked up {name}@{ref} upstream") + + async def fetch(name, sha, fmt): + raise AssertionError(f"fetched {name}@{sha} upstream") + monkeypatch.setattr(dt, "resolve_action_sha", resolve) + monkeypatch.setattr(dt, "fetch_action_archive", fetch) + + +async def _archive(client, token, name, sha): + basic = base64.b64encode(f"x-access-token:{token}".encode()).decode() + return await client.get( + f"/_apis/distributedtask/actions/archives/{name}/{sha}/archive.tar.gz", + headers={"Authorization": f"Basic {basic}"}, + ) + + +@pytest.mark.asyncio +async def test_another_owners_private_repository_is_not_an_action_here( + client, uses_workflow, test_token, admin_token, monkeypatch # noqa: F811 +): + await _private_repository(client, admin_token, "private-action") + _no_upstream(monkeypatch) + sha = (await client.get( + f"{API}/repos/admin/private-action/commits/main", headers=auth_headers(admin_token), + )).json()["sha"] + assert len(sha) == 40 + + body = await _claim_job(client, test_token) + token = body["variables"]["system.github.token"]["Value"] + resp = await _download_info(client, body, token, "admin/private-action", "main") + assert resp.status_code == 404 + assert resp.json()["typeKey"] == "UnresolvableActionDownloadInfoException" + + archive = await _archive(client, token, "admin/private-action", sha) + assert archive.status_code == 404 + + +@pytest.mark.asyncio +async def test_a_private_repository_with_the_jobs_owner_is_not_an_action_here( + client, uses_workflow, test_token, monkeypatch # noqa: F811 +): + await _private_repository(client, test_token, "own-private-action") + _no_upstream(monkeypatch) + sha = (await client.get( + f"{API}/repos/testuser/own-private-action/commits/main", headers=auth_headers(test_token), + )).json()["sha"] + assert len(sha) == 40 + + body = await _claim_job(client, test_token) + token = body["variables"]["system.github.token"]["Value"] + resp = await _download_info(client, body, token, "testuser/own-private-action", "main") + assert resp.status_code == 404 + assert resp.json()["typeKey"] == "UnresolvableActionDownloadInfoException" + + archive = await _archive(client, token, "testuser/own-private-action", sha) + assert archive.status_code == 404 + + +async def _make_job_repository_private(client, token): + """The job's own repository (``uses_workflow``), made private, with a + commit on main to serve.""" + resp = await client.patch( + f"{API}/repos/testuser/uses-step-repo", json={"private": True}, + headers=auth_headers(token), + ) + assert resp.status_code == 200, resp.text + assert resp.json()["private"] is True + resp = await client.put( + f"{API}/repos/testuser/uses-step-repo/contents/action.yml", + json={ + "message": "add action", + "content": base64.b64encode(b"runs: {using: node20, main: x.js}\n").decode(), + }, + headers=auth_headers(token), + ) + assert resp.status_code == 201, resp.text + + +@pytest.mark.asyncio +async def test_the_jobs_own_private_repository_is_served( + client, uses_workflow, test_token, monkeypatch # noqa: F811 +): + await _make_job_repository_private(client, test_token) + _no_upstream(monkeypatch) + + body = await _claim_job(client, test_token) + token = body["variables"]["system.github.token"]["Value"] + resp = await _download_info(client, body, token, "testuser/uses-step-repo", "main") + assert resp.status_code == 200, resp.text + sha = resp.json()["actions"]["testuser/uses-step-repo@main"]["resolvedSha"] + + archive = await _archive(client, token, "testuser/uses-step-repo", sha) + assert archive.status_code == 200, archive.text + + +@pytest.mark.asyncio +async def test_a_ref_missing_from_a_private_repository_here_is_not_looked_up_upstream( + client, uses_workflow, test_token, monkeypatch # noqa: F811 +): + await _make_job_repository_private(client, test_token) + looked_up = [] + + async def upstream(name, ref): + looked_up.append((name, ref)) + return SHA + monkeypatch.setattr(dt, "resolve_action_sha", upstream) + + body = await _claim_job(client, test_token) + token = body["variables"]["system.github.token"]["Value"] + resp = await _download_info(client, body, token, "testuser/uses-step-repo", "v1") + assert resp.status_code == 404 + assert resp.json()["typeKey"] == "UnresolvableActionDownloadInfoException" + assert looked_up == [] + + +@pytest.mark.asyncio +async def test_a_commit_missing_from_a_private_repository_here_is_not_fetched_upstream( + client, uses_workflow, test_token, monkeypatch # noqa: F811 +): + await _make_job_repository_private(client, test_token) + _no_upstream(monkeypatch) + + body = await _claim_job(client, test_token) + token = body["variables"]["system.github.token"]["Value"] + archive = await _archive(client, token, "testuser/uses-step-repo", SHA) + assert archive.status_code == 404 diff --git a/tests/actions/test_execution.py b/tests/actions/test_execution.py index 40920a3a..97019f6c 100644 --- a/tests/actions/test_execution.py +++ b/tests/actions/test_execution.py @@ -395,7 +395,8 @@ async def test_job_if_false_is_skipped_and_not_queued( assert job.conclusion == "skipped" assert job.steps[0]["conclusion"] == "skipped" assert run.status == "completed" - assert run.conclusion == "success" + # GitHub concludes a run whose every job was skipped as skipped. + assert run.conclusion == "skipped" @pytest.mark.asyncio diff --git a/tests/actions/test_jobs_list_unstarted.py b/tests/actions/test_jobs_list_unstarted.py new file mode 100644 index 00000000..3e9dae48 --- /dev/null +++ b/tests/actions/test_jobs_list_unstarted.py @@ -0,0 +1,42 @@ +"""The jobs list shows a job once it is queued, not while it waits on needs. + +Probed on GitHub (bt-f3): while job a ran, GET /runs/{id}/jobs listed only a +(total_count 1); b and c, which need a, appeared once they started. The +emulator listed all three, b and c as "waiting", so a stage that had not +started looked like one in the run. +""" + +import pytest + +from app.models.actions import Workflow, WorkflowJob, WorkflowRun +from tests.conftest import API, auth_headers + + +@pytest.mark.asyncio +async def test_a_job_waiting_on_needs_is_not_listed_until_queued( + client, db_session, test_user, test_token, test_repo_with_init +): + _owner, _repo, repo = test_repo_with_init + workflow = Workflow(repo_id=repo["id"], name="Needs", path=".github/workflows/needs.yml") + db_session.add(workflow) + await db_session.flush() + run = WorkflowRun( + workflow_id=workflow.id, repo_id=repo["id"], head_sha="abc", head_branch="main", + event="workflow_dispatch", status="in_progress", run_number=1, actor_id=test_user.id, + ) + db_session.add(run) + await db_session.flush() + a = WorkflowJob(run_id=run.id, name="a", status="in_progress") + b = WorkflowJob(run_id=run.id, name="b", status="waiting", needs=["a"]) + db_session.add_all([a, b]) + await db_session.commit() + url = f"{API}/repos/testuser/init-repo/actions/runs/{run.id}/jobs" + + listed = (await client.get(url, headers=auth_headers(test_token))).json() + assert listed["total_count"] == 1 + assert [job["name"] for job in listed["jobs"]] == ["a"] + + b.status = "queued" + await db_session.commit() + listed = (await client.get(url, headers=auth_headers(test_token))).json() + assert sorted(job["name"] for job in listed["jobs"]) == ["a", "b"] diff --git a/tests/actions/test_reusable_caller_needs.py b/tests/actions/test_reusable_caller_needs.py new file mode 100644 index 00000000..4f5db65f --- /dev/null +++ b/tests/actions/test_reusable_caller_needs.py @@ -0,0 +1,885 @@ +"""A job that needs a reusable-workflow caller waits for the call and reads it. + +The emulator inlines the called jobs as `` / `` and the caller +itself is no job in the run, so a job with ``needs: `` waited for a +job that never existed and stayed ``waiting`` for good. And +``needs..outputs.*``, which GitHub fills from the called workflow's +``on.workflow_call.outputs``, had nothing to read. +""" + +import pytest +from sqlalchemy import select + +from app.models.actions import WorkflowJob +from app.services import workflow_service +from app.services.workflow_scheduler import dispatch_ready_jobs +from app.services.workflow_service import create_workflow_run, needs_alias_entries +from tests.actions.test_execution import executable_workflow # noqa: F401 (fixture) + +CALLED = { + "on": {"workflow_call": {"outputs": { + "got": {"description": "from inner", "value": "${{ jobs.inner.outputs.got }}"}, + "both": {"value": "${{ jobs.inner.outputs.got }}-${{ jobs.second.outputs.extra }}"}, + }}}, + "jobs": { + "inner": { + "runs-on": ["self-hosted"], + "outputs": {"got": "${{ steps.s.outputs.got }}"}, + "steps": [{"id": "s", "run": "echo"}], + }, + "second": { + "runs-on": ["self-hosted"], + "outputs": {"extra": "${{ steps.s.outputs.extra }}"}, + "steps": [{"id": "s", "run": "echo"}], + }, + }, +} + +CALLER = { + "name": "caller", + "jobs": { + "call": {"uses": "./.github/workflows/called.yml"}, + "after": { + "needs": ["call"], + "runs-on": ["self-hosted"], + "steps": [{"run": "echo ${{ needs.call.outputs.got }} ${{ needs.call.outputs.both }} ${{ needs.call.result }}"}], + }, + }, +} + + +async def _materialize(monkeypatch, caller): + async def fake_detect(path, ref="HEAD"): + return [{"_path": ".github/workflows/called.yml", **CALLED}] + + monkeypatch.setattr(workflow_service, "detect_workflows", fake_detect) + return await workflow_service.materialize_reusable_workflows(caller, "caller.git", "main", None) + + +@pytest.mark.asyncio +async def test_needs_on_a_caller_means_needs_on_every_called_job(monkeypatch): + jobs = (await _materialize(monkeypatch, CALLER))["jobs"] + assert sorted(jobs) == ["after", "call / inner", "call / second"] + assert jobs["after"]["needs"] == ["call / inner", "call / second"] + assert jobs["after"]["_needs_aliases"]["call"]["jobs"] == { + "inner": "call / inner", "second": "call / second", + } + + +@pytest.mark.asyncio +async def test_the_dependent_runs_with_the_calls_outputs_and_result( + monkeypatch, executable_workflow, db_session, test_user, # noqa: F811 +): + _repo, workflow, _ = executable_workflow + workflow_yaml = await _materialize(monkeypatch, CALLER) + run = await create_workflow_run( + db_session, workflow, workflow_yaml, event="push", + payload={"repository": {"full_name": "testuser/actions-exec-repo"}}, + actor=test_user, head_sha="caller123", head_branch="main", + ) + await db_session.commit() + + rows = { + r.job_key: r for r in (await db_session.execute( + select(WorkflowJob).where(WorkflowJob.run_id == run.id) + )).scalars().all() + } + assert rows["after"].status == "waiting" + for key, outputs in (("call / inner", {"got": "value-x"}), ("call / second", {"extra": "y"})): + rows[key].status = "completed" + rows[key].conclusion = "success" + rows[key].outputs = outputs + await db_session.commit() + + await dispatch_ready_jobs(db_session, run.id) + await db_session.commit() + after = (await db_session.execute( + select(WorkflowJob).where(WorkflowJob.run_id == run.id, WorkflowJob.job_key == "after") + )).scalar_one() + assert after.status == "queued" + assert after.steps[0]["run"] == "echo value-x value-x-y success" + + +def test_the_call_result_is_the_worst_of_its_jobs(): + aliases = {"call": {"jobs": {"a": "call / a", "b": "call / b"}, "outputs": {}}} + needs = { + "call / a": {"result": "success", "outputs": {}}, + "call / b": {"result": "failure", "outputs": {}}, + } + assert needs_alias_entries(aliases, needs)["call"]["result"] == "failure" + + +INNER = { + "on": {"workflow_call": {}}, + "jobs": {"x": {"runs-on": ["self-hosted"], "steps": [{"run": "echo"}]}}, +} + +MID = { + "on": {"workflow_call": {}}, + "jobs": { + "build": {"uses": "./.github/workflows/inner.yml"}, + "after": { + "needs": ["build"], + "runs-on": ["self-hosted"], + "steps": [{"run": "echo ${{ needs.build.result }}"}], + }, + }, +} + + +@pytest.mark.asyncio +async def test_a_nested_caller_sharing_a_skipped_top_level_callers_key_is_waited_for( + monkeypatch, executable_workflow, db_session, test_user, # noqa: F811 +): + """``deploy / after`` needs the ``build`` call inside mid.yml, not the + run's own skipped ``build`` caller that happens to share its key.""" + async def fake_detect(path, ref="HEAD"): + return [ + {"_path": ".github/workflows/inner.yml", **INNER}, + {"_path": ".github/workflows/mid.yml", **MID}, + ] + + monkeypatch.setattr(workflow_service, "detect_workflows", fake_detect) + workflow_yaml = await workflow_service.materialize_reusable_workflows({ + "name": "caller", + "jobs": { + "build": {"if": "false", "uses": "./.github/workflows/inner.yml"}, + "deploy": {"uses": "./.github/workflows/mid.yml"}, + }, + }, "caller.git", "main", None) + _repo, workflow, _ = executable_workflow + run = await create_workflow_run( + db_session, workflow, workflow_yaml, event="push", + payload={"repository": {"full_name": "testuser/actions-exec-repo"}}, + actor=test_user, head_sha="caller123", head_branch="main", + ) + await db_session.commit() + + rows = { + r.job_key: r for r in (await db_session.execute( + select(WorkflowJob).where(WorkflowJob.run_id == run.id) + )).scalars().all() + } + assert sorted(rows) == ["build", "deploy / after", "deploy / build / x"] + assert rows["build"].conclusion == "skipped" + assert rows["deploy / after"].needs == ["deploy / build / x"] + assert rows["deploy / after"].status == "waiting" + + rows["deploy / build / x"].status = "completed" + rows["deploy / build / x"].conclusion = "success" + await db_session.commit() + await dispatch_ready_jobs(db_session, run.id) + await db_session.commit() + after = (await db_session.execute( + select(WorkflowJob).where(WorkflowJob.run_id == run.id, WorkflowJob.job_key == "deploy / after") + )).scalar_one() + assert after.status == "queued" + assert after.steps[0]["run"] == "echo success" + + +async def _run(monkeypatch, db_session, workflow, test_user, caller, called): + async def fake_detect(path, ref="HEAD"): + return [{"_path": f".github/workflows/{name}", **config} for name, config in called.items()] + + monkeypatch.setattr(workflow_service, "detect_workflows", fake_detect) + workflow_yaml = await workflow_service.materialize_reusable_workflows(caller, "caller.git", "main", None) + run = await create_workflow_run( + db_session, workflow, workflow_yaml, event="push", + payload={"repository": {"full_name": "testuser/actions-exec-repo"}}, + actor=test_user, head_sha="caller123", head_branch="main", + ) + await db_session.commit() + return run + + +async def _rows(db_session, run): + return { + r.job_key: r for r in (await db_session.execute( + select(WorkflowJob).where(WorkflowJob.run_id == run.id) + )).scalars().all() + } + + +OPTIONAL = { + "on": {"workflow_call": {}}, + "jobs": { + "build": {"runs-on": ["self-hosted"], "steps": [{"run": "echo"}]}, + "optional": {"if": "false", "runs-on": ["self-hosted"], "steps": [{"run": "echo"}]}, + }, +} + +NEEDS_CALL = { + "name": "caller", + "jobs": { + "call": {"uses": "./.github/workflows/called.yml"}, + "after": { + "needs": ["call"], + "runs-on": ["self-hosted"], + "steps": [{"run": "echo ${{ needs.call.result }}"}], + }, + }, +} + + +@pytest.mark.asyncio +async def test_a_job_skipped_by_its_own_condition_in_the_call_does_not_skip_the_dependent( + monkeypatch, executable_workflow, db_session, test_user, # noqa: F811 +): + """On GitHub the call succeeds when none of its jobs failed or was + cancelled, even with one skipped by its own ``if:``, and an ordinary + ``needs: call`` dependent (implicit ``success()``) runs.""" + _repo, workflow, _ = executable_workflow + run = await _run( + monkeypatch, db_session, workflow, test_user, NEEDS_CALL, {"called.yml": OPTIONAL}, + ) + rows = await _rows(db_session, run) + assert rows["call / optional"].conclusion == "skipped" + rows["call / build"].status = "completed" + rows["call / build"].conclusion = "success" + await db_session.commit() + + await dispatch_ready_jobs(db_session, run.id) + await db_session.commit() + after = (await _rows(db_session, run))["after"] + assert after.status == "queued" + assert after.steps[0]["run"] == "echo success" + + +@pytest.mark.asyncio +async def test_a_failed_job_in_the_call_still_skips_the_dependent( + monkeypatch, executable_workflow, db_session, test_user, # noqa: F811 +): + called = { + "on": {"workflow_call": {}}, + "jobs": { + **OPTIONAL["jobs"], + "check": {"runs-on": ["self-hosted"], "steps": [{"run": "echo"}]}, + }, + } + _repo, workflow, _ = executable_workflow + run = await _run( + monkeypatch, db_session, workflow, test_user, NEEDS_CALL, {"called.yml": called}, + ) + rows = await _rows(db_session, run) + rows["call / build"].status = "completed" + rows["call / build"].conclusion = "success" + rows["call / check"].status = "completed" + rows["call / check"].conclusion = "failure" + await db_session.commit() + + await dispatch_ready_jobs(db_session, run.id) + await db_session.commit() + after = (await _rows(db_session, run))["after"] + assert after.status == "completed" + assert after.conclusion == "skipped" + + +@pytest.mark.asyncio +async def test_a_call_output_read_from_a_nested_callers_output( + monkeypatch, executable_workflow, db_session, test_user, # noqa: F811 +): + """outer.yml's output reads ``jobs.inner.outputs.v``, where ``inner`` is + itself a call; inner.yml's output reads its ``leaf`` job's output.""" + called = { + "outer.yml": { + "on": {"workflow_call": {"outputs": {"v": {"value": "${{ jobs.inner.outputs.v }}"}}}}, + "jobs": {"inner": {"uses": "./.github/workflows/inner.yml"}}, + }, + "inner.yml": { + "on": {"workflow_call": {"outputs": {"v": {"value": "${{ jobs.leaf.outputs.v }}"}}}}, + "jobs": {"leaf": { + "runs-on": ["self-hosted"], + "outputs": {"v": "${{ steps.s.outputs.v }}"}, + "steps": [{"id": "s", "run": "echo"}], + }}, + }, + } + caller = { + "name": "caller", + "jobs": { + "outer": {"uses": "./.github/workflows/outer.yml"}, + "after": { + "needs": ["outer"], + "runs-on": ["self-hosted"], + "steps": [{"run": "echo ${{ needs.outer.outputs.v }} ${{ needs.outer.result }}"}], + }, + }, + } + _repo, workflow, _ = executable_workflow + run = await _run(monkeypatch, db_session, workflow, test_user, caller, called) + rows = await _rows(db_session, run) + assert sorted(rows) == ["after", "outer / inner / leaf"] + rows["outer / inner / leaf"].status = "completed" + rows["outer / inner / leaf"].conclusion = "success" + rows["outer / inner / leaf"].outputs = {"v": "deep"} + await db_session.commit() + + await dispatch_ready_jobs(db_session, run.id) + await db_session.commit() + after = (await _rows(db_session, run))["after"] + assert after.status == "queued" + assert after.steps[0]["run"] == "echo deep success" + + +def test_a_nested_callers_entry_is_built_from_its_own_alias(): + aliases = {"outer": { + "jobs": {"inner / leaf": "outer / inner / leaf", "skipped": "outer / skipped"}, + "outputs": {"v": "${{ jobs.inner.outputs.v }}/${{ jobs.inner.result }}"}, + "callers": {"inner": { + "jobs": {"leaf": "outer / inner / leaf"}, + "outputs": {"v": "${{ jobs.leaf.outputs.v }}"}, + }}, + }} + needs = { + "outer / inner / leaf": {"result": "success", "outputs": {"v": "deep"}}, + "outer / skipped": {"result": "skipped", "outputs": {}}, + } + entry = needs_alias_entries(aliases, needs)["outer"] + assert entry == {"result": "success", "outputs": {"v": "deep/success"}} + + +VERSIONED = { + "on": {"workflow_call": { + "inputs": { + "version": {"type": "string", "required": False}, + "channel": {"type": "string", "default": "stable"}, + }, + "outputs": { + "version": {"value": "${{ inputs.version }}"}, + "channel": {"value": "${{ inputs.channel }}"}, + "event": {"value": "${{ inputs.version }}-${{ github.event_name }}"}, + }, + }}, + "jobs": {"build": {"runs-on": ["self-hosted"], "steps": [{"run": "echo"}]}}, +} + + +async def _promote_after(db_session, run, done_keys, after_key="after"): + rows = await _rows(db_session, run) + for key in done_keys: + rows[key].status = "completed" + rows[key].conclusion = "success" + await db_session.commit() + await dispatch_ready_jobs(db_session, run.id) + await db_session.commit() + return (await _rows(db_session, run))[after_key] + + +@pytest.mark.asyncio +async def test_a_call_output_reads_the_inputs_the_caller_passed( + monkeypatch, executable_workflow, db_session, test_user, # noqa: F811 +): + """``on.workflow_call.outputs..value`` may read ``inputs`` and + ``github``; with only ``jobs`` there, ``inputs.version`` came out empty.""" + caller = { + "name": "caller", + "jobs": { + "call": {"uses": "./.github/workflows/called.yml", "with": {"version": "1.2"}}, + "after": { + "needs": ["call"], + "runs-on": ["self-hosted"], + "steps": [{"run": "echo ${{ needs.call.outputs.version }} ${{ needs.call.outputs.event }}"}], + }, + }, + } + _repo, workflow, _ = executable_workflow + run = await _run(monkeypatch, db_session, workflow, test_user, caller, {"called.yml": VERSIONED}) + after = await _promote_after(db_session, run, ["call / build"]) + assert after.status == "queued" + assert after.steps[0]["run"] == "echo 1.2 1.2-push" + + +@pytest.mark.asyncio +async def test_a_call_output_reads_a_defaulted_input_the_caller_omitted( + monkeypatch, executable_workflow, db_session, test_user, # noqa: F811 +): + caller = { + "name": "caller", + "jobs": { + "call": {"uses": "./.github/workflows/called.yml", "with": {"version": "1.2"}}, + "after": { + "needs": ["call"], + "runs-on": ["self-hosted"], + "steps": [{"run": "echo ${{ needs.call.outputs.channel }}"}], + }, + }, + } + _repo, workflow, _ = executable_workflow + run = await _run(monkeypatch, db_session, workflow, test_user, caller, {"called.yml": VERSIONED}) + after = await _promote_after(db_session, run, ["call / build"]) + assert after.status == "queued" + assert after.steps[0]["run"] == "echo stable" + + +@pytest.mark.asyncio +async def test_a_nested_calls_output_from_its_inputs_is_forwarded_by_the_outer_call( + monkeypatch, executable_workflow, db_session, test_user, # noqa: F811 +): + """inner.yml's output reads its own ``inputs.tag``, passed by outer.yml + from outer's ``inputs.release``; outer.yml forwards it as its output.""" + called = { + "outer.yml": { + "on": {"workflow_call": { + "inputs": {"release": {"type": "string"}}, + "outputs": {"tag": {"value": "${{ jobs.inner.outputs.tag }}"}}, + }}, + "jobs": {"inner": { + "uses": "./.github/workflows/inner.yml", + "with": {"tag": "v${{ inputs.release }}"}, + }}, + }, + "inner.yml": { + "on": {"workflow_call": { + "inputs": {"tag": {"type": "string"}}, + "outputs": {"tag": {"value": "${{ inputs.tag }}"}}, + }}, + "jobs": {"leaf": {"runs-on": ["self-hosted"], "steps": [{"run": "echo"}]}}, + }, + } + caller = { + "name": "caller", + "jobs": { + "outer": {"uses": "./.github/workflows/outer.yml", "with": {"release": "3.4"}}, + "after": { + "needs": ["outer"], + "runs-on": ["self-hosted"], + "steps": [{"run": "echo ${{ needs.outer.outputs.tag }}"}], + }, + }, + } + _repo, workflow, _ = executable_workflow + run = await _run(monkeypatch, db_session, workflow, test_user, caller, called) + after = await _promote_after(db_session, run, ["outer / inner / leaf"]) + assert after.status == "queued" + assert after.steps[0]["run"] == "echo v3.4" + + +def test_a_call_output_reads_the_runs_github_and_vars_contexts(): + aliases = {"call": { + "jobs": {"a": "call / a"}, + "inputs": {"ref": "${{ github.ref_name }}"}, + "outputs": {"v": "${{ inputs.ref }}/${{ github.event_name }}/${{ vars.REGION }}"}, + }} + needs = {"call / a": {"result": "success", "outputs": {}}} + run_context = { + "github": {"ref_name": "main", "event_name": "push"}, + "vars": {"REGION": "eu"}, + "secrets": {"TOKEN": "not-exposed"}, + } + entry = needs_alias_entries(aliases, needs, run_context)["call"] + assert entry["outputs"] == {"v": "main/push/eu"} + + +def test_a_call_output_cannot_read_secrets(): + aliases = {"call": {"jobs": {}, "outputs": {"v": "${{ secrets.TOKEN }}"}}} + entry = needs_alias_entries(aliases, {}, {"secrets": {"TOKEN": "hidden"}})["call"] + assert entry["outputs"] == {"v": ""} + + +@pytest.mark.asyncio +async def test_a_top_level_calls_compound_with_reads_the_dispatch_inputs( + monkeypatch, executable_workflow, db_session, test_user, # noqa: F811 +): + """A compound ``with:`` expression on the run's own inputs is rendered at + promotion; ``needs..outputs`` must agree with what the called job + received, not render ``inputs`` as empty.""" + called = {"called.yml": { + "on": {"workflow_call": { + "inputs": {"v": {"type": "string"}}, + "outputs": {"v": {"value": "${{ inputs.v }}"}}, + }}, + "jobs": {"build": {"runs-on": ["self-hosted"], "steps": [{"run": "echo ${{ inputs.v }}"}]}}, + }} + caller = { + "name": "caller", + "jobs": { + "call": { + "uses": "./.github/workflows/called.yml", + "with": {"v": "${{ format('{0}-x', inputs.ver) }}"}, + }, + "after": { + "needs": ["call"], + "runs-on": ["self-hosted"], + "steps": [{"run": "echo ${{ needs.call.outputs.v }}"}], + }, + }, + } + + async def fake_detect(path, ref="HEAD"): + return [{"_path": f".github/workflows/{name}", **config} for name, config in called.items()] + + monkeypatch.setattr(workflow_service, "detect_workflows", fake_detect) + inputs = {"ver": "1.0"} + workflow_yaml = await workflow_service.materialize_reusable_workflows( + caller, "caller.git", "main", None, inputs=inputs, + ) + _repo, workflow, _ = executable_workflow + run = await create_workflow_run( + db_session, workflow, workflow_yaml, event="workflow_dispatch", + payload={"repository": {"full_name": "testuser/actions-exec-repo"}, "inputs": inputs}, + actor=test_user, head_sha="caller123", head_branch="main", + ) + await db_session.commit() + assert (await _rows(db_session, run))["call / build"].steps[0]["run"] == "echo 1.0-x" + after = await _promote_after(db_session, run, ["call / build"]) + assert after.status == "queued" + assert after.steps[0]["run"] == "echo 1.0-x" + + +CHAIN = { + "a.yml": { + "on": {"workflow_call": {"outputs": {"o": {"value": "${{ jobs.build.outputs.o }}"}}}}, + "jobs": {"build": { + "runs-on": ["self-hosted"], + "outputs": {"o": "${{ steps.s.outputs.o }}"}, + "steps": [{"id": "s", "run": "echo"}], + }}, + }, + "b.yml": { + "on": {"workflow_call": { + "inputs": {"x": {"type": "string"}}, + "outputs": {"out": {"value": "${{ inputs.x }}"}}, + }}, + "jobs": {"use": {"runs-on": ["self-hosted"], "steps": [{"run": "echo b ${{ inputs.x }}"}]}}, + }, + "c.yml": { + "on": {"workflow_call": { + "inputs": {"y": {"type": "string"}}, + "outputs": {"z": {"value": "${{ inputs.y }}"}}, + }}, + "jobs": {"use": {"runs-on": ["self-hosted"], "steps": [{"run": "echo c ${{ inputs.y }}"}]}}, + }, +} + + +@pytest.mark.asyncio +async def test_an_output_forwarded_through_a_chain_of_calls( + monkeypatch, executable_workflow, db_session, test_user, # noqa: F811 +): + """A -> B -> C: B passes ``needs.A.outputs.o`` as its input and outputs + it; C reads it from ``needs.B.outputs``. Rendering B's ``with:`` for C + needs ``needs.A``, the entry built from A's called jobs.""" + caller = { + "name": "caller", + "jobs": { + # C first: the order of the jobs must not matter. + "C": { + "uses": "./.github/workflows/c.yml", + "needs": "B", + "with": {"y": "${{ needs.B.outputs.out }}"}, + }, + "B": { + "uses": "./.github/workflows/b.yml", + "needs": ["A"], + "with": {"x": "${{ needs.A.outputs.o }}"}, + }, + "A": {"uses": "./.github/workflows/a.yml"}, + "after": { + "needs": ["C"], + "runs-on": ["self-hosted"], + "steps": [{"run": "echo ${{ needs.C.outputs.z }} ${{ needs.C.result }}"}], + }, + }, + } + _repo, workflow, _ = executable_workflow + run = await _run(monkeypatch, db_session, workflow, test_user, caller, CHAIN) + + async def finish(key, outputs=None): + row = (await _rows(db_session, run))[key] + row.status = "completed" + row.conclusion = "success" + row.outputs = outputs or {} + await db_session.commit() + await dispatch_ready_jobs(db_session, run.id) + await db_session.commit() + + await finish("A / build", {"o": "forty"}) + rows = await _rows(db_session, run) + assert rows["B / use"].status == "queued" + assert rows["B / use"].steps[0]["run"] == "echo b forty" + await finish("B / use") + rows = await _rows(db_session, run) + assert rows["C / use"].status == "queued" + assert rows["C / use"].steps[0]["run"] == "echo c forty" + await finish("C / use") + after = (await _rows(db_session, run))["after"] + assert after.status == "queued" + assert after.steps[0]["run"] == "echo forty success" + + +def test_a_chained_calls_with_is_rendered_with_its_own_needs_on_callers(): + alias_a = {"jobs": {"build": "A / build"}, "outputs": {"o": "${{ jobs.build.outputs.o }}"}} + aliases = {"B": { + "jobs": {"use": "B / use"}, + "inputs": {"x": "${{ needs.A.outputs.o }}"}, + "outputs": {"out": "${{ inputs.x }}"}, + "needs_aliases": {"A": alias_a}, + }} + needs = { + "A / build": {"result": "success", "outputs": {"o": "forty"}}, + "B / use": {"result": "success", "outputs": {}}, + } + assert needs_alias_entries(aliases, needs)["B"]["outputs"] == {"out": "forty"} + + +@pytest.mark.asyncio +async def test_a_nested_calls_compound_with_reads_its_own_workflows_inputs( + monkeypatch, executable_workflow, db_session, test_user, # noqa: F811 +): + """Inside outer.yml, ``needs.inner.outputs`` renders inner's ``with:`` + against outer.yml's inputs, not the run's (``ver`` is in both).""" + called = { + "outer.yml": { + "on": {"workflow_call": {"inputs": {"ver": {"type": "string"}}}}, + "jobs": { + "inner": { + "uses": "./.github/workflows/inner.yml", + "with": {"tag": "${{ format('v{0}', inputs.ver) }}"}, + }, + "report": { + "needs": "inner", + "runs-on": ["self-hosted"], + "steps": [{"run": "echo ${{ needs.inner.outputs.tag }}"}], + }, + }, + }, + "inner.yml": { + "on": {"workflow_call": { + "inputs": {"tag": {"type": "string"}}, + "outputs": {"tag": {"value": "${{ inputs.tag }}"}}, + }}, + "jobs": {"leaf": {"runs-on": ["self-hosted"], "steps": [{"run": "echo ${{ inputs.tag }}"}]}}, + }, + } + caller = {"name": "caller", "jobs": { + "outer": {"uses": "./.github/workflows/outer.yml", "with": {"ver": "2"}}, + }} + + async def fake_detect(path, ref="HEAD"): + return [{"_path": f".github/workflows/{name}", **config} for name, config in called.items()] + + monkeypatch.setattr(workflow_service, "detect_workflows", fake_detect) + inputs = {"ver": "run"} + workflow_yaml = await workflow_service.materialize_reusable_workflows( + caller, "caller.git", "main", None, inputs=inputs, + ) + _repo, workflow, _ = executable_workflow + run = await create_workflow_run( + db_session, workflow, workflow_yaml, event="workflow_dispatch", + payload={"repository": {"full_name": "testuser/actions-exec-repo"}, "inputs": inputs}, + actor=test_user, head_sha="caller123", head_branch="main", + ) + await db_session.commit() + assert (await _rows(db_session, run))["outer / inner / leaf"].steps[0]["run"] == "echo v2" + report = await _promote_after(db_session, run, ["outer / inner / leaf"], "outer / report") + assert report.status == "queued" + assert report.steps[0]["run"] == "echo v2" + + +THREE_LEVELS = { + "outer.yml": { + "on": {"workflow_call": { + "inputs": {"ver": {"type": "string"}}, + "outputs": { + "tag": {"value": "${{ jobs.mid.outputs.tag }}"}, + "plain": {"value": "${{ jobs.mid.outputs.plain }}"}, + }, + }}, + "jobs": {"mid": { + "uses": "./.github/workflows/mid.yml", + "with": {"ver": "${{ format('{0}-mid', inputs.ver) }}"}, + }}, + }, + "mid.yml": { + "on": {"workflow_call": { + "inputs": {"ver": {"type": "string"}}, + "outputs": { + "tag": {"value": "${{ jobs.inner.outputs.tag }}"}, + "plain": {"value": "${{ jobs.inner.outputs.plain }}"}, + }, + }}, + "jobs": { + "inner": { + "uses": "./.github/workflows/inner.yml", + "with": {"tag": "${{ format('v{0}', inputs.ver) }}", "plain": "${{ inputs.ver }}"}, + }, + "show": {"runs-on": ["self-hosted"], "steps": [{"run": "echo ${{ inputs.ver }}"}]}, + "report": { + "needs": "inner", + "runs-on": ["self-hosted"], + "steps": [{"run": "echo ${{ needs.inner.outputs.tag }} ${{ needs.inner.outputs.plain }} ${{ inputs.ver }}"}], + }, + }, + }, + "inner.yml": { + "on": {"workflow_call": { + "inputs": {"tag": {"type": "string"}, "plain": {"type": "string"}}, + "outputs": { + "tag": {"value": "${{ inputs.tag }}"}, + "plain": {"value": "${{ inputs.plain }}"}, + }, + }}, + "jobs": {"leaf": { + "runs-on": ["self-hosted"], + "steps": [{"run": "echo ${{ inputs.tag }} ${{ inputs.plain }}"}], + }}, + }, +} + + +async def _three_level_run(monkeypatch, executable_workflow, db_session, test_user): # noqa: F811 + caller = {"name": "caller", "jobs": { + "outer": {"uses": "./.github/workflows/outer.yml", "with": {"ver": "2"}}, + "after": { + "needs": "outer", + "runs-on": ["self-hosted"], + "steps": [{"run": "echo ${{ needs.outer.outputs.tag }} ${{ needs.outer.outputs.plain }}"}], + }, + }} + + async def fake_detect(path, ref="HEAD"): + return [{"_path": f".github/workflows/{name}", **config} for name, config in THREE_LEVELS.items()] + + monkeypatch.setattr(workflow_service, "detect_workflows", fake_detect) + inputs = {"ver": "run"} + workflow_yaml = await workflow_service.materialize_reusable_workflows( + caller, "caller.git", "main", None, inputs=inputs, + ) + _repo, workflow, _ = executable_workflow + run = await create_workflow_run( + db_session, workflow, workflow_yaml, event="workflow_dispatch", + payload={"repository": {"full_name": "testuser/actions-exec-repo"}, "inputs": inputs}, + actor=test_user, head_sha="caller123", head_branch="main", + ) + await db_session.commit() + return run + + +@pytest.mark.asyncio +async def test_a_twice_nested_calls_compound_with_reads_each_levels_own_inputs( + monkeypatch, executable_workflow, db_session, test_user, # noqa: F811 +): + """run (ver=run) -> outer (ver=2) -> mid (ver=format('{0}-mid', inputs.ver)) + -> inner (tag=format('v{0}', inputs.ver), plain=inputs.ver). Each + ``with:`` reads the inputs of the workflow it is written in: mid's ver is + '2-mid', inner's tag 'v2-mid' and plain '2-mid', both for the called jobs + and for needs.inner in mid.""" + run = await _three_level_run(monkeypatch, executable_workflow, db_session, test_user) + rows = await _rows(db_session, run) + assert rows["outer / mid / show"].steps[0]["run"] == "echo 2-mid" + assert rows["outer / mid / inner / leaf"].steps[0]["run"] == "echo v2-mid 2-mid" + report = await _promote_after( + db_session, run, ["outer / mid / inner / leaf"], "outer / mid / report", + ) + assert report.status == "queued" + assert report.steps[0]["run"] == "echo v2-mid 2-mid 2-mid" + + +@pytest.mark.asyncio +async def test_an_output_forwarded_up_from_a_twice_nested_call( + monkeypatch, executable_workflow, db_session, test_user, # noqa: F811 +): + """inner's output, forwarded by mid and by outer, reaches the run's own + dependent with the value inner received.""" + run = await _three_level_run(monkeypatch, executable_workflow, db_session, test_user) + after = await _promote_after( + db_session, run, + ["outer / mid / inner / leaf", "outer / mid / show", "outer / mid / report"], + ) + assert after.status == "queued" + assert after.steps[0]["run"] == "echo v2-mid 2-mid" + + +def _chain(final_if): + return { + "name": "caller", + "jobs": { + "call": {"uses": "./.github/workflows/called.yml"}, + "middle": {"needs": ["call"], "runs-on": ["self-hosted"], "steps": [{"run": "echo"}]}, + "final": { + "needs": ["middle"], + "if": final_if, + "runs-on": ["self-hosted"], + "steps": [{"run": "echo"}], + }, + }, + } + + +async def _finish(db_session, run, conclusions): + rows = await _rows(db_session, run) + for key, conclusion in conclusions.items(): + rows[key].status = "completed" + rows[key].conclusion = conclusion + await db_session.commit() + await dispatch_ready_jobs(db_session, run.id) + await db_session.commit() + return await _rows(db_session, run) + + +@pytest.mark.asyncio +async def test_success_further_down_reads_the_calls_result_not_its_skipped_job( + monkeypatch, executable_workflow, db_session, test_user, # noqa: F811 +): + """call -> middle -> final (``if: success()``). ``success()`` answers for + every ancestor, and the ancestor here is the call, which succeeded: its + job skipped by its own ``if:`` does not count against it.""" + _repo, workflow, _ = executable_workflow + run = await _run( + monkeypatch, db_session, workflow, test_user, _chain("success()"), {"called.yml": OPTIONAL}, + ) + rows = await _finish(db_session, run, {"call / build": "success"}) + assert rows["middle"].status == "queued" + rows = await _finish(db_session, run, {"middle": "success"}) + assert rows["final"].status == "queued" + + +@pytest.mark.asyncio +async def test_success_further_down_inside_a_called_workflow_reads_the_nested_calls_result( + monkeypatch, executable_workflow, db_session, test_user, # noqa: F811 +): + """The same chain one level down, inside ``deploy``: ``deploy / final``'s + ancestor is the ``deploy / call`` call, not its skipped job.""" + chain = _chain("success()") + mid = {"on": {"workflow_call": {}}, "jobs": chain["jobs"]} + caller = {"name": "caller", "jobs": {"deploy": {"uses": "./.github/workflows/mid.yml"}}} + _repo, workflow, _ = executable_workflow + run = await _run( + monkeypatch, db_session, workflow, test_user, caller, + {"called.yml": OPTIONAL, "mid.yml": mid}, + ) + rows = await _finish(db_session, run, {"deploy / call / build": "success"}) + assert rows["deploy / call / optional"].conclusion == "skipped" + assert rows["deploy / middle"].status == "queued" + rows = await _finish(db_session, run, {"deploy / middle": "success"}) + assert rows["deploy / final"].status == "queued" + + +FAILING = { + "on": {"workflow_call": {}}, + "jobs": { + **OPTIONAL["jobs"], + "check": {"runs-on": ["self-hosted"], "steps": [{"run": "echo"}]}, + }, +} + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("final_if", "final_status", "final_conclusion"), [ + ("success()", "completed", "skipped"), + ("failure()", "queued", None), +]) +async def test_a_failed_job_in_the_call_is_seen_further_down( + monkeypatch, executable_workflow, db_session, test_user, # noqa: F811 + final_if, final_status, final_conclusion, +): + """A failed called job fails the call: middle (no ``if:``) is skipped, and + final sees the failed ancestor, as it would behind a plain failed job.""" + _repo, workflow, _ = executable_workflow + run = await _run( + monkeypatch, db_session, workflow, test_user, _chain(final_if), {"called.yml": FAILING}, + ) + rows = await _finish(db_session, run, {"call / build": "success", "call / check": "failure"}) + assert rows["middle"].conclusion == "skipped" + assert rows["final"].status == final_status + assert rows["final"].conclusion == final_conclusion diff --git a/tests/actions/test_reusable_unresolved.py b/tests/actions/test_reusable_unresolved.py new file mode 100644 index 00000000..713862df --- /dev/null +++ b/tests/actions/test_reusable_unresolved.py @@ -0,0 +1,156 @@ +"""A reusable-workflow call that cannot be inlined fails, with the reason. + +It used to become a job with no steps, which passed: a run whose whole +pipeline was one call to a repository the emulator did not hold looked green. +GitHub fails such a job without assigning a runner, so it is concluded here +when it would start, not queued for a runner that may never offer its labels. +""" + +import os +import subprocess +from datetime import datetime, timezone + +import pytest +from sqlalchemy import select + +from app.config import settings +from app.models.actions import WorkflowJob, WorkflowRun +from app.services import workflow_service +from app.services.workflow_scheduler import check_run_completion, dispatch_ready_jobs +from app.services.workflow_service import create_workflow_run +from tests.actions.test_execution import executable_workflow # noqa: F401 (fixture) + +MISSING = "elsewhere/tools/.github/workflows/dispatch.yml@main" + + +class _NoRepository: + def scalar_one_or_none(self): + return None + + +class _EmptyDB: + async def execute(self, _query): + return _NoRepository() + + +async def _materialize(jobs: dict, db=None) -> dict: + return (await workflow_service.materialize_reusable_workflows( + {"jobs": jobs}, "caller.git", "main", db or _EmptyDB(), + ))["jobs"] + + +def _assert_refused(job: dict, phrase: str): + [step] = job["steps"] + assert "uses" not in job + result = subprocess.run(["bash", "-c", step["run"]], capture_output=True, text=True) + assert result.returncode == 1 + assert "::error::" in result.stderr and phrase in result.stderr + + +@pytest.mark.asyncio +async def test_a_call_to_a_repository_not_on_the_emulator_fails(): + jobs = await _materialize({ + "dispatch": { + "uses": "elsewhere/tools/.github/workflows/dispatch.yml@main", + "with": {"x": "1"}, + }, + }) + job = jobs["dispatch"] + assert job["name"] == "dispatch (reusable workflow)" + _assert_refused(job, "elsewhere/tools/.github/workflows/dispatch.yml@main was not found") + assert "was not found on this emulator" in job["_refused"] + + +async def _rows(db_session, run): + return { + r.job_key: r for r in (await db_session.execute( + select(WorkflowJob).where(WorkflowJob.run_id == run.id) + )).scalars().all() + } + + +async def _start(db_session, workflow, test_user, jobs): + run = await create_workflow_run( + db_session, workflow, {"jobs": await _materialize(jobs)}, event="push", + payload={"repository": {"full_name": "testuser/actions-exec-repo"}}, + actor=test_user, head_sha="caller123", head_branch="main", + ) + await db_session.commit() + return run + + +def _assert_failed_without_a_runner(job): + assert (job.status, job.conclusion) == ("completed", "failure") + assert job.runner_id is None + assert [(s["name"], s["conclusion"]) for s in job.steps] == [ + ("Resolve reusable workflow", "failure"), + ] + with open(os.path.join(settings.DATA_DIR, "logs", "jobs", f"{job.id}.log")) as log: + assert "was not found on this emulator" in log.read() + + +@pytest.mark.asyncio +async def test_an_unresolved_call_fails_the_run_without_a_runner( + executable_workflow, db_session, test_user, # noqa: F811 +): + _repo, workflow, _ = executable_workflow + run = await _start(db_session, workflow, test_user, {"dispatch": {"uses": MISSING}}) + + rows = await _rows(db_session, run) + _assert_failed_without_a_runner(rows["dispatch"]) + run = (await db_session.execute(select(WorkflowRun).where(WorkflowRun.id == run.id))).scalar_one() + assert (run.status, run.conclusion) == ("completed", "failure") + + +@pytest.mark.asyncio +async def test_an_unresolved_call_with_needs_fails_when_its_needs_finish( + executable_workflow, db_session, test_user, # noqa: F811 +): + _repo, workflow, _ = executable_workflow + run = await _start(db_session, workflow, test_user, { + "build": {"runs-on": ["self-hosted"], "steps": [{"run": "echo"}]}, + "dispatch": {"needs": ["build"], "uses": MISSING}, + }) + rows = await _rows(db_session, run) + assert rows["dispatch"].status == "waiting" + + rows["build"].status = "completed" + rows["build"].conclusion = "success" + rows["build"].completed_at = datetime.now(timezone.utc) + await db_session.commit() + await dispatch_ready_jobs(db_session, run.id) + await check_run_completion(db_session, run.id) + await db_session.commit() + + rows = await _rows(db_session, run) + _assert_failed_without_a_runner(rows["dispatch"]) + run = (await db_session.execute(select(WorkflowRun).where(WorkflowRun.id == run.id))).scalar_one() + assert (run.status, run.conclusion) == ("completed", "failure") + + +@pytest.mark.asyncio +async def test_a_call_that_loops_back_to_itself_fails(monkeypatch): + loop = "org/repo/.github/workflows/loop.yml@main" + + async def fake_detect(path, ref="HEAD"): + return [{"_path": ".github/workflows/loop.yml", "jobs": {"again": {"uses": loop}}}] + + class Repository: + disk_path = "repo.git" + full_name = "org/repo" + + class Found: + def scalar_one_or_none(self): + return Repository() + + class DB: + async def execute(self, _query): + return Found() + + async def fake_sha(path, ref): + return "0" * 40 + + monkeypatch.setattr(workflow_service, "detect_workflows", fake_detect) + monkeypatch.setattr(workflow_service, "_resolve_ref_sha", fake_sha) + jobs = await _materialize({"start": {"uses": loop}}, DB()) + _assert_refused(jobs["start / again"], "call themselves") diff --git a/tests/actions/test_skipped_reusable_caller.py b/tests/actions/test_skipped_reusable_caller.py new file mode 100644 index 00000000..d14bbf65 --- /dev/null +++ b/tests/actions/test_skipped_reusable_caller.py @@ -0,0 +1,311 @@ +"""A skipped caller of a reusable workflow, and runs whose jobs all skipped. + +On GitHub a job that calls a reusable workflow (``uses: ./.github/workflows/ +x.yml``) and is skipped by its own ``if:`` is never expanded: the run lists +one job, named after the caller job, concluded ``skipped``. A run whose jobs +were all skipped concludes ``skipped``, not ``success``. + +The emulator inlined the called jobs, ANDed the caller's condition into each +of them and skipped them one by one, so the Jobs API listed every called job +(``dispatch / route``, ``Triage``, ``Harness run (${{ matrix.agent }})``...) +as skipped, and the run concluded ``success``. Fullsend's behaviour tests +skip runs that concluded ``skipped`` and read a ``success`` run with a +skipped "Harness run" job as a failed dispatch. +""" + +from datetime import datetime, timezone + +import pytest +from sqlalchemy import select + +from app.models.actions import WorkflowJob, WorkflowRun +from app.services import workflow_service +from app.services.workflow_scheduler import check_run_completion, dispatch_ready_jobs +from app.services.workflow_service import create_workflow_run +from tests.actions.test_execution import executable_workflow # noqa: F401 (fixture) + +GO = "github.event_name == 'issues' && github.event.label.name == 'go'" + + +def _harness(need): + return { + "name": "Harness run (${{ matrix.agent }})", + "needs": [need], + "if": f"${{{{ !cancelled() && needs.{need}.outputs.matrix != '' }}}}", + "strategy": {"matrix": f"${{{{ fromJSON(needs.{need}.outputs.matrix || '{{\"include\":[]}}') }}}}"}, + "runs-on": ["self-hosted"], + "steps": [{"run": "echo ${{ matrix.agent }}"}], + } + + +def _stage(name): + return { + "name": name, + "needs": ["route"], + "if": "needs.route.outputs.stage == '" + name.lower() + "'", + "runs-on": ["self-hosted"], + "outputs": {"matrix": "${{ steps.m.outputs.matrix }}"}, + "steps": [{"id": "m", "run": "echo"}], + } + + +CALLED = { + "on": {"workflow_call": {}}, + "jobs": { + "route": { + "runs-on": ["self-hosted"], + "outputs": {"stage": "${{ steps.r.outputs.stage }}"}, + "steps": [{"id": "r", "run": "echo"}], + }, + "triage": _stage("Triage"), + "code": _stage("Code"), + "harness-run-triage": _harness("triage"), + "harness-run-code": _harness("code"), + }, +} + + +def _caller(**extra): + return { + "name": "fullsend", + "jobs": { + "dispatch": { + "if": GO, + "uses": "./.github/workflows/reusable-dispatch.yml", + **extra, + }, + }, + } + + +async def _materialize(monkeypatch, caller): + async def fake_detect(path, ref="HEAD"): + return [{"_path": ".github/workflows/reusable-dispatch.yml", **CALLED}] + + monkeypatch.setattr(workflow_service, "detect_workflows", fake_detect) + return await workflow_service.materialize_reusable_workflows( + caller, "caller.git", "main", None, + ) + + +async def _run(db_session, workflow, test_user, workflow_yaml, payload, event="issues"): + run = await create_workflow_run( + db_session, workflow, workflow_yaml, event=event, + payload={"repository": {"full_name": "testuser/actions-exec-repo"}, **payload}, + actor=test_user, head_sha="caller123", head_branch="main", + ) + await db_session.commit() + return run + + +async def _rows(db_session, run): + return (await db_session.execute( + select(WorkflowJob).where(WorkflowJob.run_id == run.id).order_by(WorkflowJob.id) + )).scalars().all() + + +async def _reload(db_session, run): + return (await db_session.execute( + select(WorkflowRun).where(WorkflowRun.id == run.id) + )).scalar_one() + + +@pytest.mark.asyncio +async def test_a_skipped_caller_is_one_skipped_job_and_the_run_is_skipped( + monkeypatch, executable_workflow, db_session, test_user, # noqa: F811 +): + _repo, workflow, _ = executable_workflow + workflow_yaml = await _materialize(monkeypatch, _caller()) + run = await _run(db_session, workflow, test_user, workflow_yaml, {"action": "opened"}) + + rows = await _rows(db_session, run) + assert [(r.name, r.job_key, r.status, r.conclusion) for r in rows] == [ + ("dispatch", "dispatch", "completed", "skipped"), + ] + run = await _reload(db_session, run) + assert (run.status, run.conclusion) == ("completed", "skipped") + + +@pytest.mark.asyncio +async def test_a_skipped_caller_is_listed_under_its_name( + monkeypatch, executable_workflow, db_session, test_user, # noqa: F811 +): + _repo, workflow, _ = executable_workflow + workflow_yaml = await _materialize(monkeypatch, _caller(name="Dispatch")) + run = await _run(db_session, workflow, test_user, workflow_yaml, {"action": "opened"}) + + assert [r.name for r in await _rows(db_session, run)] == ["Dispatch"] + + +@pytest.mark.asyncio +async def test_a_job_that_needs_a_skipped_caller_is_skipped( + monkeypatch, executable_workflow, db_session, test_user, # noqa: F811 +): + _repo, workflow, _ = executable_workflow + caller = _caller() + caller["jobs"]["report"] = { + "needs": ["dispatch"], "runs-on": ["self-hosted"], "steps": [{"run": "echo"}], + } + workflow_yaml = await _materialize(monkeypatch, caller) + run = await _run(db_session, workflow, test_user, workflow_yaml, {"action": "opened"}) + + rows = await _rows(db_session, run) + assert [(r.job_key, r.conclusion) for r in rows] == [ + ("dispatch", "skipped"), ("report", "skipped"), + ] + assert (await _reload(db_session, run)).conclusion == "skipped" + + +@pytest.mark.asyncio +async def test_a_job_that_always_runs_after_a_skipped_caller_reads_its_result_as_skipped( + monkeypatch, executable_workflow, db_session, test_user, # noqa: F811 +): + _repo, workflow, _ = executable_workflow + caller = _caller() + caller["jobs"]["report"] = { + "needs": ["dispatch"], + "if": "${{ always() }}", + "runs-on": ["self-hosted"], + "steps": [{"run": "echo ${{ needs.dispatch.result }}"}], + } + workflow_yaml = await _materialize(monkeypatch, caller) + run = await _run(db_session, workflow, test_user, workflow_yaml, {"action": "opened"}) + + rows = {r.job_key: r for r in await _rows(db_session, run)} + assert sorted(rows) == ["dispatch", "report"] + assert rows["report"].needs == ["dispatch"] + assert rows["report"].status == "queued" + assert rows["report"].steps[0]["run"] == "echo skipped" + + +@pytest.mark.asyncio +async def test_a_caller_that_runs_keeps_the_called_job_names( + monkeypatch, executable_workflow, db_session, test_user, # noqa: F811 +): + _repo, workflow, _ = executable_workflow + workflow_yaml = await _materialize(monkeypatch, _caller()) + run = await _run( + db_session, workflow, test_user, workflow_yaml, + {"action": "labeled", "label": {"name": "go"}}, + ) + + rows = await _rows(db_session, run) + assert [r.name for r in rows] == [ + "dispatch / route", "Triage", "Code", + "Harness run (${{ matrix.agent }})", "Harness run (${{ matrix.agent }})", + ] + assert rows[0].status == "queued" + assert all(r.status == "waiting" for r in rows[1:]) + run = await _reload(db_session, run) + assert run.conclusion is None + + +async def _finish(db_session, job, conclusion): + job.status = "completed" + job.conclusion = conclusion + job.completed_at = datetime.now(timezone.utc) + await db_session.commit() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("ran, expected", [("success", "success"), ("failure", "failure")]) +async def test_a_run_with_some_skipped_jobs_keeps_its_conclusion( + executable_workflow, db_session, test_user, ran, expected, # noqa: F811 +): + _repo, workflow, _ = executable_workflow + run = await _run(db_session, workflow, test_user, {"jobs": { + "build": {"runs-on": ["self-hosted"], "steps": [{"run": "echo"}]}, + "deploy": {"if": "false", "runs-on": ["self-hosted"], "steps": [{"run": "echo"}]}, + }}, {"ref": "refs/heads/main"}, event="push") + rows = await _rows(db_session, run) + assert [r.conclusion for r in rows] == [None, "skipped"] + + await _finish(db_session, rows[0], ran) + await dispatch_ready_jobs(db_session, run.id) + await check_run_completion(db_session, run.id) + await db_session.commit() + assert (await _reload(db_session, run)).conclusion == expected + + +@pytest.mark.asyncio +async def test_a_run_whose_jobs_all_skipped_is_skipped( + executable_workflow, db_session, test_user, # noqa: F811 +): + _repo, workflow, _ = executable_workflow + run = await _run(db_session, workflow, test_user, {"jobs": { + "build": {"if": "false", "runs-on": ["self-hosted"], "steps": [{"run": "echo"}]}, + "test": {"needs": ["build"], "runs-on": ["self-hosted"], "steps": [{"run": "echo"}]}, + }}, {"ref": "refs/heads/main"}, event="push") + + rows = await _rows(db_session, run) + assert [r.conclusion for r in rows] == ["skipped", "skipped"] + run = await _reload(db_session, run) + assert (run.status, run.conclusion) == ("completed", "skipped") + + +SKIPPED_CALL = { + "on": {"workflow_call": {}}, + "jobs": {"work": {"runs-on": ["self-hosted"], "steps": [{"run": "echo"}]}}, +} + +FORWARD_CALL = { + "on": {"workflow_call": { + "inputs": {"r": {"type": "string"}}, + "outputs": {"o": {"value": "${{ inputs.r }}"}}, + }}, + "jobs": {"forward": {"runs-on": ["self-hosted"], "steps": [{"run": "echo"}]}}, +} + + +@pytest.mark.asyncio +async def test_a_job_behind_two_callers_reads_a_skipped_callers_result_through_the_second( + monkeypatch, executable_workflow, db_session, test_user, # noqa: F811 +): + """``a`` is skipped, so ``b``'s ``needs.a.result`` is ``skipped``, and + ``c`` reads it back through ``needs.b.outputs.o``. ``c``'s copy of ``b``'s + alias holds one for ``a`` built from called jobs that were never created; + it must not replace ``a``'s own skipped row in ``needs``.""" + _repo, workflow, _ = executable_workflow + + async def fake_detect(path, ref="HEAD"): + return [ + {"_path": ".github/workflows/a.yml", **SKIPPED_CALL}, + {"_path": ".github/workflows/b.yml", **FORWARD_CALL}, + ] + + monkeypatch.setattr(workflow_service, "detect_workflows", fake_detect) + workflow_yaml = await workflow_service.materialize_reusable_workflows({ + "name": "chain", + "jobs": { + "a": {"if": "false", "uses": "./.github/workflows/a.yml"}, + "b": { + "needs": "a", + "if": "${{ always() }}", + "uses": "./.github/workflows/b.yml", + "with": {"r": "${{ needs.a.result }}"}, + }, + "c": { + "needs": "b", + "runs-on": ["self-hosted"], + "steps": [{"run": "echo ${{ needs.b.outputs.o }}"}], + }, + }, + }, "caller.git", "main", None) + run = await _run( + db_session, workflow, test_user, workflow_yaml, + {"ref": "refs/heads/main"}, event="push", + ) + + await dispatch_ready_jobs(db_session, run.id) + await db_session.commit() + rows = {r.job_key: r for r in await _rows(db_session, run)} + assert sorted(rows) == ["a", "b / forward", "c"] + assert rows["a"].conclusion == "skipped" + assert rows["b / forward"].status == "queued" + + await _finish(db_session, rows["b / forward"], "success") + await dispatch_ready_jobs(db_session, run.id) + await db_session.commit() + rows = {r.job_key: r for r in await _rows(db_session, run)} + assert rows["c"].status == "queued" + assert rows["c"].steps[0]["run"] == "echo skipped"