SqmRoot not yet resolved to TableGroup

I’m migrating an application to Hibernate 6 from 5.6. The code that worked fine prior to 6 and which has stopped working.

public static <T, E> long countByCriteriaBuilder(EntityManager em, Root<T> root, CriteriaQuery<E> criteria) {
		final CriteriaBuilder builder = em.getCriteriaBuilder();
		final CriteriaQuery<Long> countCriteria = builder.createQuery(Long.class);


		for (Root<?> fromRoot : criteria.getRoots()) {

		final Predicate whereRestriction = criteria.getRestriction();
		if (whereRestriction != null) {

		final Predicate groupRestriction = criteria.getGroupRestriction();
		if (groupRestriction != null) {

		return em.createQuery(countCriteria).getSingleResult();

This get follow error in line:
return em.createQuery(countCriteria).getSingleResult();

org.hibernate.query.sqm.InterpretationException: Error interpreting query [SqmRoot not yet resolved to TableGroup]; this may indicate a semantic (user query) problem or a bug in the parser [SqmRoot not yet resolved to TableGroup]

This was asked numerous times before:

You have to copy this differently i.e. with the SqmStatement#copy method. Look at the definition of CriteriaQuery#getRoots(), it says mutations to the list shall not alter the query.