From a30ce384f68adc70e734f7fa44bbdd749a2a0f22 Mon Sep 17 00:00:00 2001 From: Roman Zaiev Date: Tue, 17 Nov 2026 11:21:38 +0000 Subject: [PATCH] Commit a handler's write with its job's completion A handler wrote to the application's tables in a transaction of its own, before the runner recorded the job complete in another, so a runner that died between the two ran the job again and wrote twice, and every application kept its writes idempotent by hand. handle_committing has the handler answer its write, which the runner makes in the transaction that completes the job, after the statement guarded by the lease: the job is completed and the write made together, or neither, and a runner whose lease was taken makes none. A write that fails rolls the completion back and is the attempt's failure. Saving results for spool to keep, and awaiting them, was weighed and left out: the application's own tables are where its results belong. --- AGENTS.md | 7 + CHANGES.md | 7 + docs/src/content/docs/guide/handlers.mdx | 25 +++- docs/src/content/docs/guide/limits.md | 5 - docs/src/content/docs/reference.md | 3 +- src/spool.ml | 67 ++++++++-- src/spool.mli | 21 +++ test/test_spool.ml | 156 +++++++++++++++++++++++ 8 files changed, 273 insertions(+), 18 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 406bd3d..0598fac 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -95,6 +95,13 @@ you broke it. Cite an entry by its bold phrase. machine's. Symptom: a pause or a limit read from `Runner.create`'s arguments; the suite pauses a queue and finds no runner claims from it, one made after the pause among them. +- **A handler's write is made with its job's completion, under its + lease.** `handle_committing`'s write runs in the transaction that + completes the job, after the statement guarded by the lease, and a write + that fails rolls the completion back, so a write is made once, by the + runner that finished the job. Symptom: a write made by a runner whose + lease was taken, or one left by a completion rolled back; `test_spool` + takes a lease from under a write, and fails and raises in one. - **A limit holds across runners, counted under the queue's lock.** A limited queue's claim takes the queue's advisory lock and counts what runs and what began in the rate's period before it claims, since a limit diff --git a/CHANGES.md b/CHANGES.md index 48587cd..25e7a71 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,12 @@ # Changes +## Unreleased + +- `Spool.handle_committing`: a handler answers a write to the + application's own tables, made in the transaction that completes its job + and only under its lease, so the job is completed and the write made + together, or neither; a write that fails is the attempt's failure. + ## 0.7.0 (2026-11-17) - A new package, `spool-dashboard`: a live dashboard for the queue, as diff --git a/docs/src/content/docs/guide/handlers.mdx b/docs/src/content/docs/guide/handlers.mdx index 6f30933..b2fd39d 100644 --- a/docs/src/content/docs/guide/handlers.mdx +++ b/docs/src/content/docs/guide/handlers.mdx @@ -35,8 +35,29 @@ carries it. `Spool.job` is the attempt a handler is running: its `id`, its `attempt`, counting from one, its `max_attempts` and its `inserted_at`. +## A write with the completion + +Where an attempt's work ends in a write to the application's own tables, +`Spool.handle_committing` makes it in the transaction that completes the +job. The handler does its work outside every transaction, as any does, and +answers the write: + +```ocaml +Spool.handle_committing invoice (fun _job order -> + let url = Pdf.render order in + Ok (fun conn -> Invoices.set_pdf conn order url)) +``` + +The job is completed and the write made together, or neither. The write +runs after the statement guarded by the lease, so a runner whose lease was +taken makes none. A write that answers a failure rolls both back and is +that failure -- retried, or discarded -- and one that raises is a retry +named by its constructor. Its connection is the runner's own, on the +database the runner was given, so the tables it writes are there. + ## At least once -What a job runs is at least once and finished once. A handler whose effect -must happen once is idempotent, or keyed by the job -- as the handler above +What a job runs is at least once and finished once. A write made with the +completion happens once; any other effect a handler has that must happen +once is idempotent, or keyed by the job -- as the handler above gives the mail service the job's id, so a receipt sent twice is one. diff --git a/docs/src/content/docs/guide/limits.md b/docs/src/content/docs/guide/limits.md index 44565c7..be63ebe 100644 --- a/docs/src/content/docs/guide/limits.md +++ b/docs/src/content/docs/guide/limits.md @@ -7,11 +7,6 @@ title: What it does not do yet job to the request that made it owed. - **A queue's counts are exported nowhere.** `counts` answers them, and nothing turns them into metrics. -- **A handler's own writes are not part of finishing its job.** A handler - writes to the application's tables in a transaction of its own, before - the runner records the job complete in another, so a runner that dies - between the two runs the job again: a handler's write is idempotent, - keyed by the job or by what it writes about. - **The dashboard needs a Spindle server.** `spool-dashboard` is routes of one, and nothing serves it without. - **A handler that never yields cannot be stopped.** A timeout, a lost lease diff --git a/docs/src/content/docs/reference.md b/docs/src/content/docs/reference.md index bf0c3a3..9e79cf2 100644 --- a/docs/src/content/docs/reference.md +++ b/docs/src/content/docs/reference.md @@ -23,7 +23,8 @@ OCaml code names it as a module (`Spool_dashboard`). - [`Spool`](/spool/reference/spool/Spool/index.html) -- the table, kinds, enqueueing, an operator's hand, and running: `table`, `statements`, `enqueue`, `enqueue_many`, `enqueue_after`, `find`, `workflow`, `counts`, - `jobs`, `cancel`, `retry`, `run_again`, `delete` and `handle`. Its + `jobs`, `cancel`, `retry`, `run_again`, `delete`, `handle` and + `handle_committing`. Its modules: - [`Spool.Kind`](/spool/reference/spool/Spool/Kind/index.html) -- a kind of job: its name, its payload's description, and how it is run. diff --git a/src/spool.ml b/src/spool.ml index 7b1776e..4598905 100644 --- a/src/spool.ml +++ b/src/spool.ml @@ -1618,10 +1618,20 @@ type failure = | Retry_in of Mtime.Span.t * string | Discard of string +(* What a handler's success may carry: a write made in the transaction that + completes its job. *) +type commit = Pg.conn -> (unit, failure) result + type handler = - | Handler : 'a Kind.t * (job -> 'a -> (unit, failure) result) -> handler + | Handler : + 'a Kind.t * (job -> 'a -> (commit option, failure) result) + -> handler + +let handle kind f = + Handler (kind, fun job a -> Result.map (fun () -> None) (f job a)) -let handle kind f = Handler (kind, f) +let handle_committing kind f = + Handler (kind, fun job a -> Result.map Option.some (f job a)) module Runner = struct type refused = @@ -1902,10 +1912,13 @@ module Runner = struct (* ---------------------------------------------------------------- *) (* One attempt *) - type outcome = Done | Failed of failure | Interrupted of interrupted + type outcome = + | Done of commit option + | Failed of failure + | Interrupted of interrupted let outcome_words = function - | Done -> "completed" + | Done _ -> "completed" | Failed (Retry r) -> "failed, to be retried: " ^ r | Failed (Retry_in (after, r)) -> Format.asprintf "failed, to be retried in %a: %s" Mtime.Span.pp after r @@ -1929,7 +1942,7 @@ module Runner = struct Eio.Time.Timeout.run (Eio.Time.Timeout.v t.clock kind.timeout) (fun () -> match f job a with - | Ok () -> Ok Done + | Ok commit -> Ok (Done commit) | Error failure -> Ok (Failed failure)) with | Ok o -> o @@ -1953,7 +1966,8 @@ module Runner = struct (* What the attempt came to, written by one statement guarded by the claim, and the state it left the job in; [None] where nothing was written. *) - let finish t (Handler (kind, _)) ~id ~attempt ~max_attempts ~took outcome = + let rec finish t (Handler (kind, _) as h) ~id ~attempt ~max_attempts ~took + outcome = let now = t.now () in let s = t.table.s in let run_us = Int64.unsigned_div (Mtime.Span.to_uint64_ns took) 1000L in @@ -1981,13 +1995,42 @@ module Runner = struct let* n = Pg.run c st args in after_written c counted n) in + (* The handler's write, made in the transaction that completes its job + once the statement guarded by the lease has changed the row, so a + runner whose lease was taken makes none; one that fails rolls the + completion back with it, and is the attempt's failure. *) + let committed commit c n = + match commit with + | Some write when n > 0 -> ( + match write c with + | Ok () -> Ok n + | Error failure -> Error (`Write failure) + | exception (Eio.Cancel.Cancelled _ as e) -> raise e + | exception e -> + let bt = Printexc.get_raw_backtrace () in + Log.err (fun m -> + m "%s job %d attempt %d's write raised %s\n%s" kind.name id + attempt (Printexc.to_string e) + (Printexc.raw_backtrace_to_string bt)); + Error (`Write (Retry (Printexc.exn_slot_name e ^ " raised")))) + | Some _ | None -> Ok n + in let written = match outcome with | Interrupted _ -> None - | Done -> + | Done commit -> Some ( (if kind.keep then - write Counted_completed s.complete (id, t.runner, attempt, now) + use t (fun c -> + let* () = + Pg.run c s.count_attempt + (id, t.runner, attempt, now, Counted_completed, run_us) + in + let* n = + Pg.run c s.complete (id, t.runner, attempt, now) + in + let* n = after_written c Counted_completed n in + committed commit c n) else use t (fun c -> let* () = @@ -2002,7 +2045,8 @@ module Runner = struct else Pg.run c s.complete_emptied (id, t.runner, attempt, now) in - after_written c Counted_completed n)), + let* n = after_written c Counted_completed n in + committed commit c n)), Completed ) | Failed (Discard reason) -> Some @@ -2051,7 +2095,10 @@ module Runner = struct m "%s; its lease was taken or the job cancelled, so nothing changed" (said ())); None - | Some (Error e, _) -> + | Some (Error (`Write failure), _) -> + (* Rolled back with its write: the attempt is that failure. *) + finish t h ~id ~attempt ~max_attempts ~took (Failed failure) + | Some (Error (#Pg.error as e), _) -> Log.warn (fun m -> m "%s, and not recorded: %s" (said ()) (words e)); None diff --git a/src/spool.mli b/src/spool.mli index 0ec188d..792cc58 100644 --- a/src/spool.mli +++ b/src/spool.mli @@ -484,6 +484,27 @@ type handler val handle : 'a Kind.t -> (job -> 'a -> (unit, failure) result) -> handler +val handle_committing : + 'a Kind.t -> + (job -> + 'a -> + (Rowtype_postgres.conn -> (unit, failure) result, failure) result) -> + handler +(** As {!handle}, for work that ends in a write to the application's own tables: + the handler does its work outside every transaction, as any does, and + answers the write, which the runner makes in the transaction that completes + the job -- after the statement guarded by the lease, so a runner whose lease + was taken makes no write. The job is completed and the write made together, + or neither: a write that answers a {!failure} rolls both back and is that + failure, and one that raises is a {!Retry} named by its constructor. Its + connection is the runner's own, on the database the runner was given. + + {[ + Spool.handle_committing receipt (fun _job order -> + let url = Pdf.render order in + Ok (fun conn -> Invoices.set_pdf conn order url)) + ]} *) + module Runner : sig type t diff --git a/test/test_spool.ml b/test/test_spool.ml index b12d7b9..51558b6 100644 --- a/test/test_spool.ml +++ b/test/test_spool.ml @@ -378,6 +378,151 @@ let test_a_raise_is_a_retry_named_by_its_constructor () = J.Runner.stop r | _ -> Alcotest.fail "one reason") +(* ------------------------------------------------------------------ *) +(* A handler's write, committed with its job's completion *) + +exception Write_raised of string + +(* The application's own table, a row a job written by its handler. *) +let with_written f = + with_table (fun target conn -> + Db_target.exec conn + "create table written (job text primary key, note text)"; + f target conn) + +let write_row = + Rowtype.exec + ~params:Rowtype.(t2 text text) + "insert into written (job, note) values ($1, $2)" + +let written conn = + ok "written" + (Pg.run conn + (Rowtype.find ~params:Rowtype.unit ~row:Rowtype.int + "select count(*)::int from written") + ()) + +(* The write a handler hands back: the row, then what [answer] says. *) +let write ?(answer = fun () -> Ok ()) (job : J.job) note conn = + match Pg.run conn write_row (J.Id.to_string job.id, note) with + | Error e -> Error (J.Retry (Rowtype.error_to_string e)) + | Ok () -> answer () + +let test_a_write_commits_with_the_completion () = + with_written (fun target conn -> + let now, _ = clock () in + let kind = text "note" in + let id = enqueue conn ~now:(now ()) kind "hello" in + let r = + runner ~now target + [ J.handle_committing kind (fun job note -> Ok (write job note)) ] + in + Alcotest.check outcomes "completed" [ (id, J.Completed) ] (drain r); + check_int "its row written" 1 (written conn); + J.Runner.stop r) + +let test_a_write_that_fails_rolls_back_and_is_the_failure () = + with_written (fun target conn -> + let now, _ = clock () in + let kind = text "note" in + let id = enqueue conn ~now:(now ()) kind "hello" in + let r = + runner ~now target + [ + J.handle_committing kind (fun job note -> + Ok + (write ~answer:(fun () -> Error (J.Retry "not yet")) job note)); + ] + in + Alcotest.check outcomes "retried" [ (id, J.Available) ] (drain r); + check_int "its row rolled back" 0 (written conn); + (match (find conn id).errors with + | [ f ] -> Alcotest.(check string) "the write's reason" "not yet" f.reason + | _ -> Alcotest.fail "one reason"); + J.Runner.stop r) + +let test_a_write_that_raises_rolls_back_and_is_retried () = + with_written (fun target conn -> + let now, _ = clock () in + let kind = text "note" in + let id = enqueue conn ~now:(now ()) kind "hello" in + let r = + runner ~now target + [ + J.handle_committing kind (fun job note -> + Ok + (write + ~answer:(fun () -> raise (Write_raised "a secret")) + job note)); + ] + in + Alcotest.check outcomes "retried" [ (id, J.Available) ] (drain r); + check_int "its row rolled back" 0 (written conn); + (match (find conn id).errors with + | [ f ] -> + check_bool "named by its constructor" true + (String.ends_with ~suffix:"Write_raised raised" f.reason) + | _ -> Alcotest.fail "one reason"); + J.Runner.stop r) + +let test_a_write_discards () = + with_written (fun target conn -> + let now, _ = clock () in + let kind = text "note" in + let id = enqueue conn ~now:(now ()) kind "hello" in + let r = + runner ~now target + [ + J.handle_committing kind (fun job note -> + Ok + (write + ~answer:(fun () -> Error (J.Discard "no such order")) + job note)); + ] + in + Alcotest.check outcomes "discarded" [ (id, J.Discarded) ] (drain r); + check_int "its row rolled back" 0 (written conn); + J.Runner.stop r) + +(* The lease taken while the handler worked: the finish changes nothing, so + its write is not made. *) +let test_a_write_is_not_made_without_the_lease () = + with_written (fun target conn -> + let now, _ = clock () in + let kind = text "note" in + let id = enqueue conn ~now:(now ()) kind "hello" in + let r = + runner ~now target + [ + J.handle_committing kind (fun job note -> + Db_target.exec conn + (Printf.sprintf + "update spool_jobs set runner = 'somebody else' where id \ + = %s" + (J.Id.to_string job.id)); + Ok (write job note)); + ] + in + ignore (drain r : (J.Id.t * J.state) list); + check_int "no row written" 0 (written conn); + Alcotest.check state "still the other's" J.Running (find conn id).state; + J.Runner.stop r) + +let test_a_kind_that_keeps_nothing_commits_its_write () = + with_written (fun target conn -> + let now, _ = clock () in + let kind = text ~keep:false "note" in + let id = enqueue conn ~now:(now ()) kind "hello" in + let r = + runner ~now target + [ J.handle_committing kind (fun job note -> Ok (write job note)) ] + in + Alcotest.check outcomes "completed" [ (id, J.Completed) ] (drain r); + check_int "its row written" 1 (written conn); + check_bool "the job gone" true + (Option.is_none (ok "find" (J.find conn id))); + J.Runner.stop r) + let test_a_timeout_is_a_failure () = with_table (fun target conn -> let now, _ = clock () in @@ -1815,6 +1960,17 @@ let () = test_discard_uses_no_attempt; Alcotest.test_case "a raise is a retry named by its constructor" `Quick test_a_raise_is_a_retry_named_by_its_constructor; + Alcotest.test_case "a write commits with the completion" `Quick + test_a_write_commits_with_the_completion; + Alcotest.test_case "a write that fails rolls back and is the failure" + `Quick test_a_write_that_fails_rolls_back_and_is_the_failure; + Alcotest.test_case "a write that raises rolls back and is retried" + `Quick test_a_write_that_raises_rolls_back_and_is_retried; + Alcotest.test_case "a write discards" `Quick test_a_write_discards; + Alcotest.test_case "a write is not made without the lease" `Quick + test_a_write_is_not_made_without_the_lease; + Alcotest.test_case "a kind that keeps nothing commits its write" + `Quick test_a_kind_that_keeps_nothing_commits_its_write; Alcotest.test_case "a timeout is a failure" `Quick test_a_timeout_is_a_failure; Alcotest.test_case "a payload that no longer decodes is discarded"