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

Improve JSONEachRowRowInputFormat by skipping all remaining fields when all required fields are read #62210

Merged
merged 14 commits into from
Apr 17, 2024

Conversation

lgbo-ustc
Copy link
Contributor

@lgbo-ustc lgbo-ustc commented Apr 3, 2024

Changelog category (leave one):

  • Performance Improvement

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

...
When all required fields are read, skip all remaining fields directly which can save a lot of comparison.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Information about CI checks: https://clickhouse.com/docs/en/development/continuous-integration/


Modify your CI run:

NOTE: If your merge the PR with modified CI you MUST KNOW what you are doing
NOTE: Checked options will be applied if set before CI RunConfig/PrepareRunConfig step

Include tests (required builds will be added automatically):

  • Fast test
  • Integration Tests
  • Stateless tests
  • Stateful tests
  • Unit tests
  • Performance tests
  • All with ASAN
  • All with TSAN
  • All with Analyzer
  • Add your option here

Exclude tests:

  • Fast test
  • Integration Tests
  • Stateless tests
  • Stateful tests
  • Performance tests
  • All with ASAN
  • All with TSAN
  • All with MSAN
  • All with UBSAN
  • All with Coverage
  • All with Aarch64
  • Add your option here

Extra options:

  • do not test (only style check)
  • disable merge-commit (no merge from master before tests)
  • disable CI cache (job reuse)

Only specified batches in multi-batch jobs:

  • 1
  • 2
  • 3
  • 4

@lgbo-ustc
Copy link
Contributor Author

some test results

select count(uid) from
file('test.json', 'JSONEachRow', 'uid Nullable(String), latency Nullable(Int32), _region Nullable(String), shard Nullable(Int32)') settings max_threads=2
  • before
1 row in set. Elapsed: 1.919 sec. Processed 4.26 million rows, 663.47 MB (2.22 million rows/s., 345.82 MB/s.)

  • after
1 row in set. Elapsed: 1.146 sec. Processed 4.26 million rows, 663.47 MB (3.71 million rows/s., 578.76 MB/s.)

@lgbo-ustc lgbo-ustc force-pushed the json_format_early_skip branch 2 times, most recently from d5ed872 to 4fd2fc8 Compare April 3, 2024 02:17
@lgbo-ustc lgbo-ustc marked this pull request as ready for review April 3, 2024 02:21
@lgbo-ustc lgbo-ustc marked this pull request as draft April 3, 2024 02:23
@lgbo-ustc lgbo-ustc marked this pull request as ready for review April 3, 2024 02:30
@antaljanosbenjamin antaljanosbenjamin self-assigned this Apr 3, 2024
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-performance Pull request with some performance improvements label Apr 3, 2024
@robot-clickhouse-ci-1
Copy link
Contributor

robot-clickhouse-ci-1 commented Apr 3, 2024

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

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

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
Stress testRuns stateless functional tests concurrently from several clients to detect concurrency-related errors❌ failure
Successful checks
Check nameDescriptionStatus
A SyncThere's no description for the check yet, please add it to tests/ci/ci_config.py:CHECK_DESCRIPTIONS✅ success
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
ClickBenchRuns [ClickBench](https://github.com/ClickHouse/ClickBench/) with instant-attach table✅ 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 keeper imageThe check to build and optionally push the mentioned image to docker hub✅ success
Docker server imageThe check to build and optionally push the mentioned image to docker hub✅ success
Docs checkBuilds and tests the documentation✅ 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
PR CheckThere's no description for the check yet, please add it to tests/ci/ci_config.py:CHECK_DESCRIPTIONS✅ success
Performance ComparisonMeasure changes in query performance. The performance test report is described in detail here. In square brackets are the optional part/total tests✅ success
Stateful testsRuns stateful functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc✅ success
Stateless testsRuns stateless 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

Copy link
Member

@antaljanosbenjamin antaljanosbenjamin left a comment

Choose a reason for hiding this comment

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

My only concern is with this improvement we might parse invalid JSONs without any issues, e.g. when after the last necessary column there is an invalid JSON field.

As by default input_format_allow_errors_num is 0, I think this might mean that some currently not parsable JSONs become parsable.

I would at least introduce a setting to be able to disable this.

What about other formats, where we can have extra columns? Shouldn't the same logic be implemented for them too?

@antaljanosbenjamin antaljanosbenjamin added the can be tested Allows running workflows for external contributors label Apr 3, 2024
@@ -186,6 +187,11 @@ void JSONEachRowRowInputFormat::readJSONObject(MutableColumns & columns)
JSONUtils::skipColon(*in);
readField(column_index, columns);
}
if (seen_columns_count >= total_columns)
{
skipToUnescapedNextLineOrEOF(*in);
Copy link
Member

@Avogar Avogar Apr 3, 2024

Choose a reason for hiding this comment

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

This is not correct, we need to skip not up to the next line or EOF but to the next } symbol that is not inside quotes and track brackets balance (actually, we also need to do it in syncAfterError), because we support any delimiter betweeen JSON objects.

Copy link
Member

Choose a reason for hiding this comment

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

For example:

select * from format(JSONEachRow, 'a UInt32', '{"a" : 42}, {"a" : 43}')

Copy link
Member

Choose a reason for hiding this comment

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

Also string fields can have \n, and it will break this logic:

select * from format(JSONEachRow, 'a UInt32', '{"a" : 42, "b" : "\n"}, {"a" : 43}')

So yes, we need to skip up to the end of JSON object

Copy link
Member

@Avogar Avogar Apr 3, 2024

Choose a reason for hiding this comment

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

I will create a PR with fix for syncAfterError with proper data skipping

UPD: it's not so obvious as I though, because when some row is a broken JSON we cannot just skip all up to the end of JSON object as there might me no end (as it's broken). So here we just have the easies and best solution - skip up to new line delimiter as in most cases it will work.

But in case of valid JSON we definitely should skip up to the end of JSON object. The similar code how to do it fast can be found in readJSONObjectOrArrayPossiblyInvalid function in ReadHelpers

@Avogar
Copy link
Member

Avogar commented Apr 3, 2024

Totally agree with @antaljanosbenjamin, it should be done under a setting. Also we have setting input_format_skip_unknown_fields that allows to skip unknown keys during parsing, it's enabled by default but we still need to check if it's disabled before skipping any data after all columns are parsed.

@lgbo-ustc
Copy link
Contributor Author

@Avogar @antaljanosbenjamin The way to skip unused fields has been changed. I think it would have the same behavior as before in this way.

@lgbo-ustc
Copy link
Contributor Author

image

@lgbo-ustc lgbo-ustc changed the title Improve JSONEachRowRowInputFormat by skipping to the line end when all fields are read Improve JSONEachRowRowInputFormat by skipping all fields when all fields are read Apr 9, 2024
@lgbo-ustc lgbo-ustc changed the title Improve JSONEachRowRowInputFormat by skipping all fields when all fields are read Improve JSONEachRowRowInputFormat by skipping all fields when all remaining fields are read Apr 9, 2024
@lgbo-ustc lgbo-ustc changed the title Improve JSONEachRowRowInputFormat by skipping all fields when all remaining fields are read Improve JSONEachRowRowInputFormat by skipping all remaining fields when all required fields are read Apr 9, 2024
@lgbo-ustc
Copy link
Contributor Author

Hi @antaljanosbenjamin could you review this again? The latest code just skip all remaining fields without looking up the name_map. If the json is invalid, it could fail as before.

@@ -161,6 +162,12 @@ void JSONEachRowRowInputFormat::readJSONObject(MutableColumns & columns)
for (size_t key_index = 0; advanceToNextKey(key_index); ++key_index)
{
StringRef name_ref = readColumnName(*in);
if (seen_columns_count >= total_columns)
Copy link
Member

Choose a reason for hiding this comment

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

We would skip the duplicated fields check in readField in case we read all columns. Considering that I think we should introduce a new setting to enable that.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done

Copy link
Member

@antaljanosbenjamin antaljanosbenjamin left a comment

Choose a reason for hiding this comment

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

Apart from this tiny change, I am okay with this PR.

@@ -89,6 +89,7 @@ static std::map<ClickHouseVersion, SettingsChangesHistory::SettingsChanges> sett
{"ignore_drop_queries_probability", 0, 0, "Allow to ignore drop queries in server with specified probability for testing purposes"},
{"lightweight_deletes_sync", 2, 2, "The same as 'mutation_sync', but controls only execution of lightweight deletes"},
{"query_cache_system_table_handling", "save", "throw", "The query cache no longer caches results of queries against system tables"},
{"input_format_json_throw_on_duplicated_fields", false, true, "Throw an exception if there are duplicated fields in JSON object in JSON input formats. If disabled, the first field will be used"},
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
{"input_format_json_throw_on_duplicated_fields", false, true, "Throw an exception if there are duplicated fields in JSON object in JSON input formats. If disabled, the first field will be used"},
{"input_format_json_throw_on_duplicated_fields", true, true, "Throw an exception if there are duplicated fields in JSON object in JSON input formats. If disabled, the first field will be used"},

In my understanding previously we thrown an exception, so the previous value of this should true, not false.

@Avogar
Copy link
Member

Avogar commented Apr 11, 2024

Actually, I am not sure about introducing setting input_format_json_throw_on_duplicated_fields, it will be enabled by default and so this new optimization will be disabled by default. But it's a good optimization and I want it to work by default. Maybe we can add a setting for this optimization instead? We will set it to true by default, add to settings changes history and add it to docs with a note that in some cases duplicated fields won't be checked. WDYT?

@antaljanosbenjamin
Copy link
Member

As @Avogar you have much more experience in input formats and how to handle new optimizations, settings, etc, plus I also think this is a nice optimization, I am happy if we enable the optimization by default.

You also made me think again about the setting. And I think you are right: we should have a setting to enable the optimization and not to disable throwing on repeated fields, because right now if the first two fields have the same name, we will still throw an exception regardless of the value of the new setting.

Thanks for jumping in!

@lgbo-ustc My review seems to be a bit bad on this PR, sorry for that. I am still learning about formats and might miss things like this. Please let us know what do you think.

@lgbo-ustc
Copy link
Contributor Author

lgbo-ustc commented Apr 12, 2024

Indeed I want to enable this optimization at default. This optimization is inspired by a case we meet recently, In our actual production applications, json strings with invalid format or duplicated fields are rare.

Copy link
Member

@antaljanosbenjamin antaljanosbenjamin left a comment

Choose a reason for hiding this comment

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

Thanks for the really nice work!

@antaljanosbenjamin
Copy link
Member

Merging this PR.

@antaljanosbenjamin antaljanosbenjamin added this pull request to the merge queue Apr 17, 2024
Merged via the queue into ClickHouse:master with commit 6189cd4 Apr 17, 2024
233 of 240 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
can be tested Allows running workflows for external contributors pr-performance Pull request with some performance improvements 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.

5 participants