How to reproduce:

```sql
EXPLAIN SYNTAX
SELECT x
FROM 
(
    SELECT 1 AS x
    UNION DISTINCT
    SELECT 1
)

Query id: e777bc02-5d1b-4d49-ba89-4ebe31172387


Exception on client:
Code: 32. DB::Exception: Attempt to read after eof: while receiving packet from localhost:9000

```

#include <Common/ProfileEvents.h>
#include <Common/SensitiveDataMasker.h>
#include <Processors/Transforms/LimitsCheckingTransform.h>
#include <Processors/Transforms/MaterializingTransform.h>
#include <Processors/Formats/IOutputFormat.h>
namespace ProfileEvents
{
    extern const Event QueryMaskingRulesMatch;
    extern const Event FailedQuery;
    extern const Event FailedInsertQuery;
    extern const Event FailedSelectQuery;
    extern const Event QueryTimeMicroseconds;
    extern const Event SelectQueryTimeMicroseconds;
    extern const Event InsertQueryTimeMicroseconds;
}
namespace DB
{
namespace ErrorCodes
{
    extern const int INTO_OUTFILE_NOT_ALLOWED;
    extern const int QUERY_WAS_CANCELLED;
}
static void checkASTSizeLimits(const IAST & ast, const Settings & settings)
{
    if (settings.max_ast_depth)
        ast.checkDepth(settings.max_ast_depth);
    if (settings.max_ast_elements)
        ast.checkSize(settings.max_ast_elements);
}
static String joinLines(const String & query)