Skip to content

Add table function obfuscate - #42701

Closed
evillique wants to merge 91 commits into
ClickHouse:masterfrom
evillique:obfuscate-function
Closed

evillique wants to merge 91 commits into
ClickHouse:masterfrom
evillique:obfuscate-function

Conversation

@evillique

@evillique evillique commented Oct 26, 2022 •

Copy link
Copy Markdown
Member

Closes: #39067

Changelog category (leave one):

  • New Feature

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

Add table function obfuscate which applies the same transformation as the clickhouse-obfuscator tool to the result of an arbitrary query, e.g. SELECT * FROM obfuscate(SELECT * FROM table). The seed can be controlled with the obfuscate_seed setting; with an empty seed a fresh random one is derived per execution.

@evillique
evillique marked this pull request as draft October 26, 2022 13:41
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-feature Pull request with new product feature label Oct 26, 2022
@rschu1ze rschu1ze self-assigned this Nov 2, 2022
@alexey-milovidov

Copy link
Copy Markdown
Member

We need this...

@rschu1ze

Copy link
Copy Markdown
Member

Maybe another day ...

@alexey-milovidov

Copy link
Copy Markdown
Member

We need this.

@alexey-milovidov

Copy link
Copy Markdown
Member

Continued in #101027

@evillique

Copy link
Copy Markdown
Member Author

The mentioned PR is about a function that obfuscates an SQL query. This PR implements a table function that obfuscates the result of a certain query.

@evillique evillique reopened this Apr 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [055ddb9]


AI Review

Summary

This PR adds the obfuscate table function by moving the existing obfuscator logic into shared code and then wiring it through the analyzer, planner, cache, and parser layers. Most of the earlier correctness issues were addressed, but the new query_parameters support still misses some query-level SETTINGS carriers, so a subset of valid queries with local param_* bindings still fails before execution.

Findings

⚠️ Majors

  • [src/Interpreters/ReplaceQueryParameterVisitor.cpp:55] Local param_* bindings are only scoped for ASTSelectQuery::settings(). Trailing top-level SETTINGS after a UNION are stored on the last ASTSelectQuery and semantically apply to the whole union, while FORMAT ... SETTINGS ... uses ASTQueryWithOutput::settings_ast. In both shapes the visitor reaches earlier branches or the main query before installing the local bindings, so queries such as SELECT {x:UInt64} UNION ALL SELECT 0 SETTINGS param_x = '1' or SELECT 1 FORMAT Null SETTINGS max_threads = {t:UInt64}, param_t = '1' still throw UNKNOWN_QUERY_PARAMETER.
    Suggested fix: mirror the query-wide carriers handled by InterpreterSetQuery::applySettingsFromSelectWithUnion and ASTQueryWithOutput::settings_ast when building the scoped parameter map, and add regressions for both shapes.
Final Verdict

Changes requested.

Comment thread src/Common/Obfuscator/Models.h Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

Yes, that's true. Didn't notice that. The feature is still needed!

@alexey-milovidov

Copy link
Copy Markdown
Member

The flaky check failure is fixed in #102148, let's update the branch.

@evillique
evillique force-pushed the obfuscate-function branch from f1eaf7b to 53ed445 Compare April 23, 2026 16:48
# Conflicts:
#	programs/obfuscator/Obfuscator.cpp
#	src/Parsers/ExpressionListParsers.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Both reds on the superseded head 019244e0d46b were unrelated to this PR:

  1. Stress test (arm_asan_ubsan) — the fleet-wide LeakSanitizer cycle from the PromQL materialized-CTE selector subqueries, issue LeakSanitizer: abandoned cycle of a materialized PromQL selector subquery (query plan + query tree + context copy via StorageTimeSeriesSelector::readImpl) fails stress tests fleet-wide since 2026-08-10 #114291. The revert Revert the PromQL topk/limitk streaming plan and its shared-subquery materialization #114326 merged on 2026-08-12, and this branch has now re-merged master past it, so the fresh run should be clear.
  2. AST fuzzer (amd_debug) — logical error Cannot add step Limit to QueryPlan because it has incompatible header with root step Sorting on a vector search query with make_distributed_plan = 1. A master bug in the no-rescoring vector search plan rewrite (it also hit the unrelated Allow configuring syslog program name for ClickHouse logs #98789); reproduced locally without any obfuscate involvement and fixed in Fix header column order after the no-rescoring vector search rewrite #114457.

This pass also merged master (zero conflicts) and addressed the new bot Major: MarkovModel::finalize now fails closed with BAD_ARGUMENTS on frequency_add counter overflow, shared by the table function and the CLI, with test 04851_obfuscator_frequency_add_overflow.sh.

…rithmetic

On Darwin and Wasm, `size_t` is `unsigned long` while `UInt64` is
`unsigned long long`, so template deduction for `common::addOverflow`
failed with conflicting types when mixing `params.frequency_add`
(`size_t`) with the `UInt64` histogram counters. Use an explicit
`UInt64` copy of the parameter in `MarkovModel::finalize`.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=42701&sha=9cd895fe6428bb4c3f7e8b03951b7071ceb5ffaf&name_0=PR

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

Copy link
Copy Markdown
Member

🕵 The three build reds on 9cd895fe6428 — Build (amd_darwin), Build (arm_darwin), Build (wasm64) — were caused by this PR: on Darwin and Wasm, size_t is unsigned long while UInt64 is unsigned long long, so template deduction for common::addOverflow failed when the recent frequency_add checked-arithmetic fix mixed params.frequency_add (size_t) with the UInt64 histogram counters in MarkovModel::finalize. Fixed in 70e72f0 by using an explicit UInt64 copy of the parameter.

The CH Inc sync red had the same Build (arm_darwin) compile error on the private sync PR, so it should also clear on the next sync run. Its three remaining private test reds are unrelated to this PR: 03469_json_read_subcolumns_combined_2_wide_merge_tree (msan timeout, tracked private issue 62487), 04545_streaming_queries_row_policy_multi_partition (known distributed-cache read-timeout infra flake), and the amd_tsan SharedCatalog hung check (fleet-wide stress pattern).

Comment thread src/Parsers/ASTFunction.cpp Resolved
…obfuscate` in AST JSON

`obfuscate` has the same bare-`SELECT` table-function form as `view`
(`ObfuscateLayer` pushes exactly one `ASTSelectWithUnionQuery` argument, never
parameters, and always emits the canonical lowercase name), but
`ASTFunction::readJSON` applied the matching shape validation and name
canonicalization only to `view` and `viewIfPermitted`.

As a result, a handcrafted `clickhouse_json` payload could build a
parameterized `obfuscate(<SelectWithUnionQuery>)`, which
`ASTFunction::formatImplWithoutAlias` formats through `tryGetQueryArgument`,
silently dropping the parameters on round-trip; and a non-canonical spelling
such as `Obfuscate` survived deserialization even though `TableFunctionFactory`
resolves `obfuscate` case-sensitively.

Extend the existing `view` checks to `obfuscate`: reject any bare-select shape
the parser cannot produce, and canonicalize the name the way the parser does.

New test `04893_obfuscate_ast_json_shape.sql` mirrors
`04828_view_table_function_ast_json_shape.sql`.
Persist `ASTSetQuery::default_settings` in `QueryNode` so remote execution and query-cache decisions retain explicit setting resets.

ClickHouse#42701
@alexey-milovidov

alexey-milovidov commented Aug 15, 2026 •

Copy link
Copy Markdown
Member

🕵 Pushed dd5dccc5719b after merging current master (6306795de31d). The shared Planner cache path now declares Setting::use_query_cache, fixing the compile error that failed both Fast test and Build (arm_tidy). Verified with an incremental clickhouse build and a focused obfuscate table-function query returning 10 rows. The remaining NullableModel review thread is still a compatibility-vs-semantics decision for a maintainer.

Comment thread src/Analyzer/QueryTreeBuilder.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed 87651b4e1d8e to fix the current CI failure in ReplaceQueryParameterVisitor: the SETTINGS node is now cast to ASTSetQuery before accessing query_parameters. The affected translation unit compiles cleanly with the existing build configuration. The only unresolved review thread remains the nullable-model compatibility decision: filtering null placeholders would change deterministic output of the released clickhouse obfuscator CLI as well as this table function, so it needs a maintainer decision on compatibility versus changed nullable semantics.

Comment thread src/Common/Obfuscator/Models.h Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Superseded by #115004 from the main repository. It preserves this PR’s implementation, review fixes, and credits @evillique; please continue review there.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Closing as superseded by #115004.

pull Bot pushed a commit to Lobinson1/ClickHouse that referenced this pull request Aug 29, 2026
On an ASan build, a stateless run that aborts on the hung check records no
stack of the hung server anywhere:

    Hung check failed: server is not responding
    Cannot collect C stacktraces under ASan: debugger attach is disabled.

Two things combine to produce that. print_c_stacktraces declines to attach
lldb on ASan builds, because a ptrace attach disables LeakSanitizer for the
rest of the process; that refusal is correct and stays. And
print_sql_stacktraces, the collector that needs no debugger at all, was
unreachable in this state: its availability pre-check went through
check_server_liveness, which probes HTTP on http_port (default 8123), while
the collector itself shells out to args.client on the native TCP port
(default 9000). Those are different listeners on different ports served by
different code paths, so a server whose HTTP endpoint is wedged or whose
handler pool is exhausted while TCP still answers queries failed the gate and
was never asked. That is precisely the reported signature: the process alive,
not responding. The hung-check abort site did not call the SQL collector in
the first place, and neither did the FailureReason.SERVER_DIED site.

Drop the pre-check and let the bounded TCP query be its own liveness test.
The reason the pre-check existed was to keep "Code: 210 Connection refused"
tracebacks out of every failed run, and that concern is now covered where it
belongs: get_stacktraces_from_clickhouse runs under shell_get_output with
timeout=30, which caps a dead or wedged socket at 30 seconds and reduces a
failure to a single trim_for_log-bounded stderr line with no traceback. The
existing "if bt:" guard still means nothing is written and nothing is claimed
when nothing was collected; an else branch now records that the attempt was
made, so "tried and got nothing" is distinguishable from "never tried".

Then add the SQL dump to the two abort sites that had only the C path. It
goes before the C dump for the reason the per-test timeout handler documents:
dump while the client connections are still up, because once they drop the
server cancels the wedged queries and their threads disappear.

A server-side alternative was considered and rejected. Sending SIGTSTP so the
server logs its own stacks would work mechanically, but onFault emits its
report at LOG_FATAL, check_fatal_messages_in_logs greps for any <Fatal> line
and appends a result carrying Result.Label.BLOCKER, and FuzzerLogParser
classifies "Received signal" as a signal failure. The diagnostic would have
manufactured a merge-blocking failure out of itself, which is worse than the
present silence. Teaching those scanners a benign exception was rejected too:
six independent consumers key on those strings, so it would weaken real-crash
detection in six places for a diagnostic gain. Nothing in this change writes
to the server log.

This does not fix any hang, and it does not restore C++ stacks on ASan
builds. What it changes is that a server alive but not answering HTTP now
yields the full system.stack_trace view with per-thread thread_name and
query_id, which identifies the query that wedged the server.

Measured on a live server, with HTTP dead and TCP live: master skips and
writes nothing, this change writes a 357 KB sql_stacktraces.log carrying
thread_name and query_id. An abort with HTTP wedged rather than closed gets
9.7 seconds faster, because the pre-check itself blocked for 10 seconds and
then collected nothing; the worst case is 20 seconds slower when both
transports are wedged, bounded by timeout=30. Green runs are unaffected,
since no caller runs on a passing test.

Regression coverage goes in the existing ci/tests/test_print_stacktraces.py.
The oracles key on the sql_stacktraces.log artifact and its columns, or on
per-site call order, never on stdout: the unfixed code, the rejected
call-site-only variant, and print_c_stacktraces all print lines, so a test
asserting that some output appeared would pass in every case and measure
nothing. The two abort sites are asserted independently, because the per-test
timeout handler and the end-of-run hung-query check already called both
collectors and would otherwise mask a revert of either new site.

Related: ClickHouse#42701
Related: ClickHouse#112265
alexey-milovidov added a commit to niyue/ClickHouse that referenced this pull request Oct 6, 2026
The second-pass vector search optimization (`vector_search_with_rescoring = 0`)
removed the distance function from the `ExpressionStep` outputs and re-appended
the rewritten `_distance` alias at the end, changing the header column order.
Steps created above the `Sorting` before the rewrite runs - the local top-N
`Limit` and the exchange steps of a distributed plan - kept the original order,
and `makeDistributedPlan` failed to rebuild the plan fragments with a logical
error: "Cannot add step Limit to QueryPlan because it has incompatible header
with root step Sorting". Reinsert the rewritten output at the original position
instead.

Found by AST fuzzer:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=42701&sha=019244e0d46b4d9029fc261a549e1c5cd79b1bbb&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29
ClickHouse#42701

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

Labels

pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Table function obfuscate

5 participants