Skip to content

Add table function obfuscate - #115004

Merged
alexey-milovidov merged 142 commits into
masterfrom
obfuscate-function
Oct 15, 2026
Merged

alexey-milovidov merged 142 commits into
masterfrom
obfuscate-function

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 16, 2026 •

Copy link
Copy Markdown
Member

Related: #42701

Supersedes the fork PR and preserves its implementation and review history; original work by @evillique.

Changelog category (leave one):

  • New Feature

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

Add the obfuscate table function for generating anonymized query results.


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

Version info

  • Merged into: 26.10.1.2426-master (included in 26.10 and later)

evillique and others added 30 commits October 27, 2022 01:39
# Conflicts:
#	programs/obfuscator/Obfuscator.cpp
#	src/Parsers/ExpressionListParsers.cpp
The signed obfuscation model negated a negative value with `-x` before
applying the permutation. For `INT64_MIN` the negation is not representable
as a signed `Int64` and is undefined behavior. Now that obfuscation runs as
the `obfuscate` table function over arbitrary signed integer columns, this
path is reachable for user data.

Compute the magnitude using unsigned arithmetic (`-static_cast<UInt64>(x)`),
which is well-defined for all values including the minimum. The result is
bit-for-bit identical to the previous behavior for every value other than
the (previously undefined) minimum, so existing obfuscator output is
unchanged.

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

After merging master, the new code no longer compiled under the strict
`-Weverything -Werror` build:

- `ITableFunction::skipAnalysisForArguments` now returns
  `VectorWithMemoryTracking<size_t>` instead of `std::vector<size_t>`; update
  the override in `TableFunctionObfuscate` to match.
- `IQueryPlanStep::FormatSettings` is now `ExplainFormatSettings`, defined in
  `Processors/QueryPlan/QueryPlanFormat.h`; include it in `ObfuscateStep.cpp`.
- Cast the `obfuscate_markov_frequency_desaturate` setting (`Float`) explicitly
  to `double` to avoid `-Wdouble-promotion`.
- Add a forward declaration for `registerStorageObfuscate` to avoid
  `-Wmissing-prototypes`.
- Default-initialize `ObfuscateStep` members to satisfy
  `cppcoreguidelines-pro-type-member-init`.

Also add a `FunctionDocumentation` for the `obfuscate` table function so that
`02414_all_new_table_functions_must_be_documented` passes.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The style check requires chassert instead of assert.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Several correctness and robustness fixes for the `obfuscate` table function,
addressing the open review threads:

- Do not apply the query-level `limit` / `offset` result settings to the inner
  training and generation query. They are cleared for the inner execution so
  that e.g. `SELECT * FROM obfuscate(SELECT * FROM numbers(1000)) SETTINGS limit = 10`
  still trains the model from the full source, while the outer pipeline keeps
  applying them to the obfuscated output.
- Fail closed when a full generation pass over the inner query produces no rows
  (e.g. a non-repeatable inner query that became empty after a non-empty training
  pass): return EOF instead of rebuilding the inner pipeline forever.
- Validate the new `obfuscate_markov_*` settings before constructing the model:
  reject `obfuscate_markov_order = 0` (which otherwise leaves the Markov table
  empty and later throws a logical error) and `obfuscate_markov_frequency_desaturate`
  outside the documented `[0, 1]` range, both with a clear `BAD_ARGUMENTS` exception.
- Document that `obfuscate` is a repeating, effectively infinite source that must
  be bounded with an outer `LIMIT`.
- Make the empty-seed case of `04103_obfuscate_table_function_settings`
  deterministic: it asserted that two random executions differ, which is
  probabilistic for such a tiny domain and could flake. It now only checks that
  the query succeeds and returns the requested number of rows, and adds coverage
  for the rejected invalid Markov settings.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…rg::alter

PR #106102 (merged 2026-06-05 17:43 UTC) refactored Iceberg::alter to
declare last_version and compression_method outside an if/else that
assigns them in both branches. Clang-tidy cppcoreguidelines-init-variables
flags the bare declarations and Build (arm_tidy) is built with
-warnings-as-errors, so the build fails for every PR whose CI ran on
master after this commit.

CIDB shows 30+ unrelated PRs hitting this in the last 2 days
(e.g. #89360, #103540, #106120, #106386, #106404, #106522, #105102,
#106590).

Initialize both variables to safe defaults at declaration. They are
unconditionally overwritten in both if and else branches before use,
so behavior is unchanged. The new defaults are only relevant if a
future code path skips both assignments, in which case last_version=0
and compression_method=CompressionMethod::None are sane no-op values
(the same defaults the old structured-binding form would produce
through default-construction of the destructured aggregate).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
(cherry picked from commit d72cac5)
…ls.h

The refactoring that moved the obfuscator implementation into the shared
`src/Common/Obfuscator/Models.h` dropped the `file_out.finalize()` call at the
end of `mainEntryClickHouseObfuscator`. Without finalizing the output
`WriteBufferFromFileDescriptor`, its destructor aborts in debug and sanitizer
builds, which made `00092_obfuscator`, `00096_obfuscator_save_load`,
`00175_obfuscator_schema_inference` and `01472_obfuscator_uuid` fail with
`Aborted`, and the resulting core dump was reported as `Server died` in the
targeted stateless runs.

Restore the explicit `file_out.finalize()` after the generation loop.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…he query result cache

With the default empty `obfuscate_seed`, the `obfuscate` table function derives a
fresh random seed per execution (`ObfuscateStep`), so its result is
non-deterministic. The query result cache, however, only detected
non-deterministic scalar functions, so `SELECT * FROM obfuscate(...)
SETTINGS use_query_cache = 1` could cache the first random output and replay it
on later executions.

Teach `HasNonDeterministicFunctionsMatcher` to treat an `obfuscate` table
function with an empty `obfuscate_seed` as non-deterministic, following the
existing string-match precedent for `clusterAllReplicas`. A non-empty
`obfuscate_seed` produces reproducible output and remains cacheable.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The new `Obfuscate` table engine registered by this pull request appears in
`system.table_engines`, but it was missing from the `engine_to_type` mapping in
the Arrow Flight SQL `commandSelector`. As a result, `commandGetTableTypes` and
`commandGetTables` reported it as `UNKNOWN TABLE TYPE`, failing the
`test_arrowflight_interface/test_sql_server.py::test_get_table_types` integration
test, which asserts that every engine is mapped.

Map `Obfuscate` to `TABLE`, consistent with the other data-generating engines
such as `GenerateRandom`, `FuzzQuery`, and `Loop`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The AST fuzzer moved `obfuscate(SELECT ...)` into the argument position of
another table function. Evaluating it as a constant expression calls
`getColumnName`, which descended into the `ASTSelectWithUnionQuery` argument
and threw the logical error "Trying to get name of not a column". Add
`obfuscate` to the guard in `ASTFunction::appendColumnNameImpl` that already
covers `view` and other table functions holding unexpected ASTs, so it throws
a plain `UNKNOWN_FUNCTION` exception instead.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=42701&sha=685714c0c493ba0c5c7778861558efb8b4d3aef0&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
PR: #42701

Co-Authored-By: Claude Fable 5 <[email protected]>
For `INT64_MIN` the magnitude `2^63` stays in the `2^63..2^64-1` log2 bucket
of `transform`, and the final unsigned negation wraps most transformed
magnitudes into positive `Int64` values, breaking the "keep sign" invariant.
It is the only value in its bucket whose magnitude is representable, so keep
it as is.

Co-Authored-By: Claude Fable 5 <[email protected]>
…sult cache

The non-determinism check for the `obfuscate` table function only consulted
the outer query context, so an inner `SELECT ... SETTINGS obfuscate_seed = ''`
could produce a random result that was still written to the query result
cache when the outer scope had a non-empty seed. Track the effective seed
while descending into the AST, honoring the SETTINGS clause of every
enclosing SELECT (this also makes an inner non-empty seed cacheable when the
outer scope has none).

Co-Authored-By: Claude Fable 5 <[email protected]>
…cate`

`max_result_rows`, `max_result_bytes` and `extremes` describe the final query
result, not the hidden source used to train the obfuscator. Clear them in the
inner context, the same way `interpretSubquery` and `StorageView` do for
their inner executions, so the inner pipeline does not compute extremes and
future changes to how the inner query is executed cannot apply result limits
to it.

Co-Authored-By: Claude Fable 5 <[email protected]>
…t numbers gap)

The style check `test_numbers_check` failed with `Gap (4326, 5006) > 100`.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ery result cache check

`ParserSetQuery` stores the `DEFAULT` form in `ASTSetQuery::default_settings`
rather than `changes`, so the non-determinism check missed it and a query with
an outer non-empty `obfuscate_seed` and an inner `SETTINGS obfuscate_seed = DEFAULT`
could cache a random-seeded result. The default of `obfuscate_seed` is the empty
string, so such a reset always makes the result non-deterministic.

Co-Authored-By: Claude Fable 5 <[email protected]>
The `obfuscate` table function re-executes its inner query for training and
for every generation pass, reusing the same saved AST. A review raised the
concern that the analyzer is not read-only for the inner query: `QueryTreeBuilder`
removes `SETTINGS limit`/`offset` while converting them into query-tree limit
nodes, so later passes could re-read the full, unlimited inner query.

This does not happen: `buildQueryTree` clones the input AST in
`QueryTreeBuilder::buildQueryTreeNode` before any traversal, so the saved inner
query is never mutated and the inner limit is applied identically on every pass.
Add a regression test on the analyzer path asserting that
`obfuscate(numbers(100) SETTINGS limit = 2)` produces the same obfuscated stream
as `obfuscate(numbers(2))` across multiple passes, and is deterministic for a
fixed seed.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…work

# Conflicts:
#	programs/obfuscator/Obfuscator.cpp
The Style check `test_numbers_check` failed with `Gap (4339, 5017) > 100`:
the test `05017_obfuscate_inner_settings_limit_stable` sat far above the dense
test-number range. Renumber it to `04401` so the numbering stays gap-free.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`DateTimeModel` preserved the date component using `DateLUT::serverTimezoneInstance`,
but a `DateTime` column can carry its own timezone. On a server in one timezone, a
`DateTime('Asia/Tokyo')` value near local midnight could move to a neighbouring
displayed date, breaking the obfuscator contract that the date component is preserved.

Thread the column timezone (`DataTypeDateTime::getTimeZone`) from `ModelFactory`
into `DateTimeModel` and use it for both `toDate` calls. For a `DateTime` without an
explicit timezone `getTimeZone` falls back to the session/server timezone, so the
common case is unchanged. The model is shared with the `clickhouse obfuscator` tool,
so the fix applies to both and keeps them in sync.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

00443_optimize_final_vertical_merge: the fix is in #123977 (test-only). The data was correct. The checksum cityHash64(groupArray(ki)) depends on the order in which the initiator merges the replicas' partial states, and --parallel_replicas_local_plan=1 does not stop a remote replica from getting a range. In this run the coordinator gave marks 0..7 to a remote replica and 8..18 to the local one, and of all arrangements of those ranges only range(65536, 150000) followed by range(0, 65536) gives the observed hash. The check is now SELECT count() FROM $name WHERE ki != _part_offset, which does not depend on the read order and keeps the parallel replicas coverage.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai. #123977 explains 00443_optimize_final_vertical_merge: the hash depends on the order in which the replicas' partial states get merged, and the data itself was correct. The other failures already have fixing PRs, so nothing more is needed from this PR. Pushed 8355735: it adds the missing no-parallel tag to 05325_union_subquery_opt_out_query_cache_arms, which fixes the Style check, and merges master, which brings in #123763.

Comment thread src/Access/SettingsConstraints.cpp Resolved
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Oct 6, 2026
The test compared cityHash64(groupArray(ki)) over the merged table with the
hash of 0..149999, which depends on the order rows reach groupArray. Under
parallel replicas that order is the order in which the initiator merges the
replicas' partial states, and --parallel_replicas_local_plan=1 does not stop
a remote replica from being assigned ranges. In the failing CI run (PR
ClickHouse#115004, Stateless tests (arm_binary, ParallelReplicas, s3 storage,
parallel)) the coordinator gave marks 0..7 to a remote replica and 8..18 to
the local one, and only range(65536, 150000) ++ range(0, 65536) hashes to the
observed value: the part was correct, only the concatenation order differed.

Check the physical order directly with count() ... WHERE ki != _part_offset.
It does not depend on the read order, keeps parallel replicas coverage, and
together with count() = 150000 still detects an unsorted part, a lost row or
a duplicate. _part_offset is computed per read range, so it stays correct
when replicas split the part. The max_threads=1 / local plan workaround is no
longer needed.

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

`04665_obfuscate_unsupported_types` now compares the source and the obfuscated rows one by one to
check that `Date` values pass through unchanged, that `Nullable` keeps the null map, and that `Array`
keeps its sizes, as the table function documentation promises.

`05223_obfuscate_table_function_select_grant` now also checks that `EXPLAIN PLAN` over `obfuscate`
is denied without the `SELECT` grant on the source table and succeeds with it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 7, 2026 05:15
…ate` determinism

A nested `SETTINGS profile = '...'` (or `profile = DEFAULT`) can change the
effective `obfuscate_seed` of a (sub)query without mentioning
`obfuscate_seed` itself. The query result cache walk replayed only literal
`obfuscate_seed` entries, so it could cache a subquery that really ran with
the empty (random) seed, or reject a deterministic one.

Track the effective context while descending into the AST and replay the
`obfuscate_seed` and `profile` entries of each query-level `SETTINGS` clause
on a copy of it, the same way `applyQueryLevelSettings` in `QueryTreeBuilder`
builds the context of the nested query (one change at a time, clamped to the
constraints, then the resets).

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115004&sha=3f47e6703409015188406e489e78e40ffcc235f3&name_0=PR&name_1=BuzzHouse%20%28amd_debug%29 (Logical error: 'Unexpected return type from equals. Expected Nullable(UInt8). Got UInt8' on a LowCardinality(String) column; the same family also fails on master and many unrelated PRs) and provide a fix in a separate PR. If the fix is already in progress, link it here.

Comment thread src/Analyzer/QueryTreeBuilder.cpp Resolved
@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator

The fix is already in progress: #124037 (open, CI green). This failure is the route it fixes.

The failed query is an AST fuzzer variant, SELECT count() FROM merge('system', '') WHERE (database = materialize('d7')) AND (table = 't32'), in a session with optimize_prewhere_after_pushdown = 1 and move_all_conditions_to_prewhere = 0 (earlier SETs in server.log). merge('system', '') also reads the system.all_* union tables, which are Merge tables themselves; some of them (e.g. system.all_asynchronous_insert_log) have LowCardinality(String) database/table, while system.grants makes the common type Nullable(String). The second PREWHERE pass combines the new condition into the existing PREWHERE with ActionsDAG::mergeNodes, which rebinds children by name. The two materialize(table) nodes (one per Merge level) have the same name, so equals gets the inner LowCardinality(String) one and returns UInt8.

Checked on a local server with the default config, same query and these two settings:

Not caused by this PR. This exact signature appears 3 times in CIDB in the last 30 days, on three unrelated PRs, 0 on master. The master hits of this message family in the same period are different routes (Stress tests, plus/multiply/moduloOrZero/arrayElement), which #124037 does not touch.

Resolve the conflict in `src/Planner/Planner.cpp`: master added the on-disk query result cache
to the inline subquery cache read/write code, which this branch had factored out into
`tryAddReadFromQueryResultCacheStep` and `addStreamInQueryResultCacheStepIfNeeded` (also used for
`UNION`). Move the on-disk cache support into these helpers, so both query nodes and set operations use it.

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

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai, that settles the BuzzHouse failure: it's the Merge-over-Merge PREWHERE route fixed in #124037. Nothing to change in this PR. I've also merged master (c55b01a). The conflict in src/Planner/Planner.cpp came from master's new on-disk query result cache: its read/write support now lives in the shared subquery cache helpers, which the UNION/INTERSECT/EXCEPT subquery cache uses as well.

alexey-milovidov and others added 2 commits October 14, 2026 06:38
# Conflicts:
#	src/Planner/Planner.cpp
Master now requires each table engine and table function to declare its
secret arguments at registration (`registerStorage` and
`registerFunction` take a `SecretArgumentsSpec`). Neither `obfuscate`
nor `Obfuscate` has secret arguments, so pass an empty spec.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Analyzer/QueryTreeBuilder.cpp Resolved
Comment thread src/Common/Obfuscator/Models.h Resolved

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The core implementation is okay. However, this also contains a lot of pedantic changes around setting propagation. Nevertheless, I found it acceptable as a whole.

@alexey-milovidov alexey-milovidov removed the submodule changed At least one submodule changed in this PR. label Oct 15, 2026
@alexey-milovidov alexey-milovidov self-assigned this Oct 15, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 15, 2026
Merged via the queue into master with commit 0f5adf1 Oct 15, 2026
519 of 524 checks passed
@alexey-milovidov
alexey-milovidov deleted the obfuscate-function branch October 15, 2026 01:33
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 15, 2026
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 10, 2026
`DateTimeModel` attaches the obfuscated time of day to the source local date.
On the first and the last local day of the `DateTime` range, which are only
partially representable, the reconstructed timestamp could fall outside of
`UInt32` and wrap around: e.g. `2106-02-07 06:28:15 UTC` could become a time
on `1970-01-01`. Clamp it to the range; both bounds belong to the source local
day in that case.

Follow-up to review of ClickHouse#115004

Co-Authored-By: Claude Opus 5.5 <[email protected]>
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 10, 2026
…r cases

Follow-ups to the review of ClickHouse#115004:

- A nested `SETTINGS` clause is clamped one change at a time, which lost the
  batch's `compatibility` marker: `SETTINGS use_variant_as_common_type = 1,
  compatibility = '25.12'` dropped the `1` as unchanged and let `compatibility`
  override it. Keep unchanged assignments when the clause contains
  `compatibility`, as the batch check of a top-level clause does. Likewise, a
  nested `SETTINGS x = DEFAULT` of an explicitly assigned setting is no longer
  dropped as unchanged: it clears the assignment, so `compatibility` applies.
  The sequential application now lives in one place,
  `Context::applyNestedQuerySettingsClamped`, used by `QueryTreeBuilder`,
  `ApplyWithSubqueryVisitor` and the query cache check.
- The query cache check for `obfuscate` replays the whole nested clause, not
  only `obfuscate_seed` and `profile`: e.g. `readonly = 1` before the seed makes
  the constraints drop the seed assignment, so the result is random and must not
  be cached.
- `SelectIntersectExceptQueryVisitor` can nest the last operand that carries the
  trailing query-level clause of a set operation into `INTERSECT` / `EXCEPT`
  nodes (`A UNION ALL B INTERSECT ALL C SETTINGS ...`). Find it there too
  (`ASTSelectIntersectExceptQuery::getTrailingSettings`), in `QueryTreeBuilder`,
  in the query cache check and in `ReplaceQueryParameterVisitor`.
- `ReplaceQueryParameterVisitor` scopes the `param_*` bindings of both
  query-level clauses of a union - the one after `FORMAT` and the trailing one -
  in the order `QueryTreeBuilder` applies them, instead of only the first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-table-functions Table functions for temporary read/write to external systems (FROM ... tableFunction()). pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants