RpcClient.layerProtocolWorker: what's the equivalent of Piscina's abortable tasks? (terminate a stuck worker on interrupt, control respawn)
Los mantenedores suelen responder en 1 día
@effect-bot ya está trabajando en esto.
Desde el 16/10/2026.
Evaluación
Este issue todavía no se ha evaluado.
Descripción
What is the problem this feature would solve?
We moved CPU-heavy work in a Node app from Piscina to effect/rpc over worker threads (RpcClient.layerProtocolWorker with NodeWorker.layer). Typed requests, spans that cross into the worker, and Effect's interruption are a real improvement. What we couldn't find is an equivalent of Piscina's abortable tasks, so we rebuilt it around the protocol. Is there an intended way to do this that we missed?
With Piscina, pool.run(task, { signal }) gives two things:
- Aborting a running task terminates its thread. The README says "If the task is already running, the corresponding
Workerthread will be stopped" (README, source). So a deadline (AbortSignal.timeout) stops code that never yields, such as jsdom spinning on a hostile page. Abortable tasks never share a thread, so the kill takes no other task with it. A task still queued is just removed. - A dead thread is replaced only up to
minThreads. Replacement stops altogether once threads fail during bootstrap (source). WithminThreads: 0, the next task starts a fresh thread, and nothing is spawned while no task is waiting.
With layerProtocolWorker, the repro below shows four behaviours. It ran on effect and @effect/platform-node 4.0.4, Node 24.21.0, macOS arm64; the code involved is unchanged on main at 5462ed7.
- Interrupting a running request doesn't stop its thread. The client sends
Interrupt, which the worker handles only when the handler yields. A synchronous handler keeps the thread at 100% CPU. The protocol also releases the pool entry as soon as it sendsInterrupt(RpcClient.ts#L1452-L1458). So the next request goes to the same thread and waits behind the abandoned work: 3.5 s in the repro. - The only way to stop the thread is to close the client's scope, and that takes 5 s.
NodeWorkerposts a close message, waits for the exit underEffect.timeout(5000), and only then terminates (NodeWorker.ts#L55-L64). The 5 s isn't configurable. If you start a replacement meanwhile, two threads run during those 5 s. - A thread that exits is respawned a second later, whether or not a request is waiting. This is
Effect.retry(Schedule.spaced(1000))around the worker'srun(RpcClient.ts#L1397). #7147 kept the respawn deliberately. - A module that can't load is respawned every second for as long as the scope is open: five spawns in 4.5 s.
Repro
npm i [email protected] @effect/[email protected]
node main.mjs
rpcs.mjs
import { Schema } from "effect"
import { Rpc, RpcGroup } from "effect/rpc"
export class Rpcs extends RpcGroup.make(
// Synchronous work that never yields, like jsdom on a hostile page
Rpc.make("Spin", { payload: { ms: Schema.Number }, success: Schema.Number }),
Rpc.make("Ping", { success: Schema.Number }),
// The thread dies mid-request, as it would at its heap limit
Rpc.make("Crash", {})
) {}
worker.mjs
import { threadId } from "node:worker_threads"
import * as NodeRuntime from "@effect/platform-node/NodeRuntime"
import * as NodeWorkerRunner from "@effect/platform-node/NodeWorkerRunner"
import { Effect, Layer } from "effect"
import { RpcServer } from "effect/rpc"
import { Rpcs } from "./rpcs.mjs"
const handlers = Rpcs.toLayer({
Spin: ({ ms }) =>
Effect.sync(() => {
const end = Date.now() + ms
while (Date.now() < end) {
// never yields
}
return threadId
}),
Ping: () => Effect.succeed(threadId),
Crash: () => Effect.sync(() => process.exit(1))
})
RpcServer.layer(Rpcs).pipe(
Layer.provide(handlers),
Layer.provide(RpcServer.layerProtocolWorkerRunner),
Layer.provide(NodeWorkerRunner.layer),
Layer.launch,
NodeRuntime.runMain
)
broken-worker.mjs
// A worker module that can't load, e.g. a missing native dependency
throw new Error("cannot load this module")
main.mjs
import { Worker } from "node:worker_threads"
import * as NodeWorker from "@effect/platform-node/NodeWorker"
import { Duration, Effect, Exit, Fiber, Layer, Scope } from "effect"
import { RpcClient } from "effect/rpc"
import { Rpcs } from "./rpcs.mjs"
let t0 = performance.now()
const log = (...args) => console.log(`[${((performance.now() - t0) / 1000).toFixed(2)}s]`, ...args)
const threads = []
const spawner = (file) =>
NodeWorker.layer(() => {
const worker = new Worker(new URL(file, import.meta.url))
const n = threads.push(worker)
log(`spawned thread #${n}`)
worker.on("exit", (code) => log(`thread #${n} exited (code ${code})`))
return worker
})
const makeClient = (scope, file) =>
Layer.buildWithScope(RpcClient.layerProtocolWorker({ size: 1 }).pipe(Layer.provide(spawner(file))), scope).pipe(
Effect.flatMap((context) => RpcClient.make(Rpcs).pipe(Effect.provideContext(context), Scope.provide(scope)))
)
const section = (title) =>
Effect.sync(() => {
threads.length = 0
t0 = performance.now()
console.log(`\n=== ${title}`)
})
const program = Effect.gen(function*() {
yield* section("1. A request that times out leaves its thread running")
{
const scope = yield* Scope.make()
const client = yield* makeClient(scope, "./worker.mjs")
yield* client.Ping()
log("Spin(5000) with a 500 ms timeout ->", yield* client.Spin({ ms: 5000 }).pipe(Effect.timeoutOption("500 millis")))
const before = threads[0].performance.eventLoopUtilization()
yield* Effect.sleep("1 second")
const after = threads[0].performance.eventLoopUtilization(before)
log(`thread #1 utilisation over the next second: ${after.utilization.toFixed(2)}`)
const [took] = yield* Effect.timed(client.Ping())
log(`the next Ping took ${Duration.format(took)}, on the same thread, behind the abandoned Spin`)
yield* Scope.close(scope, Exit.void)
}
yield* section("2. Closing the scope while a task is stuck takes NodeWorker's 5 s")
{
const scope = yield* Scope.make()
const client = yield* makeClient(scope, "./worker.mjs")
yield* client.Ping()
yield* client.Spin({ ms: 30_000 }).pipe(Effect.timeoutOption("500 millis"))
log("Spin(30000) timed out; closing the client's scope")
const [took] = yield* Effect.timed(Scope.close(scope, Exit.void))
log(`scope closed after ${Duration.format(took)}`)
}
yield* section("3. A thread that dies is respawned a second later, with nothing waiting")
{
const scope = yield* Scope.make()
const client = yield* makeClient(scope, "./worker.mjs")
yield* client.Ping()
log("Crash ->", (yield* Effect.exit(client.Crash())).toString().slice(0, 120))
yield* Effect.sleep("2500 millis")
log(`threads spawned: ${threads.length}`)
yield* Scope.close(scope, Exit.void)
}
yield* section("4. A module that can't load is respawned every second, forever")
{
const scope = yield* Scope.make()
const client = yield* makeClient(scope, "./broken-worker.mjs")
const ping = yield* Effect.forkChild(Effect.exit(client.Ping()))
yield* Effect.sleep("4500 millis")
log(`threads spawned in 4.5 s: ${threads.length}`)
const result = ping.pollUnsafe()
log("the Ping sent at the start:", result ? result.toString().slice(0, 160) : "still waiting")
yield* Fiber.interrupt(ping)
yield* Scope.close(scope, Exit.void)
}
})
Effect.runPromise(program).then(
() => process.exit(0),
(error) => {
console.error(error)
process.exit(1)
}
)
Output:
=== 1. A request that times out leaves its thread running
[0.01s] spawned thread #1
[0.78s] Spin(5000) with a 500 ms timeout -> { _id: 'Option', _tag: 'None' }
[1.78s] thread #1 utilisation over the next second: 1.00
[5.28s] the next Ping took 3s 497ms 937833ns, on the same thread, behind the abandoned Spin
[5.29s] thread #1 exited (code 130)
=== 2. Closing the scope while a task is stuck takes NodeWorker's 5 s
[0.00s] spawned thread #1
[0.65s] Spin(30000) timed out; closing the client's scope
[5.65s] thread #1 exited (code 1)
[5.65s] scope closed after 5s 3ms 373292ns
=== 3. A thread that dies is respawned a second later, with nothing waiting
[0.00s] spawned thread #1
[0.19s] thread #1 exited (code 1)
[0.19s] Crash -> Failure(Cause([Fail(~effect/rpc/RpcClientError: WorkerReceiveError: The worker has exited with code: 1)]))
[1.20s] spawned thread #2
[2.70s] threads spawned: 2
[2.70s] thread #2 exited (code 130)
=== 4. A module that can't load is respawned every second, forever
[0.00s] spawned thread #1
[0.02s] thread #1 exited (code 1)
[1.02s] spawned thread #2
[1.05s] thread #2 exited (code 1)
[2.05s] spawned thread #3
[2.07s] thread #3 exited (code 1)
[3.07s] spawned thread #4
[3.08s] thread #4 exited (code 1)
[4.09s] spawned thread #5
[4.10s] thread #5 exited (code 1)
[4.50s] threads spawned in 4.5 s: 5
[4.50s] the Ping sent at the start: Success(Failure(Cause([Fail(~effect/rpc/RpcClientError: WorkerReceiveError: An error event was emitted)])))
What is the feature you are proposing to solve the problem?
Three suggestions. Any one of them would remove part of our wrapper; together they would cover what Piscina gave us.
-
Terminate on interrupt. An option on
layerProtocolWorker(for exampleinterruptTerminates: true), or an annotation perRpc. When a request is interrupted while its worker runs it, the protocol would:- terminate that worker at once, with no graceful close;
- fail any other requests on that worker;
- drop the worker from the pool, so the next request gets a fresh one.
As in Piscina, such requests would run one per worker. Ideally the interruption would complete only after the worker's
exitevent, so that aSemaphorearound the call bounds the real number of threads. -
A respawn policy. For example
respawn: false | ScheduleonlayerProtocolWorker.falsewould invalidate the pool entry and let the nextPool.getspawn lazily. Separately, when a worker dies before its ready handshake, the protocol would stop respawning and fail waiting requests with the worker's error, as Piscina does once bootstrap fails. -
A configurable close timeout on
NodeWorker.layer, like Piscina'scloseTimeout, where 0 would mean terminate at once.
What alternatives have you considered?
-
Keeping Piscina behind a scoped service. It works, but we would lose typed requests, spans into the worker and Effect's interruption, and the queue would sit outside Effect.
-
What we run now: a wrapper around
layerProtocolWorker({ size: 1 }), one per worker module.- It keeps the
Workerhandle. On a deadline or an interrupt, it callsworker.terminate()itself, waits for the exit, then closes the protocol's scope. - Its spawner throws on a second spawn, so the protocol's retry can't bring the thread back. The next task builds a new protocol with a fresh thread.
- One
Semaphorebounds threads across all modules.
It works, but it depends on the protocol's internals, namely which spawn happens when, rather than on an API.
- It keeps the
-
Cooperative cancellation inside the worker. That isn't possible for third-party synchronous code such as jsdom.
- Lenguaje dominante
- TypeScript
- Estrellas
- 16.7k
- Forks
- 808
- Merge medio
- 11 h 3 min
- PR fusionados (30 d)
- 839
Preparar el entorno
Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de Effect-TS/effect
-
Support OpenTelemetry JS SDK v3 and replace deprecated tracing peers in Effect v4Posiblemente ocupada @effect-bot la tomó hace 1 día. Abierto
Effect-TS/effect#10328 · 1 asignado ·
Los mantenedores suelen responder en 1 día
-
PersistedQueue: offer option that de-duplicates an id only while it is pending or processingPosiblemente ocupada @effect-bot la tomó hace 1 día. Abierto
Effect-TS/effect#10313 · 1 asignado ·
Los mantenedores suelen responder en 1 día
-
shorthand for mapping over tagged union schemaPosiblemente ocupada @effect-bot la tomó hace 2 días. Abiertoenhancement
Effect-TS/effect#10286 · 1 asignado ·
Los mantenedores suelen responder en 1 día
-
Cluster: A way to remove processed requests from storagePosiblemente ocupada @effect-bot la tomó hace 3 días. Abiertoenhancement
Effect-TS/effect#10239 · 1 asignado ·
Los mantenedores suelen responder en 1 día
-
cluster: a runner that lost its shard lock can still write replies and messages for that shardAbierto
Dificultad 5/5 Más de una semana Aptitud para principiantes 35/100
Los mantenedores suelen responder en 1 día
Todos los issues de Effect-TS/effect
Issues similares
-
Add: Yichang TVAbiertocheck:passed streams:add
Dificultad 2/5 1-3 horas Aptitud para principiantes 74/100
Los mantenedores suelen responder en 1 día
-
vtselect: data race in Tempo search tags APIs for invalid TraceQL queriesPosiblemente ocupada @Shubham19032004 la tomó hoy. Abiertobug
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
VictoriaMetrics/VictoriaTraces#304 ·
Los mantenedores suelen responder en 1 día
-
test: claim-conflict drop leaves both facts active and is never re-proposed (untested review cell)Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 83/100
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
microsoft/vscode-pull-request-github#9159 ·
Los mantenedores suelen responder en 1 día
-
[Feature]: Usage page should show API-equivalent cost and say when a connected plan shows info onlyAbiertoenhancement from-x
Dificultad 2/5 1-3 horas Aptitud para principiantes 66/100
nightly-labs/openbot#4867 ·
Los mantenedores suelen responder en 1 día