Potential memory leak in Hibernate 6 ScrollableResultsConsumer

When scrolling over nested scrollable resultsets some entities remain referenced even when evicted from the session.

From what I’ve gathered from the code the ScrollableResultsConsumer registers the jdbcValuesSourceProcessingState in the LoadContexts . But deregister is never called with the jdbcValuesSourceProcessingState like it is in the ListResultsConsumer. This is probably fine if you just have one Stream/ScrollableResults but if you have nested streams it can become a problem.

      final LoadContexts loadContexts =
      final Field stackField =
      final StandardStack<JdbcValuesSourceProcessingState> stack =

      try (Stream<Event> events = session.createQuery("from Event", Event.class).stream()) {
        events.forEach(event -> {
          try (Stream<Item> items = session.createQuery("from Item", Item.class).stream()) {
            items.forEach(item -> {
              System.out.println("Item (" + item.getName() + ")");

In this example the stack.depth() will be the number of events + 1 and will hold references to Items and Events.
Is this a bug or is there another way to clear the stack to remove all references to entities?
I can clear the session and that removes the JdbcValuesSourceProcessingState from the stack but I’d rather avoid that if possible.

I think that through the Stream.close() call, which calls org.hibernate.ScrollableResults#close, this should be freed, but this is not happening right now, which is a bug AFAICT.
Can you please create an issue in the issue tracker(https://hibernate.atlassian.net) with a test case(https://github.com/hibernate/hibernate-test-case-templates/blob/master/orm/hibernate-orm-6/src/test/java/org/hibernate/bugs/JPAUnitTestCase.java) that reproduces the issue? For the reproduction, just assert loadContexts.isLoadingFinished() at the end, which will fail now. You don’t even need the nesting for showing the problem.