Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/Formats/FormatFactory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1188,6 +1188,18 @@ bool FormatFactory::checkIfFormatSupportsSubsetOfColumns(const String & name, co
return target.subset_of_columns_support_checker && target.subset_of_columns_support_checker(format_settings);
}

bool FormatFactory::checkIfFormatIsRandomAccessInput(
const String & name, const ContextPtr & context, const std::optional<FormatSettings> & format_settings_) const
{
const bool seekable_read
= format_settings_ ? format_settings_->seekable_read : context->getSettingsRef()[Setting::input_format_allow_seeks];
if (!seekable_read)
return false;

const auto & target = getCreators(name);
return target.random_access_input_creator || target.random_access_input_creator_with_metadata;
}

void FormatFactory::registerPrewhereSupportChecker(const String & name, PrewhereSupportChecker prewhere_support_checker)
{
auto & target = getOrCreateCreators(name).prewhere_support_checker;
Expand Down
5 changes: 5 additions & 0 deletions src/Formats/FormatFactory.h
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,11 @@ class FormatFactory final : private boost::noncopyable, public IHints<2>
bool checkIfOutputFormatPrefersLargeBlocks(const String & name) const;
bool checkIfOutputFormatIsTTYFriendly(const String & name) const;
bool checkIfOutputFormatMayProduceRawBytes(const String & name, const FormatSettings & settings, const Block & header) const;
/// Whether reading `name` will seek instead of consuming the input from the start. A
/// random-access format reads its footer at the tail first, but only while it is allowed to
/// seek: with `input_format_allow_seeks = 0` it reads sequentially from the start instead.
bool checkIfFormatIsRandomAccessInput(
const String & name, const ContextPtr & context, const std::optional<FormatSettings> & format_settings_ = std::nullopt) const;

bool checkParallelizeOutputAfterReading(const String & name, const ContextPtr & context) const;

Expand Down
6 changes: 6 additions & 0 deletions src/IO/ReadSettings.h
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ struct RemoteFSReadSettings
/// Enable async prefetching for remote reads.
bool prefetch = false;

/// Hint that the consumer reads the object at arbitrary offsets rather than streaming it
/// sequentially from the start (for example, it reads a trailing index before the body). Read
/// paths may use this to skip speculative from-start read-ahead that such a consumer would not
/// consume.
bool random_access = false;

/// TODO: `max_backoff_ms` / `max_retries` are dead — assigned from public
/// Settings `remote_fs_read_max_backoff_ms` / `remote_fs_read_backoff_max_tries`
/// but no internal read path actually consumes them. Either wire them into
Expand Down
4 changes: 3 additions & 1 deletion src/Processors/Formats/Impl/Parquet/Prefetcher.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,9 @@ Prefetcher::~Prefetcher()

void Prefetcher::determineReadModeAndFileSize(ReadBuffer * reader_, const ReadOptions & options)
{
if (options.seekable_read)
/// `input_format_allow_seeks`. When seeks are disallowed we read the whole file sequentially
/// below instead of fetching the footer and the needed column ranges.
if (options.format.seekable_read)
{
bool has_file_size = isBufferWithFileSize(*reader_);
auto * seekable = dynamic_cast<SeekableReadBuffer *>(reader_);
Expand Down
2 changes: 0 additions & 2 deletions src/Processors/Formats/Impl/Parquet/ReadCommon.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@ struct ReadOptions
{
FormatSettings format;

bool seekable_read = true;

bool schema_inference_force_nullable = false;
bool schema_inference_force_not_nullable = false;

Expand Down
18 changes: 16 additions & 2 deletions src/Storages/ObjectStorage/DataLakes/DeltaLakeMetadata.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -529,14 +529,28 @@ struct DeltaLakeMetadataImpl
LOG_TRACE(log, "Using checkpoint file: {}", checkpoint_path.string());

auto read_settings = context->getReadSettings();
/// The checkpoint is a Parquet file: skip the generic from-start prefetch, the reader seeks
/// to the footer at the tail first, unless seeks are disabled.
read_settings.remote_fs_settings.random_access
= FormatFactory::instance().checkIfFormatIsRandomAccessInput("Parquet", context);
RelativePathWithMetadata object_info(checkpoint_path);
auto buf = createReadBuffer(object_info, object_storage, context, log);
auto format_settings = getFormatSettings(context);

/// Force nullable, because this parquet file for some reason does not have nullable
/// in parquet file metadata while the type are in fact nullable.
format_settings.schema_inference_make_columns_nullable = true;
auto columns = NativeParquetSchemaReader(*buf, format_settings).readSchema();

/// The schema pass gets its own buffer: with `input_format_allow_seeks = 0` the reader
/// cannot seek to the footer, so it streams the whole file and leaves the buffer at EOF,
/// and the data pass below would then find no `PAR1` magic left to read. Opening the object
/// again costs no extra HEAD: `createReadBuffer` memoises the metadata into `object_info`.
NamesAndTypesList columns;
{
auto schema_buf = createReadBuffer(object_info, object_storage, context, log, read_settings);
columns = NativeParquetSchemaReader(*schema_buf, format_settings).readSchema();
}

auto buf = createReadBuffer(object_info, object_storage, context, log, read_settings);

/// Read only columns that we need.
auto filter_column_names = NameSet{"add", "metaData"};
Expand Down
7 changes: 6 additions & 1 deletion src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,12 @@ static void writeDataFiles(

ObjectStoragePtr storage_to_use = data_file->data_object_info->getResolvedStorage(object_storage);
RelativePathWithMetadata relative_path(data_file->data_object_info->getPath());
auto read_buffer = createReadBuffer(relative_path, storage_to_use, context, getLogger("IcebergCompaction"));
/// A data file may be Parquet/ORC/Avro; only the ones that will actually seek to a footer at
/// the tail should skip the generic from-start prefetch.
auto read_settings = context->getReadSettings();
read_settings.remote_fs_settings.random_access = FormatFactory::instance().checkIfFormatIsRandomAccessInput(
data_file->data_object_info->getFileFormat().value_or(write_format), context);
auto read_buffer = createReadBuffer(relative_path, storage_to_use, context, getLogger("IcebergCompaction"), read_settings);

const Settings & settings = context->getSettingsRef();
auto parser_shared_resources = std::make_shared<FormatParserSharedResources>(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1980,8 +1980,13 @@ void IcebergMetadata::addDeleteTransformers(
persistent_components.path_resolver);

RelativePathWithMetadata delete_file_object(resolved_delete_key);
/// Equality deletes may be Parquet/ORC/Avro; only the ones that will actually seek to a
/// footer at the tail should skip the generic from-start prefetch.
auto read_settings = local_context->getReadSettings();
read_settings.remote_fs_settings.random_access
= FormatFactory::instance().checkIfFormatIsRandomAccessInput(delete_file.file_format, local_context);
{
auto schema_read_buffer = createReadBuffer(delete_file_object, delete_storage_to_use, local_context, log);
auto schema_read_buffer = createReadBuffer(delete_file_object, delete_storage_to_use, local_context, log, read_settings);
auto schema_reader = FormatFactory::instance().getSchemaReader(delete_file.file_format, *schema_read_buffer, local_context);
auto columns_with_names = schema_reader->readSchema();
ColumnsWithTypeAndName initial_header_data;
Expand All @@ -2008,7 +2013,7 @@ void IcebergMetadata::addDeleteTransformers(
}
/// Then we read the content of the delete file.
auto mutable_columns_for_set = block_for_set.cloneEmptyColumns();
std::unique_ptr<ReadBuffer> data_read_buffer = createReadBuffer(delete_file_object, delete_storage_to_use, local_context, log);
std::unique_ptr<ReadBuffer> data_read_buffer = createReadBuffer(delete_file_object, delete_storage_to_use, local_context, log, read_settings);
CompressionMethod compression_method = chooseCompressionMethod(delete_file.file_path, "auto");
auto delete_format = FormatFactory::instance().getInput(
delete_file.file_format,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,14 @@ void IcebergPositionDeleteTransform::initializeDeleteSources()
if (boost::to_lower_copy(format) != "parquet")
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Position deletes are supported only for parquet format");

/// Parquet reads the footer at the tail first, so hint the object-storage read buffer to
/// skip the generic from-start prefetch that it would drop, unless seeks are disabled.
auto read_settings = context->getReadSettings();
read_settings.remote_fs_settings.random_access = FormatFactory::instance().checkIfFormatIsRandomAccessInput(format, context);

Block initial_header;
{
std::unique_ptr<ReadBuffer> read_buf_schema = createReadBuffer(object_info, delete_storage_to_use, context, log);
std::unique_ptr<ReadBuffer> read_buf_schema = createReadBuffer(object_info, delete_storage_to_use, context, log, read_settings);
auto schema_reader = FormatFactory::instance().getSchemaReader(format, *read_buf_schema, context);
auto columns_with_names = schema_reader->readSchema();
ColumnsWithTypeAndName initial_header_data;
Expand All @@ -102,7 +107,7 @@ void IcebergPositionDeleteTransform::initializeDeleteSources()

CompressionMethod compression_method = chooseCompressionMethod(resolved_key, "auto");

delete_read_buffers.push_back(createReadBuffer(object_info, delete_storage_to_use, context, log));
delete_read_buffers.push_back(createReadBuffer(object_info, delete_storage_to_use, context, log, read_settings));

auto syntax_result = TreeRewriter(context).analyze(where_ast, initial_header.getNamesAndTypesList());
ExpressionAnalyzer analyzer(where_ast, syntax_result, context);
Expand Down
17 changes: 14 additions & 3 deletions src/Storages/ObjectStorage/StorageObjectStorageSource.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1465,8 +1465,14 @@ StorageObjectStorageSource::ReaderHolder StorageObjectStorageSource::createReade
{
ProfileEvents::increment(ProfileEvents::ObjectStorageReadObjects);
compression_method = chooseCompressionMethod(object_info->getFileName(), configuration->compression_method);
ReadSettings read_settings = context_->getReadSettings();
/// A from-start read-ahead is wasted on a reader that seeks straight to a footer at the
/// tail, but it is exactly what a reader that cannot seek consumes.
read_settings.remote_fs_settings.random_access
= FormatFactory::instance().checkIfFormatIsRandomAccessInput(format_name, context_, format_settings);
read_buf = createReadBuffer(
object_info->relative_path_with_metadata, object_info->getResolvedStorage(object_storage), context_, log, std::nullopt, !headers_requested);
object_info->relative_path_with_metadata, object_info->getResolvedStorage(object_storage), context_, log,
read_settings, !headers_requested);
}

Block initial_header = read_from_format_info.format_header;
Expand Down Expand Up @@ -2025,8 +2031,13 @@ std::unique_ptr<ReadBufferFromFileBase> createReadBuffer(
// Create a read buffer that will prefetch the first ~1 MB of the file.
// When reading lots of tiny files, this prefetching almost doubles the throughput.
// For bigger files, parallel reading is more useful.
const bool object_too_small = is_size_known
&& object_size <= 2 * context_->getSettingsRef()[Setting::max_download_buffer_size];
// For formats with random access (Parquet), we need footer to understand what we should read.
// So, it disabled for random access formats, if prefetch doesn't reach footer. (file size > 1MB)

const size_t prefetch_size_limit = modified_read_settings.remote_fs_settings.random_access
? modified_read_settings.remote_fs_settings.buffer_size
: 2 * context_->getSettingsRef()[Setting::max_download_buffer_size];
const bool object_too_small = is_size_known && object_size <= prefetch_size_limit;
const bool use_prefetch = object_too_small
&& modified_read_settings.remote_fs_settings.method == RemoteFSReadMethod::threadpool
&& modified_read_settings.remote_fs_settings.prefetch;
Expand Down
12 changes: 12 additions & 0 deletions tests/integration/test_storage_delta/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -681,6 +681,18 @@ def test_checkpoint(started_cluster, use_delta_kernel, storage_type):
).strip()
)

# The legacy metadata reader reads the checkpoint twice, once for the schema and once for the
# data. With `input_format_allow_seeks = 0` the schema pass cannot seek to the footer, so it
# streams the whole file and leaves its buffer at EOF; the data pass has to open its own.
assert (
int(
instance.query(
f"SELECT count() FROM {TABLE_NAME} SETTINGS input_format_allow_seeks = 0"
)
)
== 20
)


@pytest.mark.parametrize("use_delta_kernel", ["1", "0"])
def test_multiple_log_files(started_cluster, use_delta_kernel):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
0
0
0
1
1
1
103 changes: 103 additions & 0 deletions tests/queries/0_stateless/05024_parquet_s3_no_footer_prefetch.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
#!/usr/bin/env bash
# Tags: no-fasttest, no-random-settings, no-distributed-cache
# no-fasttest: reads from S3 (MinIO).
# no-random-settings / no-distributed-cache: the test asserts the read-ahead prefetch count,
# which depends on buffer sizes and the read method.

# The object-storage read path issues a from-start read-ahead prefetch for "small" objects. For
# column-oriented random-access formats (`Parquet`) - which read the `FileMetaData` footer at the
# tail first - that prefetch cannot reach the footer once the object is larger than one read
# buffer, so it is dropped: a wasted object read. The reader must gate it, prefetching only when
# the whole object fits a single read buffer.
#
# The query prunes every row group by footer min/max statistics (a predicate above the column
# maximum), so it answers from the footer alone and reads no data pages. That isolates the
# from-start prefetch as the only read-ahead that could fire, asserted via
# ProfileEvents['RemoteFSPrefetches']:
# - big object (> one read buffer) -> prefetch suppressed -> RemoteFSPrefetches = 0
# - small object (<= one read buffer) -> whole-file prefetch fires -> RemoteFSPrefetches >= 1

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

url="http://localhost:11111/test/${CLICKHOUSE_DATABASE}"

# Force the prefetch path deterministically:
# - threadpool method + prefetch on, so the from-start prefetch is eligible.
# - max_read_buffer_size = 1 MiB: the new gate prefetches a random-access object only when it
# fits one read buffer, so the ~11 MiB "big" object is above it and must NOT prefetch.
# - max_download_buffer_size = 10 MiB: the OLD heuristic prefetched objects up to
# 2 * max_download_buffer_size = 20 MiB, so the ~11 MiB object sits in the band where the old
# code WOULD have prefetched - making RemoteFSPrefetches = 0 a proof of the gate, not just of
# the object being too large for any prefetch.
read_settings="remote_filesystem_read_method='threadpool', remote_filesystem_read_prefetch=1, max_read_buffer_size=1048576, max_download_buffer_size=10485760, input_format_parquet_filter_push_down=1, optimize_count_from_files=0"

# big object: > 1 read buffer. The incompressible string column inflates it well past 1 MiB.
${CLICKHOUSE_CLIENT} --query "
INSERT INTO FUNCTION s3('${url}/big.parquet', 'test', 'testtest', 'Parquet')
SELECT number AS v, randomPrintableASCII(64) AS s FROM numbers(200000)
SETTINGS s3_truncate_on_insert = 1, output_format_parquet_row_group_size = 50000
"

# small object: whole file fits one read buffer.
${CLICKHOUSE_CLIENT} --query "
INSERT INTO FUNCTION s3('${url}/small.parquet', 'test', 'testtest', 'Parquet')
SELECT number AS v, randomPrintableASCII(8) AS s FROM numbers(50)
SETTINGS s3_truncate_on_insert = 1
"

run() {
local query_id=$1 file=$2 extra_settings=$3
# The schema is passed explicitly on purpose: an inferred schema opens the object once more
# through the schema-inference path (a separate read buffer), which would add its own prefetch
# and mask the one under test. v is at most 199999, so the predicate prunes every row group by
# footer statistics - the query answers from the footer alone, reading no data pages.
${CLICKHOUSE_CLIENT} --query_id "$query_id" --query "
SELECT count() FROM s3('${url}/${file}', 'test', 'testtest', 'Parquet', 'v UInt64, s String') WHERE v > 100000000
SETTINGS ${read_settings}${extra_settings:+, ${extra_settings}}
"
}

qid_big="${CLICKHOUSE_DATABASE}_big"
qid_small="${CLICKHOUSE_DATABASE}_small"
qid_big_no_seeks="${CLICKHOUSE_DATABASE}_big_no_seeks"

run "$qid_big" big.parquet
run "$qid_small" small.parquet
# The same big object with seeks disabled: the reader can no longer read the footer at the tail, it
# reads the object sequentially from the start, so the from-start prefetch must not be gated off.
run "$qid_big_no_seeks" big.parquet "input_format_allow_seeks=0"

${CLICKHOUSE_CLIENT} --query "SYSTEM FLUSH LOGS query_log"

# The object is not necessarily read by the initiator: with parallel replicas enabled server-side
# (the ParallelReplicas job installs that into the default profile)
# `parallel_replicas_for_cluster_engines` rewrites `s3` to `s3Cluster`, and the read - along with
# its profile events - happens on a replica. Sum over `initial_query_id` so every node that ran the
# query is counted, in both topologies. The default `file` split granularity gives the whole object
# to one node, so the totals match the single-node ones. `count() > 0` guards the `= 0` assertion
# against passing on an empty set, where `sum` would also be 0.
#
# A secondary query runs with `current_database = 'default'`, not the initiator's database, so
# requiring `currentDatabase()` of every row drops exactly the replica rows that carry the prefetch
# counters. `initial_query_id` already isolates this test - the id is prefixed with the unique
# `$CLICKHOUSE_DATABASE` - so the database condition only has to hold for the initiator's own row.
prefetches() {
${CLICKHOUSE_CLIENT} --query "
SELECT $2
FROM system.query_log
WHERE initial_query_id = '$1' AND type = 'QueryFinish'
AND (current_database = currentDatabase() OR NOT is_initial_query)
"
}

# big object -> from-start prefetch is gated off.
prefetches "$qid_big" "sum(ProfileEvents['RemoteFSPrefetches']) = 0 AND count() > 0"

# small object -> whole-file prefetch still fires (and serves the footer from memory).
prefetches "$qid_small" "sum(ProfileEvents['RemoteFSPrefetches']) >= 1"

# big object with input_format_allow_seeks=0 -> the read is sequential from the start, so the
# from-start prefetch is useful and must still fire.
prefetches "$qid_big_no_seeks" "sum(ProfileEvents['RemoteFSPrefetches']) >= 1"
Loading