Skip to content

Add LOOKUP INDEX support for MergeTree - #101401

Open
dunda18 wants to merge 129 commits into
ClickHouse:masterfrom
dunda18:set-and-join-tables-as-indices
Open

dunda18 wants to merge 129 commits into
ClickHouse:masterfrom
dunda18:set-and-join-tables-as-indices

Conversation

@dunda18

@dunda18 dunda18 commented Mar 31, 2026 •

Copy link
Copy Markdown

This change adds table-wide LOOKUP INDEX support for MergeTree tables and implements the Set and Join tables as indices task from #87836. Unlike secondary data-skipping indices, these indices build reusable in-memory lookup structures for repeated key-value style queries against the right-hand side table.

It introduces:

  • LOOKUP INDEX ... TYPE table_set for IN table lookups and trivial key-only subqueries
  • LOOKUP INDEX ... TYPE table_join for direct-compatible equality joins with join_algorithm = 'direct'
  • parser, metadata, ALTER, and ReplicatedMergeTree support
  • planner integration, runtime cache invalidation for both data and metadata changes, stateless tests, performance benchmarks, and minimal user documentation

Current limitations:

  • lookup keys must be plain columns
  • table_join requires non-nullable key columns
  • table_join is only used for direct-compatible equality joins
  • table_join is not always faster than hash; the included benchmarks show win, near-parity, and lose cases depending on the relative sizes of the left and right tables

Changelog category (leave one):

  • Experimental Feature

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

Add LOOKUP INDEX support for MergeTree tables with table_set and table_join table-wide lookup indexes.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Note

High Risk
High risk because it adds a new experimental index type that touches SQL parsing/formatting, ALTER/replication metadata, MergeTree read paths and caching, and join/set planner optimizations (including direct join behavior), which can affect query correctness and performance.

Overview
Adds experimental LOOKUP INDEX support to MergeTree-family tables (gated by allow_experimental_lookup_index) with two new index types: table_set to accelerate IN table/trivial key-only subqueries and table_join to accelerate direct-compatible equality joins.

Extends SQL/metadata plumbing end-to-end: new AST fields and parser/formatter support for LOOKUP INDEX (including ALTER TABLE ... ADD/DROP LOOKUP INDEX), metadata storage and replication via ReplicatedMergeTreeTableMetadata, and validation to prevent misuse (e.g., no GRANULARITY, no expressions/args, and non-nullable keys for table_join).

Implements runtime lookup caches in MergeTreeData (with invalidation on metadata/part changes) and integrates planner fast paths for sets (CollectSets) and joins (PlannerJoins/DirectKeyValueJoin) while preserving correctness by disabling the optimization when row policies or unsupported modifiers/parallel replicas are in play. Adds documentation plus new stateless/performance tests for both lookup modes.

Reviewed by Cursor Bugbot for commit 6d94b00. Bugbot is set up for automated code reviews on this repo. Configure here.


Workflow [PR]
Sync PR [sync-upstream/pr/101401]

@UnamedRus

Copy link
Copy Markdown
Contributor

Will there be any keyword/control over ANY/ALL behavior?

@dunda18

dunda18 commented Mar 31, 2026

Copy link
Copy Markdown
Author

No, ANY/ALL is controlled by the JOIN strictness in the query itself, not by a separate LOOKUP INDEX option.

@CurtizJ CurtizJ added the can be tested Allows running workflows for external contributors label Mar 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [deabffe]

Summary: ❌

job_name test_name status info comment
Style check FAIL
settings_changes_history FAIL cidb
various FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL
Code Review DROPPED
Build (amd_asan_ubsan) DROPPED
Build (arm_asan_ubsan) DROPPED
Integration tests (amd_asan_ubsan, db disk, targeted) DROPPED
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Mar 31, 2026
@CLAassistant

CLAassistant commented Mar 31, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Comment thread src/Planner/CollectSets.cpp Resolved
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
Comment thread src/Planner/PlannerJoins.cpp Resolved

@clickhouse-gh clickhouse-gh Bot left a comment

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.

Submitting pending review to unblock inline comments

Comment thread src/Planner/CollectSets.cpp Resolved
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
alexey-milovidov and others added 2 commits October 21, 2026 13:24
…-as-indices

Conflict in `StorageInMemoryMetadata::addImplicitIndicesForColumn`: master moved the push of the implicit min-max index into a `try` block that swallows `BAD_ARGUMENTS`. The check that rejects an implicit index name reserved by a lookup index is moved before that block so it still throws.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lookup index is rejected

`RESTORE` creates the table with `SECONDARY_CREATE` and writes fresh replicated metadata into ZooKeeper, which is exactly what the guard prevents. The old comment wrongly claimed that restore from a backup is allowed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mintlify

mintlify Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit deabffe.

Approve preview

@Blargian
Blargian removed the request for review from a team October 21, 2026 14:53
alexey-milovidov and others added 2 commits October 28, 2026 21:13
…-as-indices

Conflicts were caused by master adding `codec_declarations` to `ASTColumns` next to
the `lookup_indices` added by this PR; both are kept. `IWindowFunction.h` was renamed to
`IGeneralWindowFunction.h` on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged the latest master and resolved conflicts in ASTCreateQuery, ParserCreateQuery, InterpreterCreateQuery, DatabasesCommon.cpp (master added codec_declarations to ASTColumns next to this PR's lookup_indices; both are kept) and Planner/Utils.cpp (IWindowFunction.h was renamed to IGeneralWindowFunction.h). Fixed the Style check / settings_changes_history red: allow_experimental_lookup_index is now recorded under 26.11. Built locally; the PR's .sql tests pass under clickhouse local (the ReplicatedMergeTree test was not run because it needs ZooKeeper). A table with both a LOOKUP INDEX and a subcolumn CODEC declaration round-trips through SHOW CREATE TABLE.

Comment thread src/Planner/CollectSets.cpp Resolved
Comment thread src/Planner/PlannerJoins.cpp Outdated

bool allowed_inner = isInner(table_join->kind()) && table_join->strictness() == JoinStrictness::All;
bool allowed_inner = isInner(table_join->kind()) && (table_join->strictness() == JoinStrictness::All
|| table_join->strictness() == JoinStrictness::Any);

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.

[P1] Preserve duplicate-left semantics before enabling inner ANY

With any_join_distinct_right_table_keys = 0 (the default), ANY INNER JOIN emits one row per matching key across both sides. DirectKeyValueJoin instead probes every left row independently; FirstMatch limits only the right matches and never suppresses repeated left keys.

For a left table containing (id, payload) = (1, 100), (1, 200) and a right lookup-index table containing (id, value) = (1, 10), selecting both payloads through ANY INNER JOIN ... ON f.id = d.id produces two rows with join_algorithm = 'direct,hash', versus one with hash. HashJoin enforces this through setUsedOnce. This allowance also changes existing dictionary/key-value joins without the experimental lookup setting.

Please decline inner Any in both planner paths until direct joins implement query-local, thread-safe used-key tracking across blocks. Tracking usage in the shared lookup entity would incorrectly couple separate queries.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 Addressed in 206e85bd1545: inner ANY is declined again in both tryExtractLookupJoinRightKeys and tryDirectJoin. That also restores the previous behaviour for dictionary and key-value joins. 04360 now uses ANY LEFT JOIN for its "lookup is used" check, and 05564_lookup_index_review_fixes covers your example: two left rows with the same key give one row.

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.

[Blocker] The fix leaves the old-analyzer entrypoint enabled: src/Interpreters/ExpressionAnalyzer.cpp:1214-1215 still accepts inner JoinStrictness::Any in tryKeyValueJoin. tryCreateJoin then selects DirectKeyValueJoin and discards the ordinary right-side plan.

With enable_analyzer = 0, any_join_distinct_right_table_keys = 0, left rows (1, 100), (1, 200), and an EmbeddedRocksDB right table keyed by id containing (1, 10), the code still emits both left rows for ANY INNER JOIN with join_algorithm = 'direct,hash'. The hash path emits one through setUsedOnce. This also affects dictionaries and requires no lookup index or experimental setting.

Please restore the All-only inner gate in tryKeyValueJoin too and cover this case with the old analyzer; 05564_lookup_index_review_fixes explicitly enables the new analyzer, so it does not exercise this remaining path.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 Addressed in 50bf5a71551f: tryKeyValueJoin in src/Interpreters/ExpressionAnalyzer.cpp accepts only All for inner joins again, so the file is identical to master. 05872_direct_join_any_inner_old_analyzer joins a table with a repeated left key to a dictionary with any_join_distinct_right_table_keys = 0 and join_algorithm = 'direct,hash' under both analyzers and expects one row.

Comment thread src/Planner/CollectSets.cpp Resolved
Comment thread src/Planner/CollectSets.cpp Resolved
Comment thread src/Storages/IndicesDescription.cpp Resolved
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
alexey-milovidov and others added 5 commits November 6, 2026 14:25
# Conflicts:
#	src/Interpreters/InterpreterCreateQuery.cpp
#	src/Storages/AlterCommands.cpp
#	src/Storages/MergeTree/MergeTreeData.cpp
- Decline inner `ANY` joins for direct joins again: with `any_join_distinct_right_table_keys = 0`
  `HashJoin` emits one row per matching key across both sides, while `DirectKeyValueJoin` probes
  every left row independently. This also restores the previous behaviour for dictionary and
  key-value joins.
- Do not replace a subquery with `LIMIT AFTER` or `LIMIT UNTIL` by the whole lookup set.
- Do not use the lookup set when the plan may be serialized for remote execution:
  `FutureSetFromStorage` is serialized as a reference to a `StorageSet`.
- Take the regular path for a lazily loaded table behind `StorageTableProxy`: its snapshot has
  no `MergeTreeData` parts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… entries

- A lookup read inherits the query limits, and some of them (`timeout_overflow_mode = 'break'`,
  `read_overflow_mode = 'break'`) finish the pipeline normally after a partial read. Publish the
  result to the shared cache only when it has exactly the rows of the snapshot's parts.
- Include the columns description in the cache signature: a non-replicated `MergeTree` does not
  maintain the metadata version, and an `ALTER` changing only a column default creates no
  mutation, so an old builder could otherwise publish an entry that matches the new snapshot.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The flag can come from the `clickhouse_json` dialect, so an ordinary data skipping index such as
`minmax` could use it to skip the granularity check and later fail with `Attempt to write empty
minmax index`. Reject the flag on a type that is not a lookup index type.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…atedMergeTree`

`ATTACH TABLE ... AS REPLICATED` persisted the replicated definition before the
`StorageReplicatedMergeTree` constructor rejected the lookup index, and the startup
`convert_to_replicated` flag loaded the converted table with `FORCE_ATTACH` and published its
metadata to Keeper. Reject the former before any side effect, and make the latter keep the
table as is with an error in the log, like for `table_readonly`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (conflicts in InterpreterCreateQuery.cpp, AlterCommands.cpp and MergeTreeData.cpp, resolved by keeping both sides) and addressed the 8 open review threads; see the replies on each thread.

The previous red was only from Performance Comparison (arm, 4/6 and 5/6). Its "1 errors" are the new perf tests lookup_index_table_join / lookup_index_table_set failing on the reference master server with Unknown setting 'allow_experimental_lookup_index', which is expected for a setting this PR adds. The "too long" entries are pre-existing tests that this PR does not touch.

alexey-milovidov and others added 4 commits November 14, 2026 17:09
…-as-indices

Conflict resolution:
- `StorageFactory`: master moved the engine feature checks into `checkEngineFeatures`; the lookup index check was moved there.
- `AlterCommands`: kept the lookup index rebuild after master's text index permission check.
- `MergeTreeData.h`, `Planner/Utils`: kept both sides.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ked map

Master changed the type of `PreparedJoinStorage::column_mapping` to `UnorderedMapWithMemoryTracking`, so it can no longer be assigned from `TableExpressionData::getColumnIdentifierToColumnName` directly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…umn default

A column absent from an old part is filled on every read by evaluating its default expression, which may depend on mutable state (`dictGet`, `now`, another table). Neither the part identity nor the schema signature captures that state, so a cached `table_set` or `table_join` could keep serving values computed before, e.g., `SYSTEM RELOAD DICTIONARY`. Such snapshots are now not cacheable, both for cache hits and for publication.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`MutationsInterpreter` analyzes the mutation with `getStorageSnapshotWithoutData`, whose `SnapshotData::parts` is null, and `getLookupTableState` dereferenced it (segmentation fault found by the AST fuzzer). Decline the lookup fast path for such snapshots.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=101401&sha=c904d7c3326775edb23765e4ae9745845f17a25e&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
ClickHouse#101401

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master and resolved the conflicts. Master moved the engine feature checks into StorageFactory::checkEngineFeatures, so the lookup-index check now lives there. Also pushed:

  • an adaptation to PreparedJoinStorage::column_mapping becoming a memory-tracked map;
  • a fix for the AST fuzzer segmentation fault: MutationsInterpreter uses a storage snapshot without data, and the lookup fast path now declines it. Regression test: 05769_lookup_index_mutation_snapshot_without_data;
  • the review fix for missing-column defaults (see the thread).

The Run Errors in Performance Comparison 4/6 and 5/6 come from the reference master server, which does not know allow_experimental_lookup_index yet. That is expected for a performance test of a new feature. The iceberg performance shards failed for infrastructure reasons (missing report file, disk-almost-full).

metadata.add_minmax_index_for_block_number_column = (*storage_settings)[MergeTreeSetting::add_minmax_index_for_block_number_column] && (*storage_settings)[MergeTreeSetting::enable_block_number_column];
metadata.add_minmax_index_for_block_offset_column = (*storage_settings)[MergeTreeSetting::add_minmax_index_for_block_offset_column] && (*storage_settings)[MergeTreeSetting::enable_block_offset_column];
metadata.escape_index_filenames = (*storage_settings)[MergeTreeSetting::escape_index_filenames];
metadata.lookup_indices = getLookupIndicesFromAST(args.query.columns_list ? args.query.columns_list->lookup_indices : nullptr, columns, 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.

[Major] Lookup indexes are silently ignored when loading tables created with the old engine syntax. This assignment runs only when is_extended_storage_def is true, but isExtendedStorageDef recognizes ordinary indexes and projections without checking lookup_indices.

For example, with allow_deprecated_syntax_for_merge_tree = 1, CREATE TABLE t (d Date, id UInt64, LOOKUP INDEX s (id) TYPE table_set) ENGINE = MergeTree(d, id, 8192) passes validation but creates no runtime lookup index. An existing old-syntax table also accepts ALTER TABLE t ADD LOOKUP INDEX s (id) TYPE table_set: the old-syntax validation rejects only ADD_INDEX, so the lookup works until detach/attach or restart, when this constructor skips its persisted declaration.

Please consistently reject lookup indexes on old-syntax tables in both CREATE and ALTER, or load them correctly there. Add a focused test proving rejection or preservation across detach/attach.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 Addressed in deabffe6e3c7: lookup indexes are rejected for tables with the old engine syntax. CREATE with a LOOKUP INDEX declaration and the old syntax throws BAD_ARGUMENTS in registerStorageMergeTree.cpp, and ALTER TABLE ... ADD LOOKUP INDEX on such a table throws next to the existing ADD INDEX check in MergeTreeData::checkAlterIsPossible. 05871_lookup_index_old_syntax_rejected covers both and checks the definition after detach/attach.

alexey-milovidov and others added 4 commits November 23, 2026 17:09
…-as-indices

Conflicts:
- `src/Interpreters/DirectJoin.cpp`: kept the `previous_offset` loop of this branch in `selectFirstMatchForEachKey`.
- `src/Planner/PlannerJoins.cpp`, `src/Planner/PlannerJoins.h`: `trySetStorageInTableJoin` was removed on master as unused; kept only `tryGetLookupJoinStorage`.
- `src/Storages/MergeTree/MergeTreeData.cpp`: the invalidation of the lookup index caches moved into the new `updateCachesAfterMetadataPublish`, so both of its callers drop them.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…zer too

`tryKeyValueJoin` still accepted `ANY INNER JOIN`, so with `enable_analyzer = 0` a direct join over a
dictionary or a key-value storage emitted a row for every left row with a repeated key, while `HashJoin`
emits one row per key. Restore the `All`-only gate, as on master, and cover it with a dictionary join
under both analyzers.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…syntax

The old `MergeTree` syntax does not read index declarations, so a lookup index in `CREATE` was silently
ignored, and one added by `ALTER TABLE ... ADD LOOKUP INDEX` was lost after detach/attach or a restart.
Reject both, the same way as `ADD INDEX`.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master and resolved the conflicts: trySetStorageInTableJoin was removed on master as unused, and the invalidation of the lookup index caches moved into the new MergeTreeData::updateCachesAfterMetadataPublish, so both of its callers drop them. Also removed the duplicate include that failed the arm_tidy build, and addressed the two open review threads: inner ANY is declined for direct joins in the old analyzer too (50bf5a71551f), and LOOKUP INDEX is rejected for tables with the old engine syntax in CREATE and ALTER (deabffe6e3c7).

This branch has not been deployed

No deployments
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 comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. external Author is not a member of the ClickHouse organization manual approve Manual approve required to run CI pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants