Always reproduced (ClickHouse server version 22.3.2.1):
`
udf code, python version 3.9.6
#!/usr/bin/python

import sys
import time

if __name__ == '__main__':
    for line in sys.stdin:
        print("Python4 " + line, end='')
        sys.stdout.flush()
`

SELECT test_function_python('clickhouse')

Query id: 57da3834-1238-4da6-a984-48d4c1bb4a04

┌─test_function_python('clickhouse')─┐
│ Python4 clickhouse                 │
└────────────────────────────────────┘

1 rows in set. Elapsed: 0.001 sec.

SELECT test_function_python('clickhouse') AS uuu
GROUP BY uuu

Query id: c14131e5-e7aa-4585-a9f5-8e4b3e29fe44


0 rows in set. Elapsed: 0.002 sec.

Received exception from server (version 22.3.2):
Code: 46. DB::Exception: Received from 10.254.134.108:9000. DB::Exception: Unknown function test_function_python. (UNKNOWN_FUNCTION)


SELECT uuu
FROM
(
    SELECT test_function_python('clickhouse') AS uuu
) AS tmp
GROUP BY uuu

Query id: 20ca737b-35e1-418a-ab8e-2a296ac44e28

┌─uuu────────────────┐
│ Python4 clickhouse │
└────────────────────┘

1 rows in set. Elapsed: 0.002 sec.
{
    DuplicateOrderByVisitor::Data order_by_data{context};
    DuplicateOrderByVisitor(order_by_data).visit(query);
}
const ASTSelectQuery * getSimpleSubselect(const ASTSelectQuery & select)
{
    if (!select.tables())
        return nullptr;
    const auto & tables = select.tables()->children;
    if (tables.empty() || tables.size() != 1)
        return nullptr;
    const auto & ast_table_expression = tables[0]->as<ASTTablesInSelectQueryElement>()->table_expression;
    if (!ast_table_expression)
        return nullptr;
    const auto & table_expression = ast_table_expression->as<ASTTableExpression>();
    if (!table_expression->subquery)
        return nullptr;
    const auto & subquery = table_expression->subquery->as<ASTSubquery>();
    if (!subquery || subquery->children.size() != 1)
        return nullptr;
    const auto & subselect_union = subquery->children[0]->as<ASTSelectWithUnionQuery>();
    if (!subselect_union || !subselect_union->list_of_selects ||
        subselect_union->list_of_selects->children.size() != 1)
        return nullptr;
    const auto & subselect = subselect_union->list_of_selects->children[0]->as<ASTSelectQuery>();
    if (subselect && subselect->settings())
        return nullptr;
    return subselect;
}
std::unordered_set<String> getDistinctNames(const ASTSelectQuery & select)