**How to reproduce**
Clickhouse version 21.2-21.3

```
SELECT x
FROM
(
    SELECT 1 AS x
    UNION DISTINCT
    SELECT 1
)
LIMIT 1

Query id: b82bbb8d-dea9-4f1c-9a2f-5b0e9b6c2422


0 rows in set. Elapsed: 0.002 sec.

Received exception from server (version 21.2.3):
Code: 49. DB::Exception: Received from localhost:9000. DB::Exception: Bad cast from type DB::ASTSelectWithUnionQuery to DB::ASTSelectQuery.
```


settings.read_overflow_mode_leaf);
        }
        if (!options.ignore_quota && (options.to_stage == QueryProcessingStage::Complete))
            quota = context->getQuota();
        storage->read(query_plan, required_columns, metadata_snapshot,
                      query_info, *context, processing_stage, max_block_size, max_streams);
        if (context->hasQueryContext() && !options.is_internal)
        {
            auto local_storage_id = storage->getStorageID();
            context->getQueryContext().addQueryAccessInfo(
                backQuoteIfNeed(local_storage_id.getDatabaseName()), local_storage_id.getFullTableName(), required_columns);
        }
        
        if (!query_plan.isInitialized())
        {
            auto header = metadata_snapshot->getSampleBlockForColumns(
                    required_columns, storage->getVirtuals(), storage->getStorageID());
            addEmptySourceToQueryPlan(query_plan, header, query_info);
        }
        
        auto adding_limits_and_quota = std::make_unique<SettingQuotaAndLimitsStep>(
                query_plan.getCurrentDataStream(),
                storage,
                std::move(table_lock),
                limits,
                leaf_limits,
                std::move(quota),
                context);
        adding_limits_and_quota->setStepDescription("Set limits and quota after reading from storage");
        query_plan.addStep(std::move(adding_limits_and_quota));