Skip to content

Preserve known identifiers in obfuscateQuery - #103843

Merged
alexey-milovidov merged 7 commits into
masterfrom
obfuscate-query-known-identifiers
May 4, 2026
Merged

alexey-milovidov merged 7 commits into
masterfrom
obfuscate-query-known-identifiers

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented May 1, 2026 •

Copy link
Copy Markdown
Member

The SQL function obfuscateQuery (and obfuscateQueryWithSeed) used to pass an empty known_identifier_func to obfuscateQueries, so names of built-in functions, aggregate functions, table functions, formats, data types, storages, codecs and settings were replaced by random words. This made the output less readable and inconsistent with clickhouse-format --obfuscate, which already builds a comprehensive set of known names from all factories.

This PR mirrors the logic from programs/format/Format.cpp: build a KnownIdentifierFunc once per process that consults FunctionFactory, AggregateFunctionFactory, TableFunctionFactory, FormatFactory, plus storages, data types, settings, MergeTree settings, MergeTree indices, codecs, databases, dictionary layouts and sources, and time-zone components, with a case-insensitive fallback. Inside the server, all these factories are already populated at startup, so no additional registration is needed.

Before:

:) SELECT obfuscateQueryWithSeed('SELECT count(*), sum(x), avg(y) FROM t', 'seed');
SELECT noticing(*), drilling(rabbit), regiment(steady) FROM ninja

After:

:) SELECT obfuscateQueryWithSeed('SELECT count(*), sum(x), avg(y) FROM t', 'seed');
SELECT count(*), sum(wolf), avg(blessing) FROM ninja

Changelog category (leave one):

  • Not for changelog

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

obfuscateQuery and obfuscateQueryWithSeed now preserve names of built-in functions, aggregate functions, table functions, formats, data types, storages, codecs and settings, matching the behaviour of clickhouse-format --obfuscate.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Backported to: 26.4.2.9

The SQL function `obfuscateQuery` (and `obfuscateQueryWithSeed`) used to
pass an empty `known_identifier_func` to `obfuscateQueries`, so names of
built-in functions, aggregate functions, table functions, formats, data
types, storages, codecs and settings were replaced by random words —
making the output less readable and inconsistent with
`clickhouse-format --obfuscate`.

Mirror the logic from `programs/format/Format.cpp` so all registered
names are kept as-is. The set is built lazily once per process.

Adds a regression test in
`tests/queries/0_stateless/04145_obfuscate_query_known_identifiers.sql`.
@clickhouse-gh

clickhouse-gh Bot commented May 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ea742cb]

Summary: ❌

job_name test_name status info comment
Docs check FAIL
Generate system tables documentation FAIL
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/check_report_messages.py FAIL

AI Review

Summary

This PR makes obfuscateQuery and obfuscateQueryWithSeed preserve known identifiers (functions, table functions, formats, types, settings, codecs, etc.) via a process-wide KnownIdentifierFunc, aligns behavior with clickhouse-format --obfuscate, and adds focused stateless coverage. I did not find correctness, safety, concurrency, or performance issues in the current patch.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label May 1, 2026
Comment thread src/Functions/obfuscateQuery.cpp Resolved
…ery`

`TableFunctionFactory::isTableFunctionName` only checks the
case-sensitive map and ignores aliases, so table functions written in
uppercase (e.g. `NUMBERS(10)`) were still obfuscated.

Add table function names to the pre-built `names` set instead — the
existing case-insensitive fallback then matches `NUMBERS` to `numbers`,
and `getAllRegisteredNames` already includes aliases.
@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog and removed pr-improvement Pull request with some product improvements labels May 1, 2026
`Format.cpp` had the same bug as the SQL function: table function names
written in uppercase or via aliases (e.g. `NUMBERS(10)`) were obfuscated
because `TableFunctionFactory::isTableFunctionName` is exact-case only
and ignores aliases.

Add the table function names to the `additional_names` set so the
existing case-insensitive fallback covers them.
The previous workarounds in \`obfuscateQuery\` and \`clickhouse-format\`
papered over a real bug in \`TableFunctionFactory::isTableFunctionName\`,
which only checked the exact-case map and ignored aliases as well as the
\`case_insensitive_table_functions\` map maintained by the same factory.

Mirror the lookup logic from \`tryGet\` so the method now resolves
aliases via \`getAliasToOrName\` and falls back to the case-insensitive
map. This benefits all callers (e.g. \`TableFunctionRemote\`,
\`QueryAnalyzer\`, \`QueryFuzzer\`) and lets the obfuscators rely on
\`isTableFunctionName\` directly without their own table function set.

Revert the workarounds in \`obfuscateQuery.cpp\` and \`Format.cpp\`. Update
the regression test to use \`VALUES\` (a case-insensitive table function)
instead of \`NUMBERS\`, which is in fact case-sensitive.
alexey-milovidov and others added 3 commits May 1, 2026 19:30
`master` added `04145_h3_polygon_to_cells_invalid_type` and
`04145_url_glob_parallelize_output` after this branch was created, so
shift our test to the next available number.

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

clickhouse-gh Bot commented May 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 100.00% (51/51) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov merged commit 1c87274 into master May 4, 2026
320 of 326 checks passed
@alexey-milovidov
alexey-milovidov deleted the obfuscate-query-known-identifiers branch May 4, 2026 03:20
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label May 4, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label May 4, 2026
pull Bot pushed a commit to Mattlk13/ClickHouse that referenced this pull request May 5, 2026
…Logs` flush

`SystemLogs::flushImpl` calls `BaseDaemon::instance().flushTextLogs()` to drain
the async logger before iterating system log queues. `BaseDaemon::instance()` is
`dynamic_cast<BaseDaemon &>(Poco::Util::Application::instance())`, so when the
application is `ClientApplicationBase`-derived (e.g. `clickhouse-local`,
`clickhouse-client`) the cast throws `std::bad_cast`. The exception escapes
`SystemLogs::flushAndShutdown` -> `DatabaseCatalog::shutdownImpl` -> `Context::shutdown`,
leaving the saving threads alive.

When the holder of the last `Context` reference drops it, `~ContextSharedPart`
runs `~SystemLogs` -> `~SystemLog<T>`. `queue` lives in `SystemLogBase<T>` and
`saving_thread` in `ISystemLog`, so member destruction tears down the
`SystemLogQueue` and its condition variables before the saving thread has been
joined. `pthread_cond_destroy` then blocks forever because the saving thread is
still parked in `pop()` waiting on `flush_event`. Meanwhile the periodic
saving-thread flushes that fire after `~Application` has already nulled
`_pInstance` show up as `Null pointer: _pInstance` from
`Context::getConfigRef()` -> `Application::instance().config()` (via
`InterpreterCreateQuery::createTable` -> `UserDefinedSQLFunctionFactory::empty`
-> `Context::getUserDefinedSQLObjectsStorage`), which is the symptom reported
on the docs check.

Two fixes:

* `SystemLogs::flushImpl` now calls a small `flushAsyncTextLogsIfPossible`
  helper that uses `BaseDaemon::tryGetInstance` (a `dynamic_cast<BaseDaemon *>`
  internally) and skips the call when the application is not a `BaseDaemon`,
  so flushing on `clickhouse-local`/`clickhouse-client` is a no-op instead of
  raising `std::bad_cast`.
* `SystemLogBase<T>` now has an explicit destructor that calls
  `stopFlushThread()`, joining the saving thread before any of the queue's
  condition variables can be destroyed. This is defence-in-depth so that any
  future path that bypasses `flushAndShutdown` cannot reproduce the same hang.

Reproduction with the affected docs config (~30 system log sections,
`SELECT 1`) on master: query takes 54+ s and the process hangs in
`pthread_cond_destroy` from `~SystemLogQueue<FilesystemCacheLogElement>`.
With this change the same invocation completes in ~3.2 s (the residual time
is the cost of constructing every configured `SystemLog`) and exits cleanly.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103843&sha=41c0a8a98f6f189f2c3c7025a979112c40ce7220&name_0=PR&name_1=Docs%20check
PR: ClickHouse#103843

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
alexey-milovidov added a commit that referenced this pull request May 6, 2026
The original PR fixes both the SQL `obfuscateQuery` function (which does
not exist in 26.4) and `clickhouse-format --obfuscate`. The root-cause
fix in `TableFunctionFactory::isTableFunctionName` — consulting aliases
and the case-insensitive map in addition to the exact-case map — is the
only part that applies to 26.4 and is sufficient to preserve known table
function names (including aliases like `VALUES` and `url`) when running
`clickhouse-format --obfuscate`.

Original pull-request: #103843

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robot-ch-test-poll1 added a commit that referenced this pull request May 6, 2026
Cherry pick #103843 to 26.4: Preserve known identifiers in `obfuscateQuery`
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label May 6, 2026
alexey-milovidov added a commit that referenced this pull request May 6, 2026
The SQL function `obfuscateQuery` (and `obfuscateQueryWithSeed`) used to
pass an empty `known_identifier_func` to `obfuscateQueries`, so names of
built-in functions, aggregate functions, table functions, formats, data
types, storages, codecs and settings were replaced by random words —
making the output less readable and inconsistent with
`clickhouse-format --obfuscate`.

Mirror the logic from `programs/format/Format.cpp` so all registered
names are kept as-is. The set is built lazily once per process.

Also fix `TableFunctionFactory::isTableFunctionName` to consult aliases
and the case-insensitive map (mirroring `tryGet`), so table functions
written in uppercase (e.g. `VALUES`) or via aliases are recognized as
known identifiers by both `obfuscateQuery` and `clickhouse-format
--obfuscate`.

Adds a regression test in
`tests/queries/0_stateless/04146_obfuscate_query_known_identifiers.sql`.

Original pull-request: #103843

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
alexey-milovidov added a commit that referenced this pull request May 6, 2026
Backport #103843 to 26.4: Preserve known identifiers in `obfuscateQuery`
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…fuscateQuery`

The SQL function `obfuscateQuery` (and `obfuscateQueryWithSeed`) used to
pass an empty `known_identifier_func` to `obfuscateQueries`, so names of
built-in functions, aggregate functions, table functions, formats, data
types, storages, codecs and settings were replaced by random words —
making the output less readable and inconsistent with
`clickhouse-format --obfuscate`.

Mirror the logic from `programs/format/Format.cpp` so all registered
names are kept as-is. The set is built lazily once per process.

Also fix `TableFunctionFactory::isTableFunctionName` to consult aliases
and the case-insensitive map (mirroring `tryGet`), so table functions
written in uppercase (e.g. `VALUES`) or via aliases are recognized as
known identifiers by both `obfuscateQuery` and `clickhouse-format
--obfuscate`.

Adds a regression test in
`tests/queries/0_stateless/04146_obfuscate_query_known_identifiers.sql`.

Original pull-request: ClickHouse#103843

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…3843

Backport ClickHouse#103843 to 26.4: Preserve known identifiers in `obfuscateQuery`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants