Skip to content

Add AI FUNCTIONS privilege group - #127057

Merged
george-larionov merged 31 commits into
masterfrom
ai-functions-rbac-privileges
Nov 7, 2026
Merged

george-larionov merged 31 commits into
masterfrom
ai-functions-rbac-privileges

Conversation

@george-larionov

@george-larionov george-larionov commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Closes: #121411

Calling an AI function previously required only NAMED COLLECTION access to the selected credentials. This adds an explicit entitlement to use AI functionality, independent of credential access.

Each AI function gets its own GLOBAL privilege (aiClassify, aiEmbed, aiExtract, aiFilter, aiGenerate, aiRedact, aiSimilarity, aiTranslate), grouped under AI FUNCTIONS. The check runs in each function's create, i.e. at query analysis time: before any outbound request, also for zero-row queries, and with the usual effective-user semantics for SQL SECURITY DEFINER / INVOKER views and SQL UDFs.

Functions used in expressions stored in a MergeTree table definition (keys, TTL, skip indexes, projections) are now checked against the privileges of the user creating the table. This applies to all function privileges, not only AI ones. Definitions loaded from stored metadata are not checked.

AI functions are not executed with a context without a user, which is the case for merges, mutations and Buffer flushes. They are rejected, even when the user has the privilege, in newly defined MergeTree keys, TTL expressions, skip indexes and projections, in the DEFAULT/MATERIALIZED expression of a column with a TTL or of a column added or modified by ALTER, and in mutations. A background operation that fails on an AI function adds an entry to system.warnings. DEFAULT and MATERIALIZED columns defined at CREATE without a TTL are evaluated by the insert and keep working. To fill a column of existing rows, use a lightweight UPDATE or INSERT ... SELECT instead of ALTER TABLE ... UPDATE.

Changelog category (leave one):

  • Backward Incompatible Change

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

Added the AI FUNCTIONS privilege group and per-function privileges (aiGenerate, aiEmbed, etc.) that control who can call AI functions, e.g. GRANT AI FUNCTIONS ON *.* TO role or GRANT aiGenerate, aiClassify ON *.* TO role. Calling an AI function now requires its privilege in addition to NAMED COLLECTION access to the selected credentials. To keep existing users working, run GRANT AI FUNCTIONS ON *.* TO <user_or_role>. Functions used in the keys, TTL, skip indexes and projections of a new MergeTree table now require the privileges of the user creating the table. AI functions are rejected in newly defined MergeTree keys, TTL expressions, skip indexes and projections, in DEFAULT and MATERIALIZED expressions computed in the background, and in mutations, even when the user has the AI privilege; use a lightweight UPDATE or INSERT ... SELECT instead of ALTER TABLE ... UPDATE to fill a column with AI function results.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1614-master (included in 26.11 and later)

george-larionov and others added 4 commits October 20, 2026 21:04
Per-function privileges (`aiGenerate`, `aiEmbed`, ...) grouped under `AI FUNCTIONS`,
checked when the function is created. Widen `AccessType` to `uint16_t`.

Closes: #121411

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

mintlify Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Oct 30, 2026, 10:55 PM

@clickhouse-gh

clickhouse-gh Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d1c77cd]

Summary: ✅


AI Review

Summary

This PR introduces per-function AI privileges and rejects AI expressions in background operations. Request changes: a definer view loses the new validation marker and allows an unsupported mutation to be persisted. The current head also retains the previously discussed alias-dependency and compatibility failures below. Those author-dismissed findings are recorded here without further inline replies. The column-TTL/default issue is fixed in the current head.

Findings

⚠️ Majors

  • [P1] Definer views bypass mutation submission validation. src/Interpreters/InterpreterAlterQuery.cpp:456 marks the validation context, but StorageInMemoryMetadata::getSQLSecurityOverriddenContext starts a definer view's context from the global context and drops that marker. With allow_nondeterministic_mutations = 1 and mutations_execute_subqueries_on_initiator = 0, ALTER TABLE t UPDATE x = (SELECT s FROM v) WHERE 1 is accepted when v exposes aiGenerate under SQL SECURITY DEFINER. Reproduced with the PR-head CI binary: the mutation is persisted, the worker fails with THERE_IS_NO_QUERY, and synchronous submission returns UNFINISHED. Pending commands can obstruct subsequent mutations of the affected parts. Preserve the marker across SQL-security context changes and reject the command before persistence.

  • [P1] An alias change can introduce an unsupported AI skip index. src/Storages/AlterCommands.cpp:1914 rebuilds retained indexes with the global context. Starting with a String ALIAS x and INDEX i a TYPE minmax, ALTER TABLE t MODIFY COLUMN a String ALIAS toString(aiEmbed(x, 'm')) succeeds, then INSERT INTO t (x) VALUES ('hello') fails with ACCESS_DENIED because the index executes without a user. This deterministic aiEmbed variant was reproduced with the PR-head binary. [dismissed by author -- Add AI FUNCTIONS privilege group #127057 (comment)] The issue remains material because a successful schema change makes a newly created table reject subsequent inserts. Validate the expanded dependencies when an alias changes.

  • [P1] A new stored default can hide an AI call behind an alias. src/Storages/AlterCommands.cpp:2701 validates defaults against column names and types without expanding alias definitions. For a table with a String ALIAS aiGenerate(x) and an existing row, ALTER TABLE t ADD COLUMN d String DEFAULT a succeeds, then SELECT d FROM t fails with ACCESS_DENIED. Reproduced with the PR-head binary; filling the default during merges has the same missing-user path. [dismissed by author -- Add AI FUNCTIONS privilege group #127057 (comment)] The issue remains material because an accepted alter makes existing data unreadable through the new column. Validate the required alias/default dependencies with the background marker.

  • [P2] Materializing an existing AI index still queues a failing mutation. src/Interpreters/MutationsInterpreter.cpp:1343 only rewrites the index expression to collect columns; it does not construct its functions under the marked validation context. For a loaded legacy AI index, MATERIALIZE INDEX therefore persists work that subsequently fails with ACCESS_DENIED. This is source-traced; fresh direct AI index definitions are now rejected. [dismissed by author -- Add AI FUNCTIONS privilege group #127057 (comment)] The issue remains real for upgrades because warning about the worker failure does not remove the pending mutation. Validate the stored expressions the mutation will rebuild before persistence.

  • [P2] Unchanged legacy AI expressions prevent unrelated maintenance. src/Storages/MergeTree/MergeTreeData.cpp:6290 marks every initial alter before AlterCommands::apply rebuilds retained keys, TTL and projections. A loaded legacy table with ORDER BY length(aiEmbed(x, 'm')) consequently rejects an unrelated MODIFY SETTING with NOT_IMPLEMENTED, even for an administrator. The former unchanged-index privilege issue is fixed; this retained-key case is still source-traced. [dismissed by author -- Add AI FUNCTIONS privilege group #127057 (comment)] Loading an old definition successfully does not preserve its maintenance operations. Exempt unchanged expression dependencies or provide an explicit migration path.

  • [P2] Speculative function lookup breaks lambda-alias precedence. src/Functions/aiGenerate.cpp:28 checks the new privilege while tryGetRegisteredFunctionArity is still probing a bare identifier before alias resolution. Thus WITH (x -> x + 1) AS aiGenerate SELECT arrayMap(aiGenerate, [1]) requires an AI grant despite performing only arithmetic. This remains source-traced and is tracked separately in Alias named like a function with an access check fails with ACCESS_DENIED #128160. [dismissed by author -- Add AI FUNCTIONS privilege group #127057 (comment)] Failing closed still changes valid non-AI queries. Preserve alias precedence before constructing the privileged built-in.

Tests
  • ⚠️ Add a stateless definer-view mutation case with mutations_execute_subqueries_on_initiator = 0, asserting immediate rejection, no pending entry in system.mutations, and successful completion of a following ordinary mutation. The focused PR-head binary reproduction above demonstrates the current failure; it is not covered by the added direct-expression and SQL-UDF cases.
  • ⚠️ Add focused rejection cases for changing an indexed alias to a deterministic AI expression and introducing a stored default through an AI alias. Both failures were reproduced on the PR-head binary.
Final Verdict

Status: ⚠️ Request changes. Preserve background-validation state across definer views and validate indirect expression dependencies before committing mutations or metadata. The dismissed upgrade and alias-precedence concerns remain listed for an explicit merge decision; no further replies were posted on those threads.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Oct 20, 2026
Comment thread src/Access/Common/AccessType.h Resolved
@george-larionov

Copy link
Copy Markdown
Member Author

cc @rschu1ze @ayakovlev-clickhouse

@clickhouse-gh clickhouse-gh Bot added the comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. label Oct 20, 2026
Comment thread src/Functions/aiGenerate.cpp Resolved
@george-larionov george-larionov added the pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard label Oct 21, 2026

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 changes here are needed because the docs regenerator only runs nightly on master, and so links to autogenerated sections wouldn't work in this PR, and fail the Docs check.

Comment thread src/Functions/aiEmbed.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d1c77cd07 with master 6d8c8e920 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

270 object files changed (+135.24 KiB total), 0 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionBaseAI.cpp.o 528.63 KiB 562.91 KiB +34.29 KiB (+6.49%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeData.cpp.o 4.40 MiB 4.42 MiB +28.64 KiB (+0.64%)
src/CMakeFiles/dbms.dir/Storages/AlterCommands.cpp.o 811.10 KiB 835.20 KiB +24.10 KiB (+2.97%)
src/CMakeFiles/dbms.dir/Interpreters/InterpreterDeleteQuery.cpp.o 174.03 KiB 194.55 KiB +20.52 KiB (+11.79%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

1540 translation units recompiled, 10369 s compile time in total, 1539 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.8 s

Job report

…he defining user

Keys, TTL, indices and projections are built with the global context, so function
access checks in them passed for any user. Create each function with the query context
when a table is defined.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added pr-backward-incompatible Pull request with backwards incompatible changes and removed pr-feature Pull request with new product feature labels Oct 22, 2026
@Manerone Manerone self-assigned this Oct 23, 2026

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

From my point of view the PR is good. I left some comments that Claude pointed out.

  • Distributed sharding key is open. It's built with the server's full-access context, so cityHash64(aiGenerate(...)) is never checked, and every INSERT then calls the AI provider.

Comment on lines +749 to +754
if (is_fresh_definition && !is_ddl_replay && !is_stored_definition)
{
checkAccessToFunctions(*args.storage_def, args.getLocalContext());
if (args.query.columns_list)
checkAccessToFunctions(*args.query.columns_list, args.getLocalContext());
}

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.

Claude complained about this, I think it is also fine to handle this in another PR:

Doesn't check the user on Replicated databases or ON CLUSTER. There, CREATE TABLE runs under a server context with no user unless distributed_ddl_use_initial_user_and_roles is set, and it defaults to false. So the check passes for everyone. ALTERs that aren't mutations (MODIFY TTL, ADD INDEX, etc.) have the same gap. Fix: run the check in InterpreterCreateQuery/InterpreterAlterQuery with the user's context, before the query is handed off to replicas.

@george-larionov george-larionov Oct 23, 2026 •

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.

…ions`

CI enables `table_engines_require_grant`, so the denials came from the missing engine grant.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
static FunctionPtr create(ContextPtr context_) { return std::make_shared<FunctionAiGenerate>(context_); }
static FunctionPtr create(ContextPtr context_)
{
context_->checkAccess(AccessType::aiGenerate);

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.

⚠️ Preserve lambda-alias precedence when adding this check.

create is also reached by the analyzer's speculative arity lookup, before it knows whether the identifier names this built-in. In src/Analyzer/Resolve/resolveFunction.cpp, tryGetRegisteredFunctionArity calls FunctionFactory::tryGet at line 141, and the bare-function rewrite calls that helper at line 2251 before checking column/lambda aliases at lines 2280–2286. Consequently, a user without the new grant cannot run this ordinary arithmetic query:

WITH (x -> x + 1) AS aiGenerate
SELECT arrayMap(aiGenerate, [1]);

It should return [2], but the speculative lookup creates the built-in and throws ACCESS_DENIED, although the query never calls an AI function. The same problem applies to the other newly guarded names.

Please make the probe preserve alias precedence without constructing a privileged built-in first, while retaining the check when an actual AI call is resolved. Add a negative-privilege regression case for this alias-only query alongside the existing denial cases.

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.

Confirmed. The introspection functions are affected the same way, and the query fails closed, so it is tracked separately: #128160

@george-larionov

george-larionov commented Oct 24, 2026 •

Copy link
Copy Markdown
Member Author

Distributed sharding key is open. It's built with the server's full-access context, so cityHash64(aiGenerate(...)) is never checked, and every INSERT then calls the AI provider.

@Manerone Good catch, but it's also not specific to this PR so I think it should be fixed in a separate one, I added a comment on https://github.com/ClickHouse/clickhouse-private/issues/83375.

@george-larionov george-larionov changed the title Add AI FUNCTIONS privilege group for AI functions Add AI FUNCTIONS privilege group Oct 28, 2026
…y context

Replaces the AST walk, which missed `TTL ... GROUP BY ... SET` assignments.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 7, 2026
george-larionov added a commit that referenced this pull request Nov 7, 2026
Keep 26.8's `validate_mutation_query` gate, `checkAlterIsPossible` and grant parser (no generated docs on 26.8).
Use `isRecoveryFromStoredMetadata` and the ZooKeeper transaction for the fresh-definition check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-ch-test-poll added a commit that referenced this pull request Nov 7, 2026
Cherry pick #127057 to 26.8: Add AI FUNCTIONS privilege group
george-larionov added a commit that referenced this pull request Nov 7, 2026
Keep 26.9's `validate_mutation_query` gate and generated `grant.mdx`; drop master-only neighbours of the new members and checks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-ch-test-poll4 added a commit that referenced this pull request Nov 7, 2026
Cherry pick #127057 to 26.9: Add AI FUNCTIONS privilege group
george-larionov added a commit that referenced this pull request Nov 7, 2026
Keep 26.10's generated `grant.mdx`; drop master-only neighbours of the new lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-clickhouse added a commit that referenced this pull request Nov 7, 2026
Cherry pick #127057 to 26.10: Add AI FUNCTIONS privilege group
@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 Nov 7, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 7, 2026
Backport #127057 to 26.8: Add AI FUNCTIONS privilege group
clickhouse-gh Bot added a commit that referenced this pull request Nov 7, 2026
Backport #127057 to 26.9: Add AI FUNCTIONS privilege group
clickhouse-gh Bot added a commit that referenced this pull request Nov 7, 2026
Backport #127057 to 26.10: Add AI FUNCTIONS privilege group
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 9, 2026
…e ALTER's session

`AlterCommands::apply` re-derived the sorting, primary and partition keys and the
`minmax_count` projection in the context of the session that issued the `ALTER`,
while `CREATE`, a reload of the table and the part writers derive them in the
global context. A session setting that changes key analysis therefore installed
in-memory keys that the table does not really have.

With `transform_null_in = 1`, `in` is rewritten to `nullIn`, which renames the key
column and, for a `Nullable` argument, changes its type from `Nullable(UInt8)` to
`UInt8`. After such an `ALTER` (even a comment-only one):
- an INSERT into a table with a Nullable key under `IN` serialized the writer's
  `ColumnNullable` with the stored `UInt8` serialization: `Bad cast from type
  DB::ColumnNullable to DB::ColumnVector<char8_t>` in debug builds, a primary index
  of garbage bytes in release builds;
- every merge failed with `NOT_FOUND_COLUMN_IN_BLOCK: Not found column in(x, ...)`;
- a partition key wrote `partition.dat` with the session type, so after a restart
  the parts were detached as `broken-on-start`.

Derive these keys in the global context, as ClickHouse#119799 already does for skip indices
in the same function, and carry `isAnalyzingBackgroundExpressions` into it so that
AI functions stay rejected in keys (ClickHouse#127057). The sampling key, projections and
column TTLs keep the session context: the sampling key is re-analysed in the query
context at read time, and projections and TTLs are separate derivations.

Found by the targeted AST fuzzer on PR ClickHouse#130066 (STID 1499-5685).

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

@rschu1ze rschu1ze left a comment

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.


Calling an AI function requires two privileges:

- the function's privilege: either the per-function privilege (e.g. `aiGenerate`) or the `AI FUNCTIONS` group, see [`GRANT`](/reference/statements/grant#ai-functions);

@rschu1ze rschu1ze Nov 6, 2026 •

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.

Per-function privileges seem honestly too fine-granular. The purpose of the privilege (group) is to prevent unintended costly remote LLM calls. All AI functions do such calls. I doubt that DBAs would need more flexibility than just saying "Allow all remote LLM calls or forbid them.".

Could we please have just a single privilege AI FUNCTIONS? If someone asks for more fine-granular configurability, we can add that later.

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.

This is already possible with the current change, a user can just grant the AI FUNCTIONS privilege. The fine-grained privileges are included "for free" so I don't see any reason to remove them. This is how other privileges are implemented as well.

/// Set for CREATE queries a Replicated database replays from a definition it already stored.
/// Such a definition describes existing state, so validation that may reject a new one must not run.
bool is_recovery_from_stored_metadata = false;
/// Set while analyzing expressions that are executed later in the background, without a user:

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.

Could we check if the information whether we are in a background operation by already existing means instead of introducing another state variable merely for the AI functions to context?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-backward-incompatible Pull request with backwards incompatible changes pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AI functions: add RBAC privileges for executing a function

6 participants