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
3 changes: 3 additions & 0 deletions PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ Actions visibility and runner evaluation.

## Completed Tasks

- `docs/tasks/done/runner-broker-protocol-and-state.md`
- `docs/tasks/done/ref-write-ordering-and-push-replay.md`
- `docs/tasks/done/graphql-review-threads-and-minimize.md`
- `docs/tasks/done/graphql-update-refs.md`
Expand Down Expand Up @@ -196,6 +197,7 @@ Actions visibility and runner evaluation.
- `docs/bugs/fixed/ci-stack-tls-ca-rejected-by-python-3-13.md`
- `docs/bugs/fixed/ci-stack-start-gives-up-after-30-seconds.md`
- `docs/bugs/fixed/cross-fork-compare-commit-urls-name-the-base-repository.md`
- `docs/bugs/fixed/cancellation-lost-after-a-broker-restart.md`
- `docs/bugs/fixed/one-runner-claims-two-jobs.md`

## Decisions
Expand All @@ -204,6 +206,7 @@ Actions visibility and runner evaluation.
- `docs/decisions/ADR-0002-artifact-storage-on-disk.md`
- `docs/decisions/ADR-0003-org-memberships-are-active-on-add.md`
- `docs/decisions/ADR-0004-actions-results-service-for-artifacts.md`
- `docs/decisions/ADR-0005-runner-broker-state-in-one-process.md`

## CC-43

Expand Down
44 changes: 44 additions & 0 deletions alembic/versions/0023_runner_held_job_id.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"""Keep the job most recently handed to each runner.

The runner broker rebuilds a busy runner's hold after a restart. Which job a
runner holds could not be told from the database alone: a finished job keeps
its runner and cancelled conclusion, and job ids reflect creation order, not
hand-out order. The claim now records the job on the runner. NULL means none
recorded; existing runners keep it.

Revision ID: 0023_runner_held_job_id
Revises: 0022_workflow_job_timeout_minutes
Create Date: 2026-12-04
"""

import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect

revision = "0023_runner_held_job_id"
down_revision = "0022_workflow_job_timeout_minutes"
branch_labels = None
depends_on = None

_TABLE = "runners"
_COLUMN = "held_job_id"


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)
53 changes: 53 additions & 0 deletions docs/bugs/fixed/cancellation-lost-after-a-broker-restart.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Bug: a cancellation is lost after a broker restart

Status: fixed 2026-12-03.

## Summary

The runner broker keeps the job each runner holds in process memory
(`_holding`). An emulator restart forgets it while the runners keep running
their jobs. Two cancellations were then never sent:

- **A handed-out job cancelled after the restart.** The runner had not yet
polled as `Busy`. A cancelled job is no longer in progress, so the
runner's next `Online` poll found nothing in progress and marked it idle.
The cancellation check sends only to a busy runner.
- **A job deleted with its repository after the restart.** Nothing in the
database linked the runner to the deleted job, so there was nothing to
send a cancellation for.

Found in the review of #29 (#72).

## Fix

On a busy runner's poll, with no job held in memory, the broker rebuilds the
hold (`_restore_hold`), before the poll settles the runner or looks for a
cancellation:

- the job the claim last handed the runner, recorded in
`runners.held_job_id` (migration 0023), whether or not it still exists.
Neither the database's jobs nor their ids give that: a finished job keeps
its runner and cancelled conclusion, and ids follow creation order, not
hand-out order;
- for a runner busy from before the column existed, its newest job still in
progress or cancelled.

The hold then keeps the runner busy until it acknowledges the cancellation,
as it does without a restart. The decision to keep the broker state in
memory, in one process, is
[ADR-0005](../../decisions/ADR-0005-runner-broker-state-in-one-process.md).

Tests: `tests/actions/test_runner_broker_restart.py`.

- After a restart, an `Online` poll keeps the cancellation of a handed-out
job, and frees the runner once it is acknowledged.
- After a restart, the cancellation of a job deleted with its repository is
sent, to an `Online` or a `Busy` poll.
- After a restart, a runner still running its job stays busy and holds it.
- After a restart, an idle runner whose last message names a deleted job
holds nothing.
- After a restart, a deleted held job is not masked by an older cancelled
job, whichever of the two has the higher id, to an `Online` or a `Busy`
poll.
- After a restart, a runner with no recorded job holds its newest cancelled
job.
64 changes: 64 additions & 0 deletions docs/decisions/ADR-0005-runner-broker-state-in-one-process.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# ADR-0005: Keep the runner broker's state in one process

## Status

Accepted

## Context

The runner broker (`src/app/api/actions_distributed_task.py`) keeps four
maps in process memory: `_holding`, `_poll_generation`, `_acknowledged` and
`_cancellation_acknowledged`. It also keeps the per-runner locks that
serialise a runner's polls, acknowledgements and reports. The
[runner broker protocol](../guides/runner-broker-protocol.md) describes
each one. This state is lost on a restart and is not shared between worker
processes.

Two failures followed from the restart:

- A runner handed a job before the restart, which had not yet polled as
`Busy`, was marked idle by an `Online` poll once its job was cancelled.
- A job deleted with its repository left nothing to send a cancellation
for.

In both cases the cancellation never reached the runner.

Two alternatives were raised in #72:

- **Persist the state.** That means new columns or a table, and a
migration. It also means a database write for every poll and every
acknowledgement. Under SQLite every write waits on the one write lock that
pushes, dispatch and job reports also take. The locks could still not be
shared through the database without a different locking design.
- **Refuse multi-worker use at startup.** uvicorn does not tell the
application how many workers it started, so the check could only read
`WEB_CONCURRENCY`. That misses `uvicorn --workers` and other process
managers, and a partial guard reads as a guarantee it does not give.

## Decision

- **One process.** The broker runs in a single process. The shipped images
(supervisord) and `Procfile.dev` start one uvicorn process. The runner
broker protocol guide states that running more than one worker is
unsupported.
- **Rebuild after a restart.** The state stays in memory. A busy runner's
hold is rebuilt on its first poll after a restart, from
`runners.held_job_id`, which the job claim writes. That is one extra
column in a write the claim already makes, not a write per poll. Job ids
and the database's finished jobs cannot say which job a runner was handed
last. Its cancellation is therefore still sent, even for a job deleted
with its repository.
- **Acknowledgements are not rebuilt.** A runner may get a cancellation
once more after a restart, and ignores it if it no longer runs that job.

## Consequences

- **Horizontal scaling is out.** The emulator cannot be scaled to more than
one worker process. It is a single-instance test emulator, so this costs
nothing today.
- **Regression tests.** `tests/actions/test_runner_broker_restart.py`
resets the broker state between a hand-out and a cancellation, and checks
that the cancellation is still delivered.
- **Revisit when scaling.** If more than one worker is ever needed, revisit
this decision: persist the hold and the acknowledgements, and replace the
in-memory locks.
1 change: 1 addition & 0 deletions docs/guides/actions-runners.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,4 +189,5 @@ the others in your shell, or add them to `.env` after the last

- [ADR-0001: Prefer real runner compatibility for Actions](../decisions/ADR-0001-actions-runner-strategy.md)
- [ADR-0004: Actions results service for artifacts](../decisions/ADR-0004-actions-results-service-for-artifacts.md)
- [Runner broker protocol](runner-broker-protocol.md): the broker's protocol additions and its in-memory state.
- [Configuration](configuration.md) for the emulator-side Actions settings.
136 changes: 136 additions & 0 deletions docs/guides/runner-broker-protocol.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
# Runner Broker Protocol

The broker is the part of the emulator that the upstream `actions/runner`
talks to: the session long poll, message deletion, and job reports. It lives
in `src/app/api/actions_distributed_task.py`. This page records where the
broker goes beyond the documented GitHub protocol, and what state it keeps
in memory. Runner setup is in [Actions runners](actions-runners.md).

The message contracts on this page are checked against the upstream runner
version that CI runs (`2.338.2`, the default in `scripts/ci-stack.sh`) by
`tests/actions/test_runner_protocol_upstream_contract.py`. The test reads
the contracts from `tests/fixtures/upstream_runner_contracts.json`. When
you change the pinned version, re-check that file against the new tag.

## Long poll

`GET .../_apis/distributedtask/pools/{pool}/sessions/{session}/messages`
(and its `.../pools/{pool}/messages?sessionId=` form) waits up to 30 s for
a message. Without one it answers `204`. The runner sends
`status=Online|Busy` and `lastMessageId`, the id of the last message it
received, on every poll.

- **Message envelope.** Every message is a `TaskAgentMessage`:
`messageId` (an `Int64`), `messageType` and `body` (a JSON string). Each
key is sent in both camelCase and PascalCase.
- **Job message.** `messageType` is `PipelineAgentJobRequest`. Its
`messageId` is the job id.
- **A Busy poll gets cancellations only.** A runner polling as `Busy`
never gets a job.
- **Only the newest poll hands out a job.** The runner abandons a poll
whenever its status changes, and the server keeps running the abandoned
one. An older poll answers `204`, and a job it had claimed goes back to
the queue.
- **An Online poll from a busy runner is believed with care.**
- A job the runner never received goes back to the queue. That is a job
its `lastMessageId` does not name, unacknowledged for 5 s.
- A job it received and still holds after a 2 minute grace period fails.
- Either way the runner is freed.

## Cancellation message

When the job a runner holds is cancelled, the next poll answers with a
`JobCancellation` message, the shape of the runner's `JobCancelMessage`.
These cancel a held job:

- a newer job superseding it under `concurrency: cancel-in-progress`;
- a run cancelled through the API;
- deleting the job's repository, which deletes the job.

```json
{
"messageId": 1099511627777,
"messageType": "JobCancellation",
"body": "{\"jobId\":\"<job guid>\",\"timeout\":\"00:05:00\"}"
}
```

- **Message id.** The id is `(1 << 40) + job_id`, a range apart from job
message ids, so deleting one is not taken for deleting the other.
- **`timeout`.** How long the job's steps get to stop before the runner
kills them.
- **Sent until deleted.** The broker sends the cancellation again on every
live poll, `Busy` or `Online`, until the runner deletes it with
`DELETE .../pools/{pool}/messages/{messageId}`.
- **Message deletion.** A `DELETE` with an id at or above `1 << 40`
acknowledges the cancellation of job `messageId - (1 << 40)`. A lower id
acknowledges the job message, if it names the job the runner holds.
- **The runner stays busy.** A runner whose held job was cancelled within
the grace period is not freed by an `Online` poll before it acknowledges
the cancellation.

## Job reports

The runner reports a job's end through the job request routes:
`PATCH` or `DELETE .../pools/{pool}/jobrequests/{id}`. It reads a job
request back with `GET` and `POST` on the same path.

- **A job the runner no longer holds.** The job went back to the queue,
another runner took it, or it no longer exists. These routes answer
`404` with a wrapped exception whose `typeKey` is
`TaskAgentJobNotFoundException`. The runner stops renewing a job on that
exception, and keeps retrying on a bare `404`. The older
`POST .../jobs/{id}/complete` route answers a plain `404`.
- **A cancelled job stays cancelled.** A job keeps its first end, so a job
cancelled while it ran keeps `conclusion=cancelled` when its runner
reports the end.
- **The report frees the runner,** unless the runner has taken another job
since.

## Runner deletion

- **A runner deleting itself succeeds.** That is the pool agent route,
`DELETE .../pools/{pool}/agents/{id}` (used by `config.sh remove`), or a
pipelines route, `DELETE /_services/pipelines/.../_apis/pipelines/runs/{id}`.
The jobs the runner was still running fail, and the runner's job history
is detached from it.
- **The REST deletes refuse a busy runner.**
`DELETE /repos/{owner}/{repo}/actions/runners/{id}`,
`DELETE /enterprises/{enterprise}/actions/runners/{id}` and the admin UI
answer `422` while the runner is running a job.

## In-memory state and the single process

The broker keeps four maps in process memory:

| State | Holds |
|---|---|
| `_holding` | The job each runner was last handed. |
| `_poll_generation` | Each runner's newest poll. |
| `_acknowledged` | The job message each runner last deleted. |
| `_cancellation_acknowledged` | The job whose cancellation each runner last deleted. |

The per-runner locks that serialise polls, acknowledgements and reports are
in memory too. **The broker therefore needs a single process.** Do not run
the emulator with more than one worker (`uvicorn --workers`,
`WEB_CONCURRENCY`). Each worker would keep its own maps and locks, so
workers would hand out jobs and decide cancellations without seeing one
another. The shipped images and `Procfile.dev` start one uvicorn process.
See [ADR-0005](../decisions/ADR-0005-runner-broker-state-in-one-process.md)
for why the state is not persisted.

A restart empties the maps while the runners keep running their jobs. On the
next poll from a runner that the database records as busy, the broker
rebuilds the runner's hold from `runners.held_job_id`, the job the claim
last handed it. The job need not still exist: a job deleted with its
repository is still held, and its cancellation is sent. The database's jobs
cannot say which job a runner holds. A finished job keeps its runner and its
cancelled conclusion, and job ids follow creation order, not hand-out order,
so a runner can be handed a job with a lower id than its previous one. A
runner that was busy before the column existed has none recorded; its newest
job still in progress or cancelled stands in until its next hand-out.

The runner then still gets the cancellation of the job it holds. The
acknowledgements are not rebuilt: after a restart a runner may get a
cancellation once more, which it ignores if it no longer runs that job.
`tests/actions/test_runner_broker_restart.py` covers these cases.
44 changes: 44 additions & 0 deletions docs/tasks/done/runner-broker-protocol-and-state.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Document the runner broker's protocol additions and in-memory state

## Goal

Record the broker behaviour the runner lifecycle work (#29) added, check its
messages against a pinned upstream runner, and make the in-memory broker
state's limits explicit (#72).

## Implementation

- `docs/guides/runner-broker-protocol.md` covers the following:
- the `JobCancellation` message and its `(1 << 40) + job_id` id range;
- re-sending a cancellation until the runner deletes it;
- the `TaskAgentJobNotFoundException` `404`;
- a cancelled job keeping `conclusion=cancelled`;
- self-delete versus REST delete of a busy runner;
- the in-memory state, and the single-process requirement.
- `tests/fixtures/upstream_runner_contracts.json` records, from the
`actions/runner` sources at `v2.338.2` (the CI stack's pinned version):
- the `TaskAgentMessage`, `JobCancelMessage` and `WrappedException`
contracts;
- the `TaskAgentJobNotFoundException` mapping.
- `tests/actions/test_runner_protocol_upstream_contract.py` covers the
following:
- it parses the broker's job message, cancellation and `404` body into
those contracts, as Newtonsoft reads them;
- it fails when the CI stack's pinned runner version moves away from the
fixture's.
- [ADR-0005](../../decisions/ADR-0005-runner-broker-state-in-one-process.md)
keeps the state in memory, in one process, rather than persisting it or
refusing multi-worker use at startup.
- The two restart cases were bugs:
[cancellation-lost-after-a-broker-restart](../../bugs/fixed/cancellation-lost-after-a-broker-restart.md).
A busy runner's hold is now rebuilt on its first poll after a restart.

## Verification

- `uv run pytest tests/actions/test_runner_broker_restart.py`:
- 4 of 5 failed before the fix;
- all 5 pass after it.
- `uv run pytest tests/actions/test_runner_protocol_upstream_contract.py`:
5 passed.
- Runner broker suites: `tests/actions/test_runner_*.py` and
`tests/actions/test_job_claim_race.py`.
2 changes: 1 addition & 1 deletion src/app/api/actions_dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -559,7 +559,7 @@ async def _claim_queued_job(db, job: WorkflowJob, runner: Runner) -> bool | None
WorkflowJob.id != job.id,
),
)
.values(busy=True, status="busy")
.values(busy=True, status="busy", held_job_id=job.id)
.execution_options(synchronize_session=False)
)
if reserved.rowcount != 1:
Expand Down
Loading
Loading