There is a problem with the StaticJoinOptimizer for queries containing complex subqueries that will (in the end) be transformed into named subquery includes. The problem is that the StaticJoinOptimizer optimizes JoinGroups in these subqueries in the context of an ancestry. While this is perfectly valid for non-complex subqueries (which will be evaluated inline and where we indeed pass in bindings from prior evaluation steps), the complex ones are evaluated bottom-up (i.e., first) without knowledge of any ancestry variables. We thus need to void the ancestry when recursing into such complex subqueries.
See https://www.mediawiki.org/wiki/Wikidata_query_service/Problematic_queries#Most_frequent_properties_by_class for an example query. The problem here is that the inner SELECT query is optimized using an ancestry that includes ?p (from the outer statement pattern for ?p), but translated into a named subquery include afterwards where ?p is not visible.