Hibernate Reactive: Detected use of the reactive Session from a different Thread
Discussed in https://github.com/micronaut-projects/micronaut-data/discussions/2083
Originally posted by nenad-kosanovic-tam March 22, 2023 When using Hibernate Reactive with vertx-mysql-client and have service method annotated with transaction, vert.x thread is used. If there are no other async calls, except to Hibernate Reactive repository, all works good.
But, if in this execution chane, we need to call Reactive REST client, this call will switch to different thread (not vert.x), and exception will be thrown on callback, as new session will be created instead of re-using the previously existing session residing in context.
HR000069: Detected use of the reactive Session from a different Thread than the one which was used to open the reactive Session - this suggests an invalid integration; original thread [52]: 'vert.x-eventloop-thread-1' current Thread [55]: 'vert.x-eventloop-thread-2
How should we work with Reactive REST Client and Hibernate Reactive Transactions?
Here is the repository and test method in it, that will reproduce issue: https://github.com/nenad-kosanovic-tam/Hibernate-Reactive-Transactions-with-Reactive-REST-Client
Issue is reproducable by running test ThingServiceTest#createWithRestCall_should_fail.
@dstepanov perhaps related to context propagation?
I'm very puzzled about how it is supported to work in the reactive world where the thread context can switch and later be processed on a different thread, which is also from the vertx thread pool but different.
Is there any update on this issue? It seems to be a stopping issue for anyone wanting to work with reactive data.
bug is in Hibernate Reactive not here, follow https://github.com/hibernate/hibernate-reactive/issues/1667 for updates
I'm very puzzled about how it is supported to work in the reactive world where the thread context can switch and later be processed on a different thread, which is also from the vertx thread pool but different.
Vert.x has its own notion of a "duplicated" context, which is logically a sort of thread (though it of course there's no bijection between contexts and Threads).
You can't share a reactive session between Vert.x contexts, for the exact same reason that you can't share a regular session between Threads: a session holds mutable (and transactional) state associated with a certain unit of work.
[Part of the problem here is that people have been mislead into believing that reactive programming is automatically thread-safe. Which is completely false. It's Thread-safe but not thread-safe.]
so probably micronaut context propagation needs to be somehow integrated with vertx context propagation
so probably micronaut context propagation needs to be somehow integrated with vertx context propagation
Yeah, that's what we did in Quarkus, but I recall it being a bit subtle and I'm definitely not an expert on Vert.x.