# [VOTE] Fibers

- Thread: https://externals.io/message/113419
- Original archive: https://news-web.php.net/php.internals/113419
- Started by Aaron Piotrowski on 2021-03-08T19:40:07+00:00
- Messages: 61
- RFC: Fibers (Implemented (PHP 8.1)) — https://externals.io/rfc/fibers.md
- Page 1 of 3: messages 1 to 25 (25 per page, add `?page=N` to the URL)
- Next page: https://externals.io/message/113419.md?page=2
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · RFCs at https://externals.io/rfc.md · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #113419 — Aaron Piotrowski — 2021-03-08T19:40:07+00:00

URL: https://externals.io/message/113419#113419

Greetings everyone!

The vote has started on the fiber RFC: https://wiki.php.net/rfc/fibers <https://wiki.php.net/rfc/fibers>

Voting will run through March 22nd.

Cheers,
Aaron Piotrowski

---

## #113420 — Larry Garfield — 2021-03-08T22:56:50+00:00

URL: https://externals.io/message/113419#113420 · In reply to: #113419

> Greetings everyone!
> 
> The vote has started on the fiber RFC: https://wiki.php.net/rfc/fibers 
> <https://wiki.php.net/rfc/fibers>
> 
> Voting will run through March 22nd.
> 
> Cheers,
> Aaron Piotrowski

This is vastly improved from the earlier drafts I saw.  Well done, Aaron!

There is one issue that still stands out like a sore thumb to me, which I really should have reviewed and caught earlier.  (Entirely my fault.)  Fiber::this() seems like a very poorly chosen name for that method.  "this" in PHP implies "the object I am currently in."  Even if there's no $ on a method, that's still the mental association that word has in PHP.  But in this case, Fiber::this() does not mean "the object I'm currently in," but "the Fiber object that wraps the callable I'm currently in, which is itself an object but not the object I mean, but there may be an arbitrary number of call stack levels between me and that Fiber object."  That's... very confusing for a human, even if syntactically unambiguous.

I am still voting Yes on the RFC, but I would urge you to follow-up (with another RFC, or a consensus agreement, no one telling you not to, or whatever the process is, I'm easy) with renaming that method to something less confusing.  Fiber::active() seems like the best name to me (after some discussion with Aaron off-list), as it refers the fiber that is currently "actively" executing opcodes.

Otherwise, well done and I look forward to when we can build a standardized user-facing API on top of it. :-)

--Larry Garfield

---

## #113423 — Peter Stalman — 2021-03-09T04:47:04+00:00

URL: https://externals.io/message/113419#113423 · In reply to: #113420

Here we go again!  Looking at you, attributes syntax.

Seriously though, any of `this`, `active`, `current`, or even `Fiber::self`
are fine with me.

You might have the same issue with that last one.

Thanks,
Peter





> 
> > […]
>
> This is vastly improved from the earlier drafts I saw.  Well done, Aaron!
>
> There is one issue that still stands out like a sore thumb to me, which I
> really should have reviewed and caught earlier.  (Entirely my fault.)
> Fiber::this() seems like a very poorly chosen name for that method.  "this"
> in PHP implies "the object I am currently in."  Even if there's no $ on a
> method, that's still the mental association that word has in PHP.  But in
> this case, Fiber::this() does not mean "the object I'm currently in," but
> "the Fiber object that wraps the callable I'm currently in, which is itself
> an object but not the object I mean, but there may be an arbitrary number
> of call stack levels between me and that Fiber object."  That's... very
> confusing for a human, even if syntactically unambiguous.
>
> I am still voting Yes on the RFC, but I would urge you to follow-up (with
> another RFC, or a consensus agreement, no one telling you not to, or
> whatever the process is, I'm easy) with renaming that method to something
> less confusing.  Fiber::active() seems like the best name to me (after some
> discussion with Aaron off-list), as it refers the fiber that is currently
> "actively" executing opcodes.
>
> Otherwise, well done and I look forward to when we can build a
> standardized user-facing API on top of it. :-)
>
> --Larry Garfield
>
> --
> 
> To unsubscribe, visit: https://www.php.net/unsub.php

---

## #113425 — Aaron Piotrowski — 2021-03-09T18:58:10+00:00

URL: https://externals.io/message/113419#113425 · In reply to: #113419

> 
> 
> Greetings everyone!
> 
> The vote has started on the fiber RFC: https://wiki.php.net/rfc/fibers <https://wiki.php.net/rfc/fibers>
> 
> Voting will run through March 22nd.
> 
> Cheers,
> Aaron Piotrowski

Hi all!

A concern was raised off list that due to the complexity of the way this feature interacts with the engine, it may be best to mark the feature as experimental. This would allow some changes to be made to certain edge-case behaviors and, while I don't think it would be necessary, the public API.

We (Niklas and I) agree with this and propose that if this feature is accepted, it is marked as experimental through the 8.x release cycle or until we're comfortable removing that label, whichever comes first.

Experimental in this context would mean fibers would be compiled and available in all releases, but the documentation would denote that behavioral and API changes may be made in future minor releases – use at your own risk.

As this feature is targeted at library authors and not average PHP users, we believe there would be little effect to the community to take this step.

Cheers,
Aaron Piotrowski

---

## #113428 — twosee — 2021-03-10T02:02:49+00:00

URL: https://externals.io/message/113419#113428 · In reply to: #113425

> 2021年3月10日 上午2:58，Aaron Piotrowski <aaron@trowski.com> 写道：
> 
> 
> > […]
> 
> Hi all!
> 
> A concern was raised off list that due to the complexity of the way this feature interacts with the engine, it may be best to mark the feature as experimental. This would allow some changes to be made to certain edge-case behaviors and, while I don't think it would be necessary, the public API.
> 
> We (Niklas and I) agree with this and propose that if this feature is accepted, it is marked as experimental through the 8.x release cycle or until we're comfortable removing that label, whichever comes first.
> 
> Experimental in this context would mean fibers would be compiled and available in all releases, but the documentation would denote that behavioral and API changes may be made in future minor releases – use at your own risk.
> 
> As this feature is targeted at library authors and not average PHP users, we believe there would be little effect to the community to take this step.
> 
> Cheers,
> Aaron Piotrowski
> --
> 
> To unsubscribe, visit: https://www.php.net/unsub.php
> 
> 

Sorry for being late, writing an English manuscript is still a bit difficult for me. Here I want to continue to express some of my views.

Firstly, I want to emphasize that the separate Fiber API has no meaning to users. Many people have a misunderstanding about this. They think that the Fiber feature can make PHP have the same high-performance network programming capabilities as Golang and support it blindly. There is a complete and complex system behind Goroutine. In terms of the amount of work implemented, the context switching capability, which is the capability provided by the ext-fiber extension, is only a very insignificant part.

In my opinion, Fiber is just an enhancement of Generator. As far as my superficial understanding is concerned, the evolution direction of amphp and reactphp should be similar to that of node.js. And node.js is not implemented with on any stacked-coroutines. In theory, the performance of stackless-coroutine is better. Furthermore, the implementation of await/async does not require stacked-coroutine. Therefore, I'm confused about the content of the Fiber proposal, because, it seems to put it in the wrong direction.

The implementation of the coroutine and the entire system are complementary and inseparable. With the optimization and update of the entire system, there will be more and more customization requirements, which influence the implementation details of the coroutine. This is also the reason why Swoole did not merge its coroutine capabilities into php-src, individually. As stripping out a separate coroutine extension, many customized things will lose their reason for existence. Therefore, we hope to incorporate the entire system, which will make everything more logical.

As Nikita said, if it is unnecessary, it is better to let the expansion stay in PECL, which will bring more freedom to the project and be more conducive to the rapid development of the project. Swoole has mastered all the technologies applied to ext-fiber in 2018 and built a complete network programming system based on coroutine. Since then, in order to better integrate with the original ecosystem of PHP, Swoole has coroutinefied PDO, mysqli, phpredis, libcurl, etc., and applied them to a large number of real-world projects. These projects also contributed to the development of the PHP coroutine technology and ecosystem. Of course, the Swoole community still expects to merge it into php-src at an appropriate time.

Therefore, I have to point out that there is no practical experience in the design of ext-fiber. It skips the progress, which to be a PECL extension, and does not have any guidance of practical application. This is very dangerous. The proposal regards the PHP kernel as a large test ground in the way that incorporating Fiber into php-src as an experimental feature. And one of the main reasons is simply that the installation of extensions is difficult for some users. For many years, I have always thought that the PHP kernel's attitude towards merging anything is scientific and rigorous, so I have always been cautious and respectful. But this time, it makes me confused and a little bit disappointed.

In various design details, there are still many questions that make me confused. I will point out a few here:

1. Fiber class should not be designed as final

We should try to avoid any internal class being designed as final unless there are any necessary security reasons, otherwise, the scalability of the class will be greatly restricted. For instance, in practice, we usually assign a Context for every Fiber, it seems like $GLOBALS, so that we can write like this

    class MyFiber extends \Fiber {
        public $context = [];
    }

Or, we can add a custom log for the switch of the coroutine, or switch some contexts we want to switch

    class MyFiber extends \Fiber {
        public function resume(...$data):mixed {
            log('resume to {$this->getId()}');
            return parent::resume($data);
        }
    }

There are also some coroutine frameworks that want to track and count the coroutines created by users and will perform some injection operations, so they have their own special version of the coroutine implementation. If inheritance is not possible, then we need twice the number of objects, and mounting Fiber as a property on the newly implemented class. It is bad for performance and very inelegant.

If ext-fiber is declared as final for technical reasons, then I can only say that this is a technically problematic implementation.

2. Coroutine state acquisition problem

The ext-fiber defines many methods to obtain the state of the coroutine, such as isRunning(), etc. Why not directly export the status constants and provide a getStatus() function, if we just want the simplest implementation?

If there are some internal states on the status, then these states should be distinguishable. For example, they can be removed by bit operations or stored on other attributes.


The following are some technical issues about the implementation of ext-fiber. Due to the limited time, I have only read part of the source code limitedly. Excuse me, if there are any inaccuracies.

1. The code about coroutine switching could be simplified

There is essentially only one kind of switch API for coroutines that is resume(), in boost it called jump(). Its function is to switch to a coroutine, and yield()/suspend() is equivalent to $previousCoroutine->resume(). So I can’t understand why resume() and suspend() are implemented twice in the implementation of ext-fiber.

If we indicate the correct implementation of suspend() in PHP, it should look like this:

    public static function suspend(...$data): mixed
    {
        return static::this()->getPrevious()->resume(...$data);
    }

If there are any technical reasons for implementing resume() twice in ext-fiber, then I can only say that this is still a wrong implementation.

2. Switch notification

In zend_fiber_switch_to(), call zend_observer_fiber_switch_notify() twice at the beginning and ending of switch is an obviously wrong implementation. After we solve the previous problem, we only need to notify once before switching, because the second notification will be sent by another coroutine before it's switching back.

Other issues

1. C extension support

This Fiber proposal is dedicated to providing PHP with coroutine capabilities, but it does not consider the C extension. For example, it can consider turning some APIs into function pointers so that other extensions can add some content.

2. Unsolvable blocking

The Fiber proposal mentions the blocking problem but does not give a good idea or solution to solve it. In the coroutine system, no blocking is allowed. Blocking will greatly affect the normal operation of the entire program. Unlike JavaScript, PHP is not a naturally asynchronous language. Implementing coroutines and EventLoop in the user space can only solve some blocking from network calls, but other blocking problems such as file reading and writing, DNS queries, etc., can hardly be solved. However, PHP is very similar to node.js, which is more suitable for the 'multi-process with single-thread' model. Therefore, integrating libuv and tightly combining with coroutine features to achieve a complete coroutine system is a good asynchronous network IO solution.

3. CPU starvation

The capability of the 'multi-process with single-thread' model in CPU scheduling is not that good as Golang's multi-thread model. Solving the CPU starvation problem is another issue that needs to be considered

For example, in Swow (https://github.com/swow/swow, the latest research result of the Swoole community), the WatchDog component based on the monitoring the number of coroutine switching rounds and the interrupt feature of ZendVM solves this problem. It can issue an alarm when the CPU starvation occurs. Through configuration or PHP programming, it can also actively suspend the coroutine when the CPU starvation occurs, restore the average response speed of the entire program, and even directly kill the coroutine when the CPU infinite loop occurs.

4. Pure C coroutine

The Fiber proposal never mentions the support for pure C coroutines. In Swow, the event scheduler is a pure C function and does not need a PHP stack. It only needs to switch the C stack when switching to other coroutines and its switching performance is almost double that of PHP, because, in such a coroutine system, most exchanges occur between the scheduler and other coroutines.

5. Not compatible with Swoole

In my opinion, Swoole is an important part of the PHP ecosystem. But now, Fiber cannot work with Swoole. And based on the above reasons, Swoole will not consider compatible fiber.

We would expect some ZendAPI rather than Fiber extensions to provide support for coroutine switching.

6. Boost-context is not used on the Windows

The performance of win-fiber is far inferior to boost-context. I can not find any reason to use win-fiber instead of boost-context in Windows.

The Swow extension uses boost-context on all platforms and has been actively tested (https://github.com/swow/swow/runs/2053921797). CI will also automate execute nightly build and release DLL (https://github.com/swow/swow/releases), and there is no issue so far.

Also, there are many fragmentary issues. Due to limited time, I cannot write them all at once.

Of course, some designs of ext-fiber still refresh me, such as using Reflection to get coroutine status (in Swoole, we just keep adding methods to the coroutine class). Nevertheless, I don’t know what the benefits of using Reflection to get these states are.

I'm not particularly satisfied with all aspects of ext-fiber's overall plan and C code implementation, so I have to point them out here.

Regards,
Twosee

---

## #113431 — Peter Stalman — 2021-03-10T10:56:49+00:00

URL: https://externals.io/message/113419#113431 · In reply to: #113428

>
> 5. Not compatible with Swoole
>
> In my opinion, Swoole is an important part of the PHP ecosystem. But now,
> Fiber cannot work with Swoole. And based on the above reasons, Swoole will
> not consider compatible fiber.
>
> We would expect some ZendAPI rather than Fiber extensions to provide
> support for coroutine switching.
>
>
 Hi Twosee,

Are you saying that by adding this Fiber code to core it will prevent
Swoole from functioning? If so, that is concerning.  Or are you
simply saying that Swoole doesn't like this implementation and will not use
it with their own code?

One thing to consider when comparing the Fiber implementation is that the
vast majority of PHP applications are still run behind a web server in
short-lived requests.  Unlike Swoole, Swow, and Parallel, it isn't limited
to ZTS or CLI.  It might not be the ideal solution, but IMO it is a step in
the right direction for PHP to allow for better async support.

And I think you are right that "Fiber is just an enhancement of
Generator'', but so what?  The Generator addition in 5.5 opened up PHP to a
hacky way of doing async, but it worked everywhere.  Fiber allows that to
be much more convenient in switching contexts deep inside a call stack.  I
don't think it needs to be the end-all-be-all coroutine solution to rival
Goroutines, and I'm pretty sure it's not trying to be.

Thanks,
Peter

---

## #113435 — Aaron Piotrowski — 2021-03-10T16:04:29+00:00

URL: https://externals.io/message/113419#113435 · In reply to: #113431

> 
> 
> 
> 
> 5. Not compatible with Swoole
> 
> In my opinion, Swoole is an important part of the PHP ecosystem. But now, Fiber cannot work with Swoole. And based on the above reasons, Swoole will not consider compatible fiber.
> 
> We would expect some ZendAPI rather than Fiber extensions to provide support for coroutine switching.
> 
> 
>  Hi Twosee,
> 
> Are you saying that by adding this Fiber code to core it will prevent Swoole from functioning? If so, that is concerning.  Or are you simply saying that Swoole doesn't like this implementation and will not use it with their own code?
> 
> One thing to consider when comparing the Fiber implementation is that the vast majority of PHP applications are still run behind a web server in short-lived requests.  Unlike Swoole, Swow, and Parallel, it isn't limited to ZTS or CLI.  It might not be the ideal solution, but IMO it is a step in the right direction for PHP to allow for better async support.
> 
> And I think you are right that "Fiber is just an enhancement of Generator'', but so what?  The Generator addition in 5.5 opened up PHP to a hacky way of doing async, but it worked everywhere.  Fiber allows that to be much more convenient in switching contexts deep inside a call stack.  I don't think it needs to be the end-all-be-all coroutine solution to rival Goroutines, and I'm pretty sure it's not trying to be.
> 
> Thanks,
> Peter
> 

Hello,

This Fiber implementation does not conflict with Swoole. Both could coexist. However, Swoole's implementation does provide some other features that this does not, so I believe Twosee was simply saying that Swoole cannot directly use this fiber implementation. My focus was to provide a minimalistic implementation in core so user space code can make other API decisions as they saw fit.

Regarding some of the other concerns raised:

- Switch notification: The observer notification is triggered before switching to a fiber and after suspending from a fiber. The timing here was an open question I've discussed with others and we planned to examine it later. Moving the second notification before suspending the second fiber was already being considered. As this was an internal API I felt it was not needed directly in the RFC.
- Fiber is final, as is Generator. I believe it is better to compose classes rather than extend them. Of course it is always possible to remove final.
- Using Fiber::resume() and Fiber::suspend() models fibers as a stack and simplifies logic of resuming/suspending fibers. Ruby fibers share this exact API, though their API uses the term yield instead of suspend.
- State functions: Separate methods (i.e., isRunning, isTerminated) returning a boolean are preferable IMO to comparing integer constants to a value returned by a status method. This is really a matter of opinion than one being strictly better than the other.
- Pure C coroutine: The extension code provides user space fibers. Adding functions to create fiber C-only fibers can certainly be done if the need arises.
- Being marked experimental: I was hoping this would be a good compromise between allowing people to experiment with fibers and providing the ability to make minor BC breaks if the need arose. I realize this is generally not the PHP way, however this is, IMO, not entirely without precedent. JIT and FFI were not widely used before being added to PHP.

Thanks for the feedback!

Aaron Piotrowski

---

## #113441 — Aaron Piotrowski — 2021-03-10T17:52:37+00:00

URL: https://externals.io/message/113419#113441

> 
> 
> Hi ereryone, My name is Tianfeng.Han, I am founder of swoole project. We have done a lot of exploration in cli server side programming of php
> 
> I think, ext-fiber is more suitable as a pecl project.
> 
> Coroutine and asynchronous IO is a new concurrency model,  This is very different from blocking io.
> 
> I am afraid that fiber can only be used in the amphp framework and is of no value to other php projects.
> 
> If the PHP language wants to support CSP programming like golang, asynchronous io and coroutine system can be designed in the next major version (PHP9), this requires a lot of work.
> 
> 
> Tianfeng.Han 
> 

Hi Tianfeng.Han,

Fibers will immediately benefit projects that use async I/O. This is not limited to amphp, but also includes ReactPHP, Guzzle, Symfony, and Psalm, to name that I am aware of that could use it in conjunction with I/O and multi-processing.

One of the ReactPHP maintainers and I collaborated on a proof-of-concept for ReactPHP, which is mentioned in the RFC: https://github.com/trowski/react-fiber

This fiber API was meant to be a lightweight implementation to enable user space green-threads/coroutines. I would love to see more async tools in PHP, but that will require much more work. This is meant to be a first step toward that eventual goal, without conflicting with or restricting future additions.

Cheers,
Aaron Piotrowski

---

## #113445 — Dan Ackroyd — 2021-03-10T18:21:52+00:00

URL: https://externals.io/message/113419#113445 · In reply to: #113419

Hi internals,

Well, technically this is addressed more to people who read internals.

Please don't contact people off list putting pressure on them to vote
in a particular way.

It _really_ is not appreciated, no matter how well intentioned the
sender thinks it is.

I maintain some notes on RFC etiquette here:
https://github.com/Danack/RfcCodex/blob/master/rfc_etiquette.md#dont-pressure-people-by-private-communication-to-vote
(which not even is going to fully agree with), but getting unsolicited
pressure to vote in a particular way makes people uncomfortable, and
less likely to take part in the project in the future.

cheers
Dan
Ack


= Don't pressure people by private communication to vote

Even with the best intentions, unsolicited off-list communications
putting pressure on people to vote a particular way are rude. At best
they don't have any effect, but most of the time they make the
recipient uncomfortable.

If you want to influence how people are going to vote, these things
are appropriate:

* Sending an email to internals saying that you would like to see this pass.
* Posting on Reddit /r/php or other platform where discussions take
place, and then posting a link to internals, saying "these are my
thoughts".
* Asking in a public communication channel asking someone in a neutral
way 'are you going to vote?'.

Private communications trying to change people's minds are a burden
that make people receiving them feel bad, even if they are intentioned
to help the project.

---

## #113447 — Aaron Piotrowski — 2021-03-10T19:19:00+00:00

URL: https://externals.io/message/113419#113447 · In reply to: #113445

> 
> 
> Hi internals,
> 
> Well, technically this is addressed more to people who read internals.
> 
> Please don't contact people off list putting pressure on them to vote
> in a particular way.
> 
> It _really_ is not appreciated, no matter how well intentioned the
> sender thinks it is.
> 
> I maintain some notes on RFC etiquette here:
> https://github.com/Danack/RfcCodex/blob/master/rfc_etiquette.md#dont-pressure-people-by-private-communication-to-vote
> (which not even is going to fully agree with), but getting unsolicited
> pressure to vote in a particular way makes people uncomfortable, and
> less likely to take part in the project in the future.
> 
> cheers
> Dan
> Ack
> 

Hi everyone,

While I appreciate the support from the individual that sent the email, I do not condone sending emails to people privately off list asking them to vote in a particular way.

For clarification to those that may have not received the email in question, I did not send the email nor did I request that it be sent.

Thanks,
Aaron Piotrowski

---

## #113457 — Kalle Sommer Nielsen — 2021-03-10T21:51:31+00:00

URL: https://externals.io/message/113419#113457 · In reply to: #113445

Den ons. 10. mar. 2021 kl. 20.22 skrev Dan Ackroyd <Danack@basereality.com>:
>
> Hi internals,
>
> Well, technically this is addressed more to people who read internals.
>
> Please don't contact people off list putting pressure on them to vote
> in a particular way.
>
> It _really_ is not appreciated, no matter how well intentioned the
> sender thinks it is.

For the sake of integrity, I believe the vote should be halted and
restarted at a later date to prevent the influence of referenced email
from having a favored vote. This has no relation to my personal vote
on the matter of the RFC however.

-- 
regards,

Kalle Sommer Nielsen
kalle@php.net

---

## #113477 — Aaron Piotrowski — 2021-03-11T16:05:00+00:00

URL: https://externals.io/message/113419#113477 · In reply to: #113425

> Hi all!
> 
> A concern was raised off list that due to the complexity of the way this feature interacts with the engine, it may be best to mark the feature as experimental. This would allow some changes to be made to certain edge-case behaviors and, while I don't think it would be necessary, the public API.
> 
> We (Niklas and I) agree with this and propose that if this feature is accepted, it is marked as experimental through the 8.x release cycle or until we're comfortable removing that label, whichever comes first.
> 
> Experimental in this context would mean fibers would be compiled and available in all releases, but the documentation would denote that behavioral and API changes may be made in future minor releases – use at your own risk.
> 
> As this feature is targeted at library authors and not average PHP users, we believe there would be little effect to the community to take this step.
> 
> Cheers,
> Aaron Piotrowski
> --
> 
> To unsubscribe, visit: https://www.php.net/unsub.php
> 

Hi everyone!

I’m concerned my email above may have had the opposite effect from which I had hoped.

I think the Fiber implementation is sound and the API, mirroring that of Ruby, is proven and unlikely to require change.

There are certain edge case behaviors that I’m concerned may need to changed, such as the error reporting level that is active when a fiber is switched. If the @ operator is active, should it remain active after a fiber switch? Right now, it does not, the @ operator is on a per-fiber basis, restoring error reporting when switching fibers. Perhaps though this was the wrong decision. What I was hoping to accomplish with marking the feature as experimental was to get feedback on such behaviors and make sure we make the right choices.

Recent changes to the JIT also make fibers as an extension incompatible due to defining a user opcode handler. This is unfortunate, as cli apps including amphp and ReactPHP greatly benefited from the JIT: https://www.php.net/releases/8.0/en.php (see Relative JIT contribution to PHP 8 performance). Integrating fibers in core will allow the opcode handler to be predefined.

Hopefully that provides some clarity to our intensions. Cheers!

Aaron Piotrowski

---

## #113483 — Benjamin Eberlei — 2021-03-11T18:51:00+00:00

URL: https://externals.io/message/113419#113483 · In reply to: #113457

> Den ons. 10. mar. 2021 kl. 20.22 skrev Dan Ackroyd <Danack@basereality.com
> > […]
>
> For the sake of integrity, I believe the vote should be halted and
> restarted at a later date to prevent the influence of referenced email
> from having a favored vote. This has no relation to my personal vote
> on the matter of the RFC however.
>

If the email was sent by the RFC authors itself I would agree, but it was
not.

Stopping the vote because of this would provide precedent to bombard any
RFC vote by just emailing all voters a nasty email.

>
> --
> regards,
>
> Kalle Sommer Nielsen
> kalle@php.net
>
> --
> 
> To unsubscribe, visit: https://www.php.net/unsub.php

---

## #113486 — Dan Ackroyd — 2021-03-11T21:50:42+00:00

URL: https://externals.io/message/113419#113486 · In reply to: #113428

Hi Twosee, Tianfeng.Han

I was drafting a longer reply to you both, but I realised I might be
missing some information.

Please could you disclose the commercial interests of the Swoole
maintainers, and the ties to the for profit companies that provide
services implementing Swoole?

Having people vote on RFCs who have ties to companies that provide
services via commercial entities isn't unprecedented. For example
zend.com has had employees who are involved in voting on RFCs, but to
a large extent that was done openly, with all of them using zend.com
email addresses.

twosee wrote:
> Of course, the Swoole community still expects to merge it into php-src at an appropriate time.

What's your idea of an appropriate time and how do you plan to start
this conversation?

If something hasn't been merged back after 8 years, it sounds
reasonably unlikely that it's ever going to be merged back.

cheers
Dan
Ack

---

## #113491 — rango@swoole.com — 2021-03-12T04:06:26+00:00

URL: https://externals.io/message/113419#113491 · In reply to: #113486

Hi&nbsp;Dan,


We have no commercial purpose on the swoole open source project.&nbsp;This is a purely technical project.&nbsp;
If possible, we can remove the name of swoole, contribute the source code of swoole-src to php-src, and transfer the copyright.
Here is just a technical discussion.&nbsp;My opinion is that if PHP will support fiber/green-threads, this is a major change, should redesign language syntax, standard library, ZendVM.
This proposal must be discussed extensively and in-depth,&nbsp;should not make a hasty decision.


There are 7 parts to consider with my experience:

EventLoop API


Fiber/Coroutine/GreenThread


IO-Scheduler (Socket/FileSystem/ChildProcess/Signal/Timer/Stdout/Stdin)


CPU-Scheduler


Compatible with existing extesions&nbsp; (php_streams/ext-sockets/ext-redis/ext-mysqli/ext-pdo-mysql/ext-curl ...) and builtin-functions (sleep/gethostbyname/proc_open/file_get_contents)


Service container,&nbsp;How to support php-fpm and provide a coroutine version of http server


Coroutine communication,&nbsp;How to pass messages between two coroutines

It’s nice to see php has such topic. This may be the key technology in the next generation of PHP.



Thanks


Tianfeng.Han


------------------&nbsp;Original&nbsp;------------------
From: &nbsp;"Dan Ackroyd"<Danack@basereality.com&gt;;
Date: &nbsp;Fri, Mar 12, 2021 05:50 AM
To: &nbsp;"twosee"<twose@qq.com&gt;; "韩天峰"<rango@swoole.com&gt;; 
Cc: &nbsp;"Aaron Piotrowski"<aaron@trowski.com&gt;; "php internals"<internals@lists.php.net&gt;; 
Subject: &nbsp;Re: [PHP-DEV] [VOTE] Fibers

&nbsp;

Hi Twosee, Tianfeng.Han

I was drafting a longer reply to you both, but I realised I might be
missing some information.

Please could you disclose the commercial interests of the Swoole
maintainers, and the ties to the for profit companies that provide
services implementing Swoole?

Having people vote on RFCs who have ties to companies that provide
services via commercial entities isn't unprecedented. For example
zend.com has had employees who are involved in voting on RFCs, but to
a large extent that was done openly, with all of them using zend.com
email addresses.

twosee wrote:
&gt; Of course, the Swoole community still expects to merge it into php-src at an appropriate time.

What's your idea of an appropriate time and how do you plan to start
this conversation?

If something hasn't been merged back after 8 years, it sounds
reasonably unlikely that it's ever going to be merged back.

cheers
Dan
Ack

---

## #113493 — twosee — 2021-03-12T09:00:33+00:00

URL: https://externals.io/message/113419#113493 · In reply to: #113486

> 2021年3月12日 上午5:50，Dan Ackroyd <Danack@basereality.com> 写道：
> 
> Hi Twosee, Tianfeng.Han
> 
> I was drafting a longer reply to you both, but I realised I might be
> missing some information.
> 
> Please could you disclose the commercial interests of the Swoole
> maintainers, and the ties to the for profit companies that provide
> services implementing Swoole?
> 
> Having people vote on RFCs who have ties to companies that provide
> services via commercial entities isn't unprecedented. For example
> zend.com has had employees who are involved in voting on RFCs, but to
> a large extent that was done openly, with all of them using zend.com
> email addresses.
> 
> twosee wrote:
> > […]
> 
> What's your idea of an appropriate time and how do you plan to start
> this conversation?
> 
> If something hasn't been merged back after 8 years, it sounds
> reasonably unlikely that it's ever going to be merged back.
> 
> cheers
> Dan
> Ack
> 
> -- 
> 
> To unsubscribe, visit: https://www.php.net/unsub.php
> 
> 

Hi all,

The following are some of my personal views, any comment is welcome:

> What's your idea of an appropriate time and how do you plan to start
> this conversation?

Maybe, I misunderstood the rules of the PHP RFC voting. In my opinion, the PHP RFC drafters need to have considerable experience in PHP kernel development (I mean that I don’t think I have met such requirements yet). And the RFC content needs to be fully verified by unit tests and actual projects, and the API or code implementation should be very stable. Once determined, no major changes will be made in principle.

But now, there is another way shown in front of me. We can draft an RFC first, then complete it based on community feedback, mark it as experimental, and continue to iterate in the PHP core. What I have to admit here is that drafting Swow's RFC will be more difficult than Fiber, because the content of the former is many times than that of the latter. However, to my surprise, it seems that there are not as many people who care about the details of the internal implementation as I thought. Most people care more about the content in the user space, and things under the user space are very easy to modify.

In addition, due to language and network barriers, people active in the Swoole community rarely participate in discussions in the PHP core community. In fact, I started subscribing to the PHP internal mailing list in July 2020 and occasionally show my opinion there. I often worry that incorrect translations will cause my intentions to be misinterpreted, and other members of the Swoole community never participated in discussions. We hardly use non-local social media. I just registered an account on Reddit, a great community exchange website yesterday, and I haven't had time to read all the discussions on that.

For all of the above reasons, it is extremely difficult for me to draft the RFC, and I have always hoped that I can make more contributions to other aspects of the PHP kernel, and then try to propose a huge coroutine draft as a goal of PHP9. And I have not taken the first step so far, I am very sorry about that.

Anyway, I will share content about Swow soon and try to draft a proposal.

> If something hasn't been merged back after 8 years, it sounds
> reasonably unlikely that it's ever going to be merged back.

Swoole does have a long history, what I have to point out is that the early Swoole did not really participate in the international open-source community. And Swoole switched from the pure asynchronous mode to the coroutine mode in 2018. At that time, we found that the PHP kernel has a good wrapping for various IO operations. We only need to implement the coroutine version of php_stream_wrapper to turn all relevant synchronous clients into coroutine clients or make synchronization blocking file operations into coroutine way. In this case, we can use a very small amount of work to achieve the reuse of most of the original libraries of the PHP native ecosystem. But Swoole gradually becomes a C++ project with some technical plan, so that it makes Swoole hard to be merged into php-src.

I started programming in 2017 and contributed to the Swoole project in 2018. In 2019, I learned and mastered almost all the technical content of Swoole. In 2020, I obtained a php.net account. At the same time, I also created a new systematic pure C coroutine project called Swow (for sure, it can be called any other name, but the name Swow is only respect for Swoole because Swow leans in the implementation principle of Swoole and its technical experience) , and I plan to propose a systematic draft of coroutine this year. I have paid my best to accelerate this process. For the PHP community, everyone really needs a real asynchronous/coroutine solution. Therefore, I totally understand the criticism of the slow progress. But, sorry from the bottom of my heart. I can't do it faster.

> Are you saying that by adding this Fiber code to core it will prevent
> Swoole from functioning? If so, that is concerning.  Or are you
> simply saying that Swoole doesn't like this implementation and will not use
> it with their own code?

First of all, please let me pay tribute to your work. I fully understand that the implementation of Fiber could be indeed compatible with Swoole/Swow because theoretically nothing is incompatible. However, undoubtedly, for some reasons I mentioned or not mentioned, this requires a considerable amount of work. Of course, I am not completely denying the feature of Fiber, I just cannot agree with the merger of ext-fiber now. We always regard merging the coroutine system into php-src as a systematic plan. Even if the implementation of ext-fiber is merged, I am still willing to overcome difficulties to make more changes to promote the merger of Swow into php-src, it's my pleasure.

> One thing to consider when comparing the Fiber implementation is that the
> vast majority of PHP applications are still run behind a web server in
> short-lived requests.  Unlike Swoole, Swow, and Parallel, it isn't limited
> to ZTS or CLI.  It might not be the ideal solution, but IMO it is a step in
> the right direction for PHP to allow for better async support.

There is a misunderstanding here. Swow has made improvements in this area. It supports NTS, ZTS, supports running under all SAPIs (including FPM), and also supports running under all operating systems.

Now, Swow's working principle is a bit like Opcache. Opcache will optimize and replace the CPU instructions, which executed by the code, and Swow will replace the blocking system calls with the corresponding coroutine operation. They hardly change the behavior of the code. Opcache makes The program runs faster, and Swow can make the program's IO concurrency better.

Therefore, all PHP programs will benefit from it. We can directly use the synchronous-blocking guzzle. Any network IO will only block one coroutine instead of the entire process. You just need to open more coroutines to get better concurrency performance. For amphp and reactphp, after that, `stream_select()` and `curl_multi_select()` will become the coroutine version, and even they will no longer block the entire program.

Generally, the solution provided by Swow is completely a superset of Fiber.

By the way, Tianfeng’s translation may have caused some misunderstandings. I think what he wants to express is that Fiber is not a feature that can directly benefit all PHP projects. Of course, I know that the RFC has mentioned that Fiber is mainly provided for the author of the framework and library uses. Sorry for this that caused misunderstanding.

Regards,
Twosee

---

## #113494 — G. P. B. — 2021-03-12T14:14:54+00:00

URL: https://externals.io/message/113419#113494 · In reply to: #113491

> Hi&nbsp;Dan,
>
>
> We have no commercial purpose on the swoole open source project.&nbsp;This
> is a purely technical project.&nbsp;
> If possible, we can remove the name of swoole, contribute the source code
> of swoole-src to php-src, and transfer the copyright.
> Here is just a technical discussion.&nbsp;My opinion is that if PHP will
> support fiber/green-threads, this is a major change, should redesign
> language syntax, standard library, ZendVM.
> This proposal must be discussed extensively and in-depth,&nbsp;should not
> make a hasty decision.
>
>
> There are 7 parts to consider with my experience:
>
> EventLoop API
>
>
> Fiber/Coroutine/GreenThread
>
>
> IO-Scheduler (Socket/FileSystem/ChildProcess/Signal/Timer/Stdout/Stdin)
>
>
> CPU-Scheduler
>
>
> Compatible with existing extesions&nbsp;
> (php_streams/ext-sockets/ext-redis/ext-mysqli/ext-pdo-mysql/ext-curl ...)
> and builtin-functions (sleep/gethostbyname/proc_open/file_get_contents)
>
>
> Service container,&nbsp;How to support php-fpm and provide a coroutine
> version of http server
>
>
> Coroutine communication,&nbsp;How to pass messages between two coroutines
>
> It’s nice to see php has such topic. This may be the key technology in the
> next generation of PHP.
>
>
>
> Thanks
>
>
> Tianfeng.Han
>

So from what I understand, and correct me if I'm wrong, you're against
Fibers because it doesn't include all the other systems needed to make them
immediately usable with the traditional APIs?
This sound a bit to me to wanting to run a marathon before even having
learned how to walk.

You said it yourself Swoole took *years* to implement all those changes,
and which is pure feature creep for what the RFC process is designed for
IMHO.
The point of this RFC, from what I see, is to bring the foundational system
into core upon which one can build upon, be that in userland or in the
extension land (when an internal API is added).
Upon which all of those different tools can be added to the language
independently, via separate RFCs, by being a PHP library or a PHP extension.

So can you please explain to us, why *not* adding one of the seven parts
you've stated are necessary and doing gradual implementations of the other
tools should not be done?

Because if the idea is to add all of these tools at once in a massive RFC,
I feel this is going the same way as trying to add unicode support to PHP,
and we know where that ended.

Best regards,

George P. Banyard

---

## #113495 — Aaron Piotrowski — 2021-03-12T17:34:47+00:00

URL: https://externals.io/message/113419#113495 · In reply to: #113493

> 
> 
> Now, Swow's working principle is a bit like Opcache. Opcache will optimize and replace the CPU instructions, which executed by the code, and Swow will replace the blocking system calls with the corresponding coroutine operation. They hardly change the behavior of the code. Opcache makes The program runs faster, and Swow can make the program's IO concurrency better.
> 
> Therefore, all PHP programs will benefit from it. We can directly use the synchronous-blocking guzzle. Any network IO will only block one coroutine instead of the entire process. You just need to open more coroutines to get better concurrency performance. For amphp and reactphp, after that, `stream_select()` and `curl_multi_select()` will become the coroutine version, and even they will no longer block the entire program.
> 
> Generally, the solution provided by Swow is completely a superset of Fiber.
> 

Hi Twosee,

I wanted to address the point above from your email. I do not think auto-magically altering the behavior of existing functions to use async I/O is a good idea. Existing code that relies on a constant state during an I/O operation that previously was blocking may no longer work as expected. Changing behavior is a major BC break. It would be better to introduce new async versions of functions, e.g., asio_fwrite(), instead of altering the existing `fwrite()` function. This way libraries which have interfaces requiring blocking I/O, such as libraries implementing PSR-7/15, can create versions that are designed with async I/O in mind, while keeping existing implementations working as expected.

Changing the behavior of existing functions reminds me of the `mbstring.func_overload` feature that is now deprecated because of the compatibility problems it caused.

I took a look at Swow this morning. Again, I would compare Swow to Swoole – it is another large, opinionated framework for asynchronous PHP apps. Swow is not a lightweight, standalone feature that can be merged into PHP at one time. The Fiber API is small in scope and does not alter existing behaviors.

Looking at the fiber implementation in Swow, I see it uses the same boost library and the same asymmetric coroutine model as ext-fiber. It seems Swow could use an internal API provided by PHP for fibers, allowing it to drop the boost dependency.

This leads me to believe my proposal would be mutually beneficial to both your extension and the wider PHP community that could use fibers outside of your framework or Swoole.

Cheers,
Aaron Piotrowski

---

## #113496 — Michael Wallner — 2021-03-12T22:04:12+00:00

URL: https://externals.io/message/113419#113496 · In reply to: #113419

Hi Aaron!

Thank you, and everyone involved, for your effort.


> Greetings everyone!
> 
> The vote has started on the fiber RFC: https://wiki.php.net/rfc/fibers <https://wiki.php.net/rfc/fibers>
> 
> Voting will run through March 22nd.

I voted /no/, because of the dependency on Boost.
If my assumptions are wrong, I may reconsider my vote.


-- 
Regards,
Mike

---

## #113497 — Derick Rethans — 2021-03-12T22:08:51+00:00

URL: https://externals.io/message/113419#113497 · In reply to: #113496

>Hi Aaron!
>
>Thank you, and everyone involved, for your effort.
>
>
> > […]
>https://wiki.php.net/rfc/fibers <https://wiki.php.net/rfc/fibers>
> > […]
>
>I voted /no/, because of the dependency on Boost.
>If my assumptions are wrong, I may reconsider my vote.



IIRC, that dependency is the inclusion of a single header file, there is no linkage against boost. The header file can be bundled.

cheers,
Derick

---

## #113498 — Christoph M. Becker — 2021-03-12T22:36:29+00:00

URL: https://externals.io/message/113419#113498 · In reply to: #113496

> Thank you, and everyone involved, for your effort.
>
> 
> > […]
>
> I voted /no/, because of the dependency on Boost.
> If my assumptions are wrong, I may reconsider my vote.

Only asm files are used[1], and these can be bundled, so there is no
dependency on boost or C++ in general.

[1] <https://github.com/amphp/ext-fiber/tree/master/boost>

--
Christoph M. Becker

---

## #113499 — Aaron Piotrowski — 2021-03-12T22:54:33+00:00

URL: https://externals.io/message/113419#113499 · In reply to: #113498

> 
> 
> 
> 
> > […]
> 
> Only asm files are used[1], and these can be bundled, so there is no
> dependency on boost or C++ in general.
> 
> [1] <https://github.com/amphp/ext-fiber/tree/master/boost>
> 
> --
> Christoph M. Becker
> 

Hi Mike, Christoph, and Derick,

To add a bit more information:

These asm files are part of the low-level boost.context lib, found here: https://github.com/boostorg/context

This library has infrequent releases. Some of the files for old architectures have not changed in several years. Keeping these files up-to-date will not be a burden (and I plan to assume this responsibility).

The Boost license is extremely permissive and approved by the OSI, so there is no problem bundling with PHP.

Hopefully that provides some clarification and you’ll reconsider your vote Mike.

Cheers!
Aaron Piotrowski

---

## #113555 — Josh Di Fabio — 2021-03-16T09:30:36+00:00

URL: https://externals.io/message/113419#113555 · In reply to: #113499

>
>
> > […]
>
> Hi Mike, Christoph, and Derick,
>
> To add a bit more information:
>
> These asm files are part of the low-level boost.context lib, found here: https://github.com/boostorg/context
>
> This library has infrequent releases. Some of the files for old architectures have not changed in several years. Keeping these files up-to-date will not be a burden (and I plan to assume this responsibility).
>
> The Boost license is extremely permissive and approved by the OSI, so there is no problem bundling with PHP.
>
> Hopefully that provides some clarification and you’ll reconsider your vote Mike.
>
> Cheers!
> Aaron Piotrowski
>
> --
> 
> To unsubscribe, visit: https://www.php.net/unsub.php
>

Apologies, this is a long one!

This RFC strikes me as being very dangerous. Implicitly allowing code
which is synchronous by design to be executed asynchronously seems
sure to lead to very subtle, unpredictable, confusing and dangerous
bugs.

The issue is that executing code asynchronously introduces race
conditions and, in code which is synchronous by design, those race
conditions will lead to bugs which will never occur during QA or
development and will be incredibly hard to identify once they do occur
in production.

These are the kind of bugs where user sessions get mixed up, the wrong
package is installed by a package manager, or an ecommerce website
captures the wrong amount of money from a customer's credit card. And
developers will have no realistic way of tracking down why these
things are happening in real world, multi developer, multi vendor PHP
applications.

For example, the PHP ecosystem is full of code like this:

    private function capturePayment()
    {
        $paymentRequest = preparePaymentRequest($this->currentOrder);
        $this->paymentGateway->capturePayment($paymentRequest);
        $this->currentOrder->setTransactionId($paymentRequest->getTransactionId());
    }

In the above code snippet, the developer has relied on the fact that
the mutable value $this->currentOrder will be the same before and
after the call to $this->capturePayment(), because capturePayment() is
synchronous. In all likelihood, the authoring PHP developer is not
even familiar with asynchronicity, and the assumption that
capturePayment() is synchronous is therefore not even a conscious one.
Note that, if capturePayment is executed asynchronously, eventually we
will see payments attributed to the wrong orders.

Note that, if fibers land, there is no know whether the code above is
correct by looking at it in isolation. You can only know that by
knowing the environment in which the code is executed, as well as
understanding *all of the internals of capturePayment()*, and its
dependencies, many of which will probably managed by other developers
and will involve a bunch of injected services, many of which will do
IO and therefore are candidates for using fibers, directly or
indirectly, such as logging, HTTP, and database.

The worst characteristics to me are the following:
- These race conditions will cause problems so rarely that developers
will not even realise that their programs contain dangerous bugs. Code
which is not safe to use with fibers will appear to be functional
because the happy path will work fine, and so developers will assume
it's okay.
- Changes very, very far away from your code can cause your code to
become unexpectedly asynchronous. Imagine you are using the DynamoDB
monolog logger in your application, and that library indirectly uses
Guzzle, which gets fiber support. Any place you are logging anything
now becomes asynchronous, as well as any code which invokes that code.
If you are using some kind of event dispatch pattern then pretty much
everything in your program becomes asynchronous.
- As a library author, there is no way of knowing how your code is
going to be used, and what injected dependencies might use fibers
internally.

The counter arguments:
- "The above code snippet is suboptimal, it shouldn't assume that
mutable state remains unchanged following some IO, and the order
should be passed in as an arg." -- Whether or not this is true is
irrelevant -- developers have relied on the invariants of the PHP
language when writing their code, such as synchronous code being
synchronous, and this is how lots of code is written in the wild. If
this feature lands, that won't change -- very few userland developers
will understand this feature, including library authors.
- "Fibers should only be enabled in async first programs." and "We
could flag that certain libraries are fiber compatible or
incompatible." If code appears to work in a fiber environment, people
will just use it in a fiber environment, without understanding all of
the security issues and horrible bugs they're introducing. This
problem should rather be solved at the language level by making async
explicit.

Consider the following:

    private async function capturePayment()
    {
        $paymentRequest = preparePaymentRequest($this->currentOrder);
        await $this->paymentGateway->capturePayment($paymentRequest);
        $this->currentOrder->setTransactionId($paymentRequest->getTransactionId());
    }

Looking at the above code, I can see the race condition. It becomes
explicit. So I change the code and communicate explicitly via the type
system that this function is asynchronous and that my code expects
PaymentGateway::capturePayment() to be asynchronous.

    private async function capturePayment()
    {
        $order = $this->currentOrder;
        $paymentRequest = preparePaymentRequest($order);
        await $this->paymentGateway->capturePayment($paymentRequest);
        $order->setTransactionId($paymentRequest->getTransactionId());
    }

Regarding PHP's type system not supporting generics, and the
associated advantages of this RFC over promises; I agree that this is
a problem with promises. But the lack of generics in PHP already means
we have no language-level type safety on data structures, which is
certainly worse than not having type safety on promises. Psalm et al
have provided reasonable solutions to this issue.

Sorry for the criticism of the idea -- I've used React and Amp in
production on a product which has been in prod for many years -- and
I'd be happy to see first class asynchronous support within the
language, but I think this RFC would make the language worse, not
better. Technically, I'm sure this is great, and I do appreciate that
a lot of work has probably been put into this.

Thanks

---

## #113557 — Peter Kokot — 2021-03-16T11:09:08+00:00

URL: https://externals.io/message/113419#113557 · In reply to: #113555

Hello everyone,

I'm just adding a few cents into this discussion.

I've voted "yes" because we don't have any other async stuff RFCs available
nor in the preparation. PHP needs such functionalities very badly and very
quickly to sort of speak. Adding a brand new extension in the core is maybe
a strange practice because it usually should go into PECL first and after
being adopted by the ecosystem it could be then moved to php-src after a
vote. However, practical reasons show that PECL extensions are not first
class citizens. In most cases adopting extensions could take even longer.
With somehow similar logic, I've also supported FFI extension and even Jit
RFCs already in 7.4.

Regarding Swoole, Swoole is a great production-ready framework that
provides such functionality also already today. It is definitely worth
checking out from a user perspective and can live along the ext-fiber just
fine, I believe. If Swoole won't be integrated in core (it is a separate
standalone project), then hopefully, PHP core could learn and be inspired
by Swoole as it's already implemented in production with unbeatable
performance.

Thank you to the RFC authors and everyone involved in making this happen.

---

## #113571 — Niklas Keller — 2021-03-16T18:18:13+00:00

URL: https://externals.io/message/113419#113571 · In reply to: #113555

Hey Josh,


> Apologies, this is a long one!
>
> This RFC strikes me as being very dangerous. Implicitly allowing code
> which is synchronous by design to be executed asynchronously seems
> sure to lead to very subtle, unpredictable, confusing and dangerous
> bugs.
>

Thank you for sharing your thoughts, I'll respond inline for better
context, but shortened some paragraphs for better readability.


> [...]
>
> For example, the PHP ecosystem is full of code like this:
>
>     private function capturePayment()
>     {
>         $paymentRequest = preparePaymentRequest($this->currentOrder);
>         $this->paymentGateway->capturePayment($paymentRequest);
>
> $this->currentOrder->setTransactionId($paymentRequest->getTransactionId());
>     }
>
> In the above code snippet, the developer has relied on the fact that
> the mutable value $this->currentOrder will be the same before and
> after the call to $this->capturePayment() [...]
>

This is a very valid concern to have. However, this code won't simply break
if executed asynchronously.
It only breaks if the same method (or other methods making use of the same
state) is executed concurrently on that object.


> [...]
>
> - These race conditions will cause problems so rarely that developers
> will not even realise that their programs contain dangerous bugs. [...]
> - Changes very, very far away from your code can cause your code to
> become unexpectedly asynchronous. [...]
> - As a library author, there is no way of knowing how your code is
> going to be used, and what injected dependencies might use fibers
> internally.
>
> The counter arguments:
> - "The above code snippet is suboptimal, it shouldn't assume that
> mutable state remains unchanged following some IO, and the order
> should be passed in as an arg." [...]
> - "Fibers should only be enabled in async first programs." and "We
> could flag that certain libraries are fiber compatible or
> incompatible." [...]
>
> Consider the following:
>
>     private async function capturePayment()
>     {
>         $paymentRequest = preparePaymentRequest($this->currentOrder);
>         await $this->paymentGateway->capturePayment($paymentRequest);
>
> $this->currentOrder->setTransactionId($paymentRequest->getTransactionId());
>     }
>
> Looking at the above code, I can see the race condition. It becomes
> explicit. So I change the code and communicate explicitly via the type
> system that this function is asynchronous and that my code expects
> PaymentGateway::capturePayment() to be asynchronous.
>

If you can see the race condition here, you can probably also see the race
condition in the original snippet above.

The overall issue you're describing is thread safety and mutable state. It
exists with fibers, but a very similar issue exists with explicit async /
await.
Just because something supports asynchronous I/O, doesn't mean it also
supports concurrent operations on its state.

It might be a good idea to introduce some guarding concept in a follow-up
RFC, so objects can easily protect against being used concurrently e.g.

```
private synchronized function capturePayment()
{
     $paymentRequest = preparePaymentRequest($this->currentOrder);
     $this->paymentGateway->capturePayment($paymentRequest);

 $this->currentOrder->setTransactionId($paymentRequest->getTransactionId());
 }
```

"synchonized" isn't the right keyword here, but I can't think of a better
name right now.


> Regarding PHP's type system not supporting generics, and the
> associated advantages of this RFC over promises; I agree that this is
> a problem with promises. But the lack of generics in PHP already means
> we have no language-level type safety on data structures, which is
> certainly worse than not having type safety on promises. Psalm et al
> have provided reasonable solutions to this issue.
>

Being able to use the type system is a concern the RFC solves, but that's
rather just nice-to-have. The relevant problem is the call stack pollution
or "What color is your function" problem. It simply doesn't make sense for
applications and libraries to offer an async and non-async interface for
everything. Due to the "What color is your function" problem, there can't
be a gradual migration to non-blocking I/O, which will mostly result in
non-blocking I/O simply not being supported by the majority of libraries,
making it basically non-viable in PHP.

Best,
Niklas

---

Next page: https://externals.io/message/113419.md?page=2
