ronantakizawa/codereview-bench huggingface dataset:
Repository: ClickHouse/ClickHouse
File: ci/praktika/utils.py (Python)

Code before:
            for line in stdout_lines:
                print(f"     | {line}")
        if stderr_lines:
            print("  Err:")
            for line in stderr_lines:
                print(f"     | {line}")

    @staticmethod
    def print_quoted_list(items: List[str], prefix: str = "  ") -> None:
        print(prefix + '"' + f"\"\n{prefix}\"".join(items) + '"')

    @staticmethod
    def sleep(seconds):
        time.sleep(seconds)

    @staticmethod
    def cwd():
        return str(Path.cwd())

    @staticmethod
    def cpu_count():
        return multiprocessing.cpu_count()

    @staticmethod
    def error(error_message: str) -> None:
        print(f"[ERROR] {error_message}")
        sys.exit(1)

    # deprecated: unnecessary lines in traceback + ide linting issues
    # switch to regular raise Ex() inplace
    @staticmethod
    def raise_with_error(error_message, stdout="", stderr="", ex=None):
        Utils.print_formatted_error(error_message, stdout, stderr)
        raise ex or RuntimeError(error_message)

    @staticmethod
    def timestamp():
        return datetime.now().timestamp()

    @staticmethod
    def timestamp_to_str(timestamp):
        return datetime.utcfromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")

    @staticmethod
    def get_failed_tests_number(description: str) -> Optional[int]:
        description = description.lower()

        pattern = r"fail:\s*(\d+)\s*(?=,|$)"
        match = re.search(pattern, description)
        if match:
            return int(match.group(1))

Review comment (suggestion):
it's not aligned with other stdout logs. use "ERROR:" or rename to [ERROR] everywhere 

Code after:
            for line in stdout_lines:
                print(f"     | {line}")
        if stderr_lines:
            print("  Err:")
            for line in stderr_lines:
                print(f"     | {line}")

    @staticmethod
    def sleep(seconds):
        time.sleep(seconds)

    @staticmethod
    def cwd():
        return str(Path.cwd())

    @staticmethod
    def cpu_count():
        return multiprocessing.cpu_count()

    @staticmethod
    def exit_with_error(error_message: str) -> None:
        print(f"ERROR: {error_message}")
        sys.exit(1)

    # deprecated: unnecessary lines in traceback + ide linting issues
    # switch to regular raise Ex() inplace
    @staticmethod
    def raise_with_error(error_message, stdout="", stderr="", ex=None):
        Utils.print_formatted_error(error_message, stdout, stderr)
        raise ex or RuntimeError(error_message)

    @staticmethod
    def timestamp():
        return datetime.now().timestamp()

    @staticmethod
    def timestamp_to_str(timestamp):
        return datetime.utcfromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")

    @staticmethod
    def get_failed_tests_number(description: str) -> Optional[int]:
        description = description.lower()

        pattern = r"fail:\s*(\d+)\s*(?=,|$)"
        match = re.search(pattern, description)
        if match:
            return int(match.group(1))
        return None

    @staticmethod
    def is_killed_with_oom():
Repository: ClickHouse/ClickHouse
File: tests/queries/0_stateless/03918_insert_squashing_const_different_values.sql (SQL)

Code before:

INSERT INTO t_const_squash(s, x)
WITH a AS (SELECT 'a' AS s, number AS x FROM numbers(100)),
     b AS (SELECT 'b' AS s, number AS x FROM numbers(90))
SELECT s, x FROM a LEFT JOIN numbers(30) num1 ON a.x = num1.number
UNION ALL
SELECT s, x FROM b LEFT JOIN numbers(10) num2 ON b.x = num2.number;

SELECT s, count() FROM t_const_squash GROUP BY s ORDER BY s;

TRUNCATE TABLE t_const_squash;

TRUNCATE TABLE t_const_squash;

INSERT INTO t_const_squash(s, x)
WITH a AS (SELECT 'a' AS s, number AS x FROM numbers(100)),
     b AS (SELECT 'b' AS s, number AS x FROM numbers(90)),
     c AS (SELECT 'c' AS s, number AS x FROM numbers(80)),
     d AS (SELECT 'd' AS s, number AS x FROM numbers(70))
SELECT s, x FROM a LEFT JOIN numbers(30) num1 ON a.x = num1.number
UNION ALL
SELECT s, x FROM b LEFT JOIN numbers(10) num2 ON b.x = num2.number
UNION ALL
SELECT s, x FROM c LEFT JOIN numbers(20) num3 ON c.x = num3.number
UNION ALL
SELECT s, x FROM d LEFT JOIN numbers(15) num4 ON d.x = num4.number;

SELECT s, count() FROM t_const_squash GROUP BY s ORDER BY s;

DROP TABLE t_const_squash;


Review comment (suggestion):
Let's change `LEFT JOIN` to `JOIN` here, so that we also test a different semantic.

Code after:

INSERT INTO t_const_squash(s, x)
WITH a AS (SELECT 'a' AS s, number AS x FROM numbers(100)),
     b AS (SELECT 'b' AS s, number AS x FROM numbers(90))
SELECT s, x FROM a LEFT JOIN numbers(30) num1 ON a.x = num1.number
UNION ALL
SELECT s, x FROM b LEFT JOIN numbers(10) num2 ON b.x = num2.number;

SELECT s, count() FROM t_const_squash GROUP BY s ORDER BY s;

TRUNCATE TABLE t_const_squash;

INSERT INTO t_const_squash(s, x)
WITH a AS (SELECT 'a' AS s, number AS x FROM numbers(100)),
     b AS (SELECT 'b' AS s, number AS x FROM numbers(90)),
     c AS (SELECT 'c' AS s, number AS x FROM numbers(80)),
     d AS (SELECT 'd' AS s, number AS x FROM numbers(70))
SELECT s, x FROM a JOIN numbers(30) num1 ON a.x = num1.number
UNION ALL
SELECT s, x FROM b JOIN numbers(10) num2 ON b.x = num2.number
UNION ALL
SELECT s, x FROM c JOIN numbers(20) num3 ON c.x = num3.number
UNION ALL
SELECT s, x FROM d JOIN numbers(15) num4 ON d.x = num4.number;

SELECT s, count() FROM t_const_squash GROUP BY s ORDER BY s;

DROP TABLE t_const_squash;
Repository: ClickHouse/ClickHouse
File: src/Storages/MergeTree/MergeTreeBackgroundExecutor.cpp (C++)

Code before:
            TaskRuntimeDataPtr item;
            {
                /// The only place without lock tracing.
                std::unique_lock lock(mutex);
                has_tasks.wait(lock, [this]() TSA_REQUIRES(mutex) { return !pending.empty() || shutdown; });

                if (shutdown)
                    break;

                item = std::move(pending.pop());
                active.push_back(item);
            }

            routine(std::move(item));
        }
        catch (...)
        {
            NOEXCEPT_SCOPE({
                ALLOW_ALLOCATIONS_IN_SCOPE;
                tryLogCurrentException(__PRETTY_FUNCTION__);
            });
        }

        {
            ALLOW_ALLOCATIONS_IN_SCOPE;
            current_thread->flushUntrackedMemory();
        }
    }
}


template class MergeTreeBackgroundExecutor<RoundRobinRuntimeQueue>;
template class MergeTreeBackgroundExecutor<PriorityRuntimeQueue>;
template class MergeTreeBackgroundExecutor<DynamicRuntimeQueue>;
}


Review comment (bug):
I think we need to avoid allocations inside `updatePeak`, since otherwise deadlock can happen, i.e. `updatePeak -> std::string -> new[] -> MemoryTracker::allocImpl`

Code after:
            TaskRuntimeDataPtr item;
            {
                /// The only place without lock tracing.
                std::unique_lock lock(mutex);
                has_tasks.wait(lock, [this]() TSA_REQUIRES(mutex) { return !pending.empty() || shutdown; });

                if (shutdown)
                    break;

                item = std::move(pending.pop());
                active.push_back(item);
            }

            routine(std::move(item));
        }
        catch (...)
        {
            NOEXCEPT_SCOPE({
                ALLOW_ALLOCATIONS_IN_SCOPE;
                tryLogCurrentException(__PRETTY_FUNCTION__);
            });
        }

        current_thread->flushUntrackedMemory();
    }
}


template class MergeTreeBackgroundExecutor<RoundRobinRuntimeQueue>;
template class MergeTreeBackgroundExecutor<PriorityRuntimeQueue>;
template class MergeTreeBackgroundExecutor<DynamicRuntimeQueue>;
}
Repository: ClickHouse/ClickHouse
File: src/Disks/DiskObjectStorage/MetadataStorages/NormalizedPath.cpp (C++)

Code before:
#include <Disks/DiskObjectStorage/MetadataStorages/NormalizedPath.h>

#include <base/defines.h>

#include <algorithm>
#include <ranges>
#include <vector>

namespace DB
{

NormalizedPath NormalizedPath::parent_path() const
{
    return NormalizedPath{std::filesystem::path::parent_path()};
}

NormalizedPath normalizePath(std::string path)
{
    auto lexically_normal = std::filesystem::path(path).lexically_normal();
    auto filtered_path = lexically_normal.string();

    /// Check that paths do not use .. anytime
    chassert(std::ranges::contains(lexically_normal | std::views::transform([](const auto & step) { return step.string(); }) | std::ranges::to<std::vector<std::string>>(), "..") == false);

    /// Remove leftovers from the ends
    std::string_view normalized_path = filtered_path;
    while (normalized_path.ends_with('/') || normalized_path.ends_with('.'))
        normalized_path.remove_suffix(1);

    while (normalized_path.starts_with('/') || normalized_path.starts_with('.'))
        normalized_path.remove_prefix(1);

    return NormalizedPath{normalized_path};
}

}


Review comment (suggestion):
Is it the same?
```suggestion
    chassert(lexically_normal != "..");
```

Code after:
#include <Disks/DiskObjectStorage/MetadataStorages/NormalizedPath.h>

#include <Common/Exception.h>

namespace DB
{

namespace ErrorCodes
{
    extern const int LOGICAL_ERROR;
}

[[maybe_unused]] static bool isPathRelative(const std::filesystem::path & path)
{
    for (const auto & step : path)
        if (step.string() == "..")
            return true;

    return false;
}

NormalizedPath NormalizedPath::parent_path() const
{
    return NormalizedPath{std::filesystem::path::parent_path()};
}

NormalizedPath normalizePath(std::string path)
{
    auto lexically_normal = std::filesystem::path(path).lexically_normal();

#ifndef NDEBUG
    if (isPathRelative(lexically_normal))
        throw Exception(ErrorCodes::LOGICAL_ERROR, "Path '{}' should not be used in disks", lexically_normal.string());
#endif

    /// Remove leftovers from the ends
    auto filtered_path = lexically_normal.string();
    std::string_view normalized_path = filtered_path;
    while (normalized_path.ends_with('/') || normalized_path.ends_with('.'))
        normalized_path.remove_suffix(1);

    while (normalized_path.starts_with('/') || normalized_path.starts_with('.'))
        normalized_path.remove_prefix(1);

    return NormalizedPath{normalized_path};
}

}
Repository: ClickHouse/ClickHouse
File: tests/queries/0_stateless/03925_text_index_qualify_filter_name_mismatch.sql (SQL)

Code before:
-- Regression test for a bug where text index preprocessing modified the filter DAG
-- (recreating the AND function node with a different result_name) but
-- processAndOptimizeTextIndexDAG returned nullptr because no virtual columns were added,
-- causing the FilterStep's filter_column_name to become inconsistent with the DAG.
-- This triggered a LOGICAL_ERROR in applyOrder.

DROP TABLE IF EXISTS t_text_index_qualify;

CREATE TABLE t_text_index_qualify
(
    id UInt64,
    val Map(String, String),
    INDEX idx mapValues(val) TYPE text(tokenizer = 'splitByNonAlpha') GRANULARITY 100000000
)
ENGINE = MergeTree
ORDER BY id;

INSERT INTO t_text_index_qualify VALUES (1, {'a': 'foo'}), (2, {'b': 'bar'});

-- The combination of PREWHERE + WHERE + QUALIFY with a text-indexed function triggers the bug.
-- QUALIFY merges into WHERE as AND, then text index preprocessing rewrites hasAnyTokens
-- but returns nullptr (no virtual columns added), leaving filter_column_name stale.
SELECT DISTINCT id
FROM t_text_index_qualify
PREWHERE hasAnyTokens(mapValues(val), 'foo')
WHERE hasAnyTokens(mapValues(val), 'foo')
QUALIFY id
ORDER BY id;

DROP TABLE t_text_index_qualify;


Review comment (performance):
Is it possible to make/extend this test with a simple String column in order to make it simpler? Based in the issue description this should be possible to reproduce without the complexity of a map right?

Code after:
-- Regression test for a bug where text index preprocessing modified the filter DAG
-- (recreating the AND function node with a different result_name) but
-- processAndOptimizeTextIndexDAG returned nullptr because no virtual columns were added,
-- causing the FilterStep's filter_column_name to become inconsistent with the DAG.
-- This triggered a LOGICAL_ERROR in applyOrder.

SET enable_analyzer = 1;

-- Case 1: Map column with text index on mapValues (original reproduction case)
DROP TABLE IF EXISTS t_text_index_qualify;

CREATE TABLE t_text_index_qualify
(
    id UInt64,
    val Map(String, String),
    INDEX idx mapValues(val) TYPE text(tokenizer = 'splitByNonAlpha') GRANULARITY 100000000
)
ENGINE = MergeTree
ORDER BY id;

INSERT INTO t_text_index_qualify VALUES (1, {'a': 'foo'}), (2, {'b': 'bar'});

-- The combination of PREWHERE + WHERE + QUALIFY with a text-indexed function triggers the bug.
-- QUALIFY merges into WHERE as AND, then text index preprocessing rewrites hasAnyTokens
-- but returns nullptr (no virtual columns added), leaving filter_column_name stale.
SELECT DISTINCT id
FROM t_text_index_qualify
PREWHERE hasAnyTokens(mapValues(val), 'foo')
WHERE hasAnyTokens(mapValues(val), 'foo')
QUALIFY id
ORDER BY id;

DROP TABLE t_text_index_qualify;

-- Case 2: Simple String column with text index
DROP TABLE IF EXISTS t_text_index_qualify_string;

CREATE TABLE t_text_index_qualify_string
(
    id UInt64,
    val String,
Repository: ClickHouse/ClickHouse
File: tests/queries/0_stateless/03927_correlated_subquery_table_function_context.sql (SQL)

Code before:
-- Tags: no-fasttest, no-parallel-replicas
-- Correlated subquery with a table function should not fail with "Context has expired".
-- https://github.com/ClickHouse/ClickHouse/issues/92991

SET enable_analyzer = 1;

CREATE TABLE t0_03927 (c0 Int) ENGINE = Memory();
INSERT INTO t0_03927 VALUES (1);

SELECT (SELECT t0_03927.c0 FROM url('http://localhost:8123/?query=SELECT+1', 'CSV') tx) FROM t0_03927;

DROP TABLE t0_03927;


Review comment (suggestion):
Maybe we could add another test, that would test the codepath with EXISTS correlated subquery? This should work:

```suggestion
SELECT * FROM t0_03927 WHERE EXISTS (
    SELECT 1 FROM url('http://localhost:8123/?query=SELECT+1', 'CSV') tx 
    WHERE tx.c1 = t0_03927.c0
);
```



Code after:
-- Tags: no-fasttest, no-parallel-replicas
-- Correlated subquery with a table function should not fail with "Context has expired".
-- https://github.com/ClickHouse/ClickHouse/issues/92991

SET enable_analyzer = 1;

CREATE TABLE t0_03927 (c0 Int) ENGINE = Memory();
INSERT INTO t0_03927 VALUES (1);

SELECT (SELECT t0_03927.c0 FROM url('http://localhost:8123/?query=SELECT+1', 'CSV') tx) FROM t0_03927;
SELECT * FROM t0_03927 WHERE EXISTS (
    SELECT 1 FROM url('http://localhost:8123/?query=SELECT+1', 'CSV') tx 
    WHERE tx.c1 = t0_03927.c0
);
DROP TABLE t0_03927;
Repository: ClickHouse/ClickHouse
File: tests/queries/0_stateless/03984_kill_query_with_fill.sh (Shell)

Code before:
#!/usr/bin/env bash
# Tags: no-fasttest, no-sanitizers-lsan, long
# Test that KILL QUERY works for queries with WITH FILL generating huge ranges.
# Ref: https://github.com/ClickHouse/ClickHouse/issues/97560

CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
# shellcheck source=../shell_config.sh
. "$CURDIR"/../shell_config.sh

query_id="kill_query_with_fill_${CLICKHOUSE_DATABASE}_$RANDOM"

function wait_for_query_to_start()
{
    local timeout=120
    local start=$EPOCHSECONDS
    while [[ $($CLICKHOUSE_CURL -sS "$CLICKHOUSE_URL" -d "SELECT count() FROM system.processes WHERE query_id = '$1' SETTINGS use_query_cache = 0") == 0 ]]; do
        if ((EPOCHSECONDS - start > timeout)); then
            echo "Timeout waiting for query to start" >&2
            exit 1
        fi
        sleep 0.1
    done
}

# This query generates ~3 billion rows via WITH FILL (year 2000 to 2100, step 1 second).
# Without the fix, KILL QUERY would not be able to cancel it.
$CLICKHOUSE_CLIENT --query_id="$query_id" --query "
    SELECT ts FROM (SELECT toDateTime('2050-06-15 12:00:00') AS ts)
    ORDER BY ts WITH FILL FROM toDateTime('2000-01-01 00:00:00') TO toDateTime('2100-01-01 00:00:00') STEP 1
    FORMAT Null
" >/dev/null 2>&1 &

wait_for_query_to_start "$query_id"

$CLICKHOUSE_CLIENT --query "KILL QUERY WHERE query_id = '$query_id' SYNC" >/dev/null

wait

Review comment (suggestion):
Ideally this function must be in `tests/queries/shell_config.sh` near `wait_for_queries_to_finish()`.  But if I grep for wait_for_query_to_start() in `*.sh` I see different sub-variants of `wait_for_query_to_start()` in several files. It looks like a tech debt (to do later).

Code after:
#!/usr/bin/env bash
# Tags: no-fasttest, no-sanitizers-lsan, long
# Test that KILL QUERY works for queries with WITH FILL generating huge ranges.
# Ref: https://github.com/ClickHouse/ClickHouse/issues/97560

CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
# shellcheck source=../shell_config.sh
. "$CURDIR"/../shell_config.sh

query_id="kill_query_with_fill_${CLICKHOUSE_DATABASE}_$RANDOM"

# This query generates ~3 billion rows via WITH FILL (year 2000 to 2100, step 1 second).
# Without the fix, KILL QUERY would not be able to cancel it.
$CLICKHOUSE_CLIENT --query_id="$query_id" --query "
    SELECT ts FROM (SELECT toDateTime('2050-06-15 12:00:00') AS ts)
    ORDER BY ts WITH FILL FROM toDateTime('2000-01-01 00:00:00') TO toDateTime('2100-01-01 00:00:00') STEP 1
    FORMAT Null
" >/dev/null 2>&1 &

wait_for_query_to_start "$query_id"

# Use async KILL (without SYNC) to avoid blocking if propagation is slow.
$CLICKHOUSE_CURL -sS "$CLICKHOUSE_URL" -d "KILL QUERY WHERE query_id = '$query_id'" >/dev/null

wait

echo "OK"
Repository: ClickHouse/ClickHouse
File: tests/queries/0_stateless/03984_table_function_arg_in_remote_with_join_using.sql (SQL)

Code before:
-- Regression test: TABLE_FUNCTION node as argument of remote() must not cause
-- LOGICAL_ERROR when the same table expression is re-resolved during
-- analyzer_compatibility_join_using_top_level_identifier handling.
-- https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=b053840ef38b3b36bc7fb44fa6d5fb129571b2cd&name_0=MasterCI&name_1=BuzzHouse+%28amd_ubsan%29

SET enable_analyzer = 1;
SET analyzer_compatibility_join_using_top_level_identifier = 1;

SELECT generate_series AS c0
FROM remote('localhost', generateSeries(1, 3)) AS t
LEFT JOIN (SELECT generate_series AS c0 FROM generateSeries(1, 3)) AS t2 USING (c0)
FORMAT Null;


Review comment (suggestion):
The test is already good, I just found a more minimalistic version and wanted to share it here in case that would be of interest:

```sql
SELECT 1 AS c0
FROM remote('localhost:9000', generateSeries(1, 10)) AS t1
LEFT JOIN (SELECT 1 AS c0) AS t2 USING (c0);
```

Code after:
-- Regression test: TABLE_FUNCTION node as argument of remote() must not cause
-- LOGICAL_ERROR when the same table expression is re-resolved during
-- analyzer_compatibility_join_using_top_level_identifier handling.
-- https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=b053840ef38b3b36bc7fb44fa6d5fb129571b2cd&name_0=MasterCI&name_1=BuzzHouse+%28amd_ubsan%29

SET enable_analyzer = 1;
SET analyzer_compatibility_join_using_top_level_identifier = 1;
SET enable_parallel_replicas = 0;

SELECT generate_series AS c0
FROM remote('localhost', generateSeries(1, 3)) AS t
LEFT JOIN (SELECT generate_series AS c0 FROM generateSeries(1, 3)) AS t2 USING (c0)
FORMAT Null;

-- Simplified reproduction from Kirill Fgrtue
SELECT 1 AS c0
FROM remote('localhost:9000', generateSeries(1, 10)) AS t1
LEFT JOIN (SELECT 1 AS c0) AS t2 USING (c0)
FORMAT Null; -- { serverError INVALID_JOIN_ON_EXPRESSION }
Repository: ClickHouse/ClickHouse
File: tests/queries/0_stateless/01643_replicated_merge_tree_fsync_smoke.sql (SQL)

Code before:
-- Tags: no-object-storage

-- Temporarily skip warning 'table was created by another server at the same moment, will retry'
set send_logs_level='error';
set database_atomic_wait_for_drop_and_detach_synchronously=1;

drop table if exists rep_fsync_r1;
drop table if exists rep_fsync_r2;

select 'default';
create table rep_fsync_r1 (key Int) engine=ReplicatedMergeTree('/clickhouse/tables/{database}/rep_fsync', 'r1') order by key;
create table rep_fsync_r2 (key Int) engine=ReplicatedMergeTree('/clickhouse/tables/{database}/rep_fsync', 'r2') order by key;
insert into rep_fsync_r1 values (1);
system sync replica rep_fsync_r2;
select * from rep_fsync_r2;
optimize table rep_fsync_r1 final;
system sync replica rep_fsync_r2;
drop table rep_fsync_r1;
drop table rep_fsync_r2;

select 'compact fsync_after_insert';
create table rep_fsync_r1 (key Int) engine=ReplicatedMergeTree('/clickhouse/tables/{database}/rep_fsync', 'r1') order by key settings min_rows_for_wide_part=2, fsync_after_insert=1;
create table rep_fsync_r2 (key Int) engine=ReplicatedMergeTree('/clickhouse/tables/{database}/rep_fsync', 'r2') order by key settings min_rows_for_wide_part=2, fsync_after_insert=1;
insert into rep_fsync_r1 values (1);
system sync replica rep_fsync_r2;
select * from rep_fsync_r2;

Review comment (refactor):
This test seems not to pass the flaky check because it takes too long: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=97961&sha=6cd81e063481926a2d62a5acb25da42c7a6032da&name_0=PR&name_1=Stateless+tests+%28amd_binary%2C+flaky+check%29

>2026-02-26 01:57:26 Reason: Test runs too long (> 180s). Make it faster. 

Should we consider adding `no-flacky-check`?
```suggestion
-- Tags: no-object-storage, no-flaky-check
```

Code after:
-- Tags: no-object-storage, no-flaky-check

-- Temporarily skip warning 'table was created by another server at the same moment, will retry'
set send_logs_level='error';
set database_atomic_wait_for_drop_and_detach_synchronously=1;

drop table if exists rep_fsync_r1;
drop table if exists rep_fsync_r2;

select 'default';
create table rep_fsync_r1 (key Int) engine=ReplicatedMergeTree('/clickhouse/tables/{database}/rep_fsync', 'r1') order by key;
create table rep_fsync_r2 (key Int) engine=ReplicatedMergeTree('/clickhouse/tables/{database}/rep_fsync', 'r2') order by key;
insert into rep_fsync_r1 values (1);
system sync replica rep_fsync_r2;
select * from rep_fsync_r2;
optimize table rep_fsync_r1 final;
system sync replica rep_fsync_r2;
drop table rep_fsync_r1;
drop table rep_fsync_r2;

select 'compact fsync_after_insert';
create table rep_fsync_r1 (key Int) engine=ReplicatedMergeTree('/clickhouse/tables/{database}/rep_fsync', 'r1') order by key settings min_rows_for_wide_part=2, fsync_after_insert=1;
create table rep_fsync_r2 (key Int) engine=ReplicatedMergeTree('/clickhouse/tables/{database}/rep_fsync', 'r2') order by key settings min_rows_for_wide_part=2, fsync_after_insert=1;
insert into rep_fsync_r1 values (1);
system sync replica rep_fsync_r2;
select * from rep_fsync_r2;