160 points · by thunderbong · 2y ago · 126 comments
For timeouts, I want to be able to build web application features which are guaranteed to terminate early after eg 2s in a way that resets all resources related to the operation.
The best way I've found of doing this so far involves proceses: run the time-bound operation in an entirely separate process and terminate it early if necessary.
I do that with "rg" here: https://github.com/simonw/datasette-ripgrep/blob/a40161f6273...
It seems to me that the root issue is that encapsulation becomes our enemy here. We want to be able to call some code and not care about the details of how it is implemented. But reliable cancellation requires some sort of design that lets us know exactly what side-effects code has, control them, and force them to be done in a way that's transactional, while still letting us cancel the operation at the right time. We don't want a black box.
I suspect the two general solutions are: 1) elbow grease: manually inspecting the code that you're calling to understand whether it's safe to cancel and designing a bespoke sandbox: a thread in some cases, a process in others, re-architecting the code you're calling in others... 2) something about algebraic effects or capability systems that I can't speak to because I only have vague ideas how they work and haven't applied them in anger.
All processes should be prepared for a sudden crash without corrupting state. Things get OOM killed, machines get unplugged, networks go offline. We have things like journals and write-ahead-logs and at-least-one messaging precisely because of these kinds of problems. If your process can't handle being terminated at any time then you have problems regardless of if it's wrapped in timeout code.
Doing this for a block of code within a process is a lot harder, because a) there's generally more surface area of externally-observable state, and b) code does not normally need to be prepared to handle it.
In particular, I'd challenge you to find one large program that handles OOM situations 100% correctly, especially since most code runs atop an OS configured to over-allocate memory. But even if it wasn't, I doubt there's any sizeable codebase that handles every memory allocation failure correctly and gracefully.
That context then has a .Done() method that returns a channel; when a value is written to that channel, whatever functions are using that context are expected to stop themselves at the soonest point that makes sense to them.
Typically this is done inside a for loop in long-running processes. I.e. for something that copies, it looks like
for {
select {
case <-ctx.Done():
// we should stop and return a timeout error or something
default:
// copy some number of bytes, or check if a network call is done
}
}
It does require all of the involved functions to implement support for this, though I think most things do at this point. I wouldn't call a library high quality unless it supports context.Context for long-running operations.It gives library authors the ability to determine at what points their code can be interrupted, run cleanup code as part of the timeout, etc.
> The best way I've found of doing this so far involves proceses: run the time-bound operation in an entirely separate process and terminate it early if necessary.
This doesn't handle remote resources cleanly, does it? E.g. if I were to lock a Postgres table for a query, and that query times out, will that correctly unlock the table and close the client? Or e.g. lock files? I'm sure some of that can be handled very carefully by managing it in the main process, but that seems error prone.
Except for reading and writing data from a file using 'os.File', or reading and writing data from a network socket using a 'net.Conn'.
Support for contexts is quite lacking in that the 'io.Writer' and 'io.Reader' interface don't have it, and those are the most important places to have it.
Context also has the problem of waiting for cancellation to complete.
Once you call "cancel()", it async tells a lot of goroutines to teardown, but it's painfully hard to know when they've noticed the cancellation and halted work, which in practice often leads to very subtle data-races.
> [Terminating processes] doesn't handle remote resources cleanly, does it? E.g. if I were to lock a Postgres table for a query, and that query times out, will that correctly unlock the table and close the client? Or e.g. lock files?
Both postgres and file locks will correctly handle cleanup if the process dies (postgres notices the connection is dead and ends the transaction, the kernel releases filesystem locks a process is holding when it terminates).
This is necessary because a process may exit basically at any time for any number of reasons, such as the kernel OOM-killing it.
> Support for contexts is quite lacking in that the 'io.Writer' and 'io.Reader' interface don't have it, and those are the most important places to have it.
In a context world, you would use io.Writer/Reader or net.Conn to write small bits of data and check whether the context is cancelled in between 1KB writes (or whatever size).
There is an edge case where it hangs (e.g. on writing to a crappy NFS share) but to the best of my knowledge, that stems from the kernel not being able to interrupt already-queued IO and some knock-on effects related to PIDs owning FDs. E.g. `ls` can't be interrupted when trying to list an NFS dir that's unstable.
Would love to be told I'm wrong there if I am.
> Once you call "cancel()", it async tells a lot of goroutines to teardown, but it's painfully hard to know when they've noticed the cancellation and halted work, which in practice often leads to very subtle data-races.
I typically just defer a function in the goroutine that either writes to an "IsDead" channel or sets a mutex-protected boolean (depending on whether I need a single notification that it's dead, or a persistent way to check whether it's dead). It's not as simple as I'd like, but it's also not terribly hard.
> Both postgres and file locks will correctly handle cleanup if the process dies (postgres notices the connection is dead and ends the transaction, the kernel releases filesystem locks a process is holding when it terminates).
I was under the impression that it takes time for Postgres to notice the connection is dead; am I incorrect there? I thought that if a process terminates unexpectedly, Postgres would wait for its own timeout before terminating the client and freeing any resources used by it. I know it won't leak memory for forever, but having a table locked for 30 extra seconds could be a big problem in some situations (i.e. a monolithic DB that practically the whole company uses).
goroutines observe this cancellation asynchronously. You can cancel an operation from your point of view, and begin another one (a retry of the first, or another operation altogether), but the original one is still running, creating side effects that get you into unintended states. If one can be running, potentially any number can be. You have to make sure to actually join on all past operations completing before beginning any new ones, and not all libraries give you a way to synchronously join on asynchronous operations. If you write your own, it's very possible, it just takes a lot of care.
When you select { } multiple non-default arms like this, and more than one of them is "ready", which one gets selected is random. This avoids starvation and is the right way to implement select { }, but most code that checks for cancellation incorrectly pretends this is not the case and that it will observe cancellation at the earliest possible time. It actually has an exponential probability series of observing cancellation later and later, compounding with the above issue. If the work done between select is long (e.g. CPU or IO work) this compounds even further. The correct solution is to select for cancellation again on just one non-default arm, but that is not "idiomatic" so nobody does it.
All of this is manageable with due care. Some libraries make it impossible because they kindly encapsulate not just what you don't need to know but what you actually do need to know if you want correct deterministic behavior. In my experience, very few deveopers, even of popular libraries, actually understand the semantics Go promises and how to build correct mechanisms out of them.
Allthough to the grandparent's point, whne you're dealing with executables or libraries outside of your control, the only true way I know of to get a "handle" on them is to create a process, with its pid becoming your handle.
In situations like image processing, conversion, video transcoding, document conversion, etc. you're often dealing with non-Go-native libraries (although this problem transcends language), and there's no way to time-bound processes. That is to say that you often need to consider the Halting Problem and putting time bounds and preemption around execution. So what I've had good success with is adding a process manager around those external processes, and when a timeout or deadline is missed, kill the pid. You can also give users controls to kill processes.
Obviously there are considerations with resource cleanup and all sorts of negative consequences to this, depending on your use case, but it does provide options for time bounding and preempting things that are otherwise non-preemptable.
That is awkward. My first thought is "just don't use the library" but that's obviously a non-starter for a lot of things, and my second thought was "transpile it" which sounds worse.
I suppose the signals do allow the binary/library to do its own cleanup if it's well-behaved, so it's really a binary/library quality issue at the end of the day as is something Go/Python/whatever native. There isn't a massive semantic difference between ctx.Done() and a SIGHUP handler; a SIGHUP handler can also defer killing the process until a sane point after cleanup.
Totally agree.
I've worked in the past on a multi-camera computer vision system in which I used video4linux to capture images from USB cameras which would sometimes misbehave and block on an ioctl() forever. Not even SIGALRM helped.
The only mechanism that could be properly interrupt this situation was a Process, via SIGKILL, which caused OS to clean up all the resources afterwards. Eventually, we connected the cameras to a USB-controlled relay that mechanically replugged the cameras after a certain number of timeouts (ioctl freezes) were exceeded one after another.
That sounds interesting too.
In the case of a blocked process, you may be able to force kill it at a system level but then you risk uncleaned up state (leaked connections/resources)
For instance, this is the default behavior with Postgres (queries complete even if the connection is closed)
But that only works if you trust the code you are executing. If you don't you pretty much have to either use the primitives provided by your OS or run your own interpreter (LUA and WASM are popular for a reason)
.NET and go seem to fairly good around request cancellation facilities
I wanted to add a "!calc" trigger to an IRC bot written in Python. Rather than implement the Shunting Yard Algorithm [0] to make sure PEMDAS was handled correctly, I wanted to use `eval` (With some extra steps with the AST library to make a whitelist of AST nodes to prevent code injection), but with Python supporting essentially infinite integer precision, someone writing "!calc 9 * 9 * 9 * 9 * 9 * 9 * [..]" would eat up my entire CPU.
I solved it the same way. I execute it in a separate process and terminate it if it takes more than a couple seconds.
It took me awhile to realize that good error reporting was part of the UX as much as any other feature I wanted to create for users, and that it deserved a seat at the table of the API interfaces.
I think handling timeouts properly is exactly the same case; like TFA mentioned, there is no such thing as a safe/general way to externally terminate a thread of execution. If you want timeouts to be part of your UX, you need to build it just like any other feature.
There's really no safe way to cover all cases unless you create a really scoped down interface that are explicit in what they do.
One use case might allow abrupt interruption with no cleanup (like in the case the OS is powering down) and another interrupt it might be imperative to cleanup (a long running program that can leak resources)
* This issue plays out differently for compiled languages vs interpreted languages, but does apply to both. In particular, in many interpreted languages, the unfixable (for user code, at least) issue is "what happens if I get an exception after constructing the object but before assigning it to a local/member variable"? For compiled languages a similar issue may be "what if it's still in a register", though they generally handle this.
* Even for languages without dangerous thread APIs, it usually applies to MemoryError, and possibly others (e.g. signals, at least "interrupt" and "quit") as well (e.g. Python, despite having increasingly broken signal handling in general, still causes this for the main thread)
* True asynchronous exceptions aren't actually necessary; it suffices to manually check for exceptions on every non-finite backward jump (that is, every non-unrollable loop iteration except the first), every (generally, uninterruptible) syscall (or call to native code), and every memory allocation. For some particular language design choices, you might also want to check every memory access, though this is unlikely to be the same.
* This is much less of an issue in a language with destructors; try-finally, Python-style-with, try-with-resources, defer, etc. are all fatally flawed. It's still possible to write bad code in a good language if you try hard enough, but at least it is possible to write good code as well.
fun doLongRunning(): Single<Result> {
return Single.create { emitter ->
val longProcess = /* whatever */
emitter.onSuccess(longProcess_result)
emitter.setCancellable {
cleanup(longProcess)
}
}
}
doLongRunning()
.timeout(5_secs)
.subscribe({ result ->
}, { error ->
})It throws an exception _anywhere_ in the worker process to signal the timeout, but in practice the exception is often eaten by too-generic except blocks in library code and never reaches user code.
An interesting solution is structured concurrency because it introduces "raise-safe" points (the "await"s), but the ecosystem is not there yet.
Interesting, C# has a special case for this:
>ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block.
I saw a StackOverflow post about some code that only worked on Linux and not Windows and it turns out sleeps on Windows are implemented using an uninterruptible API (I think there are other APIs on Windows but the developers of Python picked the one they did since it was simple/low overhead)
* Maybe not a perfect description but it was something about a non interruptible Windows API
Not sure if they changed it but iirc Python was using a less precise timer on Windows that couldn't sleep less than 14-15ms as well
This is kinda half-true, since C++ inherits aspects of the C environment, in this case on POSIX systems pthreads async cancellation [https://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_ca..., https://www.man7.org/linux/man-pages/man3/pthread_cancel.3.h...]
You can control this through pthread_setcancelstate(), and if it is enabled it will only trigger on specific documented places in C library / system API calls. It is vaguely saner than this generic "throw exception on another thread" concept, but still pretty insane IMHO. Haven't used it myself, not sure if there are circumstances/use cases where I'd enable it.
(To be fair, a lot of other languages are built on top of the C library too and inherit this same behavior, so this isn't quite C++ specific.)
> * If a signal handler interrupts the execution of an unsafe function, and the handler terminates via a call to longjmp(3) or siglongjmp(3) and the program subsequently calls an unsafe function, then the behavior of the program is undefined.
Also note that pthread_cancel() provides a way to block asynchronous cancellations via pthread_setcancelstate().
I have seen some libraries that do error handling via the user passing a callback for a longjmp, but even that seems ill advised. Fortunately it is always optional.
longjmp() is just one prominent item on that list of things you can't (or shouldn't do.) None of the items on that list allow you to cleanly terminate the thread (you can send another signal to yourself or another thread, but that's only very conditionally helpful.)
pthread_cancel() does the one and only sane thing - implement a flag mechanism that is checked in a bunch of well-specified places, and gated with an enable. Whether these well-specified places work for a particular application is definitely a tough question, but either way anything sane will be some type of "set flag and interrupt long-running (I/O) operations" combination.
# Recursive function that never terminates:
iex> f = fn i, f -> if rem(i, 100000) == 0 do IO.inspect(i) end; f.(i+1, f) end
# Start the function in a task with a 1 ms timeout
iex> Task.async(fn -> f.(0, f) end) |> Task.await(1)
My expectation here is that the task would output 0, then get killed when it hits the timeout. And I do get a timeout "exit" message logged with the child pid. But ALSO, the numbers keep printing as though the child task is still running! It appears to be specific to the configuration of the iex process but I'm not sure what it is - any Elixir/Erlang folks who can explain exactly what is happening here?[0] - https://github.com/elixir-lang/elixir/blob/v1.16.3/lib/elixi... [1] - https://github.com/elixir-lang/elixir/blob/v1.16.3/lib/elixi... [2] - https://github.com/elixir-lang/elixir/blob/v1.16.3/lib/elixi... [3] - https://github.com/elixir-lang/elixir/blob/v1.16.3/lib/elixi...
Relevant from https://hexdocs.pm/elixir/1.4.5/Task.html, which you've probably already seen:
> If the timeout is exceeded, await will exit; however, the task will continue to run. When the calling process exits, its exit signal will terminate the task if it is not trapping exits.
> If the timeout is exceeded, then the caller process will exit. If the task process is linked to the caller process which is the case when a task is started with async, then the task process will also exit.
Reasoning is the same though; self() preceding/following it in the IEx session still shows the same evaluator process alive.
** (exit) exited in: Task.await(%Task{mfa: {:erlang, :apply, 2}, owner: #PID<0.954.0>, pid: #PID<0.964.0>, ref: #Reference<0.1455049351.208994307.4788>}, 1)
** (EXIT) time out
(elixir 1.14.3) lib/task.ex:830: Task.await/2Alternatively, the await might killing the waiting process, not the process being waited on.
The same type of danger can be encountered with the linux `kill` command, depending on which signal you send, losing power, operating system terminate, etc. If you have state in flux, hard killing a process can have unexpected outcomes.
I'd also like to say that just because something is dangerous, doesn't mean it should not be used. Just use it carefully. Think of it as dynamite. Dynamite is very useful in some cases, and always needs to be handled with care.
InterruptedException is better, but requires something closer to cooperative multi-tasking. If the thread is in a long-running loop that's not doing IO or it swallows the InterruptedException, you won't actually be able to kill the thread.
At work, someone had implemented an interface that let you kill a thread prior to my joining the company, so I found out that the warnings are very real when someone did that and it left the application unable to fetch DB connections.
Some more discussion of the problems this creates in Rust: https://without.boats/blog/asynchronous-clean-up/
One solution would be linear types that can't be dropped, but interactions with generics and panics make it hard.
In NodeJS/Browser environments, you have the exact same behavior where promises you are awaiting can get rejected.
On the other end of the spectrum you have go, where in fact every line does need to have their error conditions explicitly checked. How do they handle this situation?
What is dangerous with finally-blocks is if they start consuming a lot of time, such that the timeout interruption itself makes the timeout miss its deadline. Usually you need 2 timeouts, one for the main operation and a second for the cleanup.
[0] https://www.schneems.com/2017/02/21/the-oldest-bug-in-ruby-w...
[1] https://github.com/zombocom/rack-timeout (c.f. term_on_timeout)
The two big benefits are (1) if you pass the cancellation token to the task that might be canceled, hopefully it will be obvious that the task might be canceled; and (2) the task that might be canceled has a way to find out it’s being canceled and, if that ever happens, it can clean up.
If you can't trust the process, fork, wait in the parent, and kill the child if it hasn't terminated.
I don't think alarm() is exposed in Ruby, unless it's been added recently, but it's easy enough to add. However since fork + kill is more reliable anyway, it's often a better choice.
Timeout is for threads not processes, and not everything that would be done on a thread can be conveniently rewritten to be a separate process.
Say you're looping over 1m items, maybe every 1k you check to see if you're out of time and return or raise
Why Ruby’s Timeout is dangerous and Thread.raise is terrifying - https://news.ycombinator.com/item?id=10638629 - Nov 2015 (20 comments)
The drawback of this approach is that the onus is on anybody writing code which might be cancelled to correctly mark the uncancelable regions.
There's a fundamental tension between 'stop now' and 'close your file handles before stopping'.
Haskell libraries are written this way all the time. Exception-safe libraries with async-aware handling are pretty commonplace nowadays (partially thanks to safe-exceptions and unsafeio providing a nice API to deal with them.)
- the shared-nothing structuring means it’s harder to corrupt external - that processes can die at any moment is part of the culture - the supervision tree means the most likely case for killing an other process is a parent killing a misbehaving child, which they can then handle as if the child had faulted
Some of it too is just Erlang being too, err, for lack of a better word "weak" to have some of the problematic resources. Since Erlang has no "locks", you simply can't take a lock and then kill the thread responsible for unlocking it. You can construct such locks at a higher level, but Erlang's design tends to encourage other designs. For instance, if I were designing a higher-level lock, I'd design it to link to the process taking the lock and release it if it dies. This can still theoretically get you into trouble but especially if this is documented as the semantics of the lock, you have to work a lot harder at it.
If you really worked at it you could manage to screw up your Erlang system with thread killing through your own lock implementation and such, but it still will be something you can recover from the REPL, you won't confuse BEAM itself. In an imperative language you'd be ranging from lucky to be able to reach in somehow and fix it to there simply being no way.
There are also plenty of footguns when you attempt to catch exceptions. A piece of code might intend to catch all synchronous exceptions (raised in the current thread) but accidentally catches asynchronous exceptions. Again this is a novice issue. When that happens, cancelling a thread doesn't work because thread cancellation is implemented with async exceptions.
What makes things good is that firstly pure code can only raise exceptions but not catch them. (If you need error handling in pure code, you use the Either monad not exceptions.) This dramatically reduces chances of coding mistakes because exceptions aren't as overused as some other languages. Secondly the Haskell community more or less shuns on direct use of these low-level exception handling APIs and everyone uses the async library https://hackage.haskell.org/package/async-2.2.5/docs/Control... which solves not only this problem but also provides nice abstractions to build concurrent computations. Check out its Concurrently type: you now have an Applicative that represents concurrent computations which reuse all your intuition from all Applicative instances. You don't even need to manually create threads or kill threads. Overall insofar as Haskell being the only language where throwing exceptions at another thread isn't a box of footguns, it's only because the language allows a sufficient amount of abstraction power that frees the programmer from using the error-prone low-level APIs. The actual low-level APIs are still full of footguns.
That said, the other big difference with Haskell is the low-level API actually provides functionality to solve the exact problem of an async exception being raised anywhere via `mask`. It's still hard to use correctly but at least it's possible.
It also has good learning material on the subject in the form of thorough blog posts.
It has robust, types abstractions for both throwing, catching, and masking exceptions.
Its exception runtime implementation is better built too.
[1]: https://hackage.haskell.org/package/base-4.20.0.1/docs/Contr...
[2]: https://hackage.haskell.org/package/base-4.20.0.1/docs/Contr...
Pretty funny that Haskell of all languages also has best-in-class exceptions & exception handling haha.
https://fasterthanli.me/articles/i-want-off-mr-golangs-wild-...
Agreed. My point was rather that this is not Ruby's only dangerous shortcut.
IKR!? Like, I'll be click-click-clicking away on my 1982 IBM PC/XT, I mean I'm REALLY hammering it, like REALLY leaning into the keystrokes. Then, all of a sudden, WHAM! Out pops some random lines of code; right at the end of my thread.abort block. I mean, D00000D. OMFG. This can happen anywhere! Anytime! How is any programmer supposed to know what their code is executing?!
I guess I tend to believe, if you don't know what you are doing, then don't do it.
If this is that big of an issue, maybe try real estate. Say it with me, "three-brrr", "two-brrr". Good. Now together...
Also, "idempotent". Everyone keeps dancing around that. Not sure why.