From a946886fad02865c1beb67946622117e851c1563 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Wed, 18 Nov 2026 16:16:12 -0500 Subject: [PATCH 01/14] Fail container jobs and unresolved reusable calls instead of passing Neither runner starts job or service containers, so a job with container: or services: ran its steps on the runner host and passed or failed for reasons unrelated to the workflow. Replace its steps with one that fails with an ::error:: naming the unsupported keys, as docker:// actions already are. A reusable-workflow call to a repository the emulator does not hold, or one that nests too deep or calls itself, became a placeholder job with no steps, and a job with no steps passed. Give the placeholder one step that fails with an ::error:: saying why, and for a missing repository, that the repository has to be pushed here first. Assisted-by: Claude Signed-off-by: Wayne Sun --- src/app/services/workflow_service.py | 58 ++++++++++++++--- tests/actions/test_container_jobs.py | 46 +++++++++++++ tests/actions/test_reusable_unresolved.py | 79 +++++++++++++++++++++++ 3 files changed, 173 insertions(+), 10 deletions(-) create mode 100644 tests/actions/test_container_jobs.py create mode 100644 tests/actions/test_reusable_unresolved.py diff --git a/src/app/services/workflow_service.py b/src/app/services/workflow_service.py index 2bdc4e1b..2709c1ae 100644 --- a/src/app/services/workflow_service.py +++ b/src/app/services/workflow_service.py @@ -227,6 +227,28 @@ 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)") + return placeholder + + 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 +278,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, @@ -572,22 +605,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( 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_reusable_unresolved.py b/tests/actions/test_reusable_unresolved.py new file mode 100644 index 00000000..e35b7131 --- /dev/null +++ b/tests/actions/test_reusable_unresolved.py @@ -0,0 +1,79 @@ +"""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. +""" + +import subprocess + +import pytest + +from app.services import workflow_service + + +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") + # It is a job of its own that a runner picks up, not one waiting forever. + [labels] = [j["runs_on"] for j in workflow_service.build_job_graph({"jobs": jobs})] + assert labels == ["ubuntu-latest"] + + +@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") From b012198a7311e321827413114cad1e76513e1459 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Wed, 18 Nov 2026 16:16:12 -0500 Subject: [PATCH 02/14] Treat a reusable-workflow caller as one job when skipped or needed On GitHub a caller skipped by its if: is one skipped job, and a run whose jobs were all skipped concludes skipped. The emulator expanded the called jobs, listed each as skipped, and concluded the run success. A caller without needs: now has its if: evaluated once at run creation; when false, the run gets one skipped job under the caller's key. A job with needs: waited for a job that never existed, since the caller is inlined as its called jobs, and needs..outputs had nothing to read. A need on a caller now becomes a need on every job the call inlined, and at promotion needs. is built from them: the worst of their results, and the callee's on.workflow_call.outputs evaluated with a jobs context of the called jobs. Nested calls re-prefix those keys at each level. Assisted-by: Claude Signed-off-by: Wayne Sun --- ...e-workflow-caller-lists-the-called-jobs.md | 50 ++++ src/app/services/workflow_scheduler.py | 11 +- src/app/services/workflow_service.py | 136 ++++++++++- tests/actions/test_execution.py | 3 +- tests/actions/test_reusable_caller_needs.py | 109 +++++++++ tests/actions/test_skipped_reusable_caller.py | 221 ++++++++++++++++++ 6 files changed, 524 insertions(+), 6 deletions(-) create mode 100644 docs/bugs/fixed/skipped-reusable-workflow-caller-lists-the-called-jobs.md create mode 100644 tests/actions/test_reusable_caller_needs.py create mode 100644 tests/actions/test_skipped_reusable_caller.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..110c80ff --- /dev/null +++ b/docs/bugs/fixed/skipped-reusable-workflow-caller-lists-the-called-jobs.md @@ -0,0 +1,50 @@ +# 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. +- `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/src/app/services/workflow_scheduler.py b/src/app/services/workflow_scheduler.py index 4c39968d..b4186d92 100644 --- a/src/app/services/workflow_scheduler.py +++ b/src/app/services/workflow_scheduler.py @@ -45,6 +45,7 @@ async def dispatch_ready_jobs(db: AsyncSession, run_id: int) -> list[WorkflowJob build_needs_context, build_run_expression_context, build_steps_data, + needs_alias_entries, render_job_labels, strategy_context, ) @@ -123,7 +124,12 @@ async def dispatch_ready_jobs(db: AsyncSession, run_id: int) -> list[WorkflowJob github_ctx = base_context.get("github") or {} context = { **base_context, - "needs": needs_context, + # 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), + }, JOB_NEEDS_KEY: _ancestors(job, all_jobs), RUN_CANCELLED_KEY: bool(base_context.get(RUN_CANCELLED_KEY)), "matrix": pending.get("matrix") or {}, @@ -327,6 +333,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 2709c1ae..a740c66e 100644 --- a/src/app/services/workflow_service.py +++ b/src/app/services/workflow_service.py @@ -315,6 +315,8 @@ def build_job_graph(workflow_yaml: dict) -> list[dict]: "_workflow_repository": config.get("_workflow_repository", ""), "_workflow_sha": config.get("_workflow_sha", ""), "_workflow_ref": config.get("_workflow_ref", ""), + "_caller": config.get("_caller"), + "_needs_aliases": config.get("_needs_aliases") or {}, "timeout_minutes": config.get("timeout-minutes", 360), }) @@ -494,6 +496,43 @@ 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) -> 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 a ``jobs`` + context holding the called jobs by their own keys. + """ + entries = {} + for caller, alias in (aliases or {}).items(): + jobs_context = { + inner: needs_context.get(outer) or {"outputs": {}, "result": ""} + for inner, outer in alias.get("jobs", {}).items() + } + result = "" + for entry in jobs_context.values(): + result = _combined_result(result, entry.get("result") or "") + outputs = { + name: str(render_expressions(expression, {"jobs": jobs_context}) or "") + for name, expression in (alias.get("outputs") or {}).items() + } + entries[caller] = {"result": result, "outputs": outputs} + return entries + + 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 {} @@ -598,6 +637,9 @@ 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, and its ``on.workflow_call.outputs``. + callers: dict[str, dict] = {} 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) @@ -672,9 +714,20 @@ async def _materialize_reusable_jobs( called_jobs = materialized.get("jobs", {}) called_keys = set(called_jobs) prefix = f"{key} / " + callers[key] = { + "jobs": {called_key: f"{prefix}{called_key}" for called_key in called_jobs}, + "outputs": _declared_call_outputs(called), + } 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. + for alias in (child.get("_needs_aliases") or {}).values(): + alias["jobs"] = { + inner: f"{prefix}{outer}" if outer in called_keys else outer + for inner, outer in alias["jobs"].items() + } caller_condition = config.get("if") child_condition = child.get("if") if caller_condition is not None: @@ -708,13 +761,43 @@ 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). + 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()) + job.setdefault("_needs_aliases", {})[need] = copy.deepcopy(callers[need]) + else: + remapped.append(need) + job["needs"] = list(dict.fromkeys(remapped)) + result["jobs"] = expanded return result @@ -1211,8 +1294,52 @@ async def create_workflow_run( job_list = build_job_graph(workflow_yaml) skipped_job_created = False + # 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. + for alias_caller, alias in (job_def.get("_needs_aliases") or {}).items(): + if caller_runs.get(alias_caller) is False: + called = set(alias.get("jobs", {}).values()) + kept = [need for need in job_def.get("needs", []) if need not in called] + job_def["needs"] = [*kept, alias_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 @@ -1265,6 +1392,7 @@ async def create_workflow_run( "_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 dynamic_matrix is not None: # Expanded at promotion, once needs.*.outputs exist. The 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_reusable_caller_needs.py b/tests/actions/test_reusable_caller_needs.py new file mode 100644 index 00000000..8bbb9ea9 --- /dev/null +++ b/tests/actions/test_reusable_caller_needs.py @@ -0,0 +1,109 @@ +"""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" diff --git a/tests/actions/test_skipped_reusable_caller.py b/tests/actions/test_skipped_reusable_caller.py new file mode 100644 index 00000000..fb335fe0 --- /dev/null +++ b/tests/actions/test_skipped_reusable_caller.py @@ -0,0 +1,221 @@ +"""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_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") From be1ab759ba726975a9eac285a68ee30d9f4fb4e1 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Wed, 18 Nov 2026 16:16:12 -0500 Subject: [PATCH 03/14] Resolve uses: actions against repositories on the emulator first Every `uses: owner/repo@ref` was resolved and fetched upstream, so an action pushed to a repository here failed with "does not exist upstream". Resolve against a repository here first and serve its archive from `git archive` (one top-level directory, as GitHub's), cached apart from upstream archives. As on GitHub, a job may use an action from a public repository, from its own repository, or from a private one with the same owner (GitHub also needs that owner to allow it; the emulator has no such setting). A repository here that the job may not use is unresolvable, and is not looked up upstream under the same name; the archive route applies the same rule. GHES goes to github.com only for a repository it lacks. The emulator also goes upstream when the repository is here but lacks the ref, so a partial local copy of a public action still works. Assisted-by: Claude Signed-off-by: Wayne Sun --- src/app/api/actions_distributed_task.py | 88 ++++++++-- src/app/services/action_download_service.py | 60 +++++++ tests/actions/test_emulator_hosted_actions.py | 165 ++++++++++++++++++ 3 files changed, 300 insertions(+), 13 deletions(-) create mode 100644 tests/actions/test_emulator_hosted_actions.py diff --git a/src/app/api/actions_distributed_task.py b/src/app/api/actions_distributed_task.py index 51ca7733..e2544d2d 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,28 @@ 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 the repository is here + # but lacks the ref, so a partial local copy of a public action works. + 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: + 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 +1978,61 @@ 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 on GitHub, a workflow may use an action from a public repository, from + its own repository, or from a private one with the same owner (GitHub + also requires that owner to allow it; this emulator has no such setting). + """ + 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 not repository.private and (repository.visibility or "public") == "public": + 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 + or _owner_login(job_repository) == _owner_login(repository) + ): + return True, repository + return True, None + + +def _owner_login(repository: Repository) -> str: + return repository.full_name.split("/", 1)[0].lower() + + @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.""" + 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) + 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/tests/actions/test_emulator_hosted_actions.py b/tests/actions/test_emulator_hosted_actions.py new file mode 100644 index 00000000..8db4c246 --- /dev/null +++ b/tests/actions/test_emulator_hosted_actions.py @@ -0,0 +1,165 @@ +"""`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 the repository is here but +lacks the ref. Before, every reference was resolved upstream, so an action in +a repository here failed with "does not exist upstream". + +As on GitHub, a job may use an action from a public repository, its own +repository, or a private repository with the same owner. Another owner's +private repository 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_served( + client, uses_workflow, test_token, monkeypatch # noqa: F811 +): + await _private_repository(client, test_token, "own-private-action") + _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/own-private-action", "main") + assert resp.status_code == 200, resp.text + sha = resp.json()["actions"]["testuser/own-private-action@main"]["resolvedSha"] + + archive = await _archive(client, token, "testuser/own-private-action", sha) + assert archive.status_code == 200, archive.text From a3ee9d81dec93d1afd84805a01d61a1f20d2af08 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Wed, 18 Nov 2026 16:16:12 -0500 Subject: [PATCH 04/14] List a run's jobs once queued, not while they wait on needs Probed side by side: while job a ran, GitHub's GET .../runs/{id}/jobs listed only a (total_count 1); b and c, which need a, appeared once they were queued. The emulator listed them as "waiting", the status GitHub uses for a job held for an environment approval, so a stage that had not started looked like part of the run. Assisted-by: Claude Signed-off-by: Wayne Sun --- src/app/api/actions.py | 7 +++- tests/actions/test_jobs_list_unstarted.py | 42 +++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 tests/actions/test_jobs_list_unstarted.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/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"] From c2e81dcb826591ed9ced279d6e75c7b761ab368a Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Wed, 18 Nov 2026 16:16:13 -0500 Subject: [PATCH 05/14] docs: bug ledger entries for these fixes One docs/bugs/fixed entry per fix, listed under Fixed Bugs in PLAN.md. Assisted-by: Claude Signed-off-by: Wayne Sun --- PLAN.md | 6 +++ ...lator-repositories-are-fetched-upstream.md | 34 +++++++++++++++++ ...ainer-and-services-jobs-run-on-the-host.md | 28 ++++++++++++++ ...-reusable-workflow-caller-waits-forever.md | 37 +++++++++++++++++++ .../jobs-list-shows-jobs-waiting-on-needs.md | 22 +++++++++++ ...e-workflow-caller-lists-the-called-jobs.md | 3 +- ...nresolved-reusable-workflow-call-passes.md | 37 +++++++++++++++++++ 7 files changed, 166 insertions(+), 1 deletion(-) create mode 100644 docs/bugs/fixed/actions-in-emulator-repositories-are-fetched-upstream.md create mode 100644 docs/bugs/fixed/container-and-services-jobs-run-on-the-host.md create mode 100644 docs/bugs/fixed/job-needing-a-reusable-workflow-caller-waits-forever.md create mode 100644 docs/bugs/fixed/jobs-list-shows-jobs-waiting-on-needs.md create mode 100644 docs/bugs/fixed/unresolved-reusable-workflow-call-passes.md 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..7c0b33df --- /dev/null +++ b/docs/bugs/fixed/actions-in-emulator-repositories-are-fetched-upstream.md @@ -0,0 +1,34 @@ +# 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 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. +- As on GitHub, a job may use a repository here as an action only when it is + public, is the job's own repository, or is private with the same owner as + the job's repository. GitHub also requires that owner to allow access to + its private actions; the emulator has no such setting. Another owner's + private repository 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..69616e35 --- /dev/null +++ b/docs/bugs/fixed/job-needing-a-reusable-workflow-caller-waits-forever.md @@ -0,0 +1,37 @@ +# 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. +- Nested calls re-prefix those keys at each level. +- 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. + +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 index 110c80ff..1fd13cc2 100644 --- 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 @@ -35,7 +35,8 @@ because no row carried that key, so it stayed waiting. - `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. + 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. 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`. From 95ee88a762dfce8f99aaddd89e3bfd6769bfc41e Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Wed, 18 Nov 2026 16:16:13 -0500 Subject: [PATCH 06/14] Fail an unresolvable reusable call without a runner; keep a skipped caller's result An unresolvable reusable-workflow call's failing placeholder defaulted to runs-on ubuntu-latest, so on a stack whose runners do not offer that label it stayed queued and the run never finished. GitHub fails such a run without a runner. The placeholder is now concluded failure by the emulator itself: at run creation when it has no needs, or when its needs finish and its if: holds. The reason goes to its step and its log. A job that needs a skipped caller read needs..result as "": the alias built from the never-created called jobs replaced the skipped row's result. A redirected need now drops that alias. Only top-level callers are redirected to their skipped row. A nested caller with the same key as a skipped top-level caller was redirected too, and its dependent was skipped instead of waiting for it. Assisted-by: Claude Signed-off-by: Wayne Sun --- src/app/services/workflow_scheduler.py | 11 ++- src/app/services/workflow_service.py | 76 +++++++++++++++-- tests/actions/test_reusable_caller_needs.py | 68 +++++++++++++++ tests/actions/test_reusable_unresolved.py | 83 ++++++++++++++++++- tests/actions/test_skipped_reusable_caller.py | 22 +++++ 5 files changed, 246 insertions(+), 14 deletions(-) diff --git a/src/app/services/workflow_scheduler.py b/src/app/services/workflow_scheduler.py index b4186d92..f194cb69 100644 --- a/src/app/services/workflow_scheduler.py +++ b/src/app/services/workflow_scheduler.py @@ -45,6 +45,7 @@ async def dispatch_ready_jobs(db: AsyncSession, run_id: int) -> list[WorkflowJob build_needs_context, build_run_expression_context, build_steps_data, + fail_refused_job, needs_alias_entries, render_job_labels, strategy_context, @@ -163,6 +164,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) @@ -193,8 +200,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)) diff --git a/src/app/services/workflow_service.py b/src/app/services/workflow_service.py index a740c66e..2097b67e 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 @@ -246,9 +247,33 @@ def _reusable_placeholder(key: str, config: dict, why: str) -> dict: } 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", {}) @@ -316,7 +341,9 @@ def build_job_graph(workflow_yaml: dict) -> list[dict]: "_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), }) @@ -793,7 +820,17 @@ async def _materialize_reusable_jobs( for need in needs: if need in callers: remapped.extend(callers[need]["jobs"].values()) - job.setdefault("_needs_aliases", {})[need] = copy.deepcopy(callers[need]) + # 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)) @@ -1294,18 +1331,30 @@ 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. - for alias_caller, alias in (job_def.get("_needs_aliases") or {}).items(): - if caller_runs.get(alias_caller) is False: - called = set(alias.get("jobs", {}).values()) - kept = [need for need in job_def.get("needs", []) if need not in called] - job_def["needs"] = [*kept, alias_caller] + # 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. @@ -1394,6 +1443,9 @@ async def create_workflow_run( "_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 @@ -1471,10 +1523,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_reusable_caller_needs.py b/tests/actions/test_reusable_caller_needs.py index 8bbb9ea9..1c2b2cc0 100644 --- a/tests/actions/test_reusable_caller_needs.py +++ b/tests/actions/test_reusable_caller_needs.py @@ -107,3 +107,71 @@ def test_the_call_result_is_the_worst_of_its_jobs(): "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" diff --git a/tests/actions/test_reusable_unresolved.py b/tests/actions/test_reusable_unresolved.py index e35b7131..713862df 100644 --- a/tests/actions/test_reusable_unresolved.py +++ b/tests/actions/test_reusable_unresolved.py @@ -2,13 +2,25 @@ 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: @@ -46,9 +58,74 @@ async def test_a_call_to_a_repository_not_on_the_emulator_fails(): job = jobs["dispatch"] assert job["name"] == "dispatch (reusable workflow)" _assert_refused(job, "elsewhere/tools/.github/workflows/dispatch.yml@main was not found") - # It is a job of its own that a runner picks up, not one waiting forever. - [labels] = [j["runs_on"] for j in workflow_service.build_job_graph({"jobs": jobs})] - assert labels == ["ubuntu-latest"] + 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 diff --git a/tests/actions/test_skipped_reusable_caller.py b/tests/actions/test_skipped_reusable_caller.py index fb335fe0..0f9c2777 100644 --- a/tests/actions/test_skipped_reusable_caller.py +++ b/tests/actions/test_skipped_reusable_caller.py @@ -156,6 +156,28 @@ async def test_a_job_that_needs_a_skipped_caller_is_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 From eae3332043b79d987f8581073b1095f89de61964 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Wed, 18 Nov 2026 18:21:44 -0500 Subject: [PATCH 07/14] Don't fall back upstream for a private action held here A private or internal repository on the emulator that a job may use, but that lacks the requested ref or commit, was resolved and fetched from github.com under the same name. That is code from an unrelated repository. It is now unresolvable (download info) and a 404 (archive). The upstream fallback for a missing ref stays for public repositories. Assisted-by: Claude Signed-off-by: Wayne Sun --- ...lator-repositories-are-fetched-upstream.md | 11 ++++-- src/app/api/actions_distributed_task.py | 22 +++++++++-- tests/actions/test_emulator_hosted_actions.py | 38 ++++++++++++++++++- 3 files changed, 62 insertions(+), 9 deletions(-) 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 index 7c0b33df..ffb39cb9 100644 --- a/docs/bugs/fixed/actions-in-emulator-repositories-are-fetched-upstream.md +++ b/docs/bugs/fixed/actions-in-emulator-repositories-are-fetched-upstream.md @@ -14,9 +14,14 @@ repository it lacks. A test stack that pushes its own actions needs the same. - `actionsdownloadinfo` resolves `owner/repo@ref` against a repository on the emulator first. A name the emulator does not hold goes upstream. -- Unlike GHES, a 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. +- 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. - As on GitHub, a job may use a repository here as an action only when it is public, is the job's own repository, or is private with the same owner as the job's repository. GitHub also requires that owner to allow access to diff --git a/src/app/api/actions_distributed_task.py b/src/app/api/actions_distributed_task.py index e2544d2d..9609b9d9 100644 --- a/src/app/api/actions_distributed_task.py +++ b/src/app/api/actions_distributed_task.py @@ -1946,8 +1946,10 @@ async def dt_resolve_action_download_info( ) # 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 the repository is here - # but lacks the ref, so a partial local copy of a public action works. + # 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 @@ -1957,6 +1959,11 @@ async def dt_resolve_action_download_info( 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) @@ -1995,7 +2002,7 @@ async def _local_action_repository( )).scalars().first() if repository is None or not repository.disk_path: return False, None - if not repository.private and (repository.visibility or "public") == "public": + if _is_public(repository): return True, repository job_repository = (await db.execute( select(Repository) @@ -2010,6 +2017,10 @@ async def _local_action_repository( return True, None +def _is_public(repository: Repository) -> bool: + return not repository.private and (repository.visibility or "public") == "public" + + def _owner_login(repository: Repository) -> str: return repository.full_name.split("/", 1)[0].lower() @@ -2020,7 +2031,8 @@ async def dt_action_archive( owner: str, repo: str, sha: str, fmt: str, request: Request, db: DbSession, ): """Serve an action archive: built from a repository here when it holds the - commit, else fetched from upstream once per SHA.""" + 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) @@ -2031,6 +2043,8 @@ async def dt_action_archive( try: 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: diff --git a/tests/actions/test_emulator_hosted_actions.py b/tests/actions/test_emulator_hosted_actions.py index 8db4c246..1ddfd82e 100644 --- a/tests/actions/test_emulator_hosted_actions.py +++ b/tests/actions/test_emulator_hosted_actions.py @@ -2,8 +2,9 @@ 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 the repository is here but -lacks the ref. Before, every reference was resolved upstream, so an action in +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". As on GitHub, a job may use an action from a public repository, its own @@ -163,3 +164,36 @@ async def test_a_private_repository_with_the_jobs_owner_is_served( archive = await _archive(client, token, "testuser/own-private-action", 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 _private_repository(client, test_token, "own-private-action") + 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/own-private-action", "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 _private_repository(client, test_token, "own-private-action") + _no_upstream(monkeypatch) + + body = await _claim_job(client, test_token) + token = body["variables"]["system.github.token"]["Value"] + archive = await _archive(client, token, "testuser/own-private-action", SHA) + assert archive.status_code == 404 From 3c5e8ef04b7ebeb5587d72b6e9e924aee4485a37 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Wed, 18 Nov 2026 18:21:44 -0500 Subject: [PATCH 08/14] Judge a need on a reusable call by the call's result; keep nested outputs - A job that needs a reusable-workflow call was skipped when one of the called jobs was skipped by its own if:, though the call's result is success. Needs that come from a call are now judged as one group, by the call's result: failure, then cancelled, then success, then skipped (skipped only when every called job was). success() and failure() in the dependent's if: read the same result. A dependent now waits for every called job to finish, as on GitHub. - A call's outputs that read a nested call's outputs (jobs..outputs.x in on.workflow_call.outputs) rendered empty, since the jobs context held only the flattened called jobs. Nested calls are now entries in that context, built the same way. Assisted-by: Claude Signed-off-by: Wayne Sun --- ...-reusable-workflow-caller-waits-forever.md | 14 ++ src/app/services/workflow_scheduler.py | 84 ++++++++- src/app/services/workflow_service.py | 86 +++++++--- tests/actions/test_reusable_caller_needs.py | 161 ++++++++++++++++++ 4 files changed, 318 insertions(+), 27 deletions(-) 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 index 69616e35..bf344df4 100644 --- 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 @@ -22,7 +22,21 @@ the run. A job with `needs: `: `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. - 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 diff --git a/src/app/services/workflow_scheduler.py b/src/app/services/workflow_scheduler.py index f194cb69..5a402c40 100644 --- a/src/app/services/workflow_scheduler.py +++ b/src/app/services/workflow_scheduler.py @@ -18,22 +18,81 @@ def _runs_after_unsuccessful_needs(job: WorkflowJob) -> bool: return uses_status_function(pending.get("if")) +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 _ancestors(job: WorkflowJob, all_jobs) -> list[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. + """ needs_by_key = {(j.job_key or j.name): list(j.needs or []) for j in all_jobs} + called = _called_jobs(job) seen: list[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, key) + if name not in seen: + seen.append(name) pending.extend(needs_by_key.get(key, [])) return seen +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]: """Find jobs whose dependencies are met and set them to queued. @@ -42,6 +101,7 @@ async def dispatch_ready_jobs(db: AsyncSession, run_id: int) -> list[WorkflowJob ``needs..outputs.*``, which only exist once those jobs have finished. """ from app.services.workflow_service import ( + _combined_result, build_needs_context, build_run_expression_context, build_steps_data, @@ -78,6 +138,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 = [] @@ -91,10 +160,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"} @@ -102,7 +174,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) diff --git a/src/app/services/workflow_service.py b/src/app/services/workflow_service.py index 2097b67e..1199dae3 100644 --- a/src/app/services/workflow_service.py +++ b/src/app/services/workflow_service.py @@ -541,23 +541,58 @@ def needs_alias_entries(aliases: dict, needs_context: dict) -> dict: The result is the worst of the called jobs' results, as for a matrix; outputs are the call's workflow_call outputs, evaluated with a ``jobs`` - context holding the called jobs by their own keys. + context holding the called jobs by their own keys. A caller inside the + called workflow (``callers``) is in that context under its own key, its + entry built the same way, so an output can read ``jobs..outputs``. """ - entries = {} - for caller, alias in (aliases or {}).items(): - jobs_context = { - inner: needs_context.get(outer) or {"outputs": {}, "result": ""} + return { + caller: _alias_entry(alias, needs_context) + for caller, alias in (aliases or {}).items() + } + + +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) -> dict: + 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) + outputs = { + name: str(render_expressions(expression, {"jobs": jobs_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) -> dict: + """An alias from a called workflow with its job keys as this level names + them, its own nested callers included.""" + return { + **alias, + "jobs": { + inner: f"{prefix}{outer}" if outer in keys else outer for inner, outer in alias.get("jobs", {}).items() - } - result = "" - for entry in jobs_context.values(): - result = _combined_result(result, entry.get("result") or "") - outputs = { - name: str(render_expressions(expression, {"jobs": jobs_context}) or "") - for name, expression in (alias.get("outputs") or {}).items() - } - entries[caller] = {"result": result, "outputs": outputs} - return entries + }, + "callers": { + name: _prefix_alias(nested, prefix, keys) + for name, nested in (alias.get("callers") or {}).items() + }, + } def _declared_call_inputs(called: dict) -> dict: @@ -741,20 +776,25 @@ 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), + "callers": { + name: _prefix_alias(nested, prefix, called_keys) + for name, nested in nested_callers.items() + }, } 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. - for alias in (child.get("_needs_aliases") or {}).values(): - alias["jobs"] = { - inner: f"{prefix}{outer}" if outer in called_keys else outer - for inner, outer in alias["jobs"].items() - } + aliases = child.get("_needs_aliases") or {} + for name, alias in aliases.items(): + aliases[name] = _prefix_alias(alias, prefix, called_keys) caller_condition = config.get("if") child_condition = child.get("if") if caller_condition is not None: @@ -836,6 +876,8 @@ async def _materialize_reusable_jobs( 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 @@ -857,7 +899,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, @@ -867,6 +909,8 @@ async def materialize_reusable_workflows( depth=0, ancestry=(), ) + materialized.pop("_callers", None) + return materialized def _instance_strategy(job_config: dict, context: dict) -> dict: diff --git a/tests/actions/test_reusable_caller_needs.py b/tests/actions/test_reusable_caller_needs.py index 1c2b2cc0..589979ec 100644 --- a/tests/actions/test_reusable_caller_needs.py +++ b/tests/actions/test_reusable_caller_needs.py @@ -175,3 +175,164 @@ async def fake_detect(path, ref="HEAD"): )).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"}} From f60d848212dc63aee5901044507f95059b734d04 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Wed, 18 Nov 2026 18:43:10 -0500 Subject: [PATCH 09/14] Evaluate a reusable call's outputs with inputs, github and vars on.workflow_call.outputs..value was rendered with only a jobs context, so an output such as ${{ inputs.version }} came out empty. GitHub makes github, jobs, vars and inputs available there (and not secrets). Each call's alias now keeps its resolved inputs (the caller's with: and the callee's defaults), and outputs are rendered with all four contexts, nested calls included. Assisted-by: Claude Signed-off-by: Wayne Sun --- ...-reusable-workflow-caller-waits-forever.md | 12 ++ src/app/services/workflow_scheduler.py | 4 +- src/app/services/workflow_service.py | 44 ++++-- tests/actions/test_reusable_caller_needs.py | 138 ++++++++++++++++++ 4 files changed, 187 insertions(+), 11 deletions(-) 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 index bf344df4..2f9439e9 100644 --- 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 @@ -46,6 +46,18 @@ the run. A job with `needs: `: 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. + +[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/src/app/services/workflow_scheduler.py b/src/app/services/workflow_scheduler.py index 5a402c40..58edefa3 100644 --- a/src/app/services/workflow_scheduler.py +++ b/src/app/services/workflow_scheduler.py @@ -201,7 +201,9 @@ async def dispatch_ready_jobs(db: AsyncSession, run_id: int) -> list[WorkflowJob # in the run; answer needs. from its called jobs. "needs": { **needs_context, - **needs_alias_entries(pending.get("_needs_aliases"), needs_context), + **needs_alias_entries( + pending.get("_needs_aliases"), needs_context, base_context, + ), }, JOB_NEEDS_KEY: _ancestors(job, all_jobs), RUN_CANCELLED_KEY: bool(base_context.get(RUN_CANCELLED_KEY)), diff --git a/src/app/services/workflow_service.py b/src/app/services/workflow_service.py index 1199dae3..9ea8f39e 100644 --- a/src/app/services/workflow_service.py +++ b/src/app/services/workflow_service.py @@ -536,17 +536,20 @@ def _declared_call_outputs(called: dict) -> dict[str, str]: } -def needs_alias_entries(aliases: dict, needs_context: dict) -> dict: +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 a ``jobs`` - context holding the called jobs by their own keys. A caller inside the - called workflow (``callers``) is in that context under its own key, its - entry built the same way, so an output can read ``jobs..outputs``. + 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``. """ + run_context = run_context or {} return { - caller: _alias_entry(alias, needs_context) + caller: _alias_entry(alias, needs_context, run_context, {}) for caller, alias in (aliases or {}).items() } @@ -561,7 +564,19 @@ def alias_result(alias: dict, results: dict) -> str: return result -def _alias_entry(alias: dict, needs_context: dict) -> dict: +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. + inputs = render_expressions(alias.get("inputs") or {}, { + "github": run_context.get("github") or {}, + "vars": run_context.get("vars") or {}, + "needs": needs_context, + "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() @@ -571,9 +586,15 @@ def _alias_entry(alias: dict, needs_context: dict) -> dict: for outer in alias.get("jobs", {}).values() }) for name, nested in (alias.get("callers") or {}).items(): - jobs_context[name] = _alias_entry(nested, needs_context) + 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, {"jobs": jobs_context}) or "") + name: str(render_expressions(expression, output_context) or "") for name, expression in (alias.get("outputs") or {}).items() } return {"result": result, "outputs": outputs} @@ -700,7 +721,7 @@ 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, and its ``on.workflow_call.outputs``. + # by the key they get here, its ``on.workflow_call.outputs`` and its inputs. callers: dict[str, dict] = {} for key, config in jobs.items(): if not isinstance(config, dict) or not config.get("uses"): @@ -782,6 +803,9 @@ async def _materialize_reusable_jobs( 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() diff --git a/tests/actions/test_reusable_caller_needs.py b/tests/actions/test_reusable_caller_needs.py index 589979ec..963720d8 100644 --- a/tests/actions/test_reusable_caller_needs.py +++ b/tests/actions/test_reusable_caller_needs.py @@ -336,3 +336,141 @@ def test_a_nested_callers_entry_is_built_from_its_own_alias(): } 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": ""} From 938b807ae322cdcb45c4ae93bc08f732f563d501 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Thu, 19 Nov 2026 12:28:54 -0500 Subject: [PATCH 10/14] Render a reusable call's inputs with the caller's inputs and needs Review follow-up: a top-level call's with: was rendered against no inputs, so needs..outputs could differ from what the called jobs received when with: held an expression on the calling workflow's inputs. It is now rendered against the run's inputs at the top level, and against the calling workflow's own inputs for a call inside a called workflow. In a chain of calls (A, then B with needs: A and with: x: ${{ needs.A.outputs.o }}, then C reading B's outputs), B's with: was rendered without needs.A, so A's output reached C empty. Each call's alias now carries the aliases of the calls it needs, and its with: is rendered with those entries in needs, as a plain dependent of A sees them. Assisted-by: Claude Signed-off-by: Wayne Sun --- ...-reusable-workflow-caller-waits-forever.md | 17 ++ src/app/services/workflow_service.py | 63 +++++- tests/actions/test_reusable_caller_needs.py | 200 ++++++++++++++++++ 3 files changed, 277 insertions(+), 3 deletions(-) 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 index 2f9439e9..14083879 100644 --- 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 @@ -56,6 +56,23 @@ the run. A job with `needs: `: 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, kept on the alias at + materialization (`parent_inputs`), not the run's. +- 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 diff --git a/src/app/services/workflow_service.py b/src/app/services/workflow_service.py index 9ea8f39e..a7968417 100644 --- a/src/app/services/workflow_service.py +++ b/src/app/services/workflow_service.py @@ -546,14 +546,36 @@ def needs_alias_entries(aliases: dict, needs_context: dict, run_context: dict | ``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 (``parent_inputs``, kept at materialization). """ run_context = run_context or {} return { - caller: _alias_entry(alias, needs_context, run_context, {}) + caller: _alias_entry( + alias, needs_context, run_context, _alias_parent_inputs(alias, needs_context, run_context), + ) for caller, alias in (aliases or {}).items() } +def _alias_parent_inputs(alias: dict, needs_context: dict, run_context: dict) -> dict: + run_inputs = run_context.get("inputs") or {} + if "parent_inputs" not in alias: + return run_inputs + # The enclosing call's resolved inputs; a value still holding an + # expression is in the run's terms one level up. + parent = render_expressions(alias["parent_inputs"] or {}, { + "github": run_context.get("github") or {}, + "vars": run_context.get("vars") or {}, + "needs": needs_context, + "inputs": run_inputs, + }) + return parent if isinstance(parent, dict) else {} + + 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 @@ -568,11 +590,20 @@ def _alias_entry(alias: dict, needs_context: dict, run_context: dict, parent_inp # 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. + # ``_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. + needs = { + **needs_context, + **{ + name: _alias_entry(upstream, needs_context, run_context, parent_inputs) + for name, upstream in (alias.get("needs_aliases") or {}).items() + }, + } inputs = render_expressions(alias.get("inputs") or {}, { "github": run_context.get("github") or {}, "vars": run_context.get("vars") or {}, - "needs": needs_context, + "needs": needs, "inputs": parent_inputs, }) if not isinstance(inputs, dict): @@ -613,6 +644,10 @@ def _prefix_alias(alias: dict, prefix: str, keys: set) -> dict: 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() + }, } @@ -723,6 +758,8 @@ async def _materialize_reusable_jobs( # 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) @@ -811,6 +848,12 @@ async def _materialize_reusable_jobs( for name, nested in nested_callers.items() }, } + if depth > 0: + # The calling workflow's inputs, which a compound ``with:`` + # expression reads when a sibling's needs. is built. + callers[key]["parent_inputs"] = copy.deepcopy(inputs) + 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}") @@ -872,6 +915,20 @@ async def _materialize_reusable_jobs( # 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 diff --git a/tests/actions/test_reusable_caller_needs.py b/tests/actions/test_reusable_caller_needs.py index 963720d8..24e80b70 100644 --- a/tests/actions/test_reusable_caller_needs.py +++ b/tests/actions/test_reusable_caller_needs.py @@ -474,3 +474,203 @@ 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" From 49c192d3cff5c89e36e35533820beba3d660647d Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Thu, 19 Nov 2026 13:03:53 -0500 Subject: [PATCH 11/14] Render each nested reusable call's inputs in its own workflow's terms A call two or more levels down had its with: rendered against the run's inputs, not its calling workflow's: run ver=run, outer ver=2, mid ver=format('{0}-mid', inputs.ver) gave mid's jobs 'run-mid' instead of '2-mid'. Each call's with: is now resolved outermost first, each level's rendered inputs being the inputs context of the next, for both the alias and the called jobs. A bare ${{ inputs.x }} is copied in at materialization only when the passed value is a literal; an expression is rendered with the job's inputs instead. Assisted-by: Claude Signed-off-by: Wayne Sun --- ...-reusable-workflow-caller-waits-forever.md | 23 +++- src/app/services/workflow_scheduler.py | 10 +- src/app/services/workflow_service.py | 102 +++++++++++++--- tests/actions/test_reusable_caller_needs.py | 114 ++++++++++++++++++ 4 files changed, 221 insertions(+), 28 deletions(-) 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 index 14083879..5fe07dcc 100644 --- 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 @@ -62,8 +62,27 @@ the run. A job with `needs: `: 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, kept on the alias at - materialization (`parent_inputs`), not the run's. + 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 diff --git a/src/app/services/workflow_scheduler.py b/src/app/services/workflow_scheduler.py index 58edefa3..eff2d927 100644 --- a/src/app/services/workflow_scheduler.py +++ b/src/app/services/workflow_scheduler.py @@ -105,6 +105,7 @@ async def dispatch_ready_jobs(db: AsyncSession, run_id: int) -> list[WorkflowJob build_needs_context, build_run_expression_context, build_steps_data, + call_inputs_context, fail_refused_job, needs_alias_entries, render_job_labels, @@ -216,13 +217,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 {}), diff --git a/src/app/services/workflow_service.py b/src/app/services/workflow_service.py index a7968417..a9caa7fb 100644 --- a/src/app/services/workflow_service.py +++ b/src/app/services/workflow_service.py @@ -336,6 +336,7 @@ 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", ""), @@ -420,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: @@ -550,7 +558,8 @@ def needs_alias_entries(aliases: dict, needs_context: dict, run_context: dict | 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 (``parent_inputs``, kept at materialization). + workflow, that workflow's, resolved from the inputs of each enclosing + call (``parent_inputs_chain``, kept at materialization). """ run_context = run_context or {} return { @@ -561,19 +570,36 @@ def needs_alias_entries(aliases: dict, needs_context: dict, run_context: dict | } +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 {} - if "parent_inputs" not in alias: + chain = alias.get("parent_inputs_chain") or [] + if not chain: return run_inputs - # The enclosing call's resolved inputs; a value still holding an - # expression is in the run's terms one level up. - parent = render_expressions(alias["parent_inputs"] or {}, { + # 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, - "inputs": run_inputs, - }) - return parent if isinstance(parent, dict) else {} + })[-1] def alias_result(alias: dict, results: dict) -> str: @@ -631,10 +657,17 @@ def _alias_entry(alias: dict, needs_context: dict, run_context: dict, parent_inp return {"result": result, "outputs": outputs} -def _prefix_alias(alias: dict, prefix: str, keys: set) -> dict: +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.""" - return { + 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 @@ -649,6 +682,11 @@ def _prefix_alias(alias: dict, prefix: str, keys: set) -> dict: 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: @@ -848,10 +886,6 @@ async def _materialize_reusable_jobs( for name, nested in nested_callers.items() }, } - if depth > 0: - # The calling workflow's inputs, which a compound ``with:`` - # expression reads when a sibling's needs. is built. - callers[key]["parent_inputs"] = copy.deepcopy(inputs) 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(): @@ -861,7 +895,7 @@ async def _materialize_reusable_jobs( # 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) + 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: @@ -874,6 +908,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 {}), } @@ -1004,6 +1044,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. @@ -1026,11 +1088,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} @@ -1563,6 +1624,7 @@ 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 "", diff --git a/tests/actions/test_reusable_caller_needs.py b/tests/actions/test_reusable_caller_needs.py index 24e80b70..0ac872ce 100644 --- a/tests/actions/test_reusable_caller_needs.py +++ b/tests/actions/test_reusable_caller_needs.py @@ -674,3 +674,117 @@ async def fake_detect(path, ref="HEAD"): 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" From c1b3c26f2c38bedfbfdfe450ef00950c4ff2b6fd Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Thu, 19 Nov 2026 13:29:29 -0500 Subject: [PATCH 12/14] Keep a skipped caller's result through a second call A job needing call B, which needs a call A skipped by its if:, read needs.B.outputs from an empty needs.A: the copy of A's alias inside B's rebuilt needs[A] from called jobs that were never created, replacing A's skipped row. An alias entry is now skipped when needs already has that key and none of that caller's called jobs exist. Assisted-by: Claude Signed-off-by: Wayne Sun --- src/app/services/workflow_service.py | 19 +++--- tests/actions/test_skipped_reusable_caller.py | 68 +++++++++++++++++++ 2 files changed, 79 insertions(+), 8 deletions(-) diff --git a/src/app/services/workflow_service.py b/src/app/services/workflow_service.py index a9caa7fb..47023272 100644 --- a/src/app/services/workflow_service.py +++ b/src/app/services/workflow_service.py @@ -618,14 +618,17 @@ def _alias_entry(alias: dict, needs_context: dict, run_context: dict, parent_inp # 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. - needs = { - **needs_context, - **{ - name: _alias_entry(upstream, needs_context, run_context, parent_inputs) - for name, upstream in (alias.get("needs_aliases") or {}).items() - }, - } + # 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 {}, diff --git a/tests/actions/test_skipped_reusable_caller.py b/tests/actions/test_skipped_reusable_caller.py index 0f9c2777..d14bbf65 100644 --- a/tests/actions/test_skipped_reusable_caller.py +++ b/tests/actions/test_skipped_reusable_caller.py @@ -241,3 +241,71 @@ async def test_a_run_whose_jobs_all_skipped_is_skipped( 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" From 8bc3c011476a07de3b91f7f337b516bc43e040f1 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Thu, 19 Nov 2026 13:29:29 -0500 Subject: [PATCH 13/14] Use a private repository here as an action only from that repository GitHub lets other repositories use a private repository's actions only once its owner enables that access, and the emulator has no such setting. A job may now use a repository here as an action only when it is public or is the job's own repository; any other private or internal one is unresolvable (download info) and a 404 (archive), and is not looked up upstream. Assisted-by: Claude Signed-off-by: Wayne Sun --- ...lator-repositories-are-fetched-upstream.md | 16 ++--- src/app/api/actions_distributed_task.py | 17 ++--- tests/actions/test_emulator_hosted_actions.py | 63 ++++++++++++++++--- 3 files changed, 67 insertions(+), 29 deletions(-) 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 index ffb39cb9..0860947a 100644 --- a/docs/bugs/fixed/actions-in-emulator-repositories-are-fetched-upstream.md +++ b/docs/bugs/fixed/actions-in-emulator-repositories-are-fetched-upstream.md @@ -22,14 +22,14 @@ repository it lacks. A test stack that pushes its own actions needs the same. 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. -- As on GitHub, a job may use a repository here as an action only when it is - public, is the job's own repository, or is private with the same owner as - the job's repository. GitHub also requires that owner to allow access to - its private actions; the emulator has no such setting. Another owner's - private repository 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. +- 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 diff --git a/src/app/api/actions_distributed_task.py b/src/app/api/actions_distributed_task.py index 9609b9d9..3a410a61 100644 --- a/src/app/api/actions_distributed_task.py +++ b/src/app/api/actions_distributed_task.py @@ -1991,9 +1991,11 @@ async def _local_action_repository( """Whether this emulator holds the repository a `uses:` reference names, and that repository when the job may use it as an action. - As on GitHub, a workflow may use an action from a public repository, from - its own repository, or from a private one with the same owner (GitHub - also requires that owner to allow it; this emulator has no such setting). + 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) @@ -2009,10 +2011,7 @@ async def _local_action_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 - or _owner_login(job_repository) == _owner_login(repository) - ): + if job_repository is not None and job_repository.id == repository.id: return True, repository return True, None @@ -2021,10 +2020,6 @@ def _is_public(repository: Repository) -> bool: return not repository.private and (repository.visibility or "public") == "public" -def _owner_login(repository: Repository) -> str: - return repository.full_name.split("/", 1)[0].lower() - - @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( diff --git a/tests/actions/test_emulator_hosted_actions.py b/tests/actions/test_emulator_hosted_actions.py index 1ddfd82e..10e4b8fb 100644 --- a/tests/actions/test_emulator_hosted_actions.py +++ b/tests/actions/test_emulator_hosted_actions.py @@ -7,9 +7,11 @@ 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". -As on GitHub, a job may use an action from a public repository, its own -repository, or a private repository with the same owner. Another owner's -private repository is not resolvable, and its name is not looked up 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 @@ -150,19 +152,60 @@ async def test_another_owners_private_repository_is_not_an_action_here( @pytest.mark.asyncio -async def test_a_private_repository_with_the_jobs_owner_is_served( +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 == 200, resp.text - sha = resp.json()["actions"]["testuser/own-private-action@main"]["resolvedSha"] + 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 @@ -170,7 +213,7 @@ async def test_a_private_repository_with_the_jobs_owner_is_served( 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 _private_repository(client, test_token, "own-private-action") + await _make_job_repository_private(client, test_token) looked_up = [] async def upstream(name, ref): @@ -180,7 +223,7 @@ async def upstream(name, ref): 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", "v1") + 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 == [] @@ -190,10 +233,10 @@ async def upstream(name, ref): async def test_a_commit_missing_from_a_private_repository_here_is_not_fetched_upstream( client, uses_workflow, test_token, monkeypatch # noqa: F811 ): - await _private_repository(client, test_token, "own-private-action") + 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/own-private-action", SHA) + archive = await _archive(client, token, "testuser/uses-step-repo", SHA) assert archive.status_code == 404 From d0bbc9273826121c4a12724681af2b516777b7e1 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Thu, 19 Nov 2026 13:55:08 -0500 Subject: [PATCH 14/14] Judge a reusable call by its result further down a chain success() and failure() read every ancestor. For call -> middle -> final, final saw the call's job skipped by its own if: as an unsuccessful ancestor and was skipped, though the call succeeded and middle ran. A called job reached through another job is now judged as its call (the worst result of the call's finished jobs), at any depth, the same rule a direct dependent uses. The caller is found from the job key ( / ). Assisted-by: Claude Signed-off-by: Wayne Sun --- ...-reusable-workflow-caller-waits-forever.md | 13 +++ src/app/services/workflow_expressions.py | 9 +- src/app/services/workflow_scheduler.py | 60 +++++++++--- tests/actions/test_reusable_caller_needs.py | 95 +++++++++++++++++++ 4 files changed, 164 insertions(+), 13 deletions(-) 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 index 5fe07dcc..2bbf57bd 100644 --- 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 @@ -30,6 +30,19 @@ the run. A job with `needs: `: 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 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 eff2d927..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 @@ -29,7 +30,22 @@ def _called_jobs(job: WorkflowJob) -> dict[str, str]: return called -def _ancestors(job: WorkflowJob, all_jobs) -> list[str]: +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. @@ -37,10 +53,20 @@ def _ancestors(job: WorkflowJob, all_jobs) -> list[str]: 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: @@ -48,11 +74,19 @@ def _ancestors(job: WorkflowJob, all_jobs) -> list[str]: if key in visited: continue visited.add(key) - name = called.get(key, 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( @@ -100,6 +134,13 @@ 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, @@ -111,12 +152,6 @@ async def dispatch_ready_jobs(db: AsyncSession, run_id: int) -> list[WorkflowJob 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) @@ -196,6 +231,7 @@ 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, # A reusable-workflow caller this job needs is not a job @@ -206,7 +242,8 @@ async def dispatch_ready_jobs(db: AsyncSession, run_id: int) -> list[WorkflowJob pending.get("_needs_aliases"), needs_context, base_context, ), }, - JOB_NEEDS_KEY: _ancestors(job, all_jobs), + 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), @@ -296,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) diff --git a/tests/actions/test_reusable_caller_needs.py b/tests/actions/test_reusable_caller_needs.py index 0ac872ce..4f5db65f 100644 --- a/tests/actions/test_reusable_caller_needs.py +++ b/tests/actions/test_reusable_caller_needs.py @@ -788,3 +788,98 @@ async def test_an_output_forwarded_up_from_a_twice_nested_call( ) 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