Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Engine Merge obeys row policy #50209

Merged
merged 37 commits into from
Nov 25, 2023
Merged

Conversation

ilejn
Copy link
Contributor

@ilejn ilejn commented May 24, 2023

Changelog category (leave one):

  • Improvement

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

Engine Merge filters the records according to the row policies of the underlying tables.

@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-bugfix Pull request with bugfix, not backported by default label May 24, 2023
@robot-ch-test-poll2
Copy link
Contributor

robot-ch-test-poll2 commented May 24, 2023

This is an automated comment for commit c2816ec with description of existing statuses. It's updated for the latest CI running

❌ Click here to open a full report in a separate page

Successful checks
Check nameDescriptionStatus
AST fuzzerRuns randomly generated queries to catch program errors. The build type is optionally given in parenthesis. If it fails, ask a maintainer for help✅ success
ClickHouse build checkBuilds ClickHouse in various configurations for use in further steps. You have to fix the builds that fail. Build logs often has enough information to fix the error, but you might have to reproduce the failure locally. The cmake options can be found in the build log, grepping for cmake. Use these options and follow the general build process✅ success
Compatibility checkChecks that clickhouse binary runs on distributions with old libc versions. If it fails, ask a maintainer for help✅ success
Docker image for serversThe check to build and optionally push the mentioned image to docker hub✅ success
Fast testNormally this is the first check that is ran for a PR. It builds ClickHouse and runs most of stateless functional tests, omitting some. If it fails, further checks are not started until it is fixed. Look at the report to see which tests fail, then reproduce the failure locally as described here✅ success
Flaky testsChecks if new added or modified tests are flaky by running them repeatedly, in parallel, with more randomization. Functional tests are run 100 times with address sanitizer, and additional randomization of thread scheduling. Integrational tests are run up to 10 times. If at least once a new test has failed, or was too long, this check will be red. We don't allow flaky tests, read the doc✅ success
Install packagesChecks that the built packages are installable in a clear environment✅ success
Mergeable CheckChecks if all other necessary checks are successful✅ success
Push to DockerhubThe check for building and pushing the CI related docker images to docker hub✅ success
SQLTestThere's no description for the check yet, please add it to tests/ci/ci_config.py:CHECK_DESCRIPTIONS✅ success
SQLancerFuzzing tests that detect logical bugs with SQLancer tool✅ success
SqllogicRun clickhouse on the sqllogic test set against sqlite and checks that all statements are passed✅ success
Stateful testsRuns stateful functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc✅ success
Style CheckRuns a set of checks to keep the code style clean. If some of tests failed, see the related log from the report✅ success
Unit testsRuns the unit tests for different release types✅ success
Upgrade checkRuns stress tests on server version from last release and then tries to upgrade it to the version from the PR. It checks if the new server can successfully startup without any errors, crashes or sanitizer asserts✅ success
Check nameDescriptionStatus
CI runningA meta-check that indicates the running CI. Normally, it's in success or pending state. The failed status indicates some problems with the PR⏳ pending
Integration testsThe integration tests report. In parenthesis the package type is given, and in square brackets are the optional part/total tests❌ failure
Performance ComparisonMeasure changes in query performance. The performance test report is described in detail here. In square brackets are the optional part/total tests❌ failure
Stateless testsRuns stateless functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc❌ failure
Stress testRuns stateless functional tests concurrently from several clients to detect concurrency-related errors❌ failure

@alexey-milovidov alexey-milovidov removed the pr-bugfix Pull request with bugfix, not backported by default label Jun 1, 2023
@robot-ch-test-poll1 robot-ch-test-poll1 added the pr-improvement Pull request with some product improvements label Jun 6, 2023
@ilejn
Copy link
Contributor Author

ilejn commented Jun 14, 2023

I believe that test failures in 00002_log_and_exception_messages_formatting are irrelevant, although AST fuzzer (ubsan) issue IS relevant.
Fuzzer generated a query
SELECT rand(NULL) % NULL FROM merge(currentDatabase(), '02763_merge_merge_1') PREWHERE (rand(1.1920928955078125e-7) % -0.) % rand(NULL) ORDER BY rand(2) % -1 DESC NULLS FIRST, x DESC NULLS FIRST SETTINGS optimize_move_to_prewhere = 0
which is wrong and produces
Code: 59. DB::Exception: Received from localhost:9000. DB::Exception: Illegal type Float64 of column for filter. Must be UInt8 or Nullable(UInt8) or Const variants of them.: While executing MergeTreeInOrder. (ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER)
on my laptop.
Looking into why it crashes in CI environment.

@ilejn ilejn changed the title WIP Engine Merge obeys row policy Engine Merge obeys row policy Jun 15, 2023
Copy link
Contributor

@Enmk Enmk left a comment

Choose a reason for hiding this comment

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

Please address the comments

required_columns.begin(), required_columns.end(),
std::inserter(filter_columns, filter_columns.begin()));

source_step_with_filter->addFilter(filter_dag_ptr, filter_columns.front());
Copy link
Contributor

Choose a reason for hiding this comment

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

Why only with columns from RBAC that are not required columns? Would filter work properly if there are some required columns in expression?

Copy link
Contributor

Choose a reason for hiding this comment

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

Why only 1 filter, what if there are many columns?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The 'extra' column here is a complex condition that may contain logical operations, something like
'field1 > x and field2 > y'.
That's why only one filter is needed.
I'll try to simulate collision between the column and what is listed in required column, this is an interesting point.

Copy link
Contributor

@Enmk Enmk Jul 10, 2023

Choose a reason for hiding this comment

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

It might be beneficial to put that info into comment for this piece of code

Names filter_columns;

std::set_difference(fa_actions_columns_sorted.begin(), fa_actions_columns_sorted.end(),
required_columns.begin(), required_columns.end(),
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
required_columns.begin(), required_columns.end(),
required_columns_sorted.begin(), required_columns_sorted.end(),

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes, required_columns_sorted must be used, thanks.



std::set_difference(fa_actions_columns_sorted.begin(), fa_actions_columns_sorted.end(),
required_columns.begin(), required_columns.end(),
Copy link
Contributor

Choose a reason for hiding this comment

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

Same here, required_columns_sorted ?

Comment on lines 1054 to 1080
if (row_policy_filter)
{
ASTPtr expr = row_policy_filter->expression;

auto syntax_result = TreeRewriter(local_context).analyze(expr, pipe_columns);
auto expression_analyzer = ExpressionAnalyzer{row_policy_filter->expression, syntax_result, local_context};

auto actions_dag = expression_analyzer.getActionsDAG(true, false);
auto filter_actions = std::make_shared<ExpressionActions>(actions_dag, ExpressionActionsSettings::fromContext(local_context, CompileExpressions::yes));
auto required_columns = filter_actions->getRequiredColumns();

LOG_TRACE(&Poco::Logger::get("ReadFromMerge::convertinfSourceStream"), "filter_actions_dag: {},<> {}, <> {}",
filter_actions->getActionsDAG().dumpNames(), filter_actions->getActionsDAG().dumpDAG(), filter_actions->getSampleBlock().dumpStructure());


auto fa_actions_columns_sorted = filter_actions->getSampleBlock().getNames();
std::sort(fa_actions_columns_sorted.begin(), fa_actions_columns_sorted.end());

Names required_columns_sorted = required_columns;
std::sort(required_columns_sorted.begin(), required_columns_sorted.end());

Names filter_columns;


std::set_difference(fa_actions_columns_sorted.begin(), fa_actions_columns_sorted.end(),
required_columns.begin(), required_columns.end(),
std::inserter(filter_columns, filter_columns.begin()));
Copy link
Contributor

Choose a reason for hiding this comment

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

This looks almost identical to the code block you've added above, maybe factor it out into a function?

Copy link
Contributor

Choose a reason for hiding this comment

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

Maybe also add RBAC based on 2 or more columns?

}

return builder;
}

void ReadFromMerge::RowPolicyData::init(RowPolicyFilterPtr row_policy_filter_ptr_,
const std::shared_ptr<DB::IStorage> storage,
Copy link
Contributor

@Enmk Enmk Jul 17, 2023

Choose a reason for hiding this comment

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

Please remove const here, it breaks the build.

Jul 14 14:16:37 /build/src/Storages/StorageMerge.cpp:391:9: error: parameter 2 is const-qualified in the function declaration; const-qualification of parameters only has an effect in function definitions [readability-avoid-const-params-in-decls,-warnings-as-errors]

https://s3.amazonaws.com/clickhouse-builds/PRs/50209/9739ed2bb4eabf2b20083bc324186d319faf34b7/binary_tidy/build_log.log

@@ -961,8 +1129,14 @@ void ReadFromMerge::convertingSourceStream(
const Aliases & aliases,
ContextPtr local_context,
QueryPipelineBuilder & builder,
const QueryProcessingStage::Enum & processed_stage)
const QueryProcessingStage::Enum & processed_stage,
Copy link
Contributor

Choose a reason for hiding this comment

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

Please remove const here too

@ilejn
Copy link
Contributor Author

ilejn commented Sep 12, 2023

Integration test failures are not related.

Please, review proposed change.

@ilejn ilejn marked this pull request as ready for review September 18, 2023 08:39
@ilejn
Copy link
Contributor Author

ilejn commented Sep 27, 2023

Hello @vitlibar ,
could you please review this PR and/or attract someone's attention to it?

@vitlibar vitlibar self-assigned this Sep 28, 2023

if (row_policy_data.needCare())
{
if (auto * source_step_with_filter = dynamic_cast<SourceStepWithFilter*>((plan.getRootNode()->step.get())))
Copy link
Member

Choose a reason for hiding this comment

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

What if that step is not derived from SourceStepWithFilter?

Copy link
Member

Choose a reason for hiding this comment

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

Please add a comment here that it's an optimization if the storage can use filtering while reading (e.g. MergeTree).

Copy link
Member

Choose a reason for hiding this comment

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

The conditions can be combined to be shorter:

if (plan.isInitialized() and row_policy_data)
{
    if (auto * source_step_with_filter = dynamic_cast<SourceStepWithFilter*>((plan.getRootNode()->step.get())))
        row_policy_data->addStorageFilter(source_step_with_filter);
}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It is not obvious that "The conditions can be combined to be shorter".
Could you explain why you are sure that going further with non initialized plan is safe and makes sense?

{
if (row_policy_data.needCare())
Copy link
Member

Choose a reason for hiding this comment

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

needCare() is not a very clear name. row_policy_data.hasRowPolicy() seems better.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Renamed, although it is usually considered bad practice if a method name contain class name (something like Vector::vector_size).
Nevertheless, let it be 'hasRowPolicy'.

Copy link
Member

Choose a reason for hiding this comment

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

Better remove the method at all, see #50209 (comment)

DROP ROW POLICY IF EXISTS 02763_filter_4 ON 02763_merge_merge_1;
DROP ROW POLICY IF EXISTS 02763_filter_5 ON 02763_merge_fancycols;
DROP ROW POLICY IF EXISTS 02763_filter_6 ON 02763_merge_fancycols;

Copy link
Member

@vitlibar vitlibar Sep 29, 2023

Choose a reason for hiding this comment

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

Could you please write in the description to this PR a very simple example how it worked before your PR and how it's going to work now?

Copy link
Member

Choose a reason for hiding this comment

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

I have made it by myself:

CREATE TABLE tbl1 (x UInt32) ENGINE=MergeTree ORDER BY tuple();
INSERT INTO tbl1 SELECT number AS x FROM numbers(10);
CREATE ROW POLICY r1 ON tbl1 USING x%2==0 TO ALL;
SELECT * FROM tbl1; -- applies the row policy
SELECT * FROM merge('default', 'tbl1'); -- doesn't apply the row policy

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Original behavior is described in the issue
#50163
which is referred.

Copy link
Member

Choose a reason for hiding this comment

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

My example is shorter :)

@ilejn
Copy link
Contributor Author

ilejn commented Oct 24, 2023

Hello @vitlibar , I think I've addressed your comments, except binary search.
I've switched to NamesAndTypesList::getDifference in RowPolicyData ctor , which probably made code more natural.

@ilejn
Copy link
Contributor Author

ilejn commented Nov 1, 2023

Hello @vitlibar , do you have ideas/suggestions what should be improved further?
Should I rebase onto fresh master?

auto storage_columns = storage_metadata_snapshot->getColumns();
auto needed_columns = storage_columns.getAllPhysical();

auto syntax_result = TreeRewriter(local_context).analyze(expr, needed_columns);
Copy link
Member

@vitlibar vitlibar Nov 1, 2023

Choose a reason for hiding this comment

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

Is it ok to use here storage_columns.getAllPhysical() as needed_columns? I mean what if a storage has an alias column and a row policy filter involves that alias? Can you please check that case?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Is it ok to use here storage_columns.getAllPhysical() as needed_columns? I mean what if a storage has an alias column and a row policy filter involves that alias? Can you please check that case?

Very good point, quite possible that it is a mistake. Will check.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Indeed we have an issue here.
But the problem is deeper, Engine Merge is not very good at aliases in general, they seem do not work via function https://fiddle.clickhouse.com/4648fd3d-3c1a-462e-919b-90dafcafc131

Copy link
Contributor Author

@ilejn ilejn Nov 6, 2023

Choose a reason for hiding this comment

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

The problem is even deeper ;) , looks like Engine Merge does not work with tables with different structures. And 'does not work' means gives wrong result.
https://fiddle.clickhouse.com/27a3d1d1-51a4-491c-b6ad-5421c11d1f0b

Sorry, my bad.

Copy link
Contributor Author

@ilejn ilejn Nov 6, 2023

Choose a reason for hiding this comment

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

Summing up issue with alias based row policy.
I've fixed it for cases where Engine Merge is used directly, not via table function merge(). Works ok. Not pushed yet.
I haven't fixed it for merge() yet.
How it looks https://pastila.nl/?00d38392/d68be2ab03fb64572f5a3f1b3bd383b2#2RTThmq3iM6cf1C1nLQVUg==

Alternatively we can

  1. expose alias via merge table function - trivial fix. Can be treated as improvement, but breaks current behavior.
  2. go with this PR further as is and fix alias based row policy for merge() in a separated PR.

Copy link
Member

@vitlibar vitlibar Nov 6, 2023

Choose a reason for hiding this comment

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

expose alias via merge table function - trivial fix. Can be treated as improvement, but breaks current behavior.

I suppose ideally the merge() function should return aliases only if that alias is requested explicitly; or if asterisk is used and asterisk_include_alias_columns is set. Because it's better to be consistent with how we treat aliases for normal tables. But of course if an alias is used in a row policy then it should work no matter if we're going to show that alias to a user or not.

Copy link
Contributor Author

@ilejn ilejn Nov 6, 2023

Choose a reason for hiding this comment

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

I assume that it is easier to have both

  1. merge() properly returning aliases and respecting asterisk_include_alias_columns
  2. alias based row policies working

implemented,
than (2) but not (1).
Working on it.

Copy link
Member

Choose a reason for hiding this comment

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

Of course a better solution is always better, I just suggested to split work between two PRs. But ok, no problem, do it the way you like.

Copy link
Contributor Author

@ilejn ilejn Nov 9, 2023

Choose a reason for hiding this comment

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

The last push brought many changes in terms of lines of code, but actually changes are not significant.
I've introduced processAliases method because I have to add new names (extendNames) before taking care of aliases and it is too much clutter for initializePipeline().
Besides this, I renamed convertingSourceStream to convertAndFilterSourceStream , because filtering is needed in-between.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

asterisk_include_alias_columns is left out of the scope despite my initial intention (and claim).

const StorageWithLockAndName & storage_with_lock,
Aliases & aliases,
const Block & sample_block,
ContextMutablePtr modified_context);
Copy link
Member

@vitlibar vitlibar Nov 13, 2023

Choose a reason for hiding this comment

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

What exactly does the function processAliases() do? I know it's named processAliases but how it processes them? A comment here would be useful.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I've moved this part of code as is, but Ok, I'll try to add some comments.

}

Aliases aliases;
processAliases(real_column_names, storage_with_lock, aliases, sample_block, modified_context);
Copy link
Member

@vitlibar vitlibar Nov 13, 2023

Choose a reason for hiding this comment

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

Maybe it's better to rename processAliases to extractAliases() and make it return Aliases?

}
if (!column_names_as_aliases.empty())
{
real_column_names = column_names_as_aliases;
Copy link
Member

Choose a reason for hiding this comment

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

So it replaces real_column_names only if !column_names_as_aliases.empty()
Such a complicated logic.

Copy link
Member

@vitlibar vitlibar Nov 13, 2023

Choose a reason for hiding this comment

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

Let's make the function processAliases() return column_names_as_aliases as is, and do replace read_column_names not here but in the function which calls processAliases()?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

processAliases should return both Aliases and column_names, that's why non constant references are used.
I think that a more complex approach with std::pair or something does not make real sense here.
If you don't mind I would like to keep processAliases in its current form and to avoid further interference in its logic.

Copy link
Member

@vitlibar vitlibar Nov 15, 2023

Choose a reason for hiding this comment

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

You've made an interference already, it doesn't add too much interference if we pass arguments this way or another. I'm ok with passing results via reference parameters. For me it's just better to avoid parameters which are input and output at the same time - just to make the life easier. So why can't we make column_names_as_aliases a pure output parameter and do this logic in createSource():

QueryPipelineBuilderPtr ReadFromMerge::createSources(...)
{
    ...
    Aliases aliases;
    Names column_names_as_aliases;
    processAliases(context, storage_with_lock, sample_block, modified_context, aliases, column_names_as_aliases);
    if (!column_names_as_aliases.empty())
        real_column_names = column_names_as_aliases;
    ...

Copy link
Contributor Author

Choose a reason for hiding this comment

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

May be because this logic is a part of processing aliases ? ;)

@vitlibar
Copy link
Member

Please resolve the conflict

@ilejn
Copy link
Contributor Author

ilejn commented Nov 15, 2023

Please resolve the conflict

The changes are rather significant.

@@ -42,6 +42,7 @@
02003_WithMergeableStateAfterAggregationAndLimit_LIMIT_BY_LIMIT_OFFSET
02404_memory_bound_merging
02725_agg_projection_resprect_PK
02763_row_policy_storage_merge_alias
Copy link
Member

Choose a reason for hiding this comment

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

Why?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Basically because of

$ grep merge_alias analyzer_tech_debt.txt 
01214_test_storage_merge_aliases_with_where
01925_test_storage_merge_aliases

Aliases in Merge do not work if analyzer enabled.

@vitlibar
Copy link
Member

The build is broken (see). Can you please fix it?

@ilejn
Copy link
Contributor Author

ilejn commented Nov 21, 2023

The build is broken (see). Can you please fix it?

Yes, sure.

@ilejn
Copy link
Contributor Author

ilejn commented Nov 22, 2023

@vitlibar
I've got rid of processAliases because in refactored version there fewer reasons for it.
And no problem of non-const references as a bonus.
To keep balance ;) I've introduced rvalue reference for real_column_names which might be strange but seems the best option to me.

@ilejn
Copy link
Contributor Author

ilejn commented Nov 23, 2023

Test failures are not caused by the proposed changes.

@vitlibar vitlibar merged commit 2e7f314 into ClickHouse:master Nov 25, 2023
319 of 336 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
pr-improvement Pull request with some product improvements
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

6 participants