diff --git a/alembic/versions/0022_workflow_job_timeout_minutes.py b/alembic/versions/0022_workflow_job_timeout_minutes.py new file mode 100644 index 00000000..5fea26c7 --- /dev/null +++ b/alembic/versions/0022_workflow_job_timeout_minutes.py @@ -0,0 +1,43 @@ +"""Keep a job's timeout-minutes. + +The upstream runner's job token lives for the job's timeout plus a margin, +but the parsed timeout-minutes was never stored, so every token was issued +for the 360-minute default: longer than a short job may run, and expiring +before a long one ends. NULL means the default; existing jobs keep it. + +Revision ID: 0022_workflow_job_timeout_minutes +Revises: 0021_runner_registration_broker +Create Date: 2026-12-03 +""" + +import sqlalchemy as sa +from alembic import op +from sqlalchemy import inspect + +revision = "0022_workflow_job_timeout_minutes" +down_revision = "0021_runner_registration_broker" +branch_labels = None +depends_on = None + +_TABLE = "workflow_jobs" +_COLUMN = "timeout_minutes" + + +def upgrade() -> None: + bind = op.get_bind() + inspector = inspect(bind) + if _TABLE not in inspector.get_table_names(): + return + if _COLUMN in {column["name"] for column in inspector.get_columns(_TABLE)}: + return + op.add_column(_TABLE, sa.Column(_COLUMN, sa.Integer(), nullable=True)) + + +def downgrade() -> None: + bind = op.get_bind() + inspector = inspect(bind) + if _TABLE not in inspector.get_table_names(): + return + if _COLUMN not in {column["name"] for column in inspector.get_columns(_TABLE)}: + return + op.drop_column(_TABLE, _COLUMN) diff --git a/docs/bugs/fixed/job-token-ignores-the-jobs-timeout-minutes.md b/docs/bugs/fixed/job-token-ignores-the-jobs-timeout-minutes.md new file mode 100644 index 00000000..4cca6c6a --- /dev/null +++ b/docs/bugs/fixed/job-token-ignores-the-jobs-timeout-minutes.md @@ -0,0 +1,39 @@ +# Bug: the upstream-runner job token ignores the job's timeout-minutes + +Status: fixed 2026-12-03 (issue #70). + +## Summary + +- `job_token_lifetime` issues the job token for the job's timeout plus 5 + minutes, capped at 24 hours. It reads `timeout_minutes` from the job, but + `WorkflowJob` had no such column. The parsed `timeout-minutes` was never + stored, so every token lived 365 minutes. That is longer than a + `timeout-minutes: 30` job may run. It also expires before a job with more + than 360 minutes ends, and that job's completion report then gets 401. +- `_with_gh_enterprise_token` filled each enterprise variable on its own. A + step that set only `GITHUB_ENTERPRISE_TOKEN` still got + `GH_ENTERPRISE_TOKEN` mirrored from `GH_TOKEN`. `gh` reads + `GH_ENTERPRISE_TOKEN` first, so it used the mirrored token, not the one + the workflow chose. + +## Fix + +- New nullable column `workflow_jobs.timeout_minutes` (migration 0022). + NULL means the default (360). +- Job creation stores the parsed `timeout-minutes` when it is a positive + number. An expression is not evaluated and gets the default. Instances of + a dynamic matrix copy it in `workflow_scheduler`. +- The token is mirrored into the enterprise variables only when the step's + environment sets neither of them. + +## Evidence + +- `tests/actions/test_runner_job_outputs.py`: jobs created with + `timeout-minutes: 30` and with none. The test checks the stored value, + `job_token_lifetime`, and the issued token's `exp - iat`. +- `tests/actions/test_dynamic_matrix.py`: every matrix instance keeps the + timeout. +- `tests/actions/test_runner_gh_host.py`: a step with + `GITHUB_ENTERPRISE_TOKEN` and `GH_TOKEN` gets no `GH_ENTERPRISE_TOKEN`. +- `tests/test_database_migrations.py`: 0022 adds the column to a database at + 0021 and keeps existing jobs, which get NULL. diff --git a/src/app/api/actions_distributed_task.py b/src/app/api/actions_distributed_task.py index c9830a1e..5bbe4fa5 100644 --- a/src/app/api/actions_distributed_task.py +++ b/src/app/api/actions_distributed_task.py @@ -913,12 +913,16 @@ def _with_gh_enterprise_token(environment: dict) -> dict: workflow declared is mirrored, as the same expression so the runner resolves it when the step starts: an ambient job token here would outrank a narrower token a step mints for itself (the Python runner learnt the - same). A workflow that sets the enterprise variables itself wins. + same). A workflow that sets either enterprise variable itself wins, and + nothing is mirrored: gh reads GH_ENTERPRISE_TOKEN first, so filling it + beside a workflow's own GITHUB_ENTERPRISE_TOKEN would override that choice. """ + if "GH_ENTERPRISE_TOKEN" in environment or "GITHUB_ENTERPRISE_TOKEN" in environment: + return environment token = environment.get("GH_TOKEN") or environment.get("GITHUB_TOKEN") if token: - environment.setdefault("GH_ENTERPRISE_TOKEN", token) - environment.setdefault("GITHUB_ENTERPRISE_TOKEN", token) + environment["GH_ENTERPRISE_TOKEN"] = token + environment["GITHUB_ENTERPRISE_TOKEN"] = token return environment diff --git a/src/app/models/actions.py b/src/app/models/actions.py index 05508883..74d604d7 100644 --- a/src/app/models/actions.py +++ b/src/app/models/actions.py @@ -186,6 +186,9 @@ class WorkflowJob(Base): # until the dependencies complete so they can be rendered with a populated # ``needs`` context. pending_render: Mapped[dict | None] = mapped_column(JSON, nullable=True) + # The job's ``timeout-minutes``; None means GitHub's default (360). The + # upstream runner's job token is issued for this long plus a margin. + timeout_minutes: Mapped[int | None] = mapped_column(Integer, nullable=True) created_at: Mapped[datetime] = mapped_column( DateTime, server_default=func.now() diff --git a/src/app/services/workflow_scheduler.py b/src/app/services/workflow_scheduler.py index 4fed266c..ad493781 100644 --- a/src/app/services/workflow_scheduler.py +++ b/src/app/services/workflow_scheduler.py @@ -377,6 +377,7 @@ async def _expand_dynamic_matrix( outputs_config=dict(job.outputs_config or {}), outputs={}, name=job.name, + timeout_minutes=job.timeout_minutes, ) instance_context = { **context, diff --git a/src/app/services/workflow_service.py b/src/app/services/workflow_service.py index 96bc3da4..8cef8ce1 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 math import os import re import uuid @@ -276,6 +277,34 @@ def fail_refused_job(job: WorkflowJob, why: str) -> None: log.write(f"##[error]{why}\n") +# The job token never outlives 24 hours, so a longer timeout is stored as 24 hours. +_MAX_TIMEOUT_MINUTES = 24 * 60 + + +def _timeout_minutes(value: object) -> int | None: + """A job's ``timeout-minutes`` as a positive whole number, or None. + + None stands for GitHub's default (360). An expression or any other value + that is not a usable positive number is not evaluated here and gets the + default. A value above 24 hours is capped at 24 hours. + """ + if isinstance(value, bool): + return None + try: + if isinstance(value, str): + text = value.strip() + if not (text.isascii() and text.isdigit()): + return None + value = int(text) + if isinstance(value, float) and not math.isfinite(value): + return None + if isinstance(value, (int, float)) and value > 0: + return min(max(1, int(value)), _MAX_TIMEOUT_MINUTES) + except (ValueError, OverflowError): + return None + return None + + def build_job_graph(workflow_yaml: dict) -> list[dict]: """Parse jobs section into a dependency-ordered list.""" jobs_config = workflow_yaml.get("jobs", {}) @@ -347,7 +376,7 @@ def build_job_graph(workflow_yaml: dict) -> list[dict]: "_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), + "timeout_minutes": _timeout_minutes(config.get("timeout-minutes")), }) return _topo_sort(jobs) @@ -1818,6 +1847,7 @@ async def create_workflow_run( outputs={}, pending_render=pending_render, workflow_ref=job_config.get("_workflow_ref") or None, + timeout_minutes=job_config.get("timeout_minutes"), ) db.add(job) if job_config.get("_refused") and not needs and conclusion is None: diff --git a/tests/actions/test_dynamic_matrix.py b/tests/actions/test_dynamic_matrix.py index 0541ed4d..ccd0641b 100644 --- a/tests/actions/test_dynamic_matrix.py +++ b/tests/actions/test_dynamic_matrix.py @@ -18,10 +18,10 @@ from app.services.workflow_scheduler import check_run_completion, dispatch_ready_jobs from app.services.workflow_service import ( build_needs_context, + create_workflow_run, matrix_combinations, matrix_job_name, ) -from app.services.workflow_service import create_workflow_run from tests.actions.test_execution import executable_workflow # noqa: F401 (fixture) STEPS = [{"name": "Mint", "run": "echo ${{ matrix.agent }} ${{ matrix.status_repo }}"}] @@ -95,6 +95,24 @@ async def test_the_matrix_expands_when_its_needs_finish(executable_workflow, db_ assert by_name["Harness run (review)"].needs == ["harness-dispatch"] +@pytest.mark.asyncio +async def test_every_instance_keeps_the_jobs_timeout(executable_workflow, db_session, test_user): # noqa: F811 + """The job token's lifetime reads timeout_minutes, so each instance needs it.""" + _repo, workflow, _ = executable_workflow + run = await _run(db_session, workflow, test_user, { + "harness-dispatch": _dispatch_job(), + "harness-run": {**HARNESS, "timeout-minutes": 30}, + }) + rows = await _rows(db_session, run) + await _finish(db_session, rows[0], "success", {"matrix": TWO}) + await dispatch_ready_jobs(db_session, run.id) + await db_session.commit() + + harness = [r for r in await _rows(db_session, run) if r.job_key == "harness-run"] + assert len(harness) == 2 + assert [r.timeout_minutes for r in harness] == [30, 30] + + @pytest.mark.asyncio async def test_an_empty_matrix_fails_the_job(executable_workflow, db_session, test_user): # noqa: F811 _repo, workflow, _ = executable_workflow diff --git a/tests/actions/test_runner_gh_host.py b/tests/actions/test_runner_gh_host.py index 8325b85f..e0230327 100644 --- a/tests/actions/test_runner_gh_host.py +++ b/tests/actions/test_runner_gh_host.py @@ -50,6 +50,8 @@ async def gh_workflow(client, db_session, test_user, test_token): {"name": "own-host", "run": "gh api user", "env": {"GH_HOST": "elsewhere.example", "GH_TOKEN": "t", "GH_ENTERPRISE_TOKEN": "explicit"}}, + {"name": "own-token", "run": "gh api user", + "env": {"GH_TOKEN": "t", "GITHUB_ENTERPRISE_TOKEN": "chosen"}}, ], }}, }, event="push", payload={"ref": "refs/heads/main"}, actor=test_user, @@ -67,7 +69,7 @@ async def test_steps_point_gh_at_the_emulator_with_the_workflows_token( client, gh_workflow, test_token ): body = await _claim_job(client, test_token) - minted, none, own = (_environment(step) for step in body["steps"]) + minted, none, own, own_token = (_environment(step) for step in body["steps"]) expected_host = _gh_host(body["contextData"]["github"]["d"][ [entry["k"] for entry in body["contextData"]["github"]["d"]].index("server_url") ]["v"]) @@ -84,3 +86,8 @@ async def test_steps_point_gh_at_the_emulator_with_the_workflows_token( # What the workflow sets itself wins. assert own["GH_HOST"] == "elsewhere.example" assert own["GH_ENTERPRISE_TOKEN"] == "explicit" + + # gh reads GH_ENTERPRISE_TOKEN first: mirroring GH_TOKEN into it would + # outrank the GITHUB_ENTERPRISE_TOKEN the workflow chose. + assert own_token["GITHUB_ENTERPRISE_TOKEN"] == "chosen" + assert "GH_ENTERPRISE_TOKEN" not in own_token diff --git a/tests/actions/test_runner_job_outputs.py b/tests/actions/test_runner_job_outputs.py index 71b724d5..d4264c13 100644 --- a/tests/actions/test_runner_job_outputs.py +++ b/tests/actions/test_runner_job_outputs.py @@ -232,6 +232,79 @@ def test_job_token_lifetime(timeout_minutes, seconds): assert job_token_lifetime(SimpleNamespace(timeout_minutes=timeout_minutes)) == seconds +@pytest.mark.parametrize( + ("value", "expected"), + [ + (30, 30), + ("45", 45), + (0.5, 1), + (2000, 24 * 60), + (2**63, 24 * 60), + ("9" * 30, 24 * 60), + (float("inf"), None), + (float("nan"), None), + ("٢", None), # an Arabic-Indic digit is not an ASCII number + ("9" * 5000, None), # beyond Python's integer-string conversion limit + (0, None), + (-5, None), + (True, None), + (None, None), + ("${{ inputs.timeout }}", None), + ], +) +def test_timeout_minutes_is_total(value, expected): + from app.services.workflow_service import _timeout_minutes + + assert _timeout_minutes(value) == expected + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("job_timeout", "stored", "seconds"), + [({"timeout-minutes": 30}, 30, 35 * 60), ({}, None, 365 * 60)], +) +async def test_the_job_token_lives_for_the_jobs_own_timeout( + client, db_session, test_user, test_token, job_timeout, stored, seconds +): + """timeout-minutes from the workflow reaches the job and its token.""" + import base64 + import json + + from app.services.job_token_service import job_token_lifetime + + resp = await client.post( + f"{API}/user/repos", json={"name": "uses-step-repo"}, headers=auth_headers(test_token) + ) + assert resp.status_code == 201 + repo = (await db_session.execute( + select(Repository).where(Repository.full_name == "testuser/uses-step-repo") + )).scalar_one() + workflow = Workflow(repo_id=repo.id, name="Timeout", path=".github/workflows/timeout.yml") + db_session.add(workflow) + await db_session.flush() + await create_workflow_run( + db_session, workflow, { + "name": "Timeout", "on": ["push"], + "jobs": {"build": { + "runs-on": ["self-hosted", "linux"], **job_timeout, + "steps": [{"run": "echo"}], + }}, + }, event="push", payload={"ref": "refs/heads/main"}, actor=test_user, + head_sha="abc123", head_branch="main", + ) + await db_session.commit() + + job = (await db_session.execute(select(WorkflowJob))).scalars().one() + assert job.timeout_minutes == stored + assert job_token_lifetime(job) == seconds + + body = await _claim_job(client, test_token) + token = body["variables"]["system.github.token"]["Value"] + payload = token.split(".")[1] + claims = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))) + assert claims["exp"] - claims["iat"] == seconds + + @pytest.mark.asyncio async def test_an_event_for_another_plan_is_not_found(client, db_session, uses_workflow, test_token): # noqa: F811 body = await _claim_job(client, test_token) diff --git a/tests/test_database_migrations.py b/tests/test_database_migrations.py index 7c153a45..45ec8c83 100644 --- a/tests/test_database_migrations.py +++ b/tests/test_database_migrations.py @@ -455,3 +455,42 @@ def test_runner_registration_broker_column_is_added_to_an_existing_database(tmp_ ).one() assert (row[0], bool(row[1])) == ("old-runner", False) engine.dispose() + + +def test_workflow_job_timeout_minutes_column_is_added_to_an_existing_database(tmp_path, monkeypatch): + """0022 adds workflow_jobs.timeout_minutes to a database at 0021 and keeps + jobs, which get the default (NULL).""" + from pathlib import Path + + from alembic import command + from alembic.config import Config + + path = tmp_path / "job-timeout.db" + monkeypatch.delenv("GITHUB_EMULATOR_DATABASE_URL", raising=False) + root = Path(__file__).resolve().parents[1] + config = Config(str(root / "alembic.ini")) + config.set_main_option("script_location", str(root / "alembic")) + config.set_main_option("sqlalchemy.url", _url(path)) + command.upgrade(config, "0021_runner_registration_broker") + engine = create_engine(f"sqlite:///{path}") + with engine.begin() as connection: + columns = {column["name"] for column in inspect(connection).get_columns("workflow_jobs")} + if "timeout_minutes" in columns: + connection.execute(text("ALTER TABLE workflow_jobs DROP COLUMN timeout_minutes")) + connection.execute(text( + "INSERT INTO workflow_jobs (id, run_id, name, status, steps, run_attempt) " + "VALUES (6, 6, 'old-job', 'completed', '[]', 1)" + )) + engine.dispose() + + upgrade_database_sync(_url(path)) + + engine = create_engine(f"sqlite:///{path}") + with engine.begin() as connection: + columns = {column["name"] for column in inspect(connection).get_columns("workflow_jobs")} + assert "timeout_minutes" in columns + row = connection.execute( + text("SELECT name, timeout_minutes FROM workflow_jobs WHERE id = 6") + ).one() + assert tuple(row) == ("old-job", None) + engine.dispose()