Skip to content

[Draft] Integration with XGBoost and LightGBM - #80363

Closed
HazyMrf wants to merge 12 commits into
ClickHouse:masterfrom
HazyMrf:boosting
Closed

HazyMrf wants to merge 12 commits into
ClickHouse:masterfrom
HazyMrf:boosting

Conversation

@HazyMrf

@HazyMrf HazyMrf commented May 16, 2025 •

Copy link
Copy Markdown

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;
  • the predict table function to run a registered model's predictions over input data.

The supported algorithms are xgboost and lightgbm, 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):

  • Experimental Feature

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

Experimental integration with XGBoost and LightGBM: added CREATE MODEL and DROP MODEL statements and the predict table function to train gradient boosting models and run their predictions inside ClickHouse.

Ilya Parfenenka added 3 commits May 12, 2025 00:29
@CLAassistant

CLAassistant commented May 16, 2025 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
2 out of 3 committers have signed the CLA.

✅ HazyMrf
✅ alexey-milovidov
❌ Ilya Parfenenka


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.

@HazyMrf HazyMrf changed the title Boosting Integration with XGBoost and LightGBM May 16, 2025
@HazyMrf HazyMrf changed the title Integration with XGBoost and LightGBM [Draft] Integration with XGBoost and LightGBM May 16, 2025
@alexey-milovidov

Copy link
Copy Markdown
Member

alexey-milovidov and others added 5 commits June 29, 2026 02:47
# 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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e3dd40e]

Summary: ❌

job_name test_name status info comment
Build (arm_tidy) FAIL
Check Submodules FAIL cidb
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED
Build (arm_tsan) DROPPED

AI Review

Summary

This PR adds experimental CREATE MODEL / DROP MODEL statements plus the predict table function for in-server XGBoost and LightGBM training and inference. The recent fixes removed several first-order problems, but the current head still leaves the feature ungated and unprivileged, and it has multiple correctness bugs in schema handling, table resolution, and LightGBM execution, so it is not ready to merge.

Findings

❌ Blockers

  • [src/Interpreters/InterpreterCreateModelQuery.cpp:78, src/Interpreters/InterpreterDropModelQuery.cpp:19, src/TableFunctions/TableFunctionPredict.cpp:81] This exposes a new stateful SQL feature without an experimental setting gate or access checks. Any user who can issue these queries can create, drop, and use process-global models, which violates the PR's own Experimental Feature contract and ClickHouse's experimental-gate / access-control requirements.
    Suggested fix: add a disabled-by-default allow_experimental_* setting and explicit access checks before create, drop, and predict execution.
  • [src/Models/LightGBMModel.cpp:111-128] LGBM_BoosterPredictForMat can emit num_class * num_data results, but the code allocates space for only num_data. With objective=multiclass this writes past the end of predictions, creating memory corruption.
    Suggested fix: compute the required output length first and reject any multi-output objective before converting the result to Targets, or widen the model contract away from one scalar prediction per input row.

⚠️ Majors

  • [src/TableFunctions/TableFunctionPredict.cpp:66-74] Prediction does not preserve the training schema: it strips only a column literally named target. Models trained with TARGET 'ttt' or any other non-target label cannot predict on the same table because the target column is fed back as a feature, and column order is also unchecked.
    Suggested fix: persist the target / feature layout on the model and project exactly that schema at predict time, or reject tables whose schema does not match.
  • [src/Interpreters/InterpreterCreateModelQuery.cpp:87-101] Qualified and quoted table identifiers are parsed but then broken by reconstructing a StorageID and raw SELECT string from ASTIdentifier::name(). FROM TABLE db.tbl becomes current-db table db.tbl, and quoted identifiers lose quoting.
    Suggested fix: carry an ASTTableIdentifier / StorageID through and build the read query from AST instead of string concatenation; apply the same fix in TableFunctionPredict.
  • [src/Interpreters/InterpreterCreateModelQuery.cpp:48-50] Signed hyperparameters are unreachable: the Int64 branch still reads safeGet<UInt64>(), so valid options like max_depth = -1 throw during option parsing.
    Suggested fix: stringify the Int64 value instead of reading it as UInt64.
  • [src/Models/LightGBMModel.cpp:84-86] The LightGBM backend performs exactly one boosting iteration regardless of num_iterations / num_boost_round, so it does not actually train the requested model.
    Suggested fix: loop the same way as the XGBoost backend, or reject multi-round training parameters explicitly.
Tests
  • ⚠️ There are only parser tests right now. Add one focused end-to-end test that trains a model with a non-target label name and runs predict on a table with the same schema; it should fail on the current head and prove the schema / target fix.
  • ⚠️ Add a regression for FROM TABLE db.tbl and a quoted identifier such as ``FROM TABLE `select``` so parser acceptance matches execution.
  • ⚠️ Add a LightGBM functional test covering both multi-round training and an explicit rejection path for multiclass / multi-output prediction if that remains unsupported.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: add an experimental gate plus access checks; fix prediction schema tracking and table-name handling; fix signed option parsing; fix LightGBM training / prediction behavior; add focused functional coverage for those paths.

@clickhouse-gh clickhouse-gh Bot added pr-experimental Experimental Feature submodule changed At least one submodule changed in this PR. labels Jun 29, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 6, 2026

const auto & create_model_query = query_ptr->as<const ASTCreateModelQuery &>();

// TODO: access

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 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.

Comment thread src/Models/ModelRegistry.cpp Resolved
Comment thread src/Models/XGBoostModel.cpp Resolved
Comment thread src/Models/LightGBMModel.cpp Resolved
# 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.
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Jul 14, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Reconciled this branch with the current master (it was ~2 weeks / thousands of commits behind and no longer building) and addressed the mechanical/build parts of the review. Pushed to boosting; the PR is MERGEABLE again.

Fixed in this update

  • Build (Fast test and other lib-less builds). The xgboost/lightgbm backends were compiled into dbms unconditionally and included <xgboost/c_api.h> / <LightGBM/c_api.h> directly, so any build without those contribs failed with file not found. Added USE_XGBOOST / USE_LIGHTGBM config flags and guarded the backend sources with #if USE_XGBOOST / #if USE_LIGHTGBM; createModel now throws SUPPORT_IS_DISABLED when a backend is not compiled in. Verified locally that the lib-less path compiles.
  • Style check (cpp). Allman braces, removed } // namespace comments, #pragma once on the first line, dropped the unused ErrorCodes::UNKNOWN_TABLE, angle-bracket includes, and reworded the contrib CMakeLists.txt comments so they no longer contain forbidden compiler-probe names.
  • ModelRegistry thread-safety. hasModel/unregisterModel touched the shared map without the lock; replaced with a single locked dropModel(name, if_exists) and locked every access.
  • Model publication. CREATE MODEL now fits first and registers only on success, so a failed training no longer leaves an untrained model visible.
  • predict table function. It now actually calls model->predict, fills the output column, and getActualTableStructure advertises prediction Float64 to match the runtime schema (was predict String).
  • LightGBM label. Training targets are stored in the label field instead of init_score.
  • XGBoost predict. Implemented via XGBoosterPredict (was a stub returning an empty vector); signature verified against the pinned xgboost header.

Remaining blockers (need the author / a maintainer — I could not do these here)

  • CLA. Co-author Ilya Parfenenka has not signed the CLA. This blocks merge regardless of the above.
  • Check Submodules. xgboost and LightGBM upstream both use nested submodules (dmlc-core, gputreeshap; eigen, fast_double_parser, …), and ClickHouse forbids recursive submodules. This needs ClickHouse-org forks with the nested submodules removed and the required sources vendored in (e.g. github.com/ClickHouse/xgboost, github.com/ClickHouse/LightGBM), then repointing .gitmodules.
  • Experimental gate + access control. The syntax is still registered unconditionally with no allow_experimental_* setting and no privilege checks — this is a design decision left to you.
  • Tests / docs. Only parser tests exist; functional tests (train a tiny model, predict, one row per input, failure paths) and user docs are still needed.

features[0].size());

std::vector<double> flat = flatten(features);
std::vector<double> predictions(features.size());

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.

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")

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.

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.

Comment on lines +87 to +101
{
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;

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.

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>());

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.

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),

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 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.

@Manerone

Copy link
Copy Markdown
Contributor

Closing this PR, it is being reworked here #109999

@Manerone Manerone closed this Jul 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors manual approve Manual approve required to run CI pr-experimental Experimental Feature submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants