Skip to content

Commit 562fc02

Browse files
robot-clickhouseleshikus
authored andcommitted
Backport #127043 to 26.3: Improve glue catalog cache
1 parent d6a3728 commit 562fc02

4 files changed

Lines changed: 99 additions & 17 deletions

File tree

‎src/Common/CurrentMetrics.cpp‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,8 @@
323323
M(AsyncInsertCacheSize, "Number of async insert hash id in cache") \
324324
M(IcebergMetadataFilesCacheBytes, "Size of the Iceberg metadata cache in bytes") \
325325
M(IcebergMetadataFilesCacheFiles, "Number of cached files in the Iceberg metadata cache") \
326+
M(GlueCatalogSchemaCacheBytes, "Size of the cache of current Iceberg schema field types in Glue catalogs in bytes") \
327+
M(GlueCatalogSchemaCacheEntries, "Number of entries in the cache of current Iceberg schema field types in Glue catalogs") \
326328
M(ParquetMetadataCacheBytes, "Size of the Parquet metadata cache in bytes") \
327329
M(ParquetMetadataCacheFiles, "Number of cached files in the Parquet metadata cache") \
328330
M(AvroSchemaCacheBytes, "Size of the Avro schema cache in bytes") \

‎src/Databases/DataLake/GlueCatalog.cpp‎

Lines changed: 31 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
#include <Common/Exception.h>
2222
#include <Common/CurrentMetrics.h>
23+
#include <base/unit.h>
2324
#include <Core/Settings.h>
2425
#include <Interpreters/Context.h>
2526

@@ -77,8 +78,8 @@ namespace DB::ServerSetting
7778

7879
namespace CurrentMetrics
7980
{
80-
extern const Metric MarkCacheBytes;
81-
extern const Metric MarkCacheFiles;
81+
extern const Metric GlueCatalogSchemaCacheBytes;
82+
extern const Metric GlueCatalogSchemaCacheEntries;
8283
}
8384

8485
namespace DataLake
@@ -95,7 +96,7 @@ GlueCatalog::GlueCatalog(
9596
, region(settings_.region)
9697
, settings(settings_)
9798
, table_engine_definition(table_engine_definition_)
98-
, metadata_objects(CurrentMetrics::MarkCacheBytes, CurrentMetrics::MarkCacheFiles, 1024)
99+
, current_schema_field_types(CurrentMetrics::GlueCatalogSchemaCacheBytes, CurrentMetrics::GlueCatalogSchemaCacheEntries, 16_MiB)
99100
{
100101
DB::S3::CredentialsConfiguration creds_config;
101102
creds_config.use_environment_credentials = true;
@@ -466,7 +467,7 @@ bool GlueCatalog::classifyTimestampTZ(const String & column_name, const TableMet
466467

467468
const String & metadata_uri = table_specific_properties->iceberg_metadata_file_location;
468469

469-
if (!metadata_objects.get(metadata_uri))
470+
auto [field_types, _] = current_schema_field_types.getOrSet(metadata_uri, [&]
470471
{
471472
auto [object_storage, bucket_name, metadata_path] = createObjectStorageForEarlyTableAccess(metadata_uri, table_metadata);
472473
const auto & read_settings = getContext()->getReadSettings();
@@ -479,28 +480,42 @@ bool GlueCatalog::classifyTimestampTZ(const String & column_name, const TableMet
479480
Poco::JSON::Parser parser;
480481
Poco::Dynamic::Var result = parser.parse(metadata_file_content);
481482
auto metadata_object = result.extract<Poco::JSON::Object::Ptr>();
482-
metadata_objects.set(metadata_uri, std::make_shared<Poco::JSON::Object::Ptr>(metadata_object));
483-
}
483+
return std::make_shared<FieldTypes>(getCurrentSchemaFieldTypes(metadata_object));
484+
});
485+
486+
auto it = field_types->find(column_name);
487+
return it != field_types->end() && it->second == DB::Iceberg::f_timestamptz;
488+
}
484489

485-
auto metadata_object = *metadata_objects.get(metadata_uri);
490+
GlueCatalog::FieldTypes GlueCatalog::getCurrentSchemaFieldTypes(const Poco::JSON::Object::Ptr & metadata_object)
491+
{
492+
FieldTypes result;
486493
auto current_schema_id = metadata_object->getValue<Int64>("current-schema-id");
487494
auto schemas = metadata_object->getArray(DB::Iceberg::f_schemas);
488495
for (size_t i = 0; i < schemas->size(); ++i)
489496
{
490497
auto schema = schemas->getObject(static_cast<UInt32>(i));
491-
if (schema->getValue<Int64>("schema-id") == current_schema_id)
498+
if (schema->getValue<Int64>("schema-id") != current_schema_id)
499+
continue;
500+
501+
auto fields = schema->getArray(DB::Iceberg::f_fields);
502+
for (size_t j = 0; j < fields->size(); ++j)
492503
{
493-
auto fields = schema->getArray(DB::Iceberg::f_fields);
494-
for (size_t j = 0; j < fields->size(); ++j)
495-
{
496-
auto field = fields->getObject(static_cast<UInt32>(j));
497-
if (field->getValue<String>(DB::Iceberg::f_name) == column_name)
498-
return field->getValue<String>(DB::Iceberg::f_type) == DB::Iceberg::f_timestamptz;
499-
}
504+
auto field = fields->getObject(static_cast<UInt32>(j));
505+
auto type = field->get(DB::Iceberg::f_type);
506+
if (type.isString())
507+
result.emplace(field->getValue<String>(DB::Iceberg::f_name), type.extract<String>());
500508
}
501509
}
510+
return result;
511+
}
502512

503-
return false;
513+
size_t GlueCatalog::FieldTypesWeightFunction::operator()(const FieldTypes & field_types) const
514+
{
515+
size_t result = 0;
516+
for (const auto & [name, type] : field_types)
517+
result += sizeof(FieldTypes::value_type) + name.size() + type.size();
518+
return result;
504519
}
505520

506521
GlueCatalog::ObjectStorageWithPath GlueCatalog::createObjectStorageForEarlyTableAccess(const String & s3_location, const TableMetadata & table_metadata) const

‎src/Databases/DataLake/GlueCatalog.h‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,9 +83,18 @@ class GlueCatalog final : public ICatalog, private DB::WithContext
8383
const String & column_name,
8484
const String & glue_column_type);
8585

86+
using FieldTypes = std::unordered_map<String, String>;
87+
88+
static FieldTypes getCurrentSchemaFieldTypes(const Poco::JSON::Object::Ptr & metadata_object);
89+
8690
private:
8791
void createNamespaceIfNotExists(const String & namespace_name) const;
8892

93+
struct FieldTypesWeightFunction
94+
{
95+
size_t operator()(const FieldTypes & field_types) const;
96+
};
97+
8998
std::unique_ptr<Aws::Glue::GlueClient> glue_client;
9099
const LoggerPtr log;
91100
std::shared_ptr<Aws::Auth::AWSCredentialsProvider> credentials_provider;
@@ -112,7 +121,7 @@ class GlueCatalog final : public ICatalog, private DB::WithContext
112121

113122
ObjectStorageWithPath createObjectStorageForEarlyTableAccess(const String & s3_location, const TableMetadata & table_metadata) const;
114123

115-
mutable DB::CacheBase<String, Poco::JSON::Object::Ptr> metadata_objects;
124+
mutable DB::CacheBase<String, FieldTypes, std::hash<String>, FieldTypesWeightFunction> current_schema_field_types;
116125
};
117126

118127
}

‎tests/integration/test_database_glue/test.py‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -588,6 +588,62 @@ def test_timestamps(started_cluster):
588588
assert node.query(f"SELECT * FROM {CATALOG_NAME}.`{root_namespace}.{table_name}`") == "2024-01-01 12:00:00.000000\t2024-01-01 12:00:00.000000\n"
589589

590590

591+
def test_timestamp_types_cache_does_not_keep_metadata(started_cluster):
592+
node = started_cluster.instances["node1"]
593+
594+
test_ref = f"test_ts_cache_{uuid.uuid4().hex}"
595+
table_name = f"{test_ref}_table"
596+
root_namespace = f"{test_ref}_namespace"
597+
database_name = f"db_{test_ref}"
598+
599+
catalog = load_catalog_impl(started_cluster)
600+
catalog.create_namespace(root_namespace)
601+
602+
schema = Schema(
603+
NestedField(field_id=1, name="timestamp", field_type=TimestampType(), required=False),
604+
NestedField(field_id=2, name="timestamptz", field_type=TimestamptzType(), required=False),
605+
)
606+
table = create_table(catalog, root_namespace, table_name, schema, dir=test_ref)
607+
608+
create_clickhouse_glue_database(started_cluster, node, database_name)
609+
610+
def cache_metrics():
611+
return [
612+
int(value)
613+
for value in node.query(
614+
"SELECT value FROM system.metrics "
615+
"WHERE metric IN ('GlueCatalogSchemaCacheBytes', 'GlueCatalogSchemaCacheEntries') ORDER BY metric"
616+
).split()
617+
]
618+
619+
bytes_before, entries_before = cache_metrics()
620+
621+
row = pa.Table.from_pylist(
622+
[{"timestamp": datetime(2024, 1, 1, 12), "timestamptz": datetime(2024, 1, 1, 12, tzinfo=pytz.UTC)}]
623+
)
624+
versions = 30
625+
for _ in range(versions):
626+
table.append(row)
627+
description = node.query(f"DESCRIBE TABLE {database_name}.`{root_namespace}.{table_name}`")
628+
assert [line.split("\t")[1] for line in description.splitlines()] == [
629+
"Nullable(DateTime64(6))",
630+
"Nullable(DateTime64(6, \\'UTC\\'))",
631+
]
632+
633+
bytes_after, entries_after = cache_metrics()
634+
assert entries_after - entries_before == versions
635+
636+
metadata_size = int(
637+
node.query(
638+
f"SELECT max(_size) FROM s3('http://minio1:9001/warehouse-glue/{test_ref}/metadata/*.metadata.json', "
639+
f"'{minio_access_key}', '{minio_secret_key}', 'One')"
640+
)
641+
)
642+
assert bytes_after - bytes_before < metadata_size
643+
644+
node.query(f"DROP DATABASE {database_name}")
645+
646+
591647
def test_insert(started_cluster):
592648
node = started_cluster.instances["node1"]
593649

0 commit comments

Comments
 (0)