DEV Community

Cover image for Make Job Cancellation a Durable State Transition
SMTasker Team for SMTasker

Posted on

Make Job Cancellation a Durable State Transition

A worker has already claimed a report. An operator clicks Cancel. The worker finishes calculating a result a moment later.

What decides whether that result can become the saved result?

Checking a cancellation flag before calculation leaves a gap. The worker can pass that check, pause, and resume after cancellation has been accepted. Stopping the caller from waiting leaves the same gap in a different place.

This example makes cancellation a durable state transition. Once the cancellation transaction commits, the normal completion path can no longer publish a result for that run. The process may still be alive. An external request it already sent may still finish.

Give the command an exact run

The previous tutorial separated the stable job, an intentionally requested run, and the worker's claim generation. Cancellation needs that distinction too.

Use (job_id, run_id) as its target. If an old cancel request is retried after a new run starts, it must still address the old run. Resolving “the current run of this job” again during the retry would change the target.

The local fixture uses these transitions:

queued  -> running -> succeeded
   |          |
   +----------+----> cancelled
Enter fullscreen mode Exit fullscreen mode

succeeded and cancelled are terminal for this execution. A deliberate rerun is a separate row. The fixture's cancelled state means the run's normal completion path is closed. It is not evidence that the worker exited or a remote operation was reversed.

Put cancellation and completion behind the same database boundary

Cancellation changes only a queued or running row with the exact job and run IDs. It also clears the current ownership fields.

Completion must still match:

  • The exact job and run.
  • The running state.
  • The worker and generation from the originally issued claim.
  • An unexpired lease.

Those predicates are evaluated inside the completion write. A previous application-level read is not permission to skip them.

The two commands can race. The API needs to describe both possible results:

First transition to commit Later command observes Saved result
Cancellation Completion is refused None
Completion Cancellation returns succeeded, with changed=False Original completed result

The caller does not get a successful cancellation merely because it pressed Cancel first. In this fixture, the database's committed order determines which transition wins.

If cancellation commits but its response disappears, repeating the same job/run cancellation returns cancelled with changed=False. It does not start another execution, delete a completed result, or retarget a newer run.

Keep protocol cancellation separate

The MCP cancellation specification, revision 2026-07-28 describes transport-specific cancellation signals and races with completed requests. It also permits a server to ignore a cancellation notification when the request has completed or cannot be cancelled.

A request ID identifies a protocol exchange. The run ID below identifies a durable execution. An application that connects them needs an explicit mapping and authorization check; a disconnected client is not proof that a business job has been cancelled or rolled back.

This tutorial implements a local job-state contract, not an MCP transport or notification handler.

Run the complete fixture

Save the file as cancel_fence.py and run it with Python 3.12 or later:

python cancel_fence.py
Enter fullscreen mode Exit fullscreen mode

It uses the standard library, a deterministic test clock and temporary SQLite files. No queue, cloud account or external API is required. The test that creates run-2 is setup for the old-request case; the earlier article covers acceptance of intentional reruns.

The write methods use short BEGIN IMMEDIATE transactions. SQLite allows one writer at a time, so cancellation and completion serialize before inspecting and changing the row. The transaction can still fail because another writer is busy or a database error occurs; those errors propagate instead of becoming a successful cancellation. SQLite documents these transaction rules.

"""A durable local cancellation boundary. Python 3.12+, standard library.
Run: python cancel_fence.py
"""
from concurrent.futures import ThreadPoolExecutor
from contextlib import closing, contextmanager
from dataclasses import dataclass
from pathlib import Path
from threading import Barrier
import sqlite3
import tempfile
import unittest


@dataclass(frozen=True)
class Claim:
    job_id: str
    run_id: str
    owner: str
    generation: int


@dataclass(frozen=True)
class CancelResult:
    state: str
    changed: bool


class CompletionRefused(Exception):
    pass


class RunNotFound(Exception):
    pass


class Clock:
    def __init__(self, now=0):
        self.now = now

    def __call__(self):
        return self.now


def connect(path):
    db = sqlite3.connect(path, timeout=5, autocommit=True)
    db.row_factory = sqlite3.Row
    return db


def one(db, sql, args=()):
    with closing(db.execute(sql, args)) as cursor:
        return cursor.fetchone()


@contextmanager
def transaction(path):
    with closing(connect(path)) as db:
        try:
            db.execute('BEGIN IMMEDIATE').close()
            yield db
            db.execute('COMMIT').close()
        except BaseException:
            if db.in_transaction:
                db.execute('ROLLBACK').close()
            raise


def initialize(path):
    with closing(connect(path)) as db:
        db.executescript("""
        CREATE TABLE runs (
            job_id TEXT NOT NULL, run_id TEXT NOT NULL,
            state TEXT NOT NULL DEFAULT 'queued'
                CHECK (state IN ('queued', 'running', 'succeeded', 'cancelled')),
            generation INTEGER NOT NULL DEFAULT 0,
            owner TEXT, lease_until INTEGER, result TEXT,
            PRIMARY KEY (job_id, run_id)
        );
        INSERT INTO runs (job_id, run_id) VALUES ('report-1', 'run-1');
        """).close()


def claim_run(path, job_id, run_id, owner, clock, ttl=10):
    if type(ttl) is not int or ttl not in range(1, 3601):
        raise ValueError('TTL must be an integer in 1..3600')
    if not isinstance(owner, str) or not owner:
        raise ValueError('owner must be non-empty')
    with transaction(path) as db:
        now = clock()
        with closing(db.execute("""UPDATE runs
            SET state = 'running', owner = ?, lease_until = ?,
                generation = generation + 1
            WHERE job_id = ? AND run_id = ?
              AND (state = 'queued' OR
                  (state = 'running' AND lease_until <= ?))""",
                (owner, now + ttl, job_id, run_id, now))) as cursor:
            if cursor.rowcount != 1:
                return None
        generation = one(db, """SELECT generation FROM runs
            WHERE job_id = ? AND run_id = ?""", (job_id, run_id))[0]
        return Claim(job_id, run_id, owner, generation)


def cancel_run(path, job_id, run_id):
    """Cancel this execution only. Does not kill a process or undo an effect."""
    with transaction(path) as db:
        with closing(db.execute("""UPDATE runs
            SET state = 'cancelled', owner = NULL, lease_until = NULL
            WHERE job_id = ? AND run_id = ?
              AND state IN ('queued', 'running')""", (job_id, run_id))) as cursor:
            if cursor.rowcount == 1:
                return CancelResult('cancelled', True)
        row = one(db, 'SELECT state FROM runs WHERE job_id = ? AND run_id = ?',
                  (job_id, run_id))
        if row is None:
            raise RunNotFound((job_id, run_id))
        return CancelResult(row[0], False)


def complete_run(path, claim, result, clock):
    with transaction(path) as db:
        now = clock()
        with closing(db.execute("""UPDATE runs
            SET state = 'succeeded', result = ?, owner = NULL, lease_until = NULL
            WHERE job_id = ? AND run_id = ? AND state = 'running'
              AND owner = ? AND generation = ? AND lease_until > ?""",
                (result, claim.job_id, claim.run_id, claim.owner,
                 claim.generation, now))) as cursor:
            if cursor.rowcount != 1:
                raise CompletionRefused('claim expired, replaced or run terminal')
    return result


def snapshot(path):
    with closing(connect(path)) as db:
        with closing(db.execute('SELECT * FROM runs ORDER BY job_id, run_id')) as cur:
            return [dict(row) for row in cur.fetchall()]


class CancellationTests(unittest.TestCase):
    def setUp(self):
        base = Path(__file__).resolve().parent / 'test-db'
        base.mkdir(exist_ok=True)
        self.temp = tempfile.TemporaryDirectory(prefix='cancel-', dir=base)
        assert Path(self.temp.name).resolve().is_relative_to(base.resolve())
        self.addCleanup(self.temp.cleanup)
        self.path = Path(self.temp.name) / 'runs.sqlite'
        self.clock = Clock()
        initialize(self.path)

    def claim(self, owner='worker-a', run='run-1'):
        return claim_run(self.path, 'report-1', run, owner, self.clock)

    def cancel(self, run='run-1'):
        return cancel_run(self.path, 'report-1', run)

    def test_cancel_queued_run_prevents_claim(self):
        self.assertEqual(self.cancel(), CancelResult('cancelled', True))
        self.assertIsNone(self.claim())

    def test_running_worker_cannot_complete_after_cancel(self):
        token = self.claim()
        self.cancel()
        before = snapshot(self.path)
        with self.assertRaises(CompletionRefused):
            complete_run(self.path, token, 'late result', self.clock)
        self.assertEqual(snapshot(self.path), before)

    def test_completion_first_returns_succeeded_to_canceller(self):
        complete_run(self.path, self.claim(), 'saved', self.clock)
        before = snapshot(self.path)
        self.assertEqual(self.cancel(), CancelResult('succeeded', False))
        self.assertEqual(snapshot(self.path), before)

    def test_lost_cancel_response_can_be_retried(self):
        self.claim()
        self.cancel()  # Pretend acknowledgement was lost.
        before = snapshot(self.path)
        self.assertEqual(self.cancel(), CancelResult('cancelled', False))
        self.assertEqual(snapshot(self.path), before)

    def test_old_run_cancel_does_not_cancel_rerun(self):
        self.cancel()
        # Test setup only: the prior tutorial defines the rerun acceptance API.
        with closing(connect(self.path)) as db:
            db.execute("INSERT INTO runs (job_id, run_id) VALUES (?, ?)",
                       ('report-1', 'run-2')).close()
        newer = self.claim(run='run-2')
        before = snapshot(self.path)
        self.assertEqual(self.cancel(), CancelResult('cancelled', False))
        self.assertEqual(snapshot(self.path), before)
        complete_run(self.path, newer, 'new run result', self.clock)

    def test_wrong_job_cancellation_has_no_effect(self):
        before = snapshot(self.path)
        with self.assertRaises(RunNotFound):
            cancel_run(self.path, 'other-job', 'run-1')
        self.assertEqual(snapshot(self.path), before)

    def test_cancel_after_takeover_blocks_current_and_stale_workers(self):
        first = self.claim()
        self.clock.now = 10
        second = self.claim('worker-b')
        self.cancel()
        before = snapshot(self.path)
        for token in (first, second):
            with self.assertRaises(CompletionRefused):
                complete_run(self.path, token, 'late', self.clock)
        self.assertEqual(snapshot(self.path), before)

    def test_expiry_alone_is_not_cancelled_state(self):
        self.claim()
        self.clock.now = 10
        self.assertEqual(snapshot(self.path)[0]['state'], 'running')
        second = self.claim('worker-b')
        complete_run(self.path, second, 'taken over', self.clock)
        self.assertEqual(snapshot(self.path)[0]['state'], 'succeeded')

    def test_cancel_write_failure_is_not_reported_as_success(self):
        self.claim()
        with closing(connect(self.path)) as db:
            db.execute("""CREATE TRIGGER reject_cancel BEFORE UPDATE OF state ON runs
                WHEN NEW.state = 'cancelled'
                BEGIN SELECT RAISE(ABORT, 'injected failure'); END""").close()
        before = snapshot(self.path)
        with self.assertRaises(sqlite3.IntegrityError):
            self.cancel()
        self.assertEqual(snapshot(self.path), before)

    def race(self, functions):
        barrier = Barrier(2)
        def run(fn):
            barrier.wait(timeout=5)
            return fn()
        with ThreadPoolExecutor(max_workers=2) as pool:
            return list(pool.map(run, functions))

    def test_concurrent_cancellers_have_one_transition(self):
        self.claim()
        outcomes = self.race([self.cancel, self.cancel])
        self.assertEqual(sum(r.changed for r in outcomes), 1)
        self.assertTrue(all(r.state == 'cancelled' for r in outcomes))

    def test_cancel_completion_race_agrees_with_committed_state(self):
        token = self.claim()
        def complete():
            try:
                complete_run(self.path, token, 'saved', self.clock)
                return 'accepted'
            except CompletionRefused:
                return 'refused'
        cancelled, completed = self.race([self.cancel, complete])
        row = snapshot(self.path)[0]
        if row['state'] == 'cancelled':
            self.assertTrue(cancelled.changed)
            self.assertEqual(completed, 'refused')
            self.assertIsNone(row['result'])
        else:
            self.assertEqual(cancelled, CancelResult('succeeded', False))
            self.assertEqual(completed, 'accepted')
            self.assertEqual(row['result'], 'saved')

    def test_negative_control_an_unguarded_writer_revives_cancelled_run(self):
        self.claim()
        self.cancel()
        # Deliberately unsafe control. Never expose this as a completion path.
        with transaction(self.path) as db:
            db.execute("""UPDATE runs SET state = 'succeeded', result = ?
                WHERE job_id = ? AND run_id = ?""",
                ('late unsafe result', 'report-1', 'run-1')).close()
        self.assertEqual(snapshot(self.path)[0]['state'], 'succeeded')
        self.assertEqual(snapshot(self.path)[0]['result'], 'late unsafe result')


if __name__ == '__main__':
    unittest.main(verbosity=2)
Enter fullscreen mode Exit fullscreen mode

Test the refusal and the unchanged row

The local run passed 12 tests. The deterministic cases force cancellation first and completion first separately. A barrier-based test then releases a canceller and a completer on separate connections and checks that their responses agree with the committed row, whichever wins.

Other tests cover a queued run, repeated cancellation after a lost response, an expired claim, takeover, a wrong job, a newer run, and a failure injected into the cancellation write.

The deliberately unsafe control is useful: an ID-only completion changes a cancelled row back to succeeded. That demonstrates why storing cancellation is insufficient when another write path ignores it. The guarded path refuses the late completion and leaves the cancelled row unchanged.

What an accepted cancel still cannot promise

There are three different observations an interface might show:

  1. Cancellation requested: the request has been sent, but no durable decision has been confirmed.
  2. Cancellation accepted: the run is terminal in the database, and its normal completion path is closed.
  3. Worker stopped: the worker has acknowledged shutdown or its process termination has been observed.

This fixture establishes the second observation. It does not implement the third. A separate cooperative signal can help the worker release resources earlier, but that signal should not be the only protection against a late write.

The guarantee is limited to the guarded database path. An email, webhook or file write performed beforehand is outside that transaction. A reversal or compensation is another operation with its own identity, authorization and outcome. Do not translate “local completion refused” into “nothing happened elsewhere.”

Production code also needs authenticated tenant/resource authorization, controlled database write permissions, a defined retention window, refusal auditing, and a trusted clock. The plain claim object assumes a trusted worker; it is not a signed capability. This example adds no shutdown handler, lease renewal or external-effect reconciler, and it makes no claim about SMTasker's internal implementation.

Which result does your Cancel button confirm: a request sent, a durable state change, or a worker that has actually stopped? Leave a race or retry case in the comments. The example is meant to make that promise testable.

Top comments (0)