Repository navigation
Description
We had issues with a service (which happens to use http4s Ember) getting killed by k8s because it became unresponsive. The unresponsiveness includes the liveness check, hence the termination by k8s.
A workaround which seems to have completely eliminate the problem was to
private implicit val network: Network[IO] = Network.forAsync[IO]when creating the Ember server.
If I understand that correctly, that works around the CE normal way of accepting connections and uses a dedicated thread (pool?) instead.
(edit by djspiewak: the following reproducer was discussed later in the thread and found to not be valid; leaving up for historical context but if you're looking into this bug, this doesn't actually represent the problem)
Here is a reproducer (AI generated 😇 ), which could hopefully lead to a proper fix in the core of the CE runtime.
//> using scala 2.13.14
//> using dep org.typelevel::cats-effect:3.7.0
//> using javaOpt -XX:ActiveProcessorCount=4
/*
* cats-effect 3.7.0 — a ready I/O event registered on the integrated `Selector` is NOT delivered
* for as long as its owning worker is not the one that parks-in-poll, EVEN WHILE other worker
* threads sit idle. Run: `scala-cli run CeLostWakeup.scala` (pins the compute pool to 4 workers).
*
* WHY (all in core/jvm-native/src/main/scala/cats/effect/unsafe, v3.7.0):
*
* 1. The poller is PER-WORKER: `WorkStealingThreadPool.pollers` holds one `java.nio.Selector`
* per worker thread.
*
* 2. `SelectorSystem.select(ch, ops)` registers interest via `ctx.accessPoller { poller => ... }`,
* and `WorkStealingThreadPool.accessPoller` always runs that callback on the CURRENT worker,
* passing THAT worker's own selector (`cb(worker.poller())`). So an interest is always armed on
* whichever worker happens to run the registering fiber, and `select` issues NO
* `selector.wakeup()`.
*
* 3. When a worker runs out of work it decides whether to poll with
* `needsPoll = !ownSelector.keys().isEmpty()` (`WorkerThread.scala`), then parks. In
* `parkLoop` / `parkLoopUntilNextSleeper` it blocks in `system.poll(selector, ...)` ONLY when
* `needsPoll` is true (its OWN selector has registered keys); otherwise it parks via plain
* `LockSupport.park()` / `parkNanos(...)` and polls NO selector at all.
*
* => A worker only ever polls its own selector, and any given FD is registered on exactly one
* worker's selector. If that worker is not the one that next parks-in-poll (e.g. it is busy, or
* an I/O loop's re-arm fiber migrated the interest onto it), the ready FD is serviced by NOBODY:
* idle peer workers park "simple" and never poll a selector they don't own. The event waits
* until the owning worker itself next polls, or until some worker's `select(nanosUntilNext-
* Sleeper)` times out at the next scheduled timer — seconds later, with CPU idle.
*
* This program arms MANY OP_READ interests on separate pipes, each on its OWN fiber, so the
* interests get spread across EVERY worker's selector. It then occupies all-but-one worker with
* non-yielding work and makes all the FDs ready at once from a non-cats-effect thread. Every
* readiness callback should fire in microseconds; instead only the interests that happened to be
* armed on the single still-idle worker's selector are delivered promptly — the rest, armed on the
* busy workers' selectors, are stranded ~the full hold while at least one core sits idle. Because
* the interests are spread over all workers, many are stranded on EVERY run (no reliance on a
* single lucky/unlucky placement). A thread dump taken while the events are pending shows the busy
* workers RUNNABLE — none of them polling the selectors on which the stranded FDs are registered —
* while the lone idle worker polls ONLY its own selector (and so delivers just its share). A worker
* with no keys of its own would instead park "simple" in `LockSupport.park`, polling nothing at
* all. Either way the stranded FDs sit on the busy workers' selectors, serviced by nobody.
* Switching fs2-io/NIO from the integrated `Selector` to a NIO2 `AsynchronousChannelGroup` (whose
* dedicated I/O thread delivers completions) avoids this entirely.
*/
import cats.effect._
import cats.syntax.all._
import java.nio.ByteBuffer
import java.nio.channels.Pipe
import java.nio.channels.SelectionKey.OP_READ
import scala.concurrent.duration._
import scala.jdk.CollectionConverters._
object CeLostWakeup extends IOApp.Simple {
private val Workers = Runtime.getRuntime.availableProcessors // = 4 (pinned via javaOpt above)
private val HoldMillis = 2000L // how long all-but-one worker is occupied
private val Interests = Workers * 8 // arm many, so every worker's selector gets some
private val Trials = 6
// A non-cats-effect thread that runs an action on request (so "becomes ready" is genuinely external).
private final class External {
private val q = new java.util.concurrent.SynchronousQueue[Runnable]
private val t = new Thread(() => while (true) q.take().run(), "external-io"); t.setDaemon(true); t.start()
def run(action: => Unit): Unit = q.put(() => action)
}
// One-shot dump: print the compute workers' states while the events are still pending.
private def dumpWorkers(): Unit = {
val sb = new StringBuilder(" [thread dump while the ready events are pending]\n")
Thread.getAllStackTraces.asScala.toSeq.filter(_._1.getName.contains("io-compute")).sortBy(_._1.getName).foreach {
case (th, st) =>
val top = st.take(6).map(_.toString)
val inEpoll = top.exists(s => s.contains("EPoll") || s.contains("SelectorImpl"))
val parkSimp = !inEpoll && top.exists(_.contains("LockSupport.park"))
val tag = if (inEpoll) " <EPOLL: polling its own selector>" else if (parkSimp) " <PARK-SIMPLE: polling NOTHING>" else ""
sb.append(s" ${th.getName} [${th.getState}]$tag\n")
}
System.out.println(sb.toString)
}
def run: IO[Unit] = Selector.get.flatMap { selector =>
val external = new External
val openPipe = IO {
val p = selector.provider.openPipe()
p.source.configureBlocking(false); p.sink.configureBlocking(false); p
}
def oneTrial(i: Int): IO[Unit] =
Resource.make(openPipe)(p => IO { p.sink.close(); p.source.close() }).replicateA(Interests).use { pipes =>
val spin = IO { val end = System.nanoTime() + HoldMillis * 1000000L; while (System.nanoTime() < end) {} }
for {
// (a) Arm OP_READ on each pipe, EACH ON ITS OWN FIBER, so the interests spread across every
// worker's selector. Each fiber records the moment its own event is delivered.
armed <- pipes.traverse(p => (selector.select(p.source, OP_READ) *> IO(System.nanoTime())).start)
_ <- IO.sleep(100.millis) // let (a) finish registering and spreading across the selectors
// (b) Occupy all-but-one worker with non-yielding work, so most workers can neither park-
// in-poll nor steal — but at least one worker stays idle and parks "simple".
spins <- List.fill(Workers - 1)(spin).traverse(_.start)
// (c) Make EVERY FD ready from the external thread, and snapshot a dump ~600ms later while
// the events are (provably) still pending and a core is idle.
firedAt <- IO {
external.run {
pipes.foreach(_.sink.write(ByteBuffer.wrap(Array[Byte](1))))
if (i == 0) { Thread.sleep(600); dumpWorkers() }
}
System.nanoTime()
}
_ <- spins.traverse_(_.joinWithNever)
deliveredAt <- armed.traverse(_.joinWithNever)
_ <- pipes.traverse_(p => IO(p.source.read(ByteBuffer.allocate(8))))
latencies = deliveredAt.map(d => (d - firedAt) / 1000000.0)
stranded = latencies.count(_ > 100)
fast = latencies.size - stranded
// NB: `fast` are the interests that happened to be armed on the one worker left free to
// poll; `stranded` landed on a held worker and waited ~the whole hold, with a core idle.
_ <- IO.println(
f"trial $i: $Interests interests -> fast=$fast stranded=$stranded " +
f"(min=${latencies.min}%.1f ms, max=${latencies.max}%.1f ms)" +
(if (stranded > 0) " <-- STRANDED (no CPU needed to deliver them; a core was idle)" else ""))
} yield ()
}
IO.println(
s"workers=$Workers, arming $Interests interests, holding ${Workers - 1} of them busy for ${HoldMillis}ms per trial\n") *>
(0 until Trials).toList.traverse_(oneTrial) *>
IO.println(
"\nExpected on a healthy runtime: every interest ~<1 ms. Observed: the majority ~the hold time, with a core idle.")
}
}
Activity
djspiewak commentedon Jun 29, 2026
This is a symptom of starvation. If you have large chunks of non-yielding work, those worker threads will not be able to do anything else. Starvation pathologies are somewhat mitigated in the pure-compute case by work stealing, and similarly in the timer case, but we don't at present support a general mechanism for stealing event registration.
More generally, Cats Effect's scheduler takes the prescription that starvation mitigation is always best effort, since there's simply no way to mitigate it in all cases: if you have long-duration thread blockage or other non-yielding tasks, the system will almost always degrade rapidly. So in other words, we try to help this case be a bit more graceful, but at the end of the day, you're just using the system in unsupported ways.
Do you genuinely have extremely large-granularity non-yielding tasks as in the reproducer? Or was that simply AI just reaching for any way to reproduce the issue?
sideeffffect commentedon Jun 30, 2026
No, we don't have large non-yielding tasks.
The spin loop in the reproducer was an AI device to force the mechanism, not a model of our workload. Sorry for the red herring. The heaviest synchronous step in the service is a ~ms RSA sign on token mint, and our thread dumps show it isn't even running when the freeze hits.
The service is a plain http4s-Ember server on cats-effect
3.6.33.7.0 (default integratedNetwork). We caught a clean mid-stall thread dump during a real liveness freeze (fired by a watchdog while the stall was in progress, before any SIGTERM). At that instant:SelectorSystem.poll→WorkerThread.parkLoopUntilNextSleeper→EPoll.wait(idle, ~0.12 of 4 cores), no business/RSA frames;/meta/healthy, just returns"ok") connects but gets no response —Read timed out— for ~20s, until the pod is killed; established/keep-alive traffic is unaffected.So a ready
OP_ACCEPT(and the static handler that would follow) isn't delivered while the pool sits idle in the poller. It's rare (~1/pod-day) and we could not minimally reproduce it 😿 . We did rule out two obvious candidates: the cross-threadinterestOps-while-another-worker-is-in-select()race (self-heals, sinceaccessPollerregisters on the running worker), andIO.blockingworker-detach orphaning a selector (the poller follows the worker index to the replacement).Switching the server to
Network.forAsync(NIO2) eliminates it entirely.Does an idle-pool stranded accept ring any bells? Somewhere the accept-loop's readiness/re-arm could be lost while workers are polling?
djspiewak commentedon Jun 30, 2026
That sounds a lot more like a proper bug. I wonder if there's some race condition here where selector registration can get lost, either in the polling system or in
Network? Do you have an easy way to try CE 3.7?sideeffffect commentedon Jul 1, 2026
Hello Daniel, let me apologize for the misinformation. On a second look, I realized we've been running on Cats Effect 3.7.0 for a long time already. That means these freezes (causing k8s terminating the pod) have been happening on 3.7. And, for what it's worth, the workaround with
Network.forAsync[IO]did the job on that version.djspiewak commentedon Jul 1, 2026
Okay excellent. Well as I said, this sounds like a fairly rare race condition in selector registration. We need to hunt it down but if you're able to get any other form of minimization it would definitely help.
sideeffffect commentedon Jul 3, 2026
Would this (AI generated) reproducer be helpful to you?
Run:
MODE=selector scala-cli run SelectorReflect.scala --java-opt -XX:ActiveProcessorCount=4(pin 4 workers). AIO control:MODE=aio ….What it is: not a hang — the pool stays healthy (max fresh-connection probe ~23–57ms). It's a reflective detector: a raw OS thread snapshots each worker-selector and flags a
SelectionKeywhose interest is READY while the owning worker is idle-parked (not in that selector'sselect) and no worker is in epoll.Result: over ~8 min / ~3.6M accepts on the integrated selector it flagged 5–6
DEFINITE-READYstrands (readyOP_ACCEPTon a parked owner); onNetwork.forAsyncunder identical load: 0.durban commentedon Jul 8, 2026
A blocker thread cannot be the owner of a poller, so something is wrong, either with the generated code, or possibly just a race with getting the thread name.
A heap dump in the known-incorrect state would be really helpful. Or at least the mentioned thread dump.
sideeffffect commentedon Jul 8, 2026
djspiewak commentedon Jul 8, 2026
Also makes me wonder if we have a weird race condition in the interaction between blocker state migration and selector events.
durban commentedon Jul 8, 2026
Yes, that seems like a good thing to look at. I tried, and couldn't find anything obvious. (Which, of course, doesn't mean there isn't one...)
durban commentedon Jul 9, 2026
There is a problem with new blockers and pollers: #4631. My theory is that that problem is causing this issue, but I can't be sure (details in the PR description). I tried really hard to reproduce this issue based on that theory, but couldn't. I think the way forward now is to make a "temporary" release from the PR branch, and maybe @sideeffffect could test it. (I really should know how to make a release from a branch, but I don't.)
sideeffffect commentedon Jul 10, 2026
Just let me know the coordinates of a JAR and I'd be happy to deploy it to our production environment.
djspiewak commentedon Jul 17, 2026
@durban Making the release now!
We definitely should get you all set up with the relevant credentials if we haven't already. You need permissions to publish on the
org.typelevelgroupId, and a GPG signing key of some sort (rip web of trust…). Sonatype has changed the procedures for the former over the years so I'm not entirely sure what's current, but once you have those two things, you can runsbt releaseat any time and it'll do the right thing. I recommend running acleanbefore you do though just to make sure zinc hasn't deceived you.djspiewak commentedon Jul 17, 2026
@sideeffffect Try
3.7.0-15-0d069d3when you get a chance!sideeffffect commentedon Jul 18, 2026
The reproducer uses
IO { spinloop }(IO.delay, notIO.blocking), so the #4631 fix (stale_polleron a blocking thread) does not apply here. The idle worker (io-compute-3) still parks without polling any selector while the OP_READ interest sits on one of the spinning workers' selectors.durban commentedon Jul 18, 2026
(@djspiewak I do have the ability to publish on maven central (under my own groupId), so likely just a permission setting is needed for
org.typelevel. My maven central username isdurban.)sideeffffect commentedon Jul 23, 2026
After a few days in Production, we see that
3.7.0-15-0d069d3did not fix the problem we have:all 4 worker threads look like this
and
io-compute-blocker-*threads are parked inSynchronousQueue.pollI'm sorry the AI reproducers are of no help 😿 Is there some other way I can be helpful in getting this fixed?
reardonj commentedon Jul 24, 2026
Have you been able to reproduce it in an environment where you can hook up a debugger and poke at the state some more?
djspiewak commentedon Jul 29, 2026
Thought about this some more…
If you're willing to spill some tokens on this problem, I would get a complete heap dump from a production pod where this is happening. Then, hand that dump to an agent together with the Cats Effect sources and tell it to piece together the state of the worker threads, selectors, and polling system. Once it does that, cross-check it carefully, then have it work backwards to form some hypotheses as to what's causing that state to arise.
This is also probably a reasonable way to distill a minimal reproducer btw, if one exists.
But you should be able to get all this and then have the agent scrub it of anything which is specific to your application, which ultimately will give you something you can share with us. Intuitively, this feels like a pretty chunky series of sessions. Probably a couple billion tokens from a Sol/Fable class model unless we get lucky and it's something stupid-simple. I wouldn't bother trying it with any of the weaker models.