@zukhruf/pool 0.8.44 → 0.8.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @zukhruf/pool
2
2
 
3
- Lends long-lived workers to jobs, one job for each worker at a time. A worker is costly to start: a native helper that loads a model, or a command-line agent that keeps a session. The pool starts workers, lends them, replaces a worker that exits, and stops all of them when you dispose it. You choose three things from standard classes: when the workers start (a startup), how many run (a sizing), and when an idle worker closes (an eviction).
3
+ One pool of long-lived workers for each computer. A worker is costly to start: a native helper that loads a model, or a command-line agent that keeps a session. Every program that needs a worker sends its jobs to one store on the computer, and one of them, the owner, runs the jobs on its workers. The owner starts the workers, lends each one to one job at a time, replaces a worker that exits, and closes an idle worker. You choose three things from standard classes: when the workers start (a startup), how many run (a sizing), and when an idle worker closes (an eviction).
4
4
 
5
5
  The words in these documents have one meaning each. See the glossary in [CONTEXT.md](./CONTEXT.md).
6
6
 
@@ -11,7 +11,27 @@ npm install @zukhruf/pool
11
11
  ```
12
12
 
13
13
  ```ts
14
- import { Fixed, NoEviction, Parallel, Pool, type Worker } from '@zukhruf/pool';
14
+ import { mkdtempDisposable } from 'node:fs/promises';
15
+ import { tmpdir } from 'node:os';
16
+ import { join } from 'node:path';
17
+
18
+ import {
19
+ Fixed,
20
+ NoEviction,
21
+ Parallel,
22
+ Pool,
23
+ PoolWorkers,
24
+ type Worker,
25
+ WorkerKind,
26
+ } from '@zukhruf/pool';
27
+
28
+ const upper = new WorkerKind<string, string>({
29
+ name: 'upper',
30
+ revision: 1,
31
+ policy: 'standard',
32
+ retryLimit: 0,
33
+ expireInSeconds: 60,
34
+ });
15
35
 
16
36
  class Upper implements Worker<string, string> {
17
37
  readonly #exit = Promise.withResolvers<void>();
@@ -25,48 +45,121 @@ class Upper implements Worker<string, string> {
25
45
  this.#exit.resolve();
26
46
  }
27
47
  async close(): Promise<void> {
28
- await this.#exit.promise;
48
+ this.#exit.resolve();
29
49
  }
30
50
  }
31
51
 
32
- await using pool = new Pool({
52
+ // A store of its own; a host of the computer gives computerStore(process.env).
53
+ await using folder = await mkdtempDisposable(join(tmpdir(), 'pool-'));
54
+ const store = join(folder.path, 'store.sqlite');
55
+
56
+ await using workers = new PoolWorkers({
57
+ kind: upper,
58
+ store,
59
+ clock: globalThis,
33
60
  size: new Fixed(2),
34
61
  startup: new Parallel(),
35
62
  eviction: new NoEviction(),
36
- clock: globalThis,
37
63
  create: () => new Upper(),
38
64
  });
65
+ await using pool = new Pool({ kind: upper, store, clock: globalThis });
66
+
39
67
  const words = await Promise.all(
40
- ['one', 'two', 'three'].map((word) => pool.use((worker) => worker.run(word))),
68
+ ['one', 'two', 'three'].map((word) => pool.run(word)),
41
69
  );
42
- console.log(words, pool.stats);
70
+ await workers.ready();
71
+ console.log(words, workers.stats);
43
72
  // [ 'ONE', 'TWO', 'THREE' ] { starting: 0, idle: 2, lent: 0, waiting: 0 }
44
73
  ```
45
74
 
46
- The pool starts two workers and lends them to three jobs, one job for each worker at a time. After the jobs, both workers are idle. The disposal at the end of the program stops them.
75
+ The program offers two workers, owns them, and sends three jobs. The owner runs the jobs on its workers, one job for each worker at a time. After the jobs, both workers are idle. The disposals at the end of the program stop sending, hand the workers over, and close them.
76
+
77
+ ## Define the worker kind
47
78
 
48
- ## Lend a worker to a job
79
+ A worker kind names the pool and holds its job rules. Export it from a module with no native code, so a host that cannot run the worker program can import it too:
49
80
 
50
81
  ```ts
51
- import { Fixed, IdleTimeout, Parallel, Pool } from '@zukhruf/pool';
82
+ import { WorkerKind } from '@zukhruf/pool';
52
83
 
53
- await using pool = new Pool({
54
- size: new Fixed(2),
55
- startup: new Parallel(),
56
- eviction: new IdleTimeout({ after: 300_000 }),
84
+ export const vision = new WorkerKind<{ path: string }, { text: string }>({
85
+ name: 'vision',
86
+ revision: 1, // raise it when run changes in a way that matters
87
+ policy: 'exclusive', // identical inputs share one job
88
+ retryLimit: 2,
89
+ expireInSeconds: 120,
90
+ });
91
+ ```
92
+
93
+ The rule names are pg-boss's queue options, with pg-boss's meaning. Each one is required. See [ADR 0014](./docs/adr/0014-pool-and-pool-workers-take-one-worker-kind.md).
94
+
95
+ ## Send jobs, and offer workers
96
+
97
+ A host that can run the worker program sends jobs and offers its workers:
98
+
99
+ ```ts
100
+ import { availableParallelism } from 'node:os';
101
+
102
+ import {
103
+ HillClimbing,
104
+ IdleTimeout,
105
+ LeaderFirst,
106
+ Pool,
107
+ PoolWorkers,
108
+ computerStore,
109
+ } from '@zukhruf/pool';
110
+
111
+ const store = computerStore(process.env);
112
+ const { availableMemory } = process;
113
+
114
+ await using ocr = new Pool({ kind: vision, store, clock: globalThis });
115
+ await using workers = new PoolWorkers({
116
+ kind: vision,
117
+ store,
57
118
  clock: globalThis,
58
119
  create: () => new VisionWorker('/path/to/vision-worker'),
120
+ size: new HillClimbing({
121
+ memoryPerWorker: 2 * 1024 ** 3,
122
+ computer: { availableParallelism, availableMemory },
123
+ }),
124
+ startup: new LeaderFirst(),
125
+ eviction: new IdleTimeout({ after: 300_000 }),
59
126
  });
60
- const text = await pool.use((worker) => worker.run('/tmp/receipt.png'));
127
+
128
+ const { text } = await ocr.run({ path: '/tmp/receipt.png' }, { signal });
61
129
  ```
62
130
 
131
+ Each host on the computer that builds a `PoolWorkers` of the kind offers its workers, and the election picks one of them as the owner. The others are standbys: they start no workers until they own. A host that cannot run the worker program builds only the `Pool`.
132
+
63
133
  A worker gives `run(input)`, `exited()`, `kill()`, `close()`, and optionally `ready()`. `run` does one job and resolves with its output ([ADR 0012](./docs/adr/0012-a-job-is-data-and-the-worker-kind-runs-it.md)). A `Coprocess` of `@zukhruf/coprocess` has all of them except `run`, so a worker class keeps the `Coprocess` and gives its `request` as `run`.
64
134
 
65
- A job takes an idle worker first. When no worker is idle, the job takes a worker that starts. Only when no worker starts does the job start a new worker. Of the idle workers, a job takes the one in the lowest slot. Thus jobs one at a time use one worker, and the other idle workers stay idle until their eviction lets them go.
135
+ A test gives a store of its own, so it never joins the user's pool:
66
136
 
67
- When a signal aborts a job that runs, the pool kills its worker. When a signal aborts a job whose worker still warms up, the warm-up continues for the next job.
137
+ ```ts
138
+ await using scratch = await mkdtempDisposable(join(tmpdir(), 'pool-'));
139
+ const store = join(scratch.path, 'store.sqlite');
140
+ ```
141
+
142
+ ## Read an output later
143
+
144
+ A host that answers at once starts the job, and reads its output later, from this host or another:
145
+
146
+ ```ts
147
+ const { id } = await ocr.start({ path: '/tmp/receipt.png' });
148
+ // later, in any host with a Pool of the same kind and revision
149
+ const { text } = await ocr.handle(id).result({ signal });
150
+ ```
68
151
 
69
- The pool waits for `ready()` with no time limit. Thus, if the warm-up of a worker can wait forever, the worker sets its own time limit, and `ready()` rejects when that limit ends. The pool then kills and closes the worker, and the job that waits for it fails. An eager startup starts a worker in that slot again after a back-off (see [Replace a worker that exits](#replace-a-worker-that-exits)). With `OnDemand`, the next job starts a new worker.
152
+ The job outlives the host that started it. A handle reads the job until the store's retention ends: 7 days after the job settled. The abort of `signal` ends only the wait of `result`. `cancel()` of the handle ends the job ([ADR 0026](./docs/adr/0026-start-accepts-a-job-now-and-a-job-handle-reads-its-output-later-from-any-host.md)).
153
+
154
+ ## Cancel a job
155
+
156
+ The abort of the signal of `run` cancels its job, and `run` rejects with the signal's reason. `cancel()` of a handle does the same. A job that waits is dropped. The owner kills the worker of a job that runs at its next touch, at most 5 s on, and the next job starts a worker in that slot after the back-off of an early exit. The cancel of a job of an `exclusive` kind is a leave: the job runs to its end for the other callers that gave the same input ([ADR 0020](./docs/adr/0020-a-cancel-of-a-shared-job-is-a-leave-and-of-any-other-job-a-drop-or-a-kill.md)).
157
+
158
+ ## How the owner lends its workers
159
+
160
+ A job takes an idle worker first. When no worker is idle, the job takes a worker that starts. Only when no worker starts does the job start a new worker. Of the idle workers, a job takes the one in the lowest slot. Thus jobs one at a time use one worker, and the other idle workers stay idle until their eviction lets them go.
161
+
162
+ The owner waits for `ready()` with no time limit. Thus, if the warm-up of a worker can wait forever, the worker sets its own time limit, and `ready()` rejects when that limit ends. The owner then kills and closes the worker, and the job that waits for it fails. An eager startup starts a worker in that slot again after a back-off (see [Replace a worker that exits](#replace-a-worker-that-exits)). With `OnDemand`, the next job starts a new worker.
70
163
 
71
164
  ## Choose when the workers start
72
165
 
@@ -124,10 +217,10 @@ A host that runs several pools on one computer can give each pool a part of the
124
217
 
125
218
  ## Choose when idle workers close
126
219
 
127
- | Eviction | Evicts |
128
- | ------------------------ | ------------------------------------------------------------ |
129
- | `NoEviction` | no worker. Each idle worker stays until you dispose the pool |
130
- | `IdleTimeout({ after })` | a worker that stays idle for `after` milliseconds |
220
+ | Eviction | Evicts |
221
+ | ------------------------ | ---------------------------------------------------------------------------- |
222
+ | `NoEviction` | no worker. Each idle worker stays until the owner disposes its `PoolWorkers` |
223
+ | `IdleTimeout({ after })` | a worker that stays idle for `after` milliseconds |
131
224
 
132
225
  A job that takes the worker before `after` ends keeps it. When the job ends, a new `after` starts. `after` is a number of milliseconds above 0 and at most 2,147,483,647. Another value throws a `RangeError`, because Node runs a timer with a larger delay after 1 ms.
133
226
 
@@ -137,21 +230,23 @@ The pool evicts only a worker in a slot that the sizing runs. A worker that the
137
230
 
138
231
  ## Read the stats
139
232
 
140
- A host can ask the pool how its workers are, for example in a health check:
233
+ `workers.stats` counts the slots of this host, for example in a health check:
141
234
 
142
235
  ```ts
143
- const { starting, idle, lent, waiting } = pool.stats;
144
- const healthy = waiting === 0 || starting + idle + lent > 0;
236
+ const { starting, idle, lent, waiting } = workers.stats;
237
+ const { waiting: queued, running } = await pool.stats();
145
238
  ```
146
239
 
147
- | Count | Is |
148
- | ---------- | -------------------------------------------------------------------------- |
149
- | `starting` | the workers that start and are not ready yet |
150
- | `idle` | the ready workers that no job has |
151
- | `lent` | the ready workers that a job has |
152
- | `waiting` | the jobs that wait for a worker: in the queue, or for a worker that starts |
240
+ | Count | Is |
241
+ | ---------- | ------------------------------------------------------------------- |
242
+ | `starting` | the workers that start and are not ready yet |
243
+ | `idle` | the ready workers that no job has |
244
+ | `lent` | the ready workers that a job has |
245
+ | `waiting` | the jobs that the owner took and that wait for a worker that starts |
153
246
 
154
- A worker that exited is in no count, and a slot whose worker the pool evicted is in no count. Thus a pool with an eviction can show zero in each count and be healthy: the next job starts a worker. Each read makes a new object, so the counts of one read agree with each other. See [ADR 0004](./docs/adr/0004-a-pool-reports-its-stats-as-one-snapshot-of-counts.md).
247
+ Each count is zero while the host does not own. A worker that exited is in no count, and a slot whose worker the owner evicted is in no count. Each read makes a new object, so the counts of one read agree with each other. See [ADR 0004](./docs/adr/0004-a-pool-reports-its-stats-as-one-snapshot-of-counts.md).
248
+
249
+ `pool.stats()` gives the jobs of the kind in the store, the same from every host: `waiting`, the jobs that wait for a worker or for a retry, and `running`, the jobs that a worker runs. It lags up to one pass of the store's monitor, a second ([ADR 0013](./docs/adr/0013-pool-sends-jobs-and-pool-workers-offers-the-workers-of-its-host.md)).
155
250
 
156
251
  ## Replace a worker that exits
157
252
 
@@ -161,311 +256,106 @@ A worker whose warm-up fails is an early exit too. An eager startup starts that
161
256
 
162
257
  ## Run the pool on a clock
163
258
 
164
- The pool measures the time of each job, waits before it replaces a worker that exited early, and gives the eviction the clock for its waits. All of these run on the `clock` that you give. Give `globalThis` in production. A test gives `createClock()` of `@sinonjs/fake-timers` and moves it with `await clock.tickAsync(ms)`, so a back-off of 60 seconds or a sizing window of 2 seconds takes no real time ([`@zukhruf/async`](../async/README.md#run-a-wait-on-a-clock)).
165
-
166
- An eviction of your own gets the clock of the pool as the third argument of `idle(busy, evict, clock)`, so the pool and its eviction always run on one clock. See [ADR 0008](./docs/adr/0008-the-pool-measures-and-waits-on-the-clock-that-the-caller-gives.md).
167
-
168
- ## One pool for the computer
169
-
170
- Design accepted 2026-11-20, partly built (backlog #3527). `WorkerKind`, `computerStore` and `PoolWorkers` are built. `PoolWorkers` touches each running job every 5 s. It kills the worker of a job at the kind's time limit, and when the store took the job back. Its `stats` count the slots of this host, and each count is zero while the host does not own. Its `ready()` resolves when the host owns and the workers that its startup starts are ready. It does not yet wake on the "new job" notification. `Pool` with `start`, `handle` and `run` is not built yet, and `use` stays until it is. The text above tells what the package does today. [ADR 0011](./docs/adr/0011-every-pool-is-a-pool-for-the-computer-and-one-owner-pulls-its-jobs-from-a-store-that-every-host-writes-to.md) to [ADR 0026](./docs/adr/0026-start-accepts-a-job-now-and-a-job-handle-reads-its-output-later-from-any-host.md) record the design. The tickets and the research named here are in the pool map, `.scratch/one-pool-for-the-computer/` at the workspace root, which git does not track.
171
-
172
- Today each host builds its own pool, so several hosts on one computer run several full pools, and they compete for one Neural Engine (#2896, #3868). In the design, every pool is a pool for the computer. On each computer, one host owns the workers of a pool. Every host writes its jobs to one store, and only the owner takes them. A job is data, so it can go from one host to another. The pool for the computer replaces the pool of today: `use((worker) => …)` goes away.
173
-
174
- The words of the design are in [CONTEXT.md](./CONTEXT.md), section "The pool for the computer".
175
-
176
- ### Define the worker kind
177
-
178
- A worker kind names the pool and holds its job rules. Export it from a module with no native code, so a host that cannot run the worker program can import it too:
179
-
180
- ```ts
181
- import { WorkerKind } from '@zukhruf/pool';
182
-
183
- export const vision = new WorkerKind<{ path: string }, { text: string }>({
184
- name: 'vision',
185
- revision: 1, // raise it when run changes in a way that matters
186
- policy: 'exclusive', // identical inputs share one job
187
- retryLimit: 2,
188
- expireInSeconds: 120,
189
- });
190
- ```
191
-
192
- The rule names are pg-boss's queue options, with pg-boss's meaning. Each one is required. See [ADR 0014](./docs/adr/0014-pool-and-pool-workers-take-one-worker-kind.md).
259
+ The owner measures the time of each job, waits before it replaces a worker that exited early, and gives the eviction the clock for its waits. All of these run on the `clock` that you give. Give `globalThis` in production. A test gives `createClock()` of `@sinonjs/fake-timers` and moves it with `await clock.tickAsync(ms)`, so a back-off of 60 seconds or a sizing window of 2 seconds takes no real time ([`@zukhruf/async`](../async/README.md#run-a-wait-on-a-clock)).
193
260
 
194
- ### Send jobs, and offer workers
261
+ An eviction of your own gets the clock of the pool as the third argument of `idle(busy, evict, clock)`, so the owner and its eviction always run on one clock. See [ADR 0008](./docs/adr/0008-the-pool-measures-and-waits-on-the-clock-that-the-caller-gives.md).
195
262
 
196
- A host that can run the worker program sends jobs and offers its workers:
197
-
198
- ```ts
199
- import { availableParallelism } from 'node:os';
263
+ The store keeps the wall time of each job, so `Pool` and `PoolWorkers` take a `WallClock` of [`@zukhruf/async`](../async/README.md). The backstops of the owner and of each `Pool` run on it too, so a test that never moves its clock still runs each job: the wakes of the store carry the news.
200
264
 
201
- import {
202
- HillClimbing,
203
- IdleTimeout,
204
- LeaderFirst,
205
- Pool,
206
- PoolWorkers,
207
- computerStore,
208
- } from '@zukhruf/pool';
265
+ ## The rules
209
266
 
210
- const store = computerStore(process.env);
211
- const { availableMemory } = process;
212
-
213
- await using ocr = new Pool({ kind: vision, store, clock: globalThis });
214
- await using workers = new PoolWorkers({
215
- kind: vision,
216
- store,
217
- clock: globalThis,
218
- create: () => new VisionWorker('/path/to/vision-worker'),
219
- size: new HillClimbing({
220
- memoryPerWorker: 2 * 1024 ** 3,
221
- computer: { availableParallelism, availableMemory },
222
- }),
223
- startup: new LeaderFirst(),
224
- eviction: new IdleTimeout({ after: 300_000 }),
225
- });
226
-
227
- const { text } = await ocr.run({ path: '/tmp/receipt.png' }, { signal });
228
- ```
229
-
230
- A host that answers at once starts the job, and reads its output later, from this host or another:
231
-
232
- ```ts
233
- const { id } = await ocr.start({ path: '/tmp/receipt.png' });
234
- // later, in any host with a Pool of the same kind
235
- const { text } = await ocr.handle(id).result({ signal });
236
- ```
267
+ - **One owner.** On each computer, one host owns the workers of a pool. `PoolWorkers` campaigns in a `SqliteElection` of [`@zukhruf/election`](../election/README.md), with the claim files in the folder of the store. The other hosts with a `PoolWorkers` are standbys ([ADR 0011](./docs/adr/0011-every-pool-is-a-pool-for-the-computer-and-one-owner-pulls-its-jobs-from-a-store-that-every-host-writes-to.md)).
268
+ - **The two roles.** `Pool` sends. `PoolWorkers` offers workers and has no `run`. They meet only through the worker kind and the store, as BullMQ's `Queue` and `Worker` meet through the queue name ([ADR 0013](./docs/adr/0013-pool-sends-jobs-and-pool-workers-offers-the-workers-of-its-host.md)).
269
+ - **A job is data.** The input and the output are JSON. A file goes by reference: a path on one computer. The code of a job is the worker's `run` ([ADR 0012](./docs/adr/0012-a-job-is-data-and-the-worker-kind-runs-it.md)).
270
+ - **The store** is a required address. A path of a SQLite file is the store of one computer, through [`@zukhruf/sqlite-queue`](../sqlite/queue/README.md). A `postgres://` address joins computers, through pg-boss. `computerStore(env)` gives `zukhruf-pool/store.sqlite` in the user's state folder: `$HOME/Library/Application Support` on macOS, `$XDG_STATE_HOME` (or `$HOME/.local/state`) on Linux, `%LOCALAPPDATA%` on Windows. It reads `process.platform`, and takes `env` as its input, as Go's `os.UserConfigDir` reads `runtime.GOOS`. Every `Pool` and `PoolWorkers` opens the store and creates the queue of its revision ([ADR 0015](./docs/adr/0015-the-store-is-a-required-input-and-computer-store-gives-the-store-of-the-computer.md)).
271
+ - **The clock.** The store keeps the wall time of each job, so `Pool` and `PoolWorkers` take a `WallClock` of [`@zukhruf/async`](../async/README.md): `globalThis` in production. The pool gives `@zukhruf/sqlite-queue` pg-boss's clock, made from it.
272
+ - **A failure of the store** that no caller waits for, in a pass of the store, a fetch, a touch or a settle of the owner, is a process warning, and the owner keeps owning: the next pass, backstop or touch tries again, and a job whose settle failed lapses by its heartbeat and runs again by the kind's rules, as pg-boss emits the failure of a pass and keeps polling. Ownership ends only by the election or the disposal. A store that fails to start ends the host, and the disposal of `PoolWorkers` rejects with that failure.
273
+ - **The disposal** of `PoolWorkers` can run again, or at the same time: each call waits for the one end of the host, which closes the store last.
274
+ - **The cap.** The owner's sizing caps the jobs of its computer. The store keeps no count of running jobs. A new owner starts its sizing fresh ([ADR 0016](./docs/adr/0016-the-owners-sizing-caps-the-jobs-of-its-computer.md)).
275
+ - **The owner asks, then takes.** It calls `fetch(name, { batchSize: free })` on the queue of its revision for its free workers, settles each job with `complete` or `fail` by its attempt, and calls `touch` for each running job every 5 s on a heartbeat of 10 s. It fetches when a worker becomes free, at a "new job" wake, and at the backstop ([ADR 0017](./docs/adr/0017-the-owner-asks-then-takes-as-many-jobs-as-it-has-free-workers.md)).
276
+ - **News travels by push.** Two channels for each pool: "a new job", with the revision, which the owner hears, and "an output", with the job id, which each waiting `Pool` hears. On one computer they go through [`@zukhruf/sqlite-notify`](../sqlite/notify/README.md), across computers through Postgres `LISTEN` / `NOTIFY`. The store is the truth, and a wake only says "read the store". A backstop each second on one computer finds a lost wake, and a job that the store's monitor failed ([ADR 0018](./docs/adr/0018-news-travels-by-push-through-the-notify-of-the-store-with-a-backstop.md)).
277
+ - **`run` waits** for the output. The kind's `retryLimit` decides how often a job runs again, its `expireInSeconds` limits one run, and the caller's `signal` limits only the caller's wait. With no owner anywhere, the job waits in the store. `run` is `start`, then `result` ([ADR 0019](./docs/adr/0019-run-waits-and-a-failed-job-rejects-with-the-pools-error.md)).
278
+ - **Accept now, read later.** `start(input)` resolves with a `JobHandle { id, result({ signal }), cancel() }`, and `handle(id)` gives the handle of a job from any host, as Temporal's `start` and `getHandle`. The job outlives the host that started it. A handle reads the job until the store's retention ends: 7 days after the job settled ([ADR 0026](./docs/adr/0026-start-accepts-a-job-now-and-a-job-handle-reads-its-output-later-from-any-host.md)).
279
+ - **A cancel.** The caller's abort of a shared job is a leave: its `run` rejects, and the job runs to its end for the other callers. The abort of any other job drops it when it waits, and the owner kills its worker at its next touch, at most 5 s on, when it runs. `cancel()` of a handle does the same ([ADR 0020](./docs/adr/0020-a-cancel-of-a-shared-job-is-a-leave-and-of-any-other-job-a-drop-or-a-kill.md); Ezz, 2026-11-14: "we need to follow top perfoerms").
280
+ - **A caller that is gone** (not built yet). Each job of a `run` will carry its caller's address: a pipe of [`@zukhruf/pipes`](../pipes/README.md) that the waiting `Pool` serves. A job of `start` carries none. The owner will connect to it before it starts the job, and keep the connection while the job runs. A refused connect or a close will be a cancel of that caller ([ADR 0021](./docs/adr/0021-a-caller-whose-host-is-gone-cancels-its-jobs-and-the-owner-learns-it-from-a-closed-connection.md)).
281
+ - **Revisions.** Each revision has its own queue, `<name>.r<revision>`, so an older owner never fetches a job of a newer revision, as Temporal routes a task by its build id. Not built yet: an owner that refuses a job of an older revision with `DeprecatedRevisionError`, and an owner that hears a wake of a newer revision, finishes its running jobs and resigns ([ADR 0022](./docs/adr/0022-the-newest-revision-takes-over-and-an-owner-refuses-a-job-of-an-older-revision.md)).
282
+ - **Ownership moves** only by the owner's own act or its end. A standby starts no workers until it owns. A clean owner finishes its jobs and resigns. The jobs of a dead owner come back by their heartbeat. `ready()` never resolves on a standby ([ADR 0023](./docs/adr/0023-ownership-moves-only-by-the-owners-own-act-or-its-end-and-a-standby-stays-cold.md)).
283
+ - **A hung owner** is ended by the election: a standby that hears no heartbeat on the leader's pipe for 15 s kills the leader's process. A late `complete` of the old owner affects 0 rows ([ADR 0024](./docs/adr/0024-a-hung-owner-is-ended-by-the-election-and-its-late-acts-are-fenced.md)).
284
+ - **Many computers** will share one Postgres store, and each computer will elect its own owner. It is built only when a second computer is real; today a `postgres://` store throws a `TypeError` ([ADR 0025](./docs/adr/0025-many-computers-share-one-postgres-store-and-each-computer-keeps-its-own-owner.md)).
237
285
 
238
- A host that cannot run the worker program only sends. To reach the workers of another computer, it gives a shared Postgres store:
286
+ ## Not built yet
239
287
 
240
- ```ts
241
- await using ocr = new Pool({
242
- kind: vision,
243
- store: 'postgres://…',
244
- clock: globalThis,
245
- });
246
- ```
288
+ - A caller that is gone cancels its jobs ([ADR 0021](./docs/adr/0021-a-caller-whose-host-is-gone-cancels-its-jobs-and-the-owner-learns-it-from-a-closed-connection.md)).
289
+ - An owner refuses a job of an older revision with `DeprecatedRevisionError`, and an owner of an older revision gives way to a newer one ([ADR 0022](./docs/adr/0022-the-newest-revision-takes-over-and-an-owner-refuses-a-job-of-an-older-revision.md)).
290
+ - Many computers on one Postgres store ([ADR 0025](./docs/adr/0025-many-computers-share-one-postgres-store-and-each-computer-keeps-its-own-owner.md)).
291
+ - The hosts elt and context-compiler move to this pool, so their Vision workers become one pool for each computer (backlog #3527).
247
292
 
248
- A test gives a store of its own, so it never joins the user's pool:
293
+ ## Errors
249
294
 
250
- ```ts
251
- await using scratch = await mkdtempDisposable(join(tmpdir(), 'pool-'));
252
- const store = join(scratch.path, 'store.sqlite');
253
- ```
295
+ | Error | When |
296
+ | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
297
+ | `JobFailedError` | `run` or `result` rejects with it when the job failed its last run. `failure` has the name and the message that the owner stored, for example the worker's error, or "handler execution exceeded 60s", or the store's "job heartbeat timeout" ([src/pool-workers.test.ts](./src/pool-workers.test.ts)). |
298
+ | `JobCancelledError` | `run` or `result` rejects with it when the job was cancelled, by `cancel()` of a handle or by the abort of a `run` of another caller. |
299
+ | `JobNotFoundError` | `result` rejects with it when the store has no job with the id: it was deleted after the retention, it belongs to another revision, or it never existed. |
300
+ | `DisposedError` | `run`, `result`, `start` or `cancel()` rejects with it when the host disposed its `Pool`, also while it waited. |
301
+ | The reason of `signal` | `run` or `result` rejects with it when the caller's signal aborted. |
302
+ | `RangeError` | `new WorkerKind` gets a name whose channel `<name>.new-job` has 64 bytes or more ([src/worker-kind.test.ts](./src/worker-kind.test.ts)). |
303
+ | `RangeError` | `new IdleTimeout({ after })` gets an `after` that is not above 0 and at most 2,147,483,647 ([src/pool.test.ts](./src/pool.test.ts)). |
304
+ | `TypeError` | `new Pool` or `new PoolWorkers` gets a `postgres://` store. Only the store of one computer, the path of a SQLite file, is built ([src/pool-workers.test.ts](./src/pool-workers.test.ts)). |
305
+ | `Error` | `computerStore(env)` finds no `$HOME` on macOS, no `$HOME` and no `$XDG_STATE_HOME` on Linux, or no `%LOCALAPPDATA%` on Windows ([src/computer-store.test.ts](./src/computer-store.test.ts)). |
306
+ | The failure of the store | The disposal of `PoolWorkers`, and `start` of a `Pool`, reject with the failure of the store's start, for example an `expireInSeconds` that the store refuses ([src/pool-workers.test.ts](./src/pool-workers.test.ts)). A later failure of the store is a process warning. |
307
+ | The error of the warm-up | `workers.ready()` rejects with it when a worker that the startup of the owner starts fails its `ready()` ([src/pool-workers.test.ts](./src/pool-workers.test.ts)). |
308
+ | `AbortError` | `workers.ready()` rejects with it when you dispose `PoolWorkers` before its host owns ([src/pool-workers.test.ts](./src/pool-workers.test.ts)). |
254
309
 
255
- ### The API
310
+ ## API
256
311
 
257
312
  ```ts
258
- import type { WallClock } from '@zukhruf/async';
313
+ import type { Clock, WallClock } from '@zukhruf/async';
259
314
 
260
- export class WorkerKind<Input, Output> {
315
+ class WorkerKind<Input, Output> {
261
316
  constructor(options: {
262
317
  name: string;
263
318
  revision: number;
264
319
  policy: 'standard' | 'exclusive';
265
320
  retryLimit: number;
266
321
  expireInSeconds: number;
267
- });
322
+ }); // RangeError: "<name>.new-job" has 64 bytes or more
268
323
  readonly name: string;
269
324
  readonly revision: number;
270
325
  readonly policy: 'standard' | 'exclusive';
271
326
  readonly retryLimit: number;
272
327
  readonly expireInSeconds: number;
273
- /** The queue of this revision in the store: `<name>.r<revision>`. */
274
- readonly queue: string;
275
- }
276
-
277
- /** Sends jobs of one kind to the store, and waits for their outputs. */
278
- export class Pool<Input, Output> implements AsyncDisposable {
279
- constructor(options: {
280
- kind: WorkerKind<Input, Output>;
281
- store: string;
282
- clock: WallClock;
283
- });
284
- /** Sends the job, and resolves when the store has it. */
285
- start(input: Input): Promise<JobHandle<Output>>;
286
- /** The handle of a job of this kind and revision that any host started. */
287
- handle(id: string): JobHandle<Output>;
288
- /** start, then result. The abort of signal cancels the job. */
289
- run(input: Input, options?: { signal?: AbortSignal }): Promise<Output>;
290
- /** The jobs of the kind in the store, the same from every host. */
291
- stats(): Promise<JobCounts>;
292
- [Symbol.asyncDispose](): Promise<void>;
328
+ readonly queue: string; // `<name>.r<revision>`
293
329
  }
294
330
 
295
- /** Offers this host's workers. Owns them while this host leads. */
296
- export class PoolWorkers<Input, Output> implements AsyncDisposable {
331
+ class Pool<Input, Output> implements AsyncDisposable {
297
332
  constructor(options: {
298
333
  kind: WorkerKind<Input, Output>;
299
- store: string;
334
+ store: string; // the path of the store's SQLite file, such as computerStore(process.env)
300
335
  clock: WallClock;
301
- create: () => Worker<Input, Output>;
302
- size: Sizing;
303
- startup: Startup;
304
- eviction: Eviction;
305
- });
306
- /** This host's slots: zero in each count while it does not own. */
307
- readonly stats: PoolStats;
308
- /** Resolves when this host owns and its startup workers are ready. */
309
- ready(): Promise<void>;
310
- [Symbol.asyncDispose](): Promise<void>;
311
- }
312
-
313
- export interface Worker<Input, Output> {
314
- run(input: Input): Promise<Output>;
315
- ready?(): Promise<unknown>;
316
- exited(): Promise<unknown>;
317
- kill(): void;
318
- close(): Promise<void>;
336
+ }); // TypeError: a postgres:// store
337
+ start(input: Input): Promise<JobHandle<Output>>; // resolves when the store has the job
338
+ handle(id: string): JobHandle<Output>; // reads nothing
339
+ run(input: Input, options?: { signal?: AbortSignal }): Promise<Output>; // start, then result; the abort of signal cancels the job
340
+ stats(): Promise<JobCounts>; // the jobs of the kind in the store
341
+ [Symbol.asyncDispose](): Promise<void>; // ends the waits with DisposedError, cancels the jobs of waiting runs
319
342
  }
320
343
 
321
- /** A job in the store, by its id. */
322
- export interface JobHandle<Output> {
344
+ interface JobHandle<Output> {
323
345
  readonly id: string;
324
- /** Waits for the output. The abort of signal ends only this wait. */
325
- result(options?: { signal?: AbortSignal }): Promise<Output>;
326
- /** A leave for a shared job; a drop or a kill for any other job. */
327
- cancel(): Promise<void>;
346
+ result(options?: { signal?: AbortSignal }): Promise<Output>; // the abort of signal ends only this wait
347
+ cancel(): Promise<void>; // a leave for a shared job; a drop or a kill for any other job
328
348
  }
329
349
 
330
- export interface JobCounts {
350
+ interface JobCounts {
331
351
  readonly waiting: number;
332
352
  readonly running: number;
333
353
  }
334
354
 
335
- /** The store of this computer, for the user of env: zukhruf-pool/store.sqlite in the user's state folder for process.platform. */
336
- export function computerStore(env: Record<string, string | undefined>): string;
337
-
338
- export class JobFailedError extends Error {
339
- readonly failure: { readonly name: string; readonly message: string };
340
- }
341
- export class JobCancelledError extends Error {}
342
- export class JobNotFoundError extends Error {}
343
- export class DeprecatedRevisionError extends Error {}
344
- export class DisposedError extends Error {}
345
- ```
346
-
347
- ### The rules
348
-
349
- - **One owner.** On each computer, one host owns the workers of a pool. `PoolWorkers` campaigns in a `SqliteElection` of [`@zukhruf/election`](../election/README.md), with the claim files in the folder of the store. The other hosts with a `PoolWorkers` are standbys ([ADR 0011](./docs/adr/0011-every-pool-is-a-pool-for-the-computer-and-one-owner-pulls-its-jobs-from-a-store-that-every-host-writes-to.md)).
350
- - **The two roles.** `Pool` sends. `PoolWorkers` offers workers and has no `run`. They meet only through the worker kind and the store, as BullMQ's `Queue` and `Worker` meet through the queue name ([ADR 0013](./docs/adr/0013-pool-sends-jobs-and-pool-workers-offers-the-workers-of-its-host.md)).
351
- - **A job is data.** The input and the output are JSON. A file goes by reference: a path on one computer. The code of a job is the worker's `run` ([ADR 0012](./docs/adr/0012-a-job-is-data-and-the-worker-kind-runs-it.md)).
352
- - **The store** is a required address. A path of a SQLite file is the store of one computer, through [`@zukhruf/sqlite-queue`](../sqlite/queue/README.md). A `postgres://` address joins computers, through pg-boss. `computerStore(env)` gives `zukhruf-pool/store.sqlite` in the user's state folder: `$HOME/Library/Application Support` on macOS, `$XDG_STATE_HOME` (or `$HOME/.local/state`) on Linux, `%LOCALAPPDATA%` on Windows. It reads `process.platform`, and takes `env` as its input, as Go's `os.UserConfigDir` reads `runtime.GOOS`. Every `Pool` and `PoolWorkers` opens the store and creates the queue of its revision ([ADR 0015](./docs/adr/0015-the-store-is-a-required-input-and-computer-store-gives-the-store-of-the-computer.md)).
353
- - **The clock.** The store keeps the wall time of each job, so `Pool` and `PoolWorkers` take a `WallClock` of [`@zukhruf/async`](../async/README.md): `globalThis` in production. The pool gives `@zukhruf/sqlite-queue` pg-boss's clock, made from it.
354
- - **A failure of the store** that no caller waits for, in a pass of the store, a fetch, a touch or a settle of the owner, is a process warning, and the owner keeps owning: the next pass, backstop or touch tries again, and a job whose settle failed lapses by its heartbeat and runs again by the kind's rules, as pg-boss emits the failure of a pass and keeps polling. Ownership ends only by the election or the disposal. A store that fails to start ends the host, and the disposal of `PoolWorkers` rejects with that failure.
355
- - **The disposal** of `PoolWorkers` can run again, or at the same time: each call waits for the one end of the host, which closes the store last.
356
- - **The cap.** The owner's sizing caps the jobs of its computer. The store keeps no count of running jobs. A new owner starts its sizing fresh ([ADR 0016](./docs/adr/0016-the-owners-sizing-caps-the-jobs-of-its-computer.md)).
357
- - **The owner asks, then takes.** It calls `fetch(name, { batchSize: free })` on the queue of its revision for its free workers, settles each job with `complete` or `fail` by its attempt, and calls `touch` for each running job every 5 s on a heartbeat of 10 s. It fetches when a worker becomes free, at a "new job" wake, and at the backstop ([ADR 0017](./docs/adr/0017-the-owner-asks-then-takes-as-many-jobs-as-it-has-free-workers.md)).
358
- - **News travels by push.** Two channels for each pool: "a new job", with the revision, which the owner hears, and "an output", with the job id, which each waiting `Pool` hears. On one computer they go through [`@zukhruf/sqlite-notify`](../sqlite/notify/README.md), across computers through Postgres `LISTEN` / `NOTIFY`. The store is the truth, and a wake only says "read the store". A backstop each second on one computer finds a lost wake, and a job that the store's monitor failed ([ADR 0018](./docs/adr/0018-news-travels-by-push-through-the-notify-of-the-store-with-a-backstop.md)).
359
- - **`run` waits** for the output. The kind's `retryLimit` decides how often a job runs again, its `expireInSeconds` limits one run, and the caller's `signal` limits only the caller's wait. With no owner anywhere, the job waits in the store. `run` is `start`, then `result` ([ADR 0019](./docs/adr/0019-run-waits-and-a-failed-job-rejects-with-the-pools-error.md)).
360
- - **Accept now, read later.** `start(input)` resolves with a `JobHandle { id, result({ signal }), cancel() }`, and `handle(id)` gives the handle of a job from any host, as Temporal's `start` and `getHandle`. The job outlives the host that started it. A handle reads the job until the store's retention ends: 7 days after the job settled ([ADR 0026](./docs/adr/0026-start-accepts-a-job-now-and-a-job-handle-reads-its-output-later-from-any-host.md)).
361
- - **A cancel.** The caller's abort of a shared job is a leave: its `run` rejects, and the job runs to its end for the other callers. The abort of any other job drops it when it waits, and kills its worker when it runs. `cancel()` of a handle does the same ([ADR 0020](./docs/adr/0020-a-cancel-of-a-shared-job-is-a-leave-and-of-any-other-job-a-drop-or-a-kill.md); Ezz, 2026-11-14: "we need to follow top perfoerms").
362
- - **A caller that is gone.** Each job of a `run` carries its caller's address: a pipe of [`@zukhruf/pipes`](../pipes/README.md) that the waiting `Pool` serves. A job of `start` carries none. The owner connects to it before it starts the job, and keeps the connection while the job runs. A refused connect or a close is a cancel of that caller ([ADR 0021](./docs/adr/0021-a-caller-whose-host-is-gone-cancels-its-jobs-and-the-owner-learns-it-from-a-closed-connection.md)).
363
- - **Revisions.** Each revision has its own queue, `<name>.r<revision>`, so an older owner never fetches a job of a newer revision, as Temporal routes a task by its build id. An owner refuses a job of an older revision with `DeprecatedRevisionError`. An owner that hears a wake of a newer revision finishes its running jobs and resigns ([ADR 0022](./docs/adr/0022-the-newest-revision-takes-over-and-an-owner-refuses-a-job-of-an-older-revision.md)).
364
- - **Ownership moves** only by the owner's own act or its end. A standby starts no workers until it owns. A clean owner finishes its jobs and resigns. The jobs of a dead owner come back by their heartbeat. `ready()` never resolves on a standby ([ADR 0023](./docs/adr/0023-ownership-moves-only-by-the-owners-own-act-or-its-end-and-a-standby-stays-cold.md)).
365
- - **A hung owner** is ended by the election: a standby that hears no heartbeat on the leader's pipe for 15 s kills the leader's process. A late `complete` of the old owner affects 0 rows ([ADR 0024](./docs/adr/0024-a-hung-owner-is-ended-by-the-election-and-its-late-acts-are-fenced.md)).
366
- - **Many computers** share one Postgres store, and each computer elects its own owner. It is built only when a second computer is real ([ADR 0025](./docs/adr/0025-many-computers-share-one-postgres-store-and-each-computer-keeps-its-own-owner.md)).
367
-
368
- ### Errors
369
-
370
- | Error | When `run` or `result` rejects with it |
371
- | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
372
- | `JobFailedError` | The job failed its last run. `failure` has the name and the message that the owner stored, for example the worker's error or "handler execution exceeded 60s". |
373
- | `DeprecatedRevisionError` | The owner runs a newer revision of the kind, and refused this job. Update the host. |
374
- | `JobCancelledError` | The job was cancelled, by `cancel()` of a handle or by the abort of a `run`. |
375
- | `JobNotFoundError` | The store has no job with the id: it was deleted after the retention, it belongs to another revision, or it never existed. |
376
- | `DisposedError` | The host disposed its `Pool` while the `run` or the `result` waited. |
377
- | The reason of `signal` | The caller's signal aborted. |
378
-
379
- ### The gaps that come first
380
-
381
- Each gap that the design found goes to the package that must have it, and is built before the pool (Ezz, 2026-11-13: "Anything that is missing then goes to the appropriate package").
382
-
383
- | Gap | Home | State |
384
- | ------------------------------------------------------------------ | ------------------------ | --------------------------------------------------- |
385
- | The socket address of a program of one computer | `@zukhruf/pipes` | Built (#2496) |
386
- | A claim that is not atomic across connections | `@zukhruf/sqlite-queue` | Built (#3700) |
387
- | pg-boss's `fetch` and `complete` | `@zukhruf/sqlite-queue` | Built (#4313) |
388
- | pg-boss's `touch` | `@zukhruf/sqlite-queue` | Built (#4370) |
389
- | No `LISTEN` / `NOTIFY` on a SQLite file | `@zukhruf/sqlite-notify` | Built (#4333) |
390
- | `useListenNotify` across instances on one file | `@zukhruf/sqlite-queue` | Built (#4334). The pool does not use it (ADR 0018). |
391
- | A standby that polls, and a hung leader that nobody ends | `@zukhruf/election` | Built (#4371) |
392
- | An older release that rebuilds a newer file | `@zukhruf/sqlite-queue` | Built (#4369) |
393
- | A count of the jobs of a queue by state, pg-boss's `getQueueStats` | `@zukhruf/sqlite-queue` | Built (#2888). `pool.stats()` needs it. |
394
- | A job from `findJobs` carries a `signal`, and pg-boss's does not | `@zukhruf/sqlite-queue` | Fixed (#4331) |
395
- | A write that waits more than the busy timeout of 5 s fails | `@zukhruf/sqlite-queue` | Open risk (#4355) |
396
- | A synced commit on macOS is a plain `fsync` | `@zukhruf/sqlite-queue` | Open risk (#4351) |
397
- | Nothing ran on Windows | each package | Deferred (#4340) |
398
-
399
- ### Decided
400
-
401
- The three open features, and the three items that the records did not decide, were decided on 2026-11-16 (backlog #3527, "DECISIONS 2026-11-16").
402
-
403
- 1. **Accept a job now, and read its output later: yes, in Temporal's shape.** Ezz: "learn from memoroies what is my style and pick". His recorded rule for a standard package: put a capability in or out for a reason of its domain, never because no consumer needs it yet. Every leading job system has it: Temporal's `start` and `getHandle`, Celery's `AsyncResult`, BullMQ's `Job.fromId` and `waitUntilFinished`, pg-boss's `send` id and `findJobs`, and Azure Asynchronous Request-Reply. Temporal's shape maps one-to-one onto pg-boss ([ADR 0026](./docs/adr/0026-start-accepts-a-job-now-and-a-job-handle-reads-its-output-later-from-any-host.md)).
404
- 2. **A result cache: no cache in the pool.** Ezz: "No cache in the pool (Recommended)". A host that wants one keeps it above the pool, keyed by content, as Bazel keeps its action cache above its workers.
405
- 3. **Cancel a running job with no kill: kill only for now.** Ezz: "Kill only for now (Recommended)". A cancel signal on the worker's `run` comes later, as Bazel sends `cancel: true` to a worker that declares `supports-worker-cancellation`. The trigger is a costly kind that cannot be shared, with a worker that can cancel ([ADR 0020](./docs/adr/0020-a-cancel-of-a-shared-job-is-a-leave-and-of-any-other-job-a-drop-or-a-kill.md)).
406
-
407
- Decided by the leaders (Ezz: "I trust your recommendation ... follow the top performers"):
408
-
409
- 4. **The address on each job** is a pipe of `@zukhruf/pipes` that each waiting `Pool` serves, as gRPC learns of a gone client from the caller's own stream. `@zukhruf/sqlite-notify` does not change ([ADR 0021](./docs/adr/0021-a-caller-whose-host-is-gone-cancels-its-jobs-and-the-owner-learns-it-from-a-closed-connection.md)).
410
- 5. **A queue for each worker revision**, so an older owner never fetches a job of a newer revision, as Temporal worker versioning routes a task by its build id and Amazon SWF by the version ([ADR 0022](./docs/adr/0022-the-newest-revision-takes-over-and-an-owner-refuses-a-job-of-an-older-revision.md)).
411
- 6. **`computerStore(env)` reads `process.platform`**, and takes `env` as its input, as Go's `os.UserConfigDir` reads `runtime.GOOS` ([ADR 0015](./docs/adr/0015-the-store-is-a-required-input-and-computer-store-gives-the-store-of-the-computer.md)).
412
-
413
- ### Moving the hosts
414
-
415
- A plan, not code. The hosts that move are elt and context-compiler (map, Revision 2026-11-13). trashbot is not in use, stays on `@zukhruf/pool` 0.6.15, and does not move.
416
-
417
- 1. **zukhruf, before the pool**: Ezz accepted ADR 0011 to ADR 0026 as built (2026-11-20). `@zukhruf/sqlite-queue` has pg-boss's `getQueueStats(name)` with its parity tests, which `pool.stats()` needs (#2888). #4331 is fixed.
418
- 2. **zukhruf, the pool**: `WorkerKind`, `Pool` with `start`, `handle` and `run`, `PoolWorkers` and `computerStore`, with tests of several real hosts on one computer: each test with its own store file, real worker processes and the real clock. `use` and its tests go. The recipes change to the new API, and this section becomes the README. Then a release.
419
- 3. **elt**: a `vision` kind (`exclusive`, with retries) and a `transcription` kind (`standard`) in modules with no native code. The worker classes implement `run`. `ImageFormat` takes a `Pool` of the `vision` kind, in place of `Pool<VisionWorker>` (`image-format.ts:56`). `local-transcription-model.ts:85` gives the path of its wav to `run`.
420
- 4. **context-compiler**: the server (`apps/server/src/startup.ts:11`) and the CLI (`apps/cli/src/parsing.ts:61`) build a `Pool` and a `PoolWorkers` of the `vision` kind with `computerStore(process.env)`. `packages/connectors/connector/src/transcription.ts:96` does the same for transcription. Each host disposes them at a termination signal, through `@zukhruf/shutdown`.
421
- 5. **elt and context-compiler** move to the new release of `@zukhruf` in one step, and release together.
422
- 6. **A measure**: the contention benchmark of 2026-11-02 runs again with two hosts on one store. One owner's sizing then caps the computer.
423
-
424
- Many computers come after map ticket 14, when a second computer is real.
425
-
426
- ## Errors
427
-
428
- These are the errors that the package throws today. The errors of the design are in the section "One pool for the computer".
429
-
430
- | Error | When |
431
- | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
432
- | `RangeError` | `new WorkerKind` gets a name whose channel `<name>.new-job` has 64 bytes or more ([src/worker-kind.test.ts](./src/worker-kind.test.ts)). |
433
- | `RangeError` | `new IdleTimeout({ after })` gets an `after` that is not above 0 and at most 2,147,483,647 ([src/pool.test.ts](./src/pool.test.ts)). |
434
- | `TypeError` | `new PoolWorkers` gets a `postgres://` store. Only the store of one computer, the path of a SQLite file, is built ([src/pool-workers.test.ts](./src/pool-workers.test.ts)). |
435
- | `Error` | `computerStore(env)` finds no `$HOME` on macOS, no `$HOME` and no `$XDG_STATE_HOME` on Linux, or no `%LOCALAPPDATA%` on Windows ([src/computer-store.test.ts](./src/computer-store.test.ts)). |
436
- | The failure of the store | The disposal of `PoolWorkers` rejects with the failure of the store's start, for example an `expireInSeconds` that the store refuses ([src/pool-workers.test.ts](./src/pool-workers.test.ts)). A later failure of the store is a process warning. |
437
- | The error of the warm-up | `workers.ready()` of `PoolWorkers` rejects with it when a worker that the startup of the owner starts fails its `ready()` ([src/pool-workers.test.ts](./src/pool-workers.test.ts)). |
438
- | `AbortError` | `workers.ready()` of `PoolWorkers` rejects with it when you dispose `PoolWorkers` before its host owns ([src/pool-workers.test.ts](./src/pool-workers.test.ts)). |
439
- | `signal.reason` | `pool.use` rejects with it when its signal aborts. |
440
- | `AbortError` | `pool.use` rejects with it when you dispose the pool, also for a job that waits ([src/pool.test.ts](./src/pool.test.ts)). |
441
- | The error of the job | `pool.use` rejects with what `job` throws, for example the error of a worker that exited while the job ran. |
442
- | The error of the warm-up | `pool.ready()` rejects with it when a worker that the startup starts with the pool fails its `ready()`. When you dispose the pool while such a worker warms up, the pool kills the worker, and `pool.ready()` rejects with the reason that the `ready()` of that worker gives ([src/pool.test.ts](./src/pool.test.ts)). |
443
-
444
- ## API
445
-
446
- The exports of today. The section "One pool for the computer" gives the design, which is not all built.
447
-
448
- ```ts
449
- import type { Clock, WallClock } from '@zukhruf/async';
450
-
451
- class Pool<T extends Worker<never, unknown>> implements AsyncDisposable {
452
- constructor(options: {
453
- size: Sizing;
454
- startup: Startup;
455
- eviction: Eviction;
456
- create: () => T;
457
- clock: Clock; // globalThis in production, a fake clock in a test
458
- });
459
- ready(): Promise<void>; // the workers that the startup starts with the pool are ready
460
- get stats(): PoolStats; // a new snapshot at each read
461
- use<R>(job: (worker: T) => Promise<R>, signal?: AbortSignal): Promise<R>;
462
- [Symbol.asyncDispose](): Promise<void>; // stops every worker
463
- }
464
-
465
355
  class PoolWorkers<Input, Output> implements AsyncDisposable {
466
356
  constructor(options: {
467
357
  kind: WorkerKind<Input, Output>;
468
- store: string; // the path of the store's SQLite file, such as computerStore(process.env)
358
+ store: string;
469
359
  clock: WallClock;
470
360
  create: () => Worker<Input, Output>;
471
361
  size: Sizing;
@@ -474,23 +364,7 @@ class PoolWorkers<Input, Output> implements AsyncDisposable {
474
364
  }); // TypeError: a postgres:// store
475
365
  readonly stats: PoolStats; // this host's slots; each count 0 while it does not own
476
366
  ready(): Promise<void>; // the host owns and its startup's workers are ready
477
- [Symbol.asyncDispose](): Promise<void>; // rejects with the failure of the store's start
478
- }
479
-
480
- class WorkerKind<Input, Output> {
481
- constructor(options: {
482
- name: string;
483
- revision: number;
484
- policy: 'standard' | 'exclusive';
485
- retryLimit: number;
486
- expireInSeconds: number;
487
- }); // RangeError: "<name>.new-job" has 64 bytes or more
488
- readonly name: string;
489
- readonly revision: number;
490
- readonly policy: 'standard' | 'exclusive';
491
- readonly retryLimit: number;
492
- readonly expireInSeconds: number;
493
- readonly queue: string; // `<name>.r<revision>`
367
+ [Symbol.asyncDispose](): Promise<void>; // a hand-over; rejects with the failure of the store's start
494
368
  }
495
369
 
496
370
  function computerStore(env: Record<string, string | undefined>): string;
@@ -503,8 +377,20 @@ interface Worker<Input, Output> {
503
377
  close(): Promise<void>;
504
378
  }
505
379
 
380
+ class JobFailedError extends Error {
381
+ readonly failure: Failure;
382
+ }
383
+ class JobCancelledError extends Error {}
384
+ class JobNotFoundError extends Error {}
385
+ class DisposedError extends Error {}
386
+
387
+ interface Failure {
388
+ readonly name: string;
389
+ readonly message: string;
390
+ }
391
+
506
392
  interface Sizing {
507
- readonly ceiling: number; // the most workers it may run, decided when the pool is built
393
+ readonly ceiling: number; // the most workers it may run, decided when the owner builds its slots
508
394
  readonly current: number; // the workers it runs now
509
395
  readonly kept: number; // the workers it keeps alive, at least current
510
396
  record(sample: Sample): void;
@@ -582,19 +468,19 @@ class IdleTimeout implements Eviction {
582
468
  - [ADR 0008](./docs/adr/0008-the-pool-measures-and-waits-on-the-clock-that-the-caller-gives.md): the pool measures and waits on the clock that the caller gives.
583
469
  - [ADR 0009](./docs/adr/0009-a-sizing-reads-the-capacity-from-the-computer-that-the-caller-gives.md): a sizing reads the capacity from the computer that the caller gives.
584
470
  - [ADR 0010](./docs/adr/0010-an-eager-pool-starts-a-worker-again-after-its-warm-up-fails.md): an eager pool starts a worker again after its warm-up fails.
585
- - [ADR 0011](./docs/adr/0011-every-pool-is-a-pool-for-the-computer-and-one-owner-pulls-its-jobs-from-a-store-that-every-host-writes-to.md): every pool is a pool for the computer, and one owner pulls its jobs from a store that every host writes to (proposed).
586
- - [ADR 0012](./docs/adr/0012-a-job-is-data-and-the-worker-kind-runs-it.md): a job is data, and the worker kind runs it (proposed).
587
- - [ADR 0013](./docs/adr/0013-pool-sends-jobs-and-pool-workers-offers-the-workers-of-its-host.md): `Pool` sends jobs, and `PoolWorkers` offers the workers of its host (proposed).
588
- - [ADR 0014](./docs/adr/0014-pool-and-pool-workers-take-one-worker-kind.md): `Pool` and `PoolWorkers` take one worker kind (proposed).
589
- - [ADR 0015](./docs/adr/0015-the-store-is-a-required-input-and-computer-store-gives-the-store-of-the-computer.md): the store is a required input, and `computerStore` gives the store of the computer (proposed).
590
- - [ADR 0016](./docs/adr/0016-the-owners-sizing-caps-the-jobs-of-its-computer.md): the owner's sizing caps the jobs of its computer (proposed).
591
- - [ADR 0017](./docs/adr/0017-the-owner-asks-then-takes-as-many-jobs-as-it-has-free-workers.md): the owner asks, then takes as many jobs as it has free workers (proposed).
592
- - [ADR 0018](./docs/adr/0018-news-travels-by-push-through-the-notify-of-the-store-with-a-backstop.md): news travels by push through the notify of the store, with a backstop (proposed).
593
- - [ADR 0019](./docs/adr/0019-run-waits-and-a-failed-job-rejects-with-the-pools-error.md): `run` waits, and a failed job rejects with the pool's error (proposed).
594
- - [ADR 0020](./docs/adr/0020-a-cancel-of-a-shared-job-is-a-leave-and-of-any-other-job-a-drop-or-a-kill.md): a cancel of a shared job is a leave, and of any other job a drop or a kill (proposed).
595
- - [ADR 0021](./docs/adr/0021-a-caller-whose-host-is-gone-cancels-its-jobs-and-the-owner-learns-it-from-a-closed-connection.md): a caller whose host is gone cancels its jobs, and the owner learns it from a closed connection (proposed).
596
- - [ADR 0022](./docs/adr/0022-the-newest-revision-takes-over-and-an-owner-refuses-a-job-of-an-older-revision.md): the newest revision takes over, and an owner refuses a job of an older revision (proposed).
597
- - [ADR 0023](./docs/adr/0023-ownership-moves-only-by-the-owners-own-act-or-its-end-and-a-standby-stays-cold.md): ownership moves only by the owner's own act or its end, and a standby stays cold (proposed).
598
- - [ADR 0024](./docs/adr/0024-a-hung-owner-is-ended-by-the-election-and-its-late-acts-are-fenced.md): a hung owner is ended by the election, and its late acts are fenced (proposed).
599
- - [ADR 0025](./docs/adr/0025-many-computers-share-one-postgres-store-and-each-computer-keeps-its-own-owner.md): many computers share one Postgres store, and each computer keeps its own owner (proposed).
600
- - [ADR 0026](./docs/adr/0026-start-accepts-a-job-now-and-a-job-handle-reads-its-output-later-from-any-host.md): `start` accepts a job now, and a `JobHandle` reads its output later from any host (proposed).
471
+ - [ADR 0011](./docs/adr/0011-every-pool-is-a-pool-for-the-computer-and-one-owner-pulls-its-jobs-from-a-store-that-every-host-writes-to.md): every pool is a pool for the computer, and one owner pulls its jobs from a store that every host writes to.
472
+ - [ADR 0012](./docs/adr/0012-a-job-is-data-and-the-worker-kind-runs-it.md): a job is data, and the worker kind runs it.
473
+ - [ADR 0013](./docs/adr/0013-pool-sends-jobs-and-pool-workers-offers-the-workers-of-its-host.md): `Pool` sends jobs, and `PoolWorkers` offers the workers of its host.
474
+ - [ADR 0014](./docs/adr/0014-pool-and-pool-workers-take-one-worker-kind.md): `Pool` and `PoolWorkers` take one worker kind.
475
+ - [ADR 0015](./docs/adr/0015-the-store-is-a-required-input-and-computer-store-gives-the-store-of-the-computer.md): the store is a required input, and `computerStore` gives the store of the computer.
476
+ - [ADR 0016](./docs/adr/0016-the-owners-sizing-caps-the-jobs-of-its-computer.md): the owner's sizing caps the jobs of its computer.
477
+ - [ADR 0017](./docs/adr/0017-the-owner-asks-then-takes-as-many-jobs-as-it-has-free-workers.md): the owner asks, then takes as many jobs as it has free workers.
478
+ - [ADR 0018](./docs/adr/0018-news-travels-by-push-through-the-notify-of-the-store-with-a-backstop.md): news travels by push through the notify of the store, with a backstop.
479
+ - [ADR 0019](./docs/adr/0019-run-waits-and-a-failed-job-rejects-with-the-pools-error.md): `run` waits, and a failed job rejects with the pool's error.
480
+ - [ADR 0020](./docs/adr/0020-a-cancel-of-a-shared-job-is-a-leave-and-of-any-other-job-a-drop-or-a-kill.md): a cancel of a shared job is a leave, and of any other job a drop or a kill.
481
+ - [ADR 0021](./docs/adr/0021-a-caller-whose-host-is-gone-cancels-its-jobs-and-the-owner-learns-it-from-a-closed-connection.md): a caller whose host is gone cancels its jobs, and the owner learns it from a closed connection.
482
+ - [ADR 0022](./docs/adr/0022-the-newest-revision-takes-over-and-an-owner-refuses-a-job-of-an-older-revision.md): the newest revision takes over, and an owner refuses a job of an older revision.
483
+ - [ADR 0023](./docs/adr/0023-ownership-moves-only-by-the-owners-own-act-or-its-end-and-a-standby-stays-cold.md): ownership moves only by the owner's own act or its end, and a standby stays cold.
484
+ - [ADR 0024](./docs/adr/0024-a-hung-owner-is-ended-by-the-election-and-its-late-acts-are-fenced.md): a hung owner is ended by the election, and its late acts are fenced.
485
+ - [ADR 0025](./docs/adr/0025-many-computers-share-one-postgres-store-and-each-computer-keeps-its-own-owner.md): many computers share one Postgres store, and each computer keeps its own owner.
486
+ - [ADR 0026](./docs/adr/0026-start-accepts-a-job-now-and-a-job-handle-reads-its-output-later-from-any-host.md): `start` accepts a job now, and a `JobHandle` reads its output later from any host.