News for hackers. Stuff that matters.
Re:Ruby 3.0 and the new FiberScheduler interface by rdw on Tuesday December 29, 2020 @03:01PM (#25574113)
> all relevant standard library methods have been patched to yield to the scheduler whenever they encounter a situation where they will block the current fiber

This is huge. They solved the function-coloring problem by deciding that all functions are now potentially async. It makes it more likely that the ecosystem as a whole actually becomes async-compatible. I wish Python had taken this approach, though I understand why they didn't.

Re:Ruby 3.0 and the new FiberScheduler interface by WJW on Tuesday December 29, 2020 @04:09PM (#25575051)
(Author here)

I kinda agree but yielding only on I/O is not enough IMO. Sooner or later we'll want to do CPU intensive work in fibers as well, which in the current implementation will block all other fibers on the same thread. Like I mentioned in the article, I'd like to see work stealing between different threads as that would allow fibers to migrate away from threads stuck in CPU intensive work. An alternative way could be to adopt a model similar to Haskells lightweight threads, where the runtime forces a `yield` after N milliseconds (configurable). That would make sure that CPU intensive work would not block other fibers "too" much.

Re:Ruby 3.0 and the new FiberScheduler interface by anonacct38 on Tuesday December 29, 2020 @04:33PM (#25575319)
Go's journey here has been interesting. Early on it was possible (though rarely seen in practice) to end up with a cpu bound thread not yielding because it didn't hit yield point like I/O.

Then they added a guarantee that if your loop called a function, the scheduler would be able to make the goroutine yield. https://golang.org/doc/go1.2#preemption

This mostly worked although you could still have a CPU-bound thread not making any function calls. I also personally ran into a pathological issue where the scheduler was being invoked, but a heuristic kept the current goroutine running so others were still starved.

Finally they added true pre-emption (not yielding) in 1.14 https://golang.org/doc/go1.14#runtime it looks like it just sends signals and saves state.

Once nice thing is that if I understand the go runtime correctly, work stealing by scheduling goroutines on different threads has been a thing for a long time.

Re:Ruby 3.0 and the new FiberScheduler interface by nesarkvechnep on Tuesday December 29, 2020 @04:31PM (#25575299)
This is not only the way Haskell's scheduler work but also Erlang VM's. Not completely the same because the BEAM scheduler uses reductions instead of time but both scheduling schemes can be classified as preemptive. Since fibers are cooperatively scheduled I don't believe the core developers of Ruby would just agree to switch the scheduling scheme.
Re:Ruby 3.0 and the new FiberScheduler interface by matheusmoreira on Tuesday December 29, 2020 @10:21PM (#25578069)
> Sooner or later we'll want to do CPU intensive work in fibers as well, which in the current implementation will block all other fibers on the same thread.

This limitation is present in every modern asynchronous programming system I've ever seen. They simply can't deal with long function calls. There's a loop under the hood which constantly executes queued functions. Any long-running function will stall the execution pipeline and increase latency. It's just like cooperative multitasking...

Re:Ruby 3.0 and the new FiberScheduler interface by Rapzid on Tuesday December 29, 2020 @10:35PM (#25578157)
Golang, .Net, and BEM all use preemptive scheduling IIRC. Don't know the specifics of each implementation, but you can use timers to signal the process and "wake" the scheduler.
Re:Ruby 3.0 and the new FiberScheduler interface by masklinn on Wednesday December 30, 2020 @02:11AM (#25579375)
Beam uses reduction, basically instructions count. I believe native functions can still lock up a scheduler (and must provide an estimate of their icount) which is one of the reasons why they’re tricky.
Re:Ruby 3.0 and the new FiberScheduler interface by valenterry on Tuesday December 29, 2020 @10:37PM (#25578177)
That depends. A long-running function is usually just a semantically long running function which consists of multiple (usually suspendable) parts. Of course there are exceptions, such as long running cpu heavy calculations for which a single atomic call takes longer than just milliseconds. But I think this is rather rare.

And for just semantically long running functions, it is not difficult to write a scheduler that tries to be "fair", however you want to interpret that. But of course it requires to fully embrace asynchronous programming, something that will probably difficult in Ruby.

Re:Ruby 3.0 and the new FiberScheduler interface by hamandcheese on Wednesday December 30, 2020 @01:16AM (#25579103)
Ruby already handles this for regular threads by setting a timer for how long one thread can hold the GVL, doesn’t it? Could the same thing work for fibers? I.e. could the ruby vm inject a yield into a running fiber after every 100ms?
Re:Ruby 3.0 and the new FiberScheduler interface by cogman10 on Tuesday December 29, 2020 @03:37PM (#25574615)
This is essentially the approach Java is taking with the upcoming loom project.
Re:Ruby 3.0 and the new FiberScheduler interface by orf on Tuesday December 29, 2020 @03:51PM (#25574817)
> They solved the function-coloring problem

Not really, they've just made it super implicit. Any FFI calls are now implicitly coloured, same with anything CPU-heavy.

Like their approach to type annotations, I think this will be a mistake in hindsight.

Re:Ruby 3.0 and the new FiberScheduler interface by rdw on Tuesday December 29, 2020 @04:13PM (#25575101)
This is gonna sound pedantic but I think it's not a coloring problem. Coloring is when syntactically a function has to change its own signature just because it started calling an inner function with the new color.

That said, you're right in that one may have to make some changes to code to get around some new problems. The problem with FFI/CPU-heavy functions is that they prevent _other_ fibers from being scheduled while they run.

If it becomes possible to implement work-stealing, then that would mitigate the problem. It would also be solvable by sprinkling "yield to scheduler" calls throughout such functions. Annoying and not always possible, but, since in these cases the signature would not change, technically not coloring.

Re:Ruby 3.0 and the new FiberScheduler interface by gpderetta on Tuesday December 29, 2020 @05:08PM (#25575646)
It is not pedantic at all, you are completely right; if this implementation were to be classified as coloroing, then everything would be, including classic threads.
Re:Ruby 3.0 and the new FiberScheduler interface by ioquatix on Tuesday December 29, 2020 @08:32PM (#25577318)
Ruby FFI has been experimenting with provided support for kicking external functions to background threads with a single keyword argument.
Re:Ruby 3.0 and the new FiberScheduler interface by lalaithion on Tuesday December 29, 2020 @05:19PM (#25575768)
In a high level dynamic language with exceptions, there's already so many implicit "colors" to a function that I think this is still the right choice.
Re:Ruby 3.0 and the new FiberScheduler interface by svieira on Tuesday December 29, 2020 @11:41PM (#25578629)
This "implicit coloring" is what's talked about in _Unyielding_ [1], which is the "explicit color is good" counterpoint to _What Color is Your Function?_ (though Unyielding predates WCIYF by about a year).

[1]: https://glyph.twistedmatrix.com/2014/02/unyielding.html

Re:Ruby 3.0 and the new FiberScheduler interface by Rapzid on Tuesday December 29, 2020 @03:43PM (#25574713)
I don't see how this solves the "coloring" problem. "Colored" functions have a different return type; a future of some sort. If you want to return a future to a caller, or have a method that blocks until the work is done, you still need a way to differentiate that.

Golang does essentially the same thing and uses channels instead of "futures". However, some APIs will have functions that return a channel that you receive a message on later.. Which is a lot like a future. And if you provide a more simple non-channel API along side(instead of making the consumer wrap your calls in a Go routine or always use a channel), you now have "colored" functions.

I believe this is just a solution to a scheduling problem(pre-emptive vs cooperative).

Re:Ruby 3.0 and the new FiberScheduler interface by chrisseaton on Tuesday December 29, 2020 @03:56PM (#25574890)
> "Colored" functions have a different return type; a future of some sort.

This is an aside and possibly pedantic, but everyone seems to have forgotten that the whole idea of futures was originally that they weren't some different type. They were the same type, but blocked transparently on demand and had no `get` operation.

The construct that came before futures, called eventual-values, had the different-type thing. The only difference of futures, the big idea, was they said 'maybe we can get rid of that part'.

> These “futures” greatly resemble the “eventual values” of Hibbard’s Algol 68 [39]. The principal difference is that eventual values are declared as a separate data type, distinct from the type of the value they take on, whereas futures cannot be distinguished from the type of the value they take on.

(Halstead, 1985)

But now people write types like `Future[T]`... which completely misses the point! If you start to write `Future[...` then think to yourself... this isn't a future. And that's how you get this colouring problem you describe... it was already fixed and people have forgotten all about it.

Re:Ruby 3.0 and the new FiberScheduler interface by LgWoodenBadger on Tuesday December 29, 2020 @07:29PM (#25576867)
This seems a lot like the “remote calls are invisibly transparent” which most people decided was a bad idea. (IIRC)
Re:Ruby 3.0 and the new FiberScheduler interface by chrisseaton on Tuesday December 29, 2020 @07:34PM (#25576911)
I'm not debating if it's a bad idea or not - I'm just saying that's the definition of future as the authors intended it. If you don't want that that, then maybe call it an eventual value instead as you don't have the single essential part of what makes a future.
Re:Ruby 3.0 and the new FiberScheduler interface by valenterry on Tuesday December 29, 2020 @10:42PM (#25578214)
I think the general meaning of this term has changed. Future is now considered a different type and I think we just have to accept that the older definition isn't really used anymore.
Re:Ruby 3.0 and the new FiberScheduler interface by chrisseaton on Wednesday December 30, 2020 @07:46AM (#25581198)
Yes and to be honest I've written Future<... myself.
Re:Ruby 3.0 and the new FiberScheduler interface by dfee on Tuesday December 29, 2020 @06:24PM (#25576332)
I don’t understand your final point. Are you saying that generics on futures are bad? I don’t see the alternative.
Re:Ruby 3.0 and the new FiberScheduler interface by chrisseaton on Tuesday December 29, 2020 @06:28PM (#25576360)
> Are you saying that generics on futures are bad?

Yes - because it means existing code that expects a T cannot accept a Future<T>, which is the colouring problem being discussed.

You end up with half your code accepting futures and the other legacy half not accepting them and there's a divide. If you want to use the legacy code you have to force the future potentially before you really needed it.

> I don’t see the alternative.

The alternative is wherever a function accepts a concrete value T t, also let it accept a future value T t. When t is actually used, then block as if get was called.

Re:Ruby 3.0 and the new FiberScheduler interface by valenterry on Wednesday December 30, 2020 @07:49AM (#25581211)
> Yes - because it means existing code that expects a T cannot accept a Future<T>

First of all, this is a programming language specific problem, not a general one. A good language allows you to write:

    someFuture.map(someFunction)
Where "someFunction" accepts the plain value of type T that is stored within "someFuture".

Yes, you cannot write someFunction(someFuture), but that is a good thing, since asynchronous execution can very well change the behaviour of the program. Hence, I want the compiler (if there is one) to warn me if a variable that I pass to a function is now a Future instead of a plain value. I then map over the Future and I'm good. Or, maybe I want to wait for completion of the future and I'm good.

In both cases, there is no reason to write a second version of "someFunction".

Therefore...

> If you want to use the legacy code you have to force the future potentially before you really needed it.

... this is only true in incapable programming languages.

Re:Ruby 3.0 and the new FiberScheduler interface by chrisseaton on Wednesday December 30, 2020 @08:13AM (#25581360)
Isn't this the point I was making?

You need support in the language to do this. If you're writing a library routine from scratch as Future<... with the compiler knowing nothing about how to handle it specially then you aren't getting a future as they were originally envisioned and you're missing out.

Re:Ruby 3.0 and the new FiberScheduler interface by valenterry on Wednesday December 30, 2020 @09:09AM (#25581782)
> Isn't this the point I was making?

I don't think so - let me try to make it more clear, hold on.

> You need support in the language to do this. If you're writing a library routine from scratch as Future<... with the compiler knowing nothing about how to handle it specially then you aren't getting a future as they were originally envisioned and you're missing out.

You seem to assume that the programming language needs to know of the existence of Futures to help. But that is not the case and probably the reason for the misunderstanding.

It is sufficient that the language supports generics/type-parameters as well as a lightweight syntax (such as in the example I gave) and optimally higher kinded types or a similar mechanism.

If that is given, the language can be totally agnostic of Futures or async programming in general and it is easily possible to define a Future type as a library-type and use it in the way I described. Scala is a good example of such a language.

Re:Ruby 3.0 and the new FiberScheduler interface by chrisseaton on Wednesday December 30, 2020 @09:19AM (#25581877)
Do you mean the simple construct

    someFuture.map(someFunction)
My understanding is that this only runs someFunction when the future has completed?

This blocks the entire of someFunction until all the values are ready. You haven't adapted someFunction to work with futures at all - you're simply not running it until all the futures are gone and only normal values remain which you then pass into it!

Imagine someFunction comes from a library so cannot be modified trivially, takes three values, and can run successfully with the first two completed values while the third completes. What would you write with map to do that?

Re:Ruby 3.0 and the new FiberScheduler interface by valenterry on Wednesday December 30, 2020 @10:01AM (#25582218)
Your understanding is correct! It is inevitable that someFunction can only be called once someFuture has completed successfully. No language or technology can change that, but it is as much of a problem as the fact that in most languages lines are executed in sequence: pretty much no one thinks that this is a problem and I think we both agree on that.

So then...

> Imagine someFunction comes from a library takes three values, and can run successfully with the first two completed values while the third completes. What would you write in someFuture.map(...) to do that?

That is a good example actually. I believe that the user (at the callsite) should both _know_ if the library operates in an async way and/or runs code in parallel _and_ the user should be in control of choosing his desired behaviour.

Hence, with a library function that just expects 3 values, this is not possible and I would say the design isn't great.

Here is how I would write it in scala-ish pseudocode:

    // library - two separate functions instead of one
    def calcX(a, b): X
    def calcY(x, c): Y
    // One "combined" synchronous function can be created easily if desired:
    combinedCalc = calcX.andThen(calcY)
    
    // all given values are (lazy) futures
    aFuture = future(...)
    aFuture = future(...)
    aFuture = future(...)
    
    // callsite - async but _no parallel execution_
    xFuture = (aFuture, bFuture).mapN(calcX) // This is actually valid Scala syntax. Returns a future
    yFuture = (xFuture, cFuture).mapN(calcY)

    // alternative Scala syntax
    yFuture = for {
      a <- aFuture
      b <- bFuture
      x <- calcX(a, b)
      c <- cFuture
    } yield calcY(x, c)
As you can see, I could also change the order:

    yFuture = for {
      a <- aFuture
      c <- cFuture
      b <- bFuture
      x <- calcX(a, b)
    } yield calcY(x, c)
This is relevant because I might want to control when things get executed - but I can b sure they run one after each other and nothing runs while something else has already failed or was already started.

How to run it in parallel?

    xFuture = (aFuture, bFuture).parMapN(calcX)
    yFuture = (xFuture, cFuture).parMapN(calcY)
Now everything runs in Parallel.

Sorry the wall of code, but it shows that the code can look rather short even without future or async specific syntax support from the language.

The important part here is that it allows me to have fine-grained control over the execution of my code. There are a lot of situations where I probably don't care and it might be nice to have a way to say "Hey compiler, I don't care, just run that code in the way you think it's best", similar to what an SQL planner does with my queries.

But often I want control. For instance, in your example: what happens if the library decides to always evaluate "c" eagerly even though "a" and "b" often fail and the whole calculation is aborted? That would be a waste of CPU. But worse: the library might change its behaviour any time and keep the same function signature.

While that might be not so bad for mere calculations, what if we start to think about actions? Such as database or file or network IO - or even in-memory transactions that should be atomic. How about _streams_ of these actions, such as running an action every second and then combining this with other streams of actions? Losing control over the fain grained execution will result in terrible hard to debug and fix bugs due to concurrency.

Re:Ruby 3.0 and the new FiberScheduler interface by chrisseaton on Wednesday December 30, 2020 @10:11AM (#25582295)
> It is inevitable that someFunction can only be called once someFuture has completed successfully. No language or technology can change that

This is just not a true statement - and that was the point of the original thread - the original paper on futures had them implemented transparently and able to be passed down into library code not expecting futures. It's also how Haskell's par works today. So it demonstrably can be implemented.

> I believe that the user (at the callsite) should both _know_

Ok but this is just a 'don't do that' argument. If a user tells us they have a good reason to do it, I'm interested in how we can enable them to do that.

> with a library function that just expects 3 values, this is not possible

But it is in Haskell using par, and other languages with more traditional futures.

> Here is how I would write it

Great... but you've rewritten the library code with 'two separate functions instead of one.' My original point was 'because it means existing code that expects a T cannot accept a Future<T>' and you're proving that back to me so hard that you've accepted you need to completely rewrite the code to do it!

Languages with traditional futures would let you just call the original, unmodified library code, with future values instead of actual values, and it would just work.

If you had library code like this, you could pass in future values of T for a, b, and c, and it would execute the expensive_operation on a and b as soon as it could, while c completes.

    def foo(T a, T b, T c)
        expensive_operation(a, b) + expensive_operation(b, c)
    end
> For instance, in your example: what happens if the library decides to always evaluate "c" eagerly even though "a" and "b" often fail and the whole calculation is aborted?

Yes this is a problem with transparent futures, as is the ordering issue you raised. But I wasn't arguing they didn't have their own issues. You're saying it's impossible and that is demonstrably false, because languages do do it.

(I did half of my PhD on these topics, and the other half on Ruby.)

Re:Ruby 3.0 and the new FiberScheduler interface by valenterry on Wednesday December 30, 2020 @10:58AM (#25582743)
> This is just not a true statement - and that was the point of the original thread - the original paper on futures had them implemented transparently and able to be passed down into library code not expecting futures. It's also how Haskell's par works today. So it demonstrably can be implemented.

Okay, technically you are right - however it changes the semantics of the program. I admit that I didn't mention this constraint though.

> Great... but you've rewritten the library code with 'two separate functions instead of one.' My original point was 'because it means existing code that expects a T cannot accept a Future<T>' and you're proving that back to me so hard that you've accepted you need to completely rewrite the code to do it!

> Yes this is a problem with transparent futures, as is the ordering issue you raised. But I wasn't arguing they didn't have their own issues.

I don't disagree with any of that. However, what you originally said:

> > Are you saying that generics on futures are bad?

> Yes - because it means existing code that expects a T cannot accept a Future<T>, which is the colouring problem being discussed.

And you imply that transparent futures are better than the ones with generics. So where we disagree is on what is worse. I am convinced that the problems (and there are certainly a lot of unknowns) you introduce with transparent futures is much worse than the performance you might gain in certain cases and the easier syntax in many cases.

Re:Ruby 3.0 and the new FiberScheduler interface by Rapzid on Wednesday December 30, 2020 @04:03PM (#25586080)
For what it's worth, I believe hiding the semantics of futures is not the way for most languages I use with concurrency primitives either.. And it would seem the language designers agree.

I believe it's important to expose the fact that an asynchronous(potentially parallel) task is doing something for you. The runtime semantics of an assignment would appear the same in code by be very different behind the scenes otherwise. Also, a lot of code is written to manage those tasks in use-case specific ways. How would you race or cancel transparent futures?

Re:Ruby 3.0 and the new FiberScheduler interface by tinco on Tuesday December 29, 2020 @08:02PM (#25577095)
Does this mean that Rust's Future trait is incorrectly named? Or at least not named according to the academic use of the word?

Of course because Rust's runtime or lack thereof aims to be zero overhead a Future could never be without the poll function.. right? You need a runtime to make regular functions accept these magic opaque future values.

Re:Ruby 3.0 and the new FiberScheduler interface by chrisseaton on Wednesday December 30, 2020 @07:37AM (#25581141)
Yes not named according to the original paper.

Yes it requires some kind of special compiler or runtime support.

Re:Ruby 3.0 and the new FiberScheduler interface by wbl on Tuesday December 29, 2020 @08:53PM (#25577442)
Isn't Future a functor?
Re:Ruby 3.0 and the new FiberScheduler interface by chrisseaton on Wednesday December 30, 2020 @07:37AM (#25581138)
That's not the intention of the original authors, no.
Re:Ruby 3.0 and the new FiberScheduler interface by rdw on Tuesday December 29, 2020 @04:02PM (#25574960)
It solves the coloring problem by not having a coloring problem in the first place. Maybe I should have said "avoids the function-coloring problem".
Re:Ruby 3.0 and the new FiberScheduler interface by Rapzid on Tuesday December 29, 2020 @09:47PM (#25577850)
I believe the example in the article "avoids the function-coloring problem" by completely avoiding its problem space of continuing the execution of an imperative block of code after starting an asynchronous task to produce some value, and then synchronizing at the production of that value. In the example each code block run in a fiber blocks at Net::HTTP.get and only continues after it returns a value.

Looking at the API for Fiber.. It looks like "resume" returns the yield(generator) or fiber return value? So Fibers can be treated as a sort of Promise? As soon as you start returning fibers from methods you have the coloring problem..

Re:Ruby 3.0 and the new FiberScheduler interface by ghostwriter on Tuesday December 29, 2020 @11:23PM (#25578504)
Python has gevent.