knaxuslearn · build · ship

Projects / Task queue / Phase 4

Phase 4 of 4 · about 2.5 hours

Stop, watch, and test it hard

You end with a worker that shuts down cleanly, a stats command, a chaos test, and a throughput number.

Step 4.1: Stop politely (about 30 minutes)

kill -9 is the emergency exit. Deploys use SIGTERM, which asks a process to stop and lets it clean up. Finish the job you hold, then quit. Replace worker.py:

import signal
import sys
import time

import taskq
from tasks import HANDLERS


def run(path, stop_when_empty=True, log=print):
    db = taskq.connect(path)
    stopping = False

    def request_stop(signum, frame):
        nonlocal stopping
        stopping = True
        log("stop requested, finishing the current job")

    signal.signal(signal.SIGTERM, request_stop)
    signal.signal(signal.SIGINT, request_stop)

    done = 0
    while not stopping:
        job = taskq.claim(db)
        if job is None:
            waiting = db.execute(
                "SELECT COUNT(*) FROM jobs WHERE state IN ('queued', 'running')"
            ).fetchone()[0]
            if stop_when_empty and waiting == 0:
                break
            time.sleep(0.05)
            continue
        try:
            HANDLERS[job["name"]](**job["payload"])
        except Exception as exc:
            outcome = taskq.fail(db, job, f"{type(exc).__name__}: {exc}")
            log(f"job {job['id']} {job['name']} failed on attempt {job['attempts']}: {outcome}")
        else:
            if taskq.finish(db, job):
                done += 1
            else:
                log(f"job {job['id']} finished too late, another worker owns it now")
    return done


if __name__ == "__main__":
    forever = "--forever" in sys.argv
    print("jobs done:", run(sys.argv[1], stop_when_empty=not forever), flush=True)

signal.signal registers request_stop, which only sets a flag. The loop checks the flag before claiming the next job, so the current job always completes. (Python runs signal handlers in the main thread between bytecode steps, so the handler is safe to write this simply.) --forever keeps the worker polling when the queue is empty, as a real worker would. Add the record handler used later to tasks.py:

def record(path, n, seconds=0.0):
    """Do some work, then leave a mark so a test can count how often it ran."""
    time.sleep(seconds)
    db = sqlite3.connect(path, timeout=30, isolation_level=None)
    db.execute("CREATE TABLE IF NOT EXISTS effects (n INTEGER)")
    db.execute("INSERT INTO effects VALUES (?)", (n,))
    db.close()


HANDLERS = {
    "add": add,
    "slow": slow,
    "flaky": flaky,
    "always_fails": always_fails,
    "record": record,
}

Run try_sigterm.py: five 1-second jobs, and a SIGTERM after 1.5 seconds.

import os
import signal
import subprocess
import sys
import time

import taskq

path = "term.db"
for suffix in ("", "-wal", "-shm"):
    if os.path.exists(path + suffix):
        os.remove(path + suffix)
db = taskq.connect(path)
for n in range(5):
    taskq.enqueue(db, "slow", seconds=1)

worker = subprocess.Popen(
    [sys.executable, "-u", "worker.py", path, "--forever"], stdout=subprocess.PIPE, text=True
)
time.sleep(1.5)  # one job is done, the second is in progress
worker.send_signal(signal.SIGTERM)
print("worker output:", worker.communicate()[0].strip().replace("\n", " | "))
print(db.execute("SELECT state, COUNT(*) FROM jobs GROUP BY state ORDER BY state").fetchall())
worker output: stop requested, finishing the current job | jobs done: 2
[('done', 2), ('queued', 3)]

The worker finished its second job, which was in progress, then exited. Three jobs stayed queued for the next worker. Nothing was cut in half.

Step 4.2: A stats command (about 40 minutes)

Operators need to see a queue without writing SQL. Add stats at the bottom of taskq.py:

def stats(db):
    rows = db.execute("SELECT state, COUNT(*) FROM jobs GROUP BY state").fetchall()
    counts = {"queued": 0, "running": 0, "done": 0, "dead": 0}
    counts.update(dict(rows))
    oldest = db.execute(
        "SELECT MIN(run_at) FROM jobs WHERE state = 'queued' AND run_at <= ?", (time.time(),)
    ).fetchone()[0]
    counts["oldest_ready_wait"] = 0.0 if oldest is None else round(time.time() - oldest, 1)
    return counts


if __name__ == "__main__":
    import sys

    db = connect(sys.argv[1])
    for key, value in stats(db).items():
        print(f"{key:18} {value}")

oldest_ready_wait is how long the oldest job has been ready and waiting. If it keeps growing, you need more workers. try_stats.py builds a small queue (one done, one running, three queued, one of those delayed by a minute):

import os

import taskq

path = "stats.db"
for suffix in ("", "-wal", "-shm"):
    if os.path.exists(path + suffix):
        os.remove(path + suffix)
db = taskq.connect(path)
for n in range(4):
    taskq.enqueue(db, "add", a=n, b=n)
taskq.enqueue(db, "add", delay=60, a=0, b=0)
done = taskq.claim(db)
taskq.finish(db, done)
taskq.claim(db)
python3 try_stats.py
python3 taskq.py stats.db
queued             3
running            1
done               1
dead               0
oldest_ready_wait  0.0

Three jobs are queued including the delayed one, and the waiting time is 0.0 because the jobs were just created.

Step 4.3: The chaos test (about 40 minutes)

Our claim: every job eventually runs, whatever happens to the workers. Let's test the claim by being cruel. try_chaos.py queues 200 record jobs (each leaves a mark in an effects table), runs 4 workers, and every 0.4 seconds kills one with kill -9 and starts a replacement. The lease is 1 second.

import os
import random
import signal
import subprocess
import sys
import time

import taskq

JOBS, WORKERS = 200, 4
path = "chaos.db"
for suffix in ("", "-wal", "-shm"):
    if os.path.exists(path + suffix):
        os.remove(path + suffix)
db = taskq.connect(path)
db.execute("BEGIN")
for n in range(JOBS):
    taskq.enqueue(db, "record", path=path, n=n, seconds=0.05, max_attempts=10)
db.execute("COMMIT")

random.seed(7)
env = dict(os.environ, TASKQ_LEASE="1")
spawn = lambda: subprocess.Popen(
    [sys.executable, "worker.py", path, "--forever"], env=env, stdout=subprocess.DEVNULL
)
workers = [spawn() for _ in range(WORKERS)]
kills, start = 0, time.time()

while time.time() - start < 60:
    time.sleep(0.4)
    counts = taskq.stats(db)
    if counts["done"] + counts["dead"] == JOBS:
        break
    victim = random.randrange(WORKERS)
    workers[victim].send_signal(signal.SIGKILL)
    workers[victim].wait()
    workers[victim] = spawn()
    kills += 1

for w in workers:
    w.send_signal(signal.SIGTERM)
    w.wait()

counts = taskq.stats(db)
runs = db.execute("SELECT n, COUNT(*) FROM effects GROUP BY n").fetchall()
print(f"workers killed with kill -9: {kills}")
print(f"states: done={counts['done']} dead={counts['dead']} queued={counts['queued']} running={counts['running']}")
print(f"jobs that ran at least once: {len(runs)} of {JOBS}")
print(f"jobs that ran more than once: {sum(1 for _, c in runs if c > 1)}")
workers killed with kill -9: 8
states: done=200 dead=0 queued=0 running=0
jobs that ran at least once: 200 of 200
jobs that ran more than once: 0

All 200 jobs finished, none dead, despite the kills. The line to read is "ran at least once: 200 of 200". The last line counts jobs that ran more than once; it may be zero or not on your machine, because it depends on whether a kill landed between a job's work and its finish. A non-zero number is not a bug. It is the "at least once" promise showing up.

What this test does not prove: it models a killed process on one machine with a working disk. It does not model a power cut that corrupts the disk, a full disk, or a clock that jumps (leases use wall-clock time).

Step 4.4: How fast, and where it stops (about 40 minutes)

Last, a number. try_speed.py runs 5,000 trivial jobs through 4 worker processes:

import multiprocessing as mp
import os
import time

import taskq
import worker

JOBS, WORKERS = 5000, 4
path = "speed.db"
for suffix in ("", "-wal", "-shm"):
    if os.path.exists(path + suffix):
        os.remove(path + suffix)
db = taskq.connect(path)
db.execute("BEGIN")
for n in range(JOBS):
    taskq.enqueue(db, "add", a=n, b=1)
db.execute("COMMIT")

start = time.perf_counter()
procs = [mp.Process(target=worker.run, args=(path,)) for _ in range(WORKERS)]
for p in procs:
    p.start()
for p in procs:
    p.join()
took = time.perf_counter() - start
print(f"{JOBS} jobs, {WORKERS} workers: {took:.2f}s, about {JOBS / took:,.0f} jobs a second")
print(taskq.stats(db))
5000 jobs, 4 workers: 3.45s, about 1,449 jobs a second
{'queued': 0, 'running': 0, 'done': 5000, 'dead': 0, 'oldest_ready_wait': 0.0}

About a thousand jobs a second here, with trivial jobs. Two things limit it: each claim and each finish is its own write, and SQLite allows one writer at a time. For emails, thumbnails and nightly reports, that is plenty. For tens of thousands of jobs a second, you need a different design.

You can also run the pieces by hand, in two terminals. Terminal one:

python3 worker.py jobs.db --forever

Terminal two:

import taskq
db = taskq.connect("jobs.db")
taskq.enqueue(db, "add", a=2, b=3)

Phase 4 done

You wrote a queue of about 110 lines plus a worker of about 40, and checked it with kills, signals and a stress test. This is the core of what libraries like Celery, RQ and Sidekiq do, with a smaller feature set.