Skip to content

[[DRAFT]] Decouple datalakes from storage object storage - #100433

Closed
divanik wants to merge 80 commits into
masterfrom
decouple-datalake-from-storage-object-storage
Closed

divanik wants to merge 80 commits into
masterfrom
decouple-datalake-from-storage-object-storage

Conversation

@divanik

@divanik divanik commented Mar 23, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

To be continued...

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

divanik and others added 2 commits March 23, 2026 12:11
…unctions in `Utils.h/cpp`

Move `resolveSchemaFromData`, `resolveFormatFromData`, `resolveSchemaAndFormatFromData`,
`getSchemaCache`, and `createReadBufferIterator` from `StorageObjectStorage` static methods
to free functions in `Utils.h/cpp`. The static methods on `StorageObjectStorage` now delegate
to these free functions. All external callers (`InterpreterSystemQuery`,
`StorageSystemSchemaInferenceCache`, `StorageObjectStorageSource`) updated to call the free
functions directly.

This is a preparatory refactor for decoupling datalake engines from `StorageObjectStorage`.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…atalake registration

Copy `StorageObjectStorage` into `StorageDataLake` and `StorageObjectStorageCluster` into
`StorageDataLakeCluster` in the `DataLakes/` subdirectory. These are near-identical copies
that will be simplified in the next commit.

Move datalake storage engine registration (`registerStorageIceberg`, `registerStorageDeltaLake`,
`registerStorageHudi`) from `registerStorageObjectStorage.cpp` to a new
`registerStorageDataLake.cpp` that creates `StorageDataLake` instances.

Update `DatabaseDataLake.cpp` to create `StorageDataLake`/`StorageDataLakeCluster` instead of
`StorageObjectStorage`/`StorageObjectStorageCluster`.

Update table function `executeImpl` methods to create `StorageDataLake`/`StorageDataLakeCluster`
when `is_data_lake=true`.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8c77492]

Summary: ⏳

job_name test_name status info comment
Build (amd_msan) failure
Build ClickHouse failure cidb
Build (arm_msan) failure
Build ClickHouse failure cidb
Build (arm_v80compat) failure
Build ClickHouse failure cidb
Build (ppc64le) failure
Build ClickHouse failure cidb
Build (s390x) failure
Build ClickHouse failure cidb
Integration tests (amd_asan_ubsan, targeted) failure
test_database_glue/test.py::test_create FAIL cidb
test_database_glue/test.py::test_drop_table FAIL cidb
test_database_glue/test.py::test_no_secrets_in_logs FAIL cidb
test_database_iceberg/test.py::test_cluster_select FAIL cidb
test_database_iceberg/test.py::test_create FAIL cidb
test_database_iceberg/test.py::test_drop_table FAIL cidb
test_database_iceberg/test.py::test_no_secrets_in_logs FAIL cidb
test_storage_delta/test.py::test_insert_select_from_cluster_with_partition_pruning[0] FAIL cidb
test_storage_delta/test.py::test_insert_select_from_cluster_with_partition_pruning[1] FAIL cidb
test_storage_hudi/test.py::test_multiple_hudi_files FAIL cidb
4 more test cases not shown
Integration tests (amd_llvm_coverage, 2/5) failure
test_database_iceberg/test.py::test_no_secrets_in_logs FAIL cidb
test_database_iceberg/test.py::test_create FAIL cidb
test_database_iceberg/test.py::test_drop_table FAIL cidb
test_database_iceberg/test.py::test_cluster_select FAIL cidb
Integration tests (amd_llvm_coverage, 3/5) failure
test_storage_delta/test.py::test_insert_select_from_cluster_with_partition_pruning[0] FAIL cidb
test_storage_delta/test.py::test_insert_select_from_cluster_with_partition_pruning[1] FAIL cidb
test_database_glue/test.py::test_no_secrets_in_logs FAIL cidb
test_database_glue/test.py::test_create FAIL cidb
test_database_glue/test.py::test_drop_table FAIL cidb
Unit tests (asan_ubsan) failure
FunctionsStress.stress failure cidb
AllTests failure cidb
Stateless tests (amd_msan, flaky check) dropped

AI Review

Summary

This PR decouples data lake engines from StorageObjectStorage, but it currently contains multiple correctness and safety problems (type-safety bugs, lifetime/concurrency risks, metadata-initialization hazards, and a removed regression test). High-confidence blockers are already present in inline review comments from clickhouse-gh[bot]; I did not post duplicate inline comments.

PR Metadata
  • ⚠️ Changelog category: Improvement is plausible for a refactor of datalake internals.
  • ⚠️ Changelog entry: current text To be continued... is not acceptable user-facing changelog text.
  • ✅ Required replacement text:
    • Decoupled Iceberg/DeltaLake/Paimon and DataLake database paths from StorageObjectStorage configuration internals; fixed metadata initialization and settings propagation for DataLake engines.
Missing context
  • ⚠️ No CI logs or Praktika report links were provided in this review context, so runtime/test-failure validation could not be verified from CI artifacts.
Findings

❌ Blockers

  • [src/Storages/ObjectStorage/DataLakes/registerStorageDataLake.cpp:~437] DeltaLakeLocal uses StorageObjectStorageSettings::hasBuiltin instead of DataLakeStorageSettings::hasBuiltin, which can reject valid DataLake settings.
  • [src/Storages/ObjectStorage/DataLakes/StorageDataLake.cpp:~97, ~380] Copy-paste bug in CDF guard/validation (delta_lake_snapshot_start_version checked twice); delta_lake_snapshot_end_version is not correctly validated.
  • [src/Storages/ObjectStorage/DataLakes/StorageDataLake.cpp:~526; src/Storages/ObjectStorage/DataLakes/Iceberg/StorageIceberg.cpp:~409,~414,~428] Mutation/alter code paths dereference current_metadata without guaranteed initialization, leading to exception-prone behavior on lazy/deferred metadata init paths.
  • [src/Storages/ObjectStorage/DataLakes/StorageDataLake.cpp:~220; src/Storages/ObjectStorage/DataLakes/StorageDataLakeCluster.cpp:~43] Unsynchronized check-then-set on mutable current_metadata in const methods introduces data-race risk under concurrent reads.
  • [src/Processors/QueryPlan/ReadFromDataLakeStep.h:~68; src/Processors/QueryPlan/ReadFromIcebergStep.h:~68] Non-owning raw metadata pointers in plan steps can dangle if metadata gets swapped concurrently (updateMetadata), risking use-after-free.
  • [src/Databases/DataLake/DatabaseDataLake.cpp:~315] DatabaseDataLakeStorageType::Other falls through to Local instead of throwing, potentially hiding misconfiguration and routing to wrong backend.
  • [src/Databases/DataLake/DatabaseDataLake.cpp:~566] Cluster datalake path drops prepared storage_settings by passing nullptr, causing inconsistent behavior vs non-cluster path.
  • [src/Storages/ObjectStorage/S3/ConfigurationInitialization.cpp:~59; src/Databases/DataLake/DatabaseDataLake.cpp:~476] Unsafe std::static_pointer_cast usage with ineffective null checks; runtime type mismatch can pass checks and fail later unsafely.
  • [src/Storages/ObjectStorage/DataLakes/DeltaLakeMetadata.cpp:~129] Weak pointer lock is dereferenced in initializer list without validating lock result (configuration_.lock()), risking null dereference.
  • [src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergSource.cpp:~366] context.lock() result is passed through without early validation in filter remap path; later failure becomes timing-dependent.
  • [src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergSource.cpp:~242] Reference dynamic_cast can throw std::bad_cast for protocol/input mismatch paths; should be checked pointer cast with controlled exception.
  • [tests/queries/0_stateless/04054_deltalake_cdf_copy_paste_bug.sql] Regression test removal violates the no-test-removal rule unless replaced by equivalent stateless coverage in same PR.

⚠️ Majors

  • [src/Storages/ObjectStorage/DataLakes/Iceberg/StorageIceberg.cpp:~127] Early return in constructor can skip metadata setup, leaving partially initialized object state for later operations.
  • [src/Databases/DataLake/GlueCatalog.cpp:~509] Dead code (storage_settings computed but unused) on metadata resolution path.
  • Typo/message quality issues:
    • [src/Storages/ObjectStorage/DataLakes/StorageDataLake.cpp:~200] LawCardinality typo in comment.
    • [src/Databases/DataLake/DatabaseDataLake.cpp:~469] user-visible text Catalog is not equals to one lake should be corrected.
    • [src/Storages/ObjectStorage/DataLakes/Iceberg/StorageIceberg.h:~35] if_no_exists typo.

💡 Nits

  • PR changelog text is placeholder-only (To be continued...) and should be replaced with concrete user-facing impact.
Tests
  • ⚠️ Add/restore stateless regression coverage for the removed DeltaLake CDF copy-paste bug test.
  • ⚠️ Add coverage for new mutation path in datalake engines (ALTER ... DELETE/UPDATE) for both initialized and deferred-metadata states.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ⚠️ Core datalake storage/read paths have unresolved safety/correctness issues.
No test removal ❌ A stateless regression test was removed without equivalent replacement in-PR.
Experimental gate ➖
No magic constants ✅
Backward compatibility ⚠️ Misrouted storage type fallback and cluster/non-cluster settings mismatch can change behavior unexpectedly.
SettingsChangesHistory.cpp ➖
PR metadata quality ⚠️ Placeholder changelog entry is not acceptable user-facing text.
Safe rollout ⚠️ Multiple blockers in metadata/lifetime/concurrency paths make rollout unsafe.
Compilation time ⚠️ Large refactor touching many headers/source units; no explicit evidence of compile-time mitigation in this PR.
No large/binary files ✅
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Fix blocker correctness/safety issues listed above (type casts, metadata init/null handling, concurrency/lifetime risks, settings consistency).
    • Restore or replace removed stateless regression test coverage.
    • Replace placeholder changelog entry with concrete user-facing text.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Mar 23, 2026
Strip all datalake-specific code from `StorageObjectStorage`:
- Remove constructor params: `catalog`, `if_not_exists`, `is_datalake_query`
- Remove members: `catalog`, `storage_id`
- Remove methods: `getExternalMetadata`, `updateExternalDynamicMetadataIfExists`,
  `mutate`, `checkMutationIsPossible`, `executeCommand`, `optimize`, `alter`,
  `checkAlterIsPossible`, `supportsDelete`, `supportsParallelInsert`
- Remove Delta Lake CDF block from `read`
- Remove datalake write path from `write`
- Remove `isDataLakeConfiguration` guards throughout
- `isDataLake` and `supportsReplication` now return `false`

Strip datalake-irrelevant code from `StorageDataLake`:
- Remove hive partitioning (sample paths, `getPathSample`,
  `hive_partition_columns_to_read_from_file_path`, `file_columns`)
- Remove archive and glob checks (not applicable to datalakes)
- Remove raw object storage write path (`StorageObjectStorageSink`,
  `PartitionedStorageObjectStorageSink`)
- Remove static schema-inference delegations (use `Utils.h` directly)
- Simplify `truncate` to always throw `NOT_IMPLEMENTED`
- Simplify `write` to delegate to `configuration->write`
- Remove all redundant `isDataLakeConfiguration` guards
- `isDataLake` and `supportsReplication` now return `true`

Strip datalake code from `StorageObjectStorageCluster`:
- Remove snapshot state pinning (moved to `StorageDataLakeCluster`)
- Empty `updateExternalDynamicMetadataIfExists`

Update `StorageSystemIcebergHistory` to use `StorageDataLake` instead of
`StorageObjectStorage`.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
.supports_settings = true,
.supports_schema_inference = true,
.source_access_type = AccessTypeObjects::Source::FILE,
.has_builtin_setting_fn = StorageObjectStorageSettings::hasBuiltin,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DeltaLakeLocal is registered with .has_builtin_setting_fn = StorageObjectStorageSettings::hasBuiltin, but this path parses DataLakeStorageSettings (including disk) just above. This mismatch can reject valid DataLake-specific settings in CREATE TABLE ... ENGINE = DeltaLakeLocal ... SETTINGS ....

Please switch this line to DataLakeStorageSettings::hasBuiltin to keep settings validation consistent with the rest of DeltaLake registrations.

@divanik divanik added the no-fast-tests Drops preliminary CI jobs: Style, clang-tidy, Fast Test label Mar 23, 2026
divanik and others added 2 commits March 23, 2026 12:49
…ctStorageConfiguration`

Add `ObjectStoragePtr ready_object_storage` as a protected member of the base
`StorageObjectStorageConfiguration`. The `initialize` method now sets it after
`fromDisk` returns, and also performs the allowed-disk check.

Introduce `doCreateObjectStorage` as the new pure virtual for concrete storage
implementations (S3, Azure, HDFS, Local). The non-virtual `createObjectStorage`
checks `ready_object_storage` first, then delegates to `doCreateObjectStorage`.

Remove `fromDisk` and `createObjectStorage` overrides from `DataLakeConfiguration`
entirely — the base class now handles disk-based initialization uniformly.

Preparatory step for eliminating `DataLakeConfiguration`.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Make `StorageDataLake` a class template parameterized by the datalake metadata
type (`IcebergMetadata`, `DeltaLakeMetadata`, `PaimonMetadata`, `HudiMetadata`).
The underlying storage backend (S3, Azure, HDFS, Local) remains dynamically
resolved via the configuration.

Add `MetadataType` type alias to `DataLakeConfiguration` for compile-time
metadata type extraction.

Explicit template instantiations are provided in `StorageDataLake.cpp` for all
four metadata types.

Update all creation sites:
- `registerStorageDataLake.cpp`: templatize `createStorageDataLake`
- `TableFunctionObjectStorage.cpp`: use `Configuration::MetadataType`
- `TableFunctionObjectStorageCluster.cpp`: same
- `DatabaseDataLake.cpp`: dispatch on catalog type to pick metadata type
- `StorageSystemIcebergHistory.cpp`: use `StorageDataLake<IcebergMetadata>`

Preparatory step for eliminating `DataLakeConfiguration`.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@kssenii kssenii self-assigned this Mar 23, 2026
@arsenmuk arsenmuk self-assigned this Mar 23, 2026
columns_in_table_or_function_definition.toString(true));

bool is_delta_lake_cdf = context->getSettingsRef()[Setting::delta_lake_snapshot_start_version] != -1
|| context->getSettingsRef()[Setting::delta_lake_snapshot_start_version] != -1;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is_delta_lake_cdf checks delta_lake_snapshot_start_version twice, so delta_lake_snapshot_end_version is never considered here.

This weakens the guard that should reject CDF settings outside deltaLake table functions.

Please change the second operand to Setting::delta_lake_snapshot_end_version.

return;
}
}
else if (auto end_version = settings[Setting::delta_lake_snapshot_start_version].value;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This branch is intended to validate delta_lake_snapshot_end_version without delta_lake_snapshot_start_version, but it reads Setting::delta_lake_snapshot_start_version again.

As a result, setting only delta_lake_snapshot_end_version will not trigger this exception.

Please read Setting::delta_lake_snapshot_end_version in this else if.

{
auto metadata_snapshot = getInMemoryMetadataPtr();
auto storage = getStorageID();
current_metadata->mutate(commands, configuration, context_, storage, metadata_snapshot, catalog, format_settings);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

StorageDataLake::mutate dereferences current_metadata unconditionally, but current_metadata can be null when metadata initialization was deferred/failed earlier (the constructor explicitly allows this in some non-CREATE paths).

That turns a user-visible error path into an exception from null dereference when ALTER TABLE ... DELETE/UPDATE reaches mutate.

Please guard this path the same way as write/optimize (e.g. call ensureMetadataInitialized(context_) first, then fail with a regular Exception if metadata is still unavailable).

Add a standalone `ReadFromDataLakeStep` query plan step for datalake reads.
Unlike `ReadFromObjectStorageStep`, it receives `IDataLakeMetadata *` directly
and calls metadata methods without going through the configuration:
- `createIterator` calls `metadata->iterate(...)` directly
- `getColumnMapperForCurrentSchema` calls `metadata->getColumnMapperForCurrentSchema(...)` directly
- `requestReadingInOrder` calls `metadata->isDataSortedBySortingKey(...)` directly

Update `StorageDataLake::read` to:
- Call `ensureMetadataInitialized` at the start
- Call `current_metadata->prepareReadingFromFormat(...)` directly
- Call `current_metadata->modifyFormatSettings(...)` directly
- Use `ReadFromDataLakeStep` instead of `ReadFromObjectStorageStep`

The old `ReadFromObjectStorageStep` still has datalake code for
`StorageDataLakeCluster` compatibility — will be cleaned up in a follow-up.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@divanik
divanik force-pushed the decouple-datalake-from-storage-object-storage branch from f8eacfd to 8b3fc0e Compare March 23, 2026 13:48
divanik and others added 6 commits March 23, 2026 15:00
Add a standalone `DataLakeSource` class that inherits from `ISource` and handles
reading from datalake tables. Unlike `StorageObjectStorageSource`, it receives
`IDataLakeMetadata *` directly and calls metadata methods without going through
the configuration:
- `metadata->getInitialSchemaByPath` for per-file schema
- `metadata->getColumnMapperForObject` for column remapping
- `metadata->addDeleteTransformers` for delete vectors
- `metadata->getSchemaTransformer` for schema transforms

No archive support or hive partitioning (not applicable to datalakes).

DeltaLake partition columns code directly casts `metadata` to `DeltaLakeMetadata *`
instead of going through configuration dynamic casts.

Update `ReadFromDataLakeStep::initializePipeline` to create `DataLakeSource`
instances instead of `StorageObjectStorageSource`.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…Step

Templatize `StorageDataLakeCluster` on `DataLakeMetadata` type, matching
`StorageDataLake`. The cluster now manages its own metadata directly:
- Creates metadata via `DataLakeMetadata::create`
- Calls `metadata->iterate(...)` directly in `getTaskIteratorExtension`
  instead of routing through `StorageObjectStorageSource::createFileIterator`
- Calls `metadata->getTableStateSnapshot(...)` etc. directly

Remove all datalake-specific code from `StorageObjectStorageSource`:
- Remove `configuration->supportsFileIterator()` / `iterate()` branch
  from `createFileIterator`
- Remove DeltaLake partition columns code from `generate`
- Remove schema evolution code from `createReader` (`getInitialSchemaByPath`,
  `getColumnMapperForObject`, `addDeleteTransformers`, `getSchemaTransformer`)

Remove datalake-specific code from `ReadFromObjectStorageStep`:
- `getColumnMapperForCurrentSchema` → nullptr
- `requestReadingInOrder` → false

Update all `StorageDataLakeCluster` creation sites to specify the metadata
type template parameter.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…keConfiguration

StorageDataLake now owns DataLakeStorageSettingsPtr and DataLakeMetadataPtr directly.
Settings are injected into the configuration via setDataLakeSettings for backward
compatibility with IcebergMetadata which accesses settings through the configuration
weak pointer.

Metadata is created directly by StorageDataLake via DataLakeMetadata::create /
DataLakeMetadata::createInitial using the template parameter. All delegation calls
(write, mutate, optimize, alter, totalRows, etc.) go through current_metadata
directly instead of routing through DataLakeConfiguration.

Move getCatalog logic to a free function getCatalogFromSettings in
registerStorageDataLake.cpp.

Strip DataLakeConfiguration to a thin wrapper that only provides:
- isDataLakeConfiguration → true
- getEngineName (combines metadata name with base engine name)
- getRawPath (ensures trailing slash)
- getDataLakeSettings / setDataLakeSettings (for metadata compat)
- Type aliases (StorageS3IcebergConfiguration, etc.)

No more metadata ownership, no delegation methods, no enable_shared_from_this.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Remove the `isDataLakeConfiguration` virtual method from
`StorageObjectStorageConfiguration` and its override in `DataLakeConfiguration`.
No code path needs this runtime type check anymore.

Move datalake-specific logic out of `StorageObjectStorageConfiguration::initialize`:
- Disk name is now passed as a parameter instead of being extracted via
  `getDataLakeSettings`
- Partition strategy validation for datalakes removed (handled by callers)
- Format defaulting to "Parquet" removed (handled by callers)

Update callers to pass disk name and set format explicitly:
- `registerStorageDataLake.cpp`: extracts disk name from settings, sets format
- `TableFunctionObjectStorage.h`: adds `getDiskName` helper, sets format
- Other callers (DatabaseDataLake, GlueCatalog, queue storage) pass empty disk name

Remove dead `isDataLakeConfiguration` checks from `Utils.cpp`
(`resolveSchemaAndFormat`).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
`DataLakeConfiguration` is now a trivial type tag that only carries
`MetadataType` for table function template resolution and forwards settings
to the base class constructor.

Moved to `StorageDataLake` and `StorageDataLakeCluster`:
- Engine name: `getName` now returns `DataLakeMetadata::name + configuration->getEngineName()`
  (e.g. "IcebergS3") instead of relying on a configuration override
- Trailing slash normalization on raw path
- Settings injection into configuration

Moved `datalake_settings` member from `DataLakeConfiguration` to the base
`StorageObjectStorageConfiguration`, with `getDataLakeSettings`/`setDataLakeSettings`
as non-virtual methods on the base class.

`DataLakeConfiguration` retains only:
- `using MetadataType = DataLakeMetadata` (for `Configuration::MetadataType` in table functions)
- Constructor forwarding settings to base
- Type aliases (`StorageS3IcebergConfiguration`, etc.)

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Delete the `DataLakeConfiguration` template class and all its type aliases
(`StorageS3IcebergConfiguration`, `StorageAzureDeltaLakeConfiguration`, etc.).

All creation sites now use the base configuration types directly
(`StorageS3Configuration`, `StorageAzureConfiguration`, etc.). Settings are
injected by `StorageDataLake`/`StorageDataLakeCluster` via
`configuration->setDataLakeSettings(...)`.

Move `MetadataType` alias to Definition structs in
`StorageObjectStorageDefinitions.h` (with forward declarations for metadata
classes). Table functions now use `Definition::MetadataType` instead of
`Configuration::MetadataType`.

`DataLakeConfiguration.h` is now empty — the file is kept only to avoid
breaking any stale includes.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
/// 1. user can want to define a table with only
/// a subset of columns from remote delta table
/// 2. user want to override some data types
/// (for example, LawCardinality<String> instead of just String)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typo in comment: LawCardinality<String> should be LowCardinality<String>.

}

template <typename DataLakeMetadata>
void StorageDataLake<DataLakeMetadata>::mutate([[maybe_unused]] const MutationCommands & commands, [[maybe_unused]] ContextPtr context_)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add coverage for this new mutation path in DataLake engines.

At minimum, add an integration test that exercises ALTER TABLE ... DELETE/UPDATE on a DataLake table and verifies behavior both when metadata is already initialized and when initialization is deferred.

divanik and others added 2 commits March 23, 2026 18:00
…nfiguration`

Remove 25+ virtual methods that were only used by the now-deleted
`DataLakeConfiguration` delegation layer. These methods are no longer called
through the configuration pointer — datalake code calls `current_metadata->`
directly.

Removed methods: `supportsTotalRows`, `totalRows`, `supportsTotalBytes`,
`totalBytes`, `isDataSortedBySortingKey`, `getExternalMetadata`,
`getInitialSchemaByPath`, `getSchemaTransformer`, `addDeleteTransformers`,
`getTableStateSnapshot`, `buildStorageMetadataFromState`,
`shouldReloadSchemaForConsistency`, `tryGetTableStructureFromMetadata`,
`supportsFileIterator`, `supportsParallelInsert`, `iterate`, `create`,
`write` (SinkToStoragePtr variant), `supportsDelete`, `mutate`,
`checkMutationIsPossible`, `checkAlterIsPossible`, `alter`,
`getColumnMapperForObject`, `getColumnMapperForCurrentSchema`,
`getCatalog`, `optimize`.

Removed 10 includes from the header that were only needed for these methods
(`IDataLakeMetadata.h`, `ICatalog.h`, `MutationCommands.h`, `AlterCommands.h`,
`StorageFactory.h`, `FormatFilterInfo.h`, etc.).

Fix cascading include issues in `Utils.h`, `IcebergIterator.h`,
`MetadataGenerator.h`, `PositionDeleteTransform.cpp`.

Simplify `StorageObjectStorage::totalRows`/`totalBytes` to return `nullopt`
(plain object storage never supported trivial count optimization).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Remove `resolveSchemaFromData`, `resolveFormatFromData`,
`resolveSchemaAndFormatFromData`, `getSchemaCache`, and `createReadBufferIterator`
static methods from `StorageObjectStorage`. These were moved to free functions in
`Utils.h/cpp` in the first commit but the delegating stubs were left behind.

Remove unused includes from `StorageObjectStorage.h` (`SchemaInferenceMode.h`,
`IObjectIterator.h`) and from `StorageObjectStorage.cpp` (`SchemaCache.h`,
`ReadBufferIterator.h`).

Add missing `IObjectIterator.h` include to `ReadFromObjectStorageStep.h` and
`ReadFromDataLakeStep.h` (was transitively included via `StorageObjectStorage.h`).

Add missing `<filesystem>` include to `Utils.h`.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@@ -508,7 +508,7 @@ GlueCatalog::ObjectStorageWithPath GlueCatalog::createObjectStorageForEarlyTable

auto storage_settings = std::make_shared<DB::DataLakeStorageSettings>();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

storage_settings is initialized but never used in this function. This is dead code on the metadata-resolution path and does extra work on every call.

Please remove:

auto storage_settings = std::make_shared<DB::DataLakeStorageSettings>();
storage_settings->loadFromSettingsChanges(settings.allChanged());

divanik and others added 2 commits March 23, 2026 18:22
Simplify `getConfiguration` to switch only on storage type (S3, Azure, HDFS,
Local) — the configuration is independent of the catalog/metadata type. This
replaces a ~170-line nested switch (catalog type × storage type) with ~15 lines.

Add `dispatchByMetadataType` template helper that maps catalog type to the
correct metadata type and calls a lambda. This eliminates the duplicated
catalog-type switch that was repeated for both `StorageDataLake` and
`StorageDataLakeCluster` creation.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Simplify `getConfiguration` to switch only on storage type (S3, Azure, HDFS,
Local) — the configuration is independent of the catalog/metadata type. This
replaces a ~170-line nested switch (catalog type × storage type) with ~15 lines.

Resolve catalog type to a `DataLakeType` enum (Iceberg, DeltaLake, Paimon)
once, then dispatch storage creation with explicit per-type `make_shared` calls.
Each datalake type gets its own `make_shared` call — straightforward, readable,
and allows different constructor signatures per type in the future.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
{
#if USE_AZURE_BLOB_STORAGE
auto azure_configuration = std::static_pointer_cast<StorageAzureIcebergConfiguration>(configuration);
auto azure_configuration = std::static_pointer_cast<StorageAzureConfiguration>(configuration);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

std::static_pointer_cast does not validate the runtime type, so these null checks are ineffective (shared_ptr stays non-null if configuration/catalog is non-null). On a wrong concrete type this can silently pass and later hit undefined behavior.

Please use std::dynamic_pointer_cast for both casts here (as already done for s3_configuration below), and keep the explicit LOGICAL_ERROR checks.

@divanik divanik removed the no-fast-tests Drops preliminary CI jobs: Style, clang-tidy, Fast Test label Apr 8, 2026
@divanik
divanik force-pushed the decouple-datalake-from-storage-object-storage branch from 6ccfc05 to 7093f59 Compare April 8, 2026 16:26
divanik and others added 4 commits April 8, 2026 18:43
- Guard `StorageIceberg.h` with `#if USE_AVRO` so it compiles in builds
  without Avro support (e.g. CI fast builds)
- Fix clang-tidy diagnostics in `StorageIceberg.cpp`
- Rewrite `registerStoragePaimon` to use `createStorageDataLake` pattern

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
std::move(parsed_arguments.s3_settings),
std::move(parsed_arguments.s3_capabilities),
std::move(parsed_arguments.headers_from_ast));
if (auto object_storage_disk = std::static_pointer_cast<DiskObjectStorage>(disk); object_storage_disk)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

std::static_pointer_cast<DiskObjectStorage>(disk) is unchecked, so this if condition does not validate the runtime type (the pointer stays non-null whenever disk is non-null). If a non-DiskObjectStorage disk implementation reaches this code, object_storage_disk->getObjectStorage() becomes unsafe.

Please use a checked cast here (for example std::dynamic_pointer_cast) and throw a clear BAD_ARGUMENTS/LOGICAL_ERROR when the disk type is unexpected.

@divanik divanik added the no-fast-tests Drops preliminary CI jobs: Style, clang-tidy, Fast Test label Apr 8, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

The Can't adjust last granule error in CI is a known issue. The fix is in #101641

DeltaLakeMetadataImpl(ObjectStoragePtr object_storage_, ObjectStorageConnectionConfigurationWeakPtr configuration_, ContextPtr context_)
: object_storage(object_storage_)
, table_path(configuration_.lock()->getPathForRead().path)
, table_path(configuration_.lock()->getRawPath().path)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DeltaLakeMetadataImpl dereferences configuration_.lock() in the initializer list without checking that the weak_ptr is still valid:

, table_path(configuration_.lock()->getRawPath().path)

If the weak pointer is expired, this becomes a null dereference in construction path.

Please lock first, validate, and throw a clear exception (for example LOGICAL_ERROR) before reading getRawPath.

@clickhouse-gh

clickhouse-gh Bot commented Apr 10, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.10% +0.10%
Functions 90.90% 90.90% +0.00%
Branches 76.50% 76.60% +0.10%

Changed lines: 79.12% (3358/4244) | lost baseline coverage: 1017 line(s) · Uncovered code

Full report · Diff report

@divanik divanik closed this Apr 14, 2026
@divanik divanik reopened this Apr 14, 2026
divanik added 2 commits April 14, 2026 13:27
…b.com:ClickHouse/ClickHouse into decouple-datalake-from-storage-object-storage
auto mapper = metadata->getColumnMapperForObject(object_info);
if (!mapper)
return format_filter_info;
return std::make_shared<FormatFilterInfo>(format_filter_info->filter_actions_dag, format_filter_info->context.lock(), mapper, format_filter_info->row_level_filter, format_filter_info->prewhere_info);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When schema_changed is true and mapper exists, this creates a new FormatFilterInfo with format_filter_info->context.lock() passed directly to the constructor.

If the weak context is already expired, lock() returns nullptr, and this constructor accepts it silently. Later, FormatFilterInfo::initKeyConditionOnce throws LOGICAL_ERROR (Context has expired) when filters are initialized, so reads can fail nondeterministically depending on timing.

Please lock once and validate before constructing the new filter object, e.g.:

auto ctx = format_filter_info->context.lock();
if (!ctx)
    throw Exception(ErrorCodes::LOGICAL_ERROR, "Context has expired");
return std::make_shared<FormatFilterInfo>(
    format_filter_info->filter_actions_dag,
    ctx,
    mapper,
    format_filter_info->row_level_filter,
    format_filter_info->prewhere_info);

@divanik divanik removed the no-fast-tests Drops preliminary CI jobs: Style, clang-tidy, Fast Test label Apr 14, 2026

void IcebergSource::addNumRowsToCache(const ObjectInfo & object_info, size_t num_rows)
{
const auto & iceberg_obj = dynamic_cast<const IcebergDataObjectInfo &>(object_info);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

addNumRowsToCache uses dynamic_cast<const IcebergDataObjectInfo &>(object_info), which throws std::bad_cast if a non-Iceberg ObjectInfo reaches this path. In distributed reads, ReadTaskIterator can deserialize tasks into plain ObjectInfo when iceberg_info is absent, so this turns a recoverable protocol/input mismatch into an exception.

Please switch to pointer cast with an explicit check and a controlled Exception message (or fallback) instead of reference cast.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants