Skip to content

Commit 9e304cd

Browse files
fix(shared): DrainableWorker shutdown uncounts only the dropped items
Zeroing the count on shutdown assumed the worker fiber had already exited. Under a parallel scope the in-flight item's own decrement could then run afterwards and leave the count at -1. Only the dropped items are uncounted now; the running item still uncounts itself. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 6794856 commit 9e304cd

1 file changed

Lines changed: 12 additions & 6 deletions

File tree

‎packages/shared/src/DrainableWorker.ts‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -40,26 +40,32 @@ export interface DrainableWorker<A> {
4040
* processing later items and `drain` still resolves.
4141
*
4242
* @param process - The effect to run for each queued item.
43-
* @returns A `DrainableWorker` with `queue` and `drain`.
43+
* @returns A `DrainableWorker` with `enqueue` and `drain`.
4444
*/
4545
export const makeDrainableWorker = <A, E, R>(
4646
process: (item: A) => Effect.Effect<void, E, R>,
4747
): Effect.Effect<DrainableWorker<A>, never, Scope.Scope | R> =>
4848
Effect.gen(function* () {
4949
const outstanding = yield* TxRef.make(0);
5050
const queue = yield* Effect.acquireRelease(TxQueue.unbounded<A>(), (queue) =>
51-
TxQueue.shutdown(queue).pipe(Effect.andThen(TxRef.set(outstanding, 0)), Effect.tx),
51+
// Uncount only the dropped items: an item still running uncounts itself,
52+
// even when a parallel scope closes it after this finalizer.
53+
TxQueue.clear(queue).pipe(
54+
Effect.flatMap((dropped) => TxRef.update(outstanding, (n) => n - dropped.length)),
55+
Effect.andThen(TxQueue.shutdown(queue)),
56+
Effect.tx,
57+
),
5258
);
5359

5460
yield* TxQueue.take(queue).pipe(
5561
Effect.flatMap((a) =>
5662
// `suspend` turns a `process` that throws while building its effect
5763
// into this item's defect instead of the loop's.
5864
Effect.suspend(() => process(a)).pipe(
59-
// Interrupting the worker fiber (its scope closing) skips this
60-
// handler, so only the item's own failure, defect, or interruption
61-
// lands here and the loop continues. Callers treat an item that only
62-
// interrupted itself as cancelled, not failed.
65+
// Only the item's own failure, defect, or interruption lands here and
66+
// the loop continues; interrupting the worker fiber still stops it.
67+
// Callers treat an item that only interrupted itself as cancelled,
68+
// not failed.
6369
Effect.catchCause((cause) =>
6470
Cause.hasInterruptsOnly(cause)
6571
? Effect.void

0 commit comments

Comments
 (0)