Repository navigation
Conversation
|
Ilya Parfenenka seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account. You have signed the CLA already but the status is still pending? Let us recheck it. |
|
Please edit the PR description: https://raw.githubusercontent.com/ClickHouse/ClickHouse/refs/heads/master/.github/PULL_REQUEST_TEMPLATE.md Otherwise, tests cannot start. |
# Conflicts: # .gitmodules # contrib/CMakeLists.txt # src/CMakeLists.txt # src/Common/ErrorCodes.cpp # src/Interpreters/InterpreterFactory.cpp # src/Interpreters/registerInterpreters.cpp # src/Parsers/CommonParsers.h # src/Parsers/ExpressionListParsers.cpp # src/TableFunctions/TableFunctionNumbers.cpp # src/TableFunctions/registerTableFunctions.cpp
- Rename overridden `getStorageTypeName` to `getStorageEngineName`; the pure-virtual was renamed on master, so the old name no longer overrides anything and left the class abstract. - Update the `TableFunctionFactory::registerFunction` call to the current two-argument form (`FunctionDocumentation` + `TableFunctionProperties`) and brace-initialize `returned_value` (now a struct, not a string). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Master now forbids build-time CMake probes (`cmake/block_build_time_checks.cmake`) because the compiler and toolchain are fixed, and it removed the `dbms_target_link_libraries` macro. Adapt the new contrib configs accordingly: - `contrib/xgboost-cmake`: replace `check_symbol_exists`/`check_include_file_cxx`/ `test_big_endian`/`check_cxx_compiler_flag`/`check_library_exists` with static decisions based on `OS_LINUX`/`ARCH_AMD64` and the known little-endian targets. - `contrib/LightGBM-cmake`: replace the `check_cxx_source_compiles` probes for `_mm_prefetch`/`_mm_malloc` with `ARCH_AMD64` gating. - `src/CMakeLists.txt`: link `ch_contrib::lightgbm`/`ch_contrib::xgboost` with `target_link_libraries(dbms ...)` instead of the removed `dbms_target_link_libraries`. - `src/Models/Model_fwd.h`: add `#pragma once` and explicit STL includes, needed under `-D_LIBCPP_REMOVE_TRANSITIVE_INCLUDES=1`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- `ASTPtr` is now `boost::intrusive_ptr<IAST>`: replace the 7 remaining `std::make_shared<AST...>` with `make_intrusive` (the AST nodes use intrusive reference counting, so `std::shared_ptr` no longer converts). - Drop the obsolete `hilite_keyword`/`hilite_none`/`hilite_function` highlighting from `formatImpl` (the `hilite` flag was removed from `FormatSettings`). - `IStorage::getInMemoryMetadataPtr` now takes `(context, bypass_metadata_cache)`. - Add the missing self-declarations for `registerInterpreterCreateModelQuery` and `registerInterpreterDropModelQuery` to satisfy `-Wmissing-prototypes`. - Guard the optional `OPTIONS` field against a null dereference in `ASTCreateModelQuery::clone` and `formatImpl`, and fix keyword spacing so the formatted `CREATE MODEL` query is valid SQL. - Initialize `Target target` to avoid an uninitialized read. - Include `<Interpreters/DatabaseCatalog.h>` directly in `TableFunctionPredict.cpp`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [e3dd40e] Summary: ❌
AI ReviewSummaryThis PR adds experimental Findings❌ Blockers
Tests
Final Verdict
|
|
|
||
| const auto & create_model_query = query_ptr->as<const ASTCreateModelQuery &>(); | ||
|
|
||
| // TODO: access |
There was a problem hiding this comment.
This exposes a new stateful SQL feature without either an experimental setting gate or a privilege check. CREATE MODEL can train and publish a process-global model, and DROP MODEL has the same issue in its interpreter; the PR description calls the feature experimental, but the parser/interpreters are registered unconditionally. Please add a disabled-by-default allow_experimental_... setting and check the appropriate access rights before creating, dropping, or using models, or keep this syntax unreachable until that contract exists.
# Conflicts: # .github/workflows/master.yml # .gitmodules # ci/docker/fasttest/Dockerfile # ci/praktika/gh.py # ci/praktika/job.py # ci/praktika/workflow.py # contrib/delta-kernel-rs # contrib/rust_vendor # docs/en/sql-reference/aggregate-functions/reference/quantiles.md # docs/en/sql-reference/data-types/date32.md # docs/en/sql-reference/functions/geo/coordinates.md # docs/en/sql-reference/functions/machine-learning-functions.md # docs/en/sql-reference/functions/udf.md # src/Access/AccessControl.cpp # src/Access/EnabledQuota.cpp # src/Access/RoleCache.cpp # src/Access/SettingsProfilesCache.cpp # src/AggregateFunctions/AggregateFunctionUniqCombined.h # src/Analyzer/Passes/ConvertOrLikeChainPass.cpp # src/Backups/BackupIO_S3.h # src/Backups/BackupInfo.cpp # src/Client/BuzzHouse/Generator/ExternalIntegrations.cpp # src/Client/ConnectionEstablisher.cpp # src/Client/LocalConnection.h # src/Columns/ColumnSparse.cpp # src/Columns/ColumnSparse.h # src/Columns/IColumn.cpp # src/Common/CurrentThread.cpp # src/Common/DateLUTImpl.h # src/Common/ErrorCodes.cpp # src/Common/MemoryTrackerUtils.cpp # src/Common/MemoryTrackerUtils.h # src/Common/OptimizedRegularExpression.cpp # src/Common/Scheduler/ClassifiersConfig.cpp # src/Common/Scheduler/ClassifiersConfig.h # src/Common/Scheduler/CustomResourceManager.cpp # src/Common/Scheduler/CustomResourceManager.h # src/Common/Scheduler/Nodes/TimeShared/FairPolicy.h # src/Common/Scheduler/Nodes/TimeShared/PriorityPolicy.h # src/Common/Scheduler/Nodes/TimeShared/ThrottlerConstraint.h # src/Common/Scheduler/Nodes/TimeShared/TimeSharedScheduler.h # src/Common/Scheduler/Nodes/tests/gtest_fair_policy.cpp # src/Common/Scheduler/Nodes/tests/gtest_priority_policy.cpp # src/Common/Scheduler/createResourceManager.cpp # src/Common/ShellCommand.cpp # src/Common/ShellCommand.h # src/Common/ThreadPoolTaskTracker.cpp # src/Common/ThreadStatus.h # src/Common/likePatternToRegexp.cpp # src/Compression/tests/gtest_compressionCodec.cpp # src/Core/BackgroundSchedulePool.cpp # src/Core/ProtocolDefines.h # src/Core/Settings.cpp # src/DataTypes/DataTypesBinaryEncoding.cpp # src/DataTypes/Serializations/SerializationVariantElementNullMap.cpp # src/DataTypes/Serializations/SerializationVariantElementNullMap.h # src/DataTypes/convertMySQLDataType.cpp # src/Dictionaries/DictionarySource.h # src/Disks/IO/AsynchronousBoundedReadBuffer.h # src/Formats/MarkInCompressedFile.h # src/Functions/FunctionStringReplace.h # src/Functions/FunctionTokens.h # src/Functions/FunctionsStringSearchToString.h # src/Functions/MatchImpl.h # src/Functions/ReplaceRegexpImpl.h # src/Functions/UserDefined/ExternalUserDefinedExecutableFunctionsLoader.cpp # src/Functions/UserDefined/UserDefinedSQLFunctionFactory.cpp # src/Functions/changeDate.cpp # src/Functions/extractAll.cpp # src/Functions/formatReadableTimeDelta.cpp # src/Functions/hypot.cpp # src/Functions/multiMatchAny.cpp # src/IO/AzureBlobStorage/copyAzureBlobStorageFile.cpp # src/IO/DistributedCacheSettings.h # src/IO/ReadBufferFromS3.cpp # src/Interpreters/ConvertFunctionOrLikeVisitor.cpp # src/Interpreters/HashJoin/AddedColumns.h # src/Interpreters/HashJoin/JoinUsedFlags.h # src/Interpreters/HashJoin/KnownRowsHolder.h # src/Interpreters/InterpreterCreateFunctionQuery.cpp # src/Interpreters/InterpreterFactory.cpp # src/Interpreters/RowRefs.cpp # src/Interpreters/TreeOptimizer.cpp # src/Interpreters/convertFieldToType.h # src/Interpreters/removeOnClusterClauseIfNeeded.cpp # src/Parsers/ASTSQLSecurity.h # src/Parsers/FunctionSecretArgumentsFinder.h # src/Parsers/ParserCreateFunctionQuery.cpp # src/Planner/PlannerJoinTree.cpp # src/Processors/QueryPlan/Optimizations/projectionsCommon.cpp # src/Processors/QueryPlan/PartsSplitter.h # src/Processors/QueryPlan/SetsSerialization.cpp # src/Processors/Transforms/DeduplicationTokenTransforms.cpp # src/Storages/Hive/HiveFile.cpp # src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp # src/Storages/MergeTree/MergeTreeDataSelectExecutor.h # src/Storages/MergeTree/MergeTreeDataWriter.cpp # src/Storages/MergeTree/MergeTreeIndexGranularity.cpp # src/Storages/MergeTree/MergeTreeMarksLoader.cpp # src/Storages/MergeTree/MergeTreeReadPoolParallelReplicas.cpp # src/Storages/MergeTree/MergeTreeReadPoolParallelReplicasInOrder.cpp # src/Storages/MergeTree/MergeTreeReadPoolParallelReplicasInOrder.h # src/Storages/MergeTree/ParallelReplicasReadingCoordinator.cpp # src/Storages/ObjectStorage/S3/Configuration.cpp # src/Storages/Statistics/tests/gtest_stats.cpp # src/Storages/StoragePostgreSQL.cpp # src/Storages/StorageView.cpp # src/Storages/System/StorageSystemTables.cpp # src/Storages/TTLDescription.cpp # src/TableFunctions/TableFunctionURL.cpp # tests/integration/helpers/cluster.py # tests/integration/test_checking_s3_blobs_paranoid/test.py # tests/integration/test_crash_log/test.py # tests/integration/test_database_iceberg/test.py # tests/integration/test_disk_over_web_server/test.py # tests/integration/test_drop_replica_with_auxiliary_zookeepers/test.py # tests/integration/test_filesystem_cache/test.py # tests/integration/test_mysql_protocol/test.py # tests/integration/test_quorum_inserts/test.py # tests/integration/test_scheduler/configs/storage_configuration.xml # tests/integration/test_scheduler/test.py # tests/integration/test_storage_delta/test.py # tests/integration/test_storage_s3/test.py # tests/integration/test_table_db_num_limit/test.py # tests/queries/0_stateless/00808_not_optimize_predicate.reference # tests/queries/0_stateless/02226_analyzer_or_like_combine.sql # tests/queries/0_stateless/02233_HTTP_ranged.python # tests/queries/0_stateless/02236_explain_pipeline_join.sql # tests/queries/0_stateless/02286_drop_filesystem_cache.sh # tests/queries/0_stateless/02344_describe_cache.reference # tests/queries/0_stateless/02441_alter_delete_and_drop_column.sql # tests/queries/0_stateless/02675_predicate_push_down_filled_join_fix.sql # tests/queries/0_stateless/02789_filesystem_cache_alignment.sh # tests/queries/0_stateless/02835_join_step_explain.sql # tests/queries/0_stateless/02841_parquet_filter_pushdown.sql # tests/queries/0_stateless/02868_select_support_from_keywords.reference # tests/queries/0_stateless/02931_max_num_to_warn.sql # tests/queries/0_stateless/02995_settings_26_6_1.tsv # tests/queries/0_stateless/03032_dynamically_resize_filesystem_cache_2.sh # tests/queries/0_stateless/03036_join_filter_push_down_equivalent_sets.sql # tests/queries/0_stateless/03130_convert_outer_join_to_inner_join.sql # tests/queries/0_stateless/03152_join_filter_push_down_equivalent_columns.sql # tests/queries/0_stateless/03210_inconsistent_formatting_of_data_types.reference # tests/queries/0_stateless/03229_async_insert_alter.sql
The `xgboost` and `lightgbm` model backends were compiled into `dbms` unconditionally and included `<xgboost/c_api.h>` / `<LightGBM/c_api.h>` directly, so any build without those contrib libraries (for example the Fast test) failed with "file not found". Introduce `USE_XGBOOST` and `USE_LIGHTGBM` config flags (set from the `ch_contrib::xgboost` / `ch_contrib::lightgbm` targets) and guard the backend sources with `#if USE_XGBOOST` / `#if USE_LIGHTGBM`. When a backend is not compiled in, `createModel` throws `SUPPORT_IS_DISABLED`. Also in these files: - Implement `XGBoostModel::predict` (previously a stub that returned an empty vector) via `XGBoosterPredict`. - Store training targets in the LightGBM `label` field instead of `init_score`, so the booster is trained on the target labels. - Reformat to Allman braces, drop unnecessary `} // namespace` comments, use angle-bracket includes, and reword the contrib CMake comments so they no longer contain forbidden compiler-probe names.
Address review findings on the experimental model feature: - `ModelRegistry::hasModel` and `unregisterModel` accessed the shared map without holding `mutex`, while other methods locked it. Replace them with a single locked `dropModel(name, if_exists)` and lock every map access, so concurrent `CREATE MODEL`, `DROP MODEL` and `predict` cannot corrupt the registry. - `InterpreterCreateModelQuery` registered the model before `fit` completed, leaving an untrained model visible in the registry if training threw. Fit first, register only after training succeeds. - `TableFunctionPredict` never called the model and left the output column empty, and advertised `predict String` while returning `prediction Float64`. Call `model->predict`, fill the column, and make `getActualTableStructure` match the runtime schema. - Allman braces and angle-bracket includes for the parser code.
|
Reconciled this branch with the current Fixed in this update
Remaining blockers (need the author / a maintainer — I could not do these here)
|
| features[0].size()); | ||
|
|
||
| std::vector<double> flat = flatten(features); | ||
| std::vector<double> predictions(features.size()); |
There was a problem hiding this comment.
Targets and the predict table function assume one scalar prediction per input row, but LGBM_BoosterPredictForMat writes num_class * num_data values for multiclass objectives. predictions(features.size()) is therefore too small as soon as objective=multiclass / num_class>1, which lets the library write past the end of this buffer. Please size the buffer from LGBM_BoosterCalcNumPredict / LGBM_BoosterGetNumClasses and reject any objective whose output cardinality is not exactly one value per row before converting it to Targets.
| { | ||
| // TODO | ||
| const Feature value = column.column->getFloat64(row); | ||
| if (column.name == "target") |
There was a problem hiding this comment.
Prediction does not preserve the training schema; it only drops a column literally named target. CREATE MODEL ... TARGET 'ttt' FROM TABLE train trains on train without ttt, but predict on the same table will feed ttt back as a feature and hit the backend's feature-dimension check. The model needs to persist the target / feature layout and predict should project exactly that schema or reject mismatches.
| { | ||
| StorageID table_id{context->getCurrentDatabase(), table_name}; | ||
| StoragePtr storage = DatabaseCatalog::instance().getTable(table_id, context); | ||
|
|
||
| const auto metadata_snapshot = storage->getInMemoryMetadataPtr(context, false); | ||
|
|
||
| if (!metadata_snapshot->columns.hasPhysical(target_name)) | ||
| throw Exception( | ||
| ErrorCodes::THERE_IS_NO_COLUMN, | ||
| "Model {} requires target column {} which does not exist in the table {}", | ||
| model_name, target_name, table_name | ||
| ); | ||
| } | ||
|
|
||
| auto io = executeQuery("SELECT * FROM " + table_name, context, QueryFlags{ .internal = true }, QueryProcessingStage::Complete).second; |
There was a problem hiding this comment.
ParserCompoundIdentifier accepts qualified and quoted table names, but this path flattens the AST back to a raw string and reconstructs both the lookup and the SELECT. StorageID{current_db, table_name} turns db.tbl into table name db.tbl inside the current database, and "SELECT * FROM " + table_name drops any identifier quoting, so FROM TABLE db.tbl and FROM TABLE \select`both break even though the parser accepts them. Please keep the parsedASTTableIdentifier/StorageIDand build the read query from AST instead of string concatenation.TableFunctionPredict` has the same bug.
| { | ||
| case Field::Types::Which::UInt64: | ||
| case Field::Types::Which::Int64: | ||
| value = toString(pair.value.safeGet<UInt64>()); |
There was a problem hiding this comment.
The Int64 case still calls safeGet<UInt64>(). Any signed option value parses into Field::Types::Int64, so parameters like max_depth = -1 throw on this path even though the switch claims Int64 is supported. Please read the Int64 value here and stringify that instead.
| initDataset(flat, targets); | ||
|
|
||
| int is_finished = 0; | ||
| throwOnError(LGBM_BoosterUpdateOneIter(booster, &is_finished), |
There was a problem hiding this comment.
This only performs one LGBM_BoosterUpdateOneIter, regardless of num_iterations / num_boost_round in hps_str. So the LightGBM backend currently trains a single boosting round even though the feature forwards arbitrary training parameters and the XGBoost backend loops over iterations. Please either parse and execute the requested number of rounds here or reject multi-round training params explicitly.
|
Closing this PR, it is being reworked here #109999 |
This pull request adds an experimental integration with the gradient boosting libraries XGBoost and LightGBM, allowing models to be trained and used for inference directly inside ClickHouse.
It introduces:
CREATE MODEL <name> ALGORITHM <algorithm> OPTIONS (...) TARGET <target> FROM TABLE <table>to train and register a model;DROP MODEL <name>to remove a registered model;predicttable function to run a registered model's predictions over input data.The supported algorithms are
xgboostandlightgbm, vendored as new contrib submodules.This is still a work in progress (the PR is marked as a draft): it lacks functional tests and documentation, and one of the commit authors has not yet signed the CLA.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Experimental integration with XGBoost and LightGBM: added
CREATE MODELandDROP MODELstatements and thepredicttable function to train gradient boosting models and run their predictions inside ClickHouse.