Repository navigation
Support the NetCDF format - #111932
Support the NetCDF format#111932alexey-milovidov wants to merge 159 commits into
Conversation
`NetCDF` is a self-describing binary format for multidimensional arrays, used mostly for climate, weather, oceanographic and other scientific data. Both reading and writing are supported for the three "classic" versions of the format: CDF-1, CDF-2 (64-bit offset) and CDF-5 (64-bit data). They are parsed directly, without a new dependency. A NetCDF-4 file, which is an HDF5 file with a different data model on top, is recognized and reported with a message that says how to convert it. Every variable of a file becomes a column, and the rows enumerate the Cartesian product of all the dimensions that the variables use; a variable that does not use some of them is repeated along them. This is the same table that the `to_dataframe` method of `xarray` produces. A `char` variable is read as a String whose length is the last dimension of the variable. Only the variables that a query needs are read, the number of rows comes from the header, and an input that cannot be seeked is read into memory instead. On output every column becomes a variable over a single dimension named `row`, so a file written by ClickHouse is read back with the same structure. The version of the format is chosen automatically. A `Nullable` column is written with the `_FillValue` attribute, and a column with dates or times gets the `units` attribute of the CF conventions. Two settings control the reading: `input_format_netcdf_fill_value_as_null` reads the values equal to the `_FillValue` or `missing_value` attribute of a variable as NULL, and `input_format_netcdf_add_dimension_columns` adds a column with the index along every dimension that has no coordinate variable of the same name. The test files were written by the netCDF C library, and the output of the new format was checked by opening it with that library.
|
Workflow [PR], commit [941725e] Summary: ❌
AI ReviewSummaryAdds reading and writing of classic Findings
💡 Nits
Tests
Missing context / blind spots
Final VerdictStatus: Remove the quadratic dimension-name search and add focused regression coverage for the enabled setting. |
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
- The value that a `Nullable` column writes its `NULL`s as is now chosen from the data of the column: the default fill value of the netCDF library is only the first candidate, and a value that the column actually contains is never used, so a value is never read back as a `NULL` with `input_format_netcdf_fill_value_as_null = 1`. - A file that does not store the number of records and whose record section is not a whole number of records is truncated, and is now rejected with `INCORRECT_DATA` instead of silently losing the last row. - `checkName` now applies the rules of the classic format for the first character of a name and for the trailing spaces, so that a quoted ClickHouse identifier cannot produce a file that other readers reject. - `input_format_netcdf_add_dimension_columns` now skips a dimension only when it has a real coordinate variable - a variable with the name of the dimension that is one-dimensional over it. A variable that merely shares the name no longer hides the index along the dimension, which is added as a column named after the dimension with the `_index` suffix. Add `04644_netcdf_names_and_truncation` with a regression for each of these, and fix the two all-formats tests: `NetCDF` was missing from the reference of `03251_insert_sparse_all_formats`, and `02187_async_inserts_all_formats` has an `Array` column that the format cannot store, which made its HTTP client retry for the whole timeout.
The dispatch of `chooseFillValue` for a `DateTime64` column still passed the name of the column, which the function no longer takes.
|
Addressed the review in a85b0d4:
The two red all-formats tests were mine: |
- The name of a generated dimension column is now deconflicted against the names of the columns that were generated before it as well, not only against the names of the variables, so a file with the dimensions `x` and `x_index` and a variable named `x` no longer produces two columns named `x_index`, of which only the first one would be reachable. - `chooseFillValue` no longer builds a set of every value of the column. It checks a window of candidate bit patterns against the data at a time, so the memory of the search does not depend on the size of the data; a window where every candidate is taken proves that the data has at least that many distinct values, and the window doubles, so the number of passes is logarithmic. - The two new settings move to the `26.8` section of the settings changes history, which is what the `Upgrade check` compares against now that `26.7` is released. The new test `04651_netcdf_dimension_column_collision` writes the file with the colliding names, which the netCDF library cannot produce.
|
Addressed the two findings of the review in 5b28b46, on top of a merge of master:
The The remaining two failures are of master and are not related to this format: |
- The reader no longer validates the declared size of a variable. `CDF-2` writes all ones there for variables larger than 4 GiB, and that sentinel does not fit into the signed 32-bit field, so a valid large file was rejected while parsing the header. The size is recalculated from the dimensions anyway. - The writer picks `CDF-5` whenever any header field that is written as a 32-bit value does not fit into it - the lengths of the dimensions and the padded size of a variable - instead of looking only at the unpadded size of the data. A large one-byte column used to be written as a malformed `CDF-2` file. - A `NULL` in a `Nullable(String)` or `Nullable(FixedString)` column is written as an empty string, as documented. The data under the null map of a `ColumnNullable` is arbitrary, and it used to be written out as is, and to stretch the dimension that holds the length of the strings.
`04652` writes a `Nullable(String)` and a `Nullable(FixedString)` whose values under the NULLs are longer than every value that is not NULL, and `04653` reads a `CDF-2` file that declares the size of its variable as all ones. The computation of the size of the domain in `chooseFillValue` shifted by the width of the type in the branch that is not taken for a 64-bit type, which some versions of `clang` reject with `-Wshift-count-overflow`.
|
All three blockers of the AI review are addressed in
New tests: Also fixed a shift by the width of the type in |
…a zero byte Two fixes for the review findings on #111932: - The duplicate-dimension check kept `string_view`s into `header.dimensions` while the vector was still growing, so after the 1024th dimension a reallocation dangled every stored view. The set now owns the names. - The reader trims trailing zero bytes from `char` values because the format pads shorter strings with them, so a `String` or `FixedString` value that itself ends in a zero byte could not be read back intact. The writer now throws `BAD_ARGUMENTS` for such a value instead of silently corrupting it, and the documentation states the restriction. The test 04652 used zero-padded `FixedString(2)` values, which is exactly the lossy round trip that is now rejected, so it uses full-width values now. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Both CI failures on
The two remaining review blockers (dangling |
|
Confirmed. This run is the instance #129283 was built from. Its #129283 was merged at 15:07Z today (bf8a735). Neither 729dca1 nor the current head 25ac42e (the 14:30Z master merge) contains it. |
Conflicts in the generated docs files `FormatSettingsExplorer.jsx` and `settings-legacy-routes/format-settings.js` are resolved by taking the master version and adding the two `input_format_netcdf_*` settings of this PR to it.
|
🕵 Thanks for confirming. Merged |
The test spent most of its time waiting for the client, limited to 1 MB/s, to drain several MB already buffered in the sockets after the query was killed, so it took more than 15 seconds in the fast test. Stop the client right after `KILL QUERY SYNC` returns and check on the server side, in `system.query_log`, that the query was cancelled and sent less than the complete file (`NetworkSendBytes`). https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111932&sha=975b6ee83d5f3e8b477d5e34907bb6c98578bee8&name_0=PR&name_1=Fast%20test #111932 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged |
Conflicts: `FormatSettings.h` (kept the `netcdf` struct; `UnsupportedGeometryHandling` moved to `FormatSettingsEnums.h` on master), and the autogenerated format-settings docs (took master's version and re-added the two `input_format_netcdf_*` entries).
The style check now requires `src/Processors/Formats` to use the `-WithMemoryTracking` aliases instead of standard containers (#126530). CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111932&sha=latest&name_0=PR&name_1=Style%20check PR: #111932 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Fixed the |
Conflicts in the generated format-settings docs were resolved by taking master's version and adding the two `input_format_netcdf_*` entries of this PR. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The reference decoder `netCDF4` treats both `true` and `True` as the value of the `_Unsigned` attribute. Only the lowercase spelling was recognized, so unsigned data with the capitalized spelling was read as negative numbers. `hasUnsignedAttribute` serves both schema inference and materialization. Add a regression test with a CDF-1 `short` variable, values above the signed range and a `_FillValue` sentinel; the expected output was cross-checked with `netCDF4` / libnetcdf. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…up in `NetCDF`
The text of the `_Unsigned` attribute is matched after removing its zero
bytes, as the reference decoder `netCDF4` does: a C writer that passes
`sizeof("true")` to `nc_put_att_text` stores `true\0`, which used to leave
the variable signed.
The sentinels of `_FillValue` and `missing_value` of a numeric variable are
prepared once per variable, sorted and deduplicated, and every value is looked
up by a binary search. Previously every value was compared to every sentinel,
so a `missing_value` of a million values made a chunk take
`rows * sentinels` comparisons and kept the query running far beyond
`max_execution_time`. The preparation observes cancellation.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # docs/_site/customizations/settings-legacy-routes/format-settings.js # docs/snippets/components/FormatSettingsExplorer/FormatSettingsExplorer.jsx # tests/queries/0_stateless/02187_async_inserts_all_formats.python
The reader decodes the `NON_NEG` fields of CDF-2 as unsigned 32-bit values, as the reference implementation does, but the writer switched to CDF-5 as soon as a header field exceeded `Int32` max. Write these fields as `UInt32` and bound them by `2^32 - 4` (the dimension-length limit of CDF-2 in the reference library), so the files stay readable by the readers without CDF-5 support. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… docs - A `char` variable read as one character per row compared every value with every byte of its `_FillValue` / `missing_value` attributes, which took `rows * attribute bytes` comparisons. Its sentinels are now prepared once per variable like those of a numeric column (deduplicated by a 256-entry bitmap) and looked up by a binary search. Add `05830_netcdf_char_many_missing_values`. - Fix `clang-tidy` errors (`cppcoreguidelines-init-variables`, `readability-redundant-casting`) in `prepareNullValues`. - Update the links in the `NetCDF` documentation sources to the current `/reference/...` layout and regenerate the docs, which now include `input_format_netcdf_allow_missing_columns`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflicts in the generated `format-settings.js` and `FormatSettingsExplorer.jsx`: both sides added `output_format_arrow_variant_as_json_string` and `output_format_parquet_data_page_row_limit`, and the branch additionally has the three `input_format_netcdf_*` settings, so the branch side is a superset and is kept. Co-Authored-By: Claude Fable 5.2 <[email protected]>
`orderRowAxes` scanned all the axes from the first one for every axis it placed. The number of axes is not bounded by the amount of data, because every repeated use of a dimension is an axis of its own and a dimension of length one adds neither rows nor bytes, so a file of one row and a couple of megabytes could take hundreds of billions of steps. Keep the axes that have no unordered predecessor in a priority queue, and find the axis that breaks a contradictory order with a position that only moves forward. The order is the same as before. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…odiscard]]` The `arm_tidy` builds failed with `modernize-use-nodiscard`: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111932&sha=e1022a3e6b63e164df094389c120dcc5360292e6&name_0=PR&name_1=Build%20%28arm_tidy%2C%201%2F4%29 #111932 Co-Authored-By: Claude Fable 5.2 <[email protected]>
# Conflicts: # docs/_site/customizations/settings-legacy-routes/format-settings.js # docs/snippets/components/FormatSettingsExplorer/FormatSettingsExplorer.jsx
`cppcoreguidelines-init-variables` failed the `arm_tidy` build on the variable that both branches assign before use. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111932&sha=637c35d68a6840a9f3e027f0a7cab5627223bb25&name_0=PR&name_1=Build%20%28arm_tidy%2C%203%2F4%29 #111932 Co-Authored-By: Claude Fable 5.2 <[email protected]>
The version on master is now 26.12, so the style check `settings_changes_history` requires the records of `input_format_netcdf_fill_value_as_null`, `input_format_netcdf_add_dimension_columns` and `input_format_netcdf_allow_missing_columns` to be under `26.12` instead of `26.11`. The generated version history in the documentation is updated to match. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111932&sha=637c35d68a6840a9f3e027f0a7cab5627223bb25&name_0=PR&name_1=Style%20check #111932 Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Merged Fixed the two CI failures:
The merged tree builds locally, and the 53 |
| for (size_t attempt = 1; used_column_names.contains(column_name); ++attempt) | ||
| column_name = dimension.name + "_index" + (attempt == 1 ? "" : "_" + std::to_string(attempt)); |
There was a problem hiding this comment.
[Major] Avoid quadratic suffix searches for repeated dimension axes
The suffix search starts over for every occurrence of a dimension. An accepted 262,224-byte CDF-1 file with one dimension d = 1, an Int32 variable v using d 65,536 times, and one value represents just one row. With input_format_netcdf_add_dimension_columns = 1, generating d, d_index, …, d_index_65535 performs 2,147,516,416 name probes here. Even an explicit structure containing only v reaches this work, because the entire layout is constructed before requested columns are selected. The loop does not check cancellation.
Please retain the next suffix per base name while preserving collision checks against all existing names, and cover repeated unit dimensions with this setting enabled. 05839_netcdf_many_unit_axes currently leaves the setting disabled. This finding follows from the current code; no local execution timing is claimed.
Adds support for the NetCDF format, a self-describing binary format for multidimensional arrays that is the standard way climate, weather, oceanographic and other scientific data is distributed. There is a lot of public data in it (ERA5, CMIP, NOAA, Copernicus), and until now the only way to query it with ClickHouse was to convert it first.
Reading is supported for the three "classic" versions of the format: CDF-1, CDF-2 (64-bit offset) and CDF-5 (64-bit data), and writing produces CDF-2 or CDF-5, whichever the data needs. The files are parsed directly, so there is no new dependency. A NetCDF-4 file, which is an HDF5 file with a different data model on top, is recognized and reported with a message that says how to convert it.
Data model. Every variable of a file becomes a column, and the rows enumerate the Cartesian product of all the dimensions that the variables use; a variable that does not use some of them is repeated along them. The
to_dataframemethod ofxarrayproduces a table with the same columns and the same set of rows, though possibly in a different order:to_dataframeputs the dimensions in alphabetical order by default, while ClickHouse keeps the order of the dimensions of the variables. So a file with the dimensionstime,lat,lonand the variablestime(time),lat(lat),lon(lon),temperature(time, lat, lon)reads as a table with four columns andtime * lat * lonrows. The classic format has no string type, so acharvariable is read as a String whose length is the last dimension of the variable, when that dimension serves only as the length of the strings; a dimension that anything else in the file uses as a real axis stays in the row space, and such acharvariable is read as one character per row.Only the variables that a query needs are read, the number of rows comes from the header (so
count()does not read any data), and an input that cannot be seeked is read into memory instead.Writing. Every column becomes a variable over a single dimension named
row, so a file written by ClickHouse is read back with the same column names and the same rows; the types come back as the closest types of the classic format (aFixedStringas aString, anEnumor aLowCardinalitycolumn as the type it wraps, dates and times as plain numbers, aNullablecolumn as its base type unless read withinput_format_netcdf_fill_value_as_null). The version of the format is chosen automatically: CDF-5 when a column needs a type that only CDF-5 has or takes more than 4 GiB, CDF-2 otherwise. ANullablecolumn that contains aNULLis written with the_FillValueattribute, and a column with dates or times gets theunitsattribute of the CF conventions, soxarraydecodes it back into timestamps.Settings.
input_format_netcdf_fill_value_as_nullreads the values equal to the_FillValue(ormissing_value) attribute of a variable as NULL, which is how the CF conventions mark missing data such as sea surface temperature over land.input_format_netcdf_add_dimension_columnsadds a column with the index along every dimension that has no coordinate variable of the same name, for the files that have none.Testing. The test files in
tests/queries/0_stateless/data_netcdfwere written by the netCDF C library, not by this code. Beyond the two functional tests, during development the reader was compared value by value against an independent reference implementation for all three format versions, the output was checked by opening it with the netCDF C library for every supported type family, and 321 truncated and bit-flipped files were fed to the reader — all of them either parsed or failed with a clean error, with no crashes.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Support the
NetCDFformat for both reading and writing. It is a self-describing binary format for multidimensional arrays, widely used for climate, weather and other scientific data. Reading supports all three classic versions of the format (CDF-1, CDF-2 and CDF-5), and writing produces CDF-2 or CDF-5, whichever the data needs.Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/111932]