Fix the Worker That Drops Its Task on Shutdown
Every deploy loses a few tasks. The rolling update sends each worker a stop signal, and the worker exits on the spot, with a task half done and nowhere. Fix worker_loop(queue, term_at, grace).
queue has pop() (the head, or None when empty), push_front(task) and items. A task is {"id", "duration"}. The stop signal arrives at tick term_at; grace is how many ticks the worker has after it before it is killed.
Return the event log, a list of tuples:
- Before taking a task, if
now >= term_at, the worker takes nothing more and logs("exit", now). - Taking a task logs
("start", id, now); it ends atnow + durationand logs("done", id, end). - If the signal arrives while a task is running (
term_at < end): the task finishes whenend <= term_at + grace, then the worker exits atend. Otherwise, atterm_at + grace, the task goes back to the front of the queue, logged("requeue", id, term_at + grace), and the worker exits then. - An empty queue means exit at once.
Nothing is lost: after the loop, every task is either done once or back on the queue. This is what SIGTERM, terminationGracePeriodSeconds and a queue with redelivery add up to; the fix is in the worker, which has to stop taking work before it stops working.