Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions alembic/versions/0022_workflow_job_timeout_minutes.py
Original file line number Diff line number Diff line change
@@ -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)
39 changes: 39 additions & 0 deletions docs/bugs/fixed/job-token-ignores-the-jobs-timeout-minutes.md
Original file line number Diff line number Diff line change
@@ -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.
10 changes: 7 additions & 3 deletions src/app/api/actions_distributed_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
3 changes: 3 additions & 0 deletions src/app/models/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
1 change: 1 addition & 0 deletions src/app/services/workflow_scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
32 changes: 31 additions & 1 deletion src/app/services/workflow_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import copy
import itertools
import logging
import math
import os
import re
import uuid
Expand Down Expand Up @@ -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:
Comment thread
fullsend-ai-coder[bot] marked this conversation as resolved.
Resolved
"""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", {})
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down
20 changes: 19 additions & 1 deletion tests/actions/test_dynamic_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}"}]
Expand Down Expand Up @@ -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
Expand Down
9 changes: 8 additions & 1 deletion tests/actions/test_runner_gh_host.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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"])
Expand All @@ -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
73 changes: 73 additions & 0 deletions tests/actions/test_runner_job_outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
39 changes: 39 additions & 0 deletions tests/test_database_migrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Loading