A flush during a transaction can cause the org.hibernate.engine.spi.ActionQueue.InsertActionSorter#sort implementation to produce an incorrect ordering with subsequent constraint violation.
A simple test case is attached.
I cloned since I'm not sure the right approach is to reopen it (plus, I don't have permissions to do that).
This is for the second test case, which I'll create a pull request for.
BTW, if you prefer to reopen and continue tracking this issue there, then please dispose of this issue any way you want.
Fixed with a bubble-sort-like approach.
Fixed in 5.1 branch as well.