tinybird-toolset 2.7.4__tar.gz → 2.8.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. {tinybird_toolset-2.7.4/src/tinybird_toolset.egg-info → tinybird_toolset-2.8.1}/PKG-INFO +2 -1
  2. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/README.md +10 -0
  3. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/conf.py +87 -19
  4. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/setup.py +2 -1
  5. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1/src/tinybird_toolset.egg-info}/PKG-INFO +2 -1
  6. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/src/tinybird_toolset.egg-info/requires.txt +1 -0
  7. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/tests/test_check_write_query.py +81 -0
  8. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/tests/test_convert_to_row_binary.py +170 -0
  9. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/tests/test_replace_tables.py +56 -0
  10. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/tests/test_tables.py +8 -0
  11. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/LICENSE +0 -0
  12. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/MANIFEST.in +0 -0
  13. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/setup.cfg +0 -0
  14. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/src/chtoolset/__init__.py +0 -0
  15. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/src/chtoolset/query.py +0 -0
  16. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/src/tinybird_toolset.egg-info/SOURCES.txt +0 -0
  17. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/src/tinybird_toolset.egg-info/dependency_links.txt +0 -0
  18. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/src/tinybird_toolset.egg-info/top_level.txt +0 -0
  19. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/tests/test_check_compatible_types.py +0 -0
  20. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/tests/test_check_ttl_partition_compatibility.py +0 -0
  21. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/tests/test_chquery.py +0 -0
  22. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/tests/test_explain_ast.py +0 -0
  23. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/tests/test_get_columns_from_create_query.py +0 -0
  24. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/tests/test_get_left_table.py +0 -0
  25. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/tests/test_internal_cache.py +0 -0
  26. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/tests/test_normalize_query_keep_names.py +0 -0
  27. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/tests/test_normalize_table_column.py +0 -0
  28. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/tests/test_parse_create_materialized_view_target_table.py +0 -0
  29. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/tests/test_replace_tables_backward_compat.py +0 -0
  30. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/tests/test_rewrite_aggregation_states.py +0 -0
  31. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/tests/test_validate_partition_key.py +0 -0
  32. {tinybird_toolset-2.7.4 → tinybird_toolset-2.8.1}/tests/test_validate_ttl.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tinybird-toolset
3
- Version: 2.7.4
3
+ Version: 2.8.1
4
4
  Home-page: https://gitlab.com/tinybird/clickhouse-toolset
5
5
  Author: Tinybird.co
6
6
  Author-email: support@tinybird.co
@@ -10,6 +10,7 @@ Provides-Extra: test
10
10
  Requires-Dist: pytest; extra == "test"
11
11
  Requires-Dist: pytest-asyncio; extra == "test"
12
12
  Requires-Dist: prettytable; extra == "test"
13
+ Requires-Dist: hypothesis; extra == "test"
13
14
  Dynamic: author
14
15
  Dynamic: author-email
15
16
  Dynamic: home-page
@@ -169,6 +169,16 @@ The best option is to use the Makefile targets which will use virtualenv to inst
169
169
  make test-3.14
170
170
  ```
171
171
 
172
+ ### Run the fuzzers
173
+
174
+ `tests/fuzz` holds property-based (Hypothesis) differential tests that check `RowBinaryEncoder` and the query
175
+ validation against a real ClickHouse: `clickhouse` on PATH locally, the official `clickhouse/clickhouse-server`
176
+ images (25.3, 25.8, 26.3) in CI. See [tests/fuzz/README.md](tests/fuzz/README.md).
177
+
178
+ ```bash
179
+ make fuzz
180
+ ```
181
+
172
182
  ### Generate pre-built packages
173
183
 
174
184
  You need to install all the necessary python releases so they are available via virtualenv.
@@ -113,13 +113,6 @@ def apply_patches():
113
113
  # trimBoth/trimLeft/trimRight calls, so the output is compatible with CH < 25.2
114
114
  apply_patch("patches/trim_format.patch")
115
115
 
116
- # Builds the functions needed by validate_ttl into libclickhouse_ttl_functions.a,
117
- # which is linked with --whole-archive/-force_load (see extra_libs).
118
- # NOTE: after editing this patch (or any other), the early-return above skips the
119
- # ClickHouse build; delete ch_build/src/Functions/libclickhouse_ttl_functions.a
120
- # (or the whole ch_build) to force it to run again.
121
- apply_patch("patches/dbmsfunctions.patch")
122
-
123
116
  # Range-check narrow-integer Field inserts so JSON/Dynamic paths widen instead of
124
117
  # silently wrapping (1944 -> -104). Backport of the ColumnVector::tryInsert fix;
125
118
  # remove once the fix lands in the pinned ClickHouse submodule.
@@ -130,17 +123,29 @@ def apply_patches():
130
123
  apply_patch("patches/ttl_result_type_compat.patch")
131
124
 
132
125
 
126
+ # Archives from the ClickHouse build tree that must exist before the toolset is linked
127
+ # (see the comment on their build step in ClickHouseBuildExt.run). They also decide
128
+ # whether that step can be skipped, so every one of them has to be listed here.
129
+ CLICKHOUSE_FUNCTIONS_DEPS_LIBS = (
130
+ 'src/Functions/JSONPath/libclickhouse_functions_jsonpath.a',
131
+ 'contrib/libfarmhash/lib_farmhash.a',
132
+ 'contrib/murmurhash/lib_murmurhash.a',
133
+ 'contrib/libmetrohash/lib_metrohash.a',
134
+ 'src/Functions/divide/libdivide_impl.a',
135
+ )
136
+
137
+
133
138
  class ClickHouseBuildExt(build_ext):
134
139
  def run(self):
135
140
 
136
141
  if not os.path.exists(os.path.join(CLICKHOUSE_PATH, 'CMakeLists.txt')):
137
142
  raise RuntimeError('Git submodules are not initialized. Run: `git submodule update --init --recursive`.')
138
143
 
139
- # One of the libraries, chosen randomly (+ the TTL functions one, added later)
140
- if os.path.isfile(os.path.join(CLICKHOUSE_BUILD_PATH,
141
- 'src/AggregateFunctions/libclickhouse_aggregate_functions.a')) \
142
- and os.path.isfile(os.path.join(CLICKHOUSE_BUILD_PATH,
143
- 'src/Functions/libclickhouse_ttl_functions.a')):
144
+ # TTL functions are now built by ToolsetBuildWithFromCH
145
+ # (functions/CMakeLists.txt), not here - see that class.
146
+ if all(os.path.isfile(os.path.join(CLICKHOUSE_BUILD_PATH, lib))
147
+ for lib in ('src/AggregateFunctions/libclickhouse_aggregate_functions.a',
148
+ *CLICKHOUSE_FUNCTIONS_DEPS_LIBS)):
144
149
  return
145
150
 
146
151
  apply_patches()
@@ -238,13 +243,23 @@ class ClickHouseBuildExt(build_ext):
238
243
  ['--config', 'Release',
239
244
  '--target', 'src/AggregateFunctions/libclickhouse_aggregate_functions.a'])
240
245
 
241
- # Functions for TTL validation, also with MinSize as performance is not a concern.
242
- # This library is linked with --whole-archive/-force_load (see extra_libs) so that
243
- # its REGISTER_FUNCTION static registrars run and DB::registerFunctions() can
244
- # register all of them without listing them one by one.
246
+ # These all used to get built as an accidental side effect of clickhouse_ttl_functions
247
+ # depending on them (directly or transitively via Functions/CMakeLists.txt's
248
+ # PUBLIC_LIBS/PRIVATE_LIBS) when that target was built from a patched
249
+ # Functions/CMakeLists.txt inside the ClickHouse build tree. Now that it's built
250
+ # from chtoolset's own functions/CMakeLists.txt instead (a separate CMake project,
251
+ # see ToolsetBuildWithFromCH), nothing in the ClickHouse build graph depends on
252
+ # them anymore, so each needs to be requested explicitly here:
253
+ # - libclickhouse_functions_jsonpath.a: JSONPathQuery.h (chtoolset's own code,
254
+ # unrelated to TTL validation) links against DB::ParserJSONPath.
255
+ # - lib_farmhash.a, lib_murmurhash.a, lib_metrohash.a, libdivide_impl.a (which
256
+ # pulls in its _sse2/_avx2 variants): the hashing/integer-division functions
257
+ # glob'd into clickhouse_ttl_functions (cityHash64, murmurHash*, intDiv, ...)
258
+ # call into these directly.
245
259
  subprocess.check_call([cmake_cmd, '--build', CLICKHOUSE_BUILD_PATH] +
246
260
  ['--config', 'Release',
247
- '--target', 'src/Functions/libclickhouse_ttl_functions.a'])
261
+ *[arg for lib in CLICKHOUSE_FUNCTIONS_DEPS_LIBS
262
+ for arg in ('--target', lib)]])
248
263
 
249
264
  # Now build with Release just the parser, which is where we want speed
250
265
  subprocess.check_call([cmake_cmd, CLICKHOUSE_PATH] + cmake_args + ['-DCMAKE_BUILD_TYPE=Release'],
@@ -293,6 +308,51 @@ class CustomBuildWithFromCH(build_ext):
293
308
  stdout=subprocess.PIPE)
294
309
  return list(task.stdout.read().decode('utf-8').split())[2:]
295
310
 
311
+ @staticmethod
312
+ def ninja_extractor_functions(which):
313
+ # Same idea as ninja_extractor_other, but scraped from a Functions/*.cpp
314
+ # compile rule instead of a dbms one - used for the clickhouse_ttl_functions
315
+ # target (functions/CMakeLists.txt), which compiles ClickHouse's own Functions/
316
+ # sources directly (no patch against ClickHouse's Functions/CMakeLists.txt).
317
+ ninja_path = os.path.join(CLICKHOUSE_BUILD_PATH, "build.ninja")
318
+ task = subprocess.Popen(
319
+ ['grep "build src/Functions/CMakeFiles/clickhouse_functions_obj.dir/plus.cpp.o" '
320
+ f'{ninja_path} -A 9 | grep {which}'], shell=True,
321
+ stdout=subprocess.PIPE)
322
+ return list(task.stdout.read().decode('utf-8').split())[2:]
323
+
324
+ @staticmethod
325
+ def function_extra_includes():
326
+ # Raw tokens from ninja: -I<path> is glued (one token), but -isystem <path>
327
+ # is two separate tokens - must consume them as a pair.
328
+ raw_tokens = CustomBuildWithFromCH.ninja_extractor_functions('INCLUDES')
329
+ dirs = []
330
+ i = 0
331
+ while i < len(raw_tokens):
332
+ tok = raw_tokens[i]
333
+ if tok == '-isystem':
334
+ i += 1
335
+ if i < len(raw_tokens):
336
+ dirs.append(raw_tokens[i])
337
+ elif tok.startswith('-isystem'):
338
+ dirs.append(tok[len('-isystem'):])
339
+ elif tok.startswith('-I'):
340
+ dirs.append(tok[len('-I'):])
341
+ i += 1
342
+ # Passed to CMake as a plain include-dirs list (via target_include_directories
343
+ # ... BEFORE), not as raw flags, so it is correctly prepended ahead of the
344
+ # global (dbms-scraped) include list instead of just being appended textually
345
+ # after it - some paths (e.g. murmurhash vs. datasketches-cpp, which both ship
346
+ # a MurmurHash3.h) must win over the global ones, not just be present somewhere
347
+ # on the command line.
348
+ dirs = list(map(transform_path, dirs))
349
+ return ';'.join(d for d in dirs if d)
350
+
351
+ @staticmethod
352
+ def function_extra_defines():
353
+ defines_list = CustomBuildWithFromCH.ninja_extractor_functions('DEFINES')
354
+ return ';'.join(flag[2:] for flag in defines_list if flag.startswith('-D'))
355
+
296
356
  @staticmethod
297
357
  def cflags():
298
358
  cflags_list = CustomBuildWithFromCH.ninja_extractor_other('FLAGS')
@@ -369,7 +429,9 @@ class CustomBuildWithFromCH(build_ext):
369
429
  def extra_libs():
370
430
  ch_libs = [f"{TOOLSET_BUILD_PATH}/{f}"
371
431
  for f in listdir(TOOLSET_BUILD_PATH)
372
- if isfile(join(TOOLSET_BUILD_PATH, f)) and f.endswith(".a")]
432
+ if isfile(join(TOOLSET_BUILD_PATH, f)) and f.endswith(".a")
433
+ # force-loaded explicitly below instead - must not also be linked normally
434
+ and f != "libclickhouse_ttl_functions.a"]
373
435
  ch_libs += CustomBuildWithFromCH.ninja_extractor_ldflags('LINK_LIBRARIES')
374
436
  ch_libs = map(transform_path, ch_libs)
375
437
  # Several changes:
@@ -384,7 +446,7 @@ class CustomBuildWithFromCH(build_ext):
384
446
  # Force-load the TTL validation functions so their REGISTER_FUNCTION static
385
447
  # registrars run even though nothing references their symbols directly.
386
448
  # DB::registerFunctions() (called from ValidateTTL.cpp) registers all of them.
387
- ttl_functions_lib = os.path.join(CLICKHOUSE_BUILD_PATH, 'src/Functions/libclickhouse_ttl_functions.a')
449
+ ttl_functions_lib = os.path.join(TOOLSET_BUILD_PATH, 'libclickhouse_ttl_functions.a')
388
450
  if sys.platform == 'darwin':
389
451
  ch_libs = [f'-Wl,-force_load,{ttl_functions_lib}'] + ch_libs
390
452
  else:
@@ -461,6 +523,12 @@ class ToolsetBuildWithFromCH(CustomBuildWithFromCH):
461
523
  f'-DCMAKE_C_COMPILER={COMPILER_CC}',
462
524
  f'-DCMAKE_CXX_COMPILER={COMPILER_CXX}',
463
525
  f'-DCMAKE_CXX_FLAGS={self.cflags()}',
526
+ # Compiles clickhouse_ttl_functions straight from the ClickHouse submodule
527
+ # source tree (see functions/CMakeLists.txt), with no patch against its own
528
+ # CMakeLists.txt.
529
+ f'-DCLICKHOUSE_FUNCTIONS_PATH={os.path.join(CLICKHOUSE_PATH, "src", "Functions")}',
530
+ f'-DCLICKHOUSE_FUNCTIONS_EXTRA_INCLUDES={self.function_extra_includes()}',
531
+ f'-DCLICKHOUSE_FUNCTIONS_EXTRA_DEFINES={self.function_extra_defines()}',
464
532
  '-G',
465
533
  'Ninja']
466
534
 
@@ -1,7 +1,7 @@
1
1
  from setuptools import setup, Extension
2
2
 
3
3
  NAME = 'tinybird-toolset'
4
- VERSION = '2.7.4'
4
+ VERSION = '2.8.1'
5
5
 
6
6
  # Shared metadata for both the full (extension) build and the metadata-only
7
7
  # fallback below, so the two setup() calls can't drift apart.
@@ -44,6 +44,7 @@ try:
44
44
  "functions/RowBinaryEncoder.h",
45
45
  "src/PythonThreadHandler.h",
46
46
  "ts_build/libCHToolset.a",
47
+ "ts_build/libclickhouse_ttl_functions.a",
47
48
  ],
48
49
  )
49
50
  setup(
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tinybird-toolset
3
- Version: 2.7.4
3
+ Version: 2.8.1
4
4
  Home-page: https://gitlab.com/tinybird/clickhouse-toolset
5
5
  Author: Tinybird.co
6
6
  Author-email: support@tinybird.co
@@ -10,6 +10,7 @@ Provides-Extra: test
10
10
  Requires-Dist: pytest; extra == "test"
11
11
  Requires-Dist: pytest-asyncio; extra == "test"
12
12
  Requires-Dist: prettytable; extra == "test"
13
+ Requires-Dist: hypothesis; extra == "test"
13
14
  Dynamic: author
14
15
  Dynamic: author-email
15
16
  Dynamic: home-page
@@ -3,3 +3,4 @@
3
3
  pytest
4
4
  pytest-asyncio
5
5
  prettytable
6
+ hypothesis
@@ -154,6 +154,37 @@ class TestCreateTable(unittest.TestCase):
154
154
  """
155
155
  self.assertEqual(query.format(query.check_valid_write_query(q)), query.format(q))
156
156
 
157
+ def test_create_table_column_list_functions(self):
158
+ restricted = [
159
+ "CREATE TABLE t (a Int32, b String DEFAULT hostName()) ENGINE = MergeTree ORDER BY a",
160
+ "CREATE TABLE t (a Int32, b UInt8 MATERIALIZED sleep(1)) ENGINE = MergeTree ORDER BY a",
161
+ "CREATE TABLE t (a Int32, b String ALIAS hostName()) ENGINE = MergeTree ORDER BY a",
162
+ "CREATE TABLE t (a Int32, b String DEFAULT a IN (SELECT hostName())) ENGINE = MergeTree ORDER BY a",
163
+ "CREATE TABLE t (a Int32, d Date, b Int32 TTL d + toIntervalDay(toUInt8(sleep(1)))) ENGINE = MergeTree ORDER BY a",
164
+ "CREATE TABLE t (a Int32 CODEC(ZSTD(toUInt64(hostName())))) ENGINE = MergeTree ORDER BY a",
165
+ "CREATE TABLE t (a Int32, INDEX i hostName() TYPE minmax) ENGINE = MergeTree ORDER BY a",
166
+ ]
167
+ for q in restricted:
168
+ with self.subTest(q=q), self.assertRaisesRegex(ValueError, "Usage of function .* is restricted"):
169
+ query.check_valid_write_query(q)
170
+
171
+ with self.assertRaisesRegex(ValueError, "CREATE TABLE: Unsupported subquery: in INDEX declaration"):
172
+ query.check_valid_write_query(
173
+ "CREATE TABLE t (a Int32, INDEX i a IN (SELECT 1 FROM system.tables) TYPE minmax) ENGINE = MergeTree ORDER BY a"
174
+ )
175
+ with self.assertRaisesRegex(ValueError, "CREATE TABLE: Unsupported function dictGetUInt8: in column TTL declaration"):
176
+ query.check_valid_write_query(
177
+ "CREATE TABLE t (a Int32, d Date, b Int32 TTL d + toIntervalDay(dictGetUInt8('d', 'x', a))) ENGINE = MergeTree ORDER BY a"
178
+ )
179
+
180
+ for q in [
181
+ "CREATE TABLE t (a Int32, b String DEFAULT dictGetString('d', 'x', a)) ENGINE = MergeTree ORDER BY a",
182
+ "CREATE TABLE t (a Nullable(Int32) CODEC(Delta, ZSTD(3)), b LowCardinality(String) DEFAULT toString(a)) ENGINE = MergeTree ORDER BY tuple()",
183
+ "CREATE TABLE t (a Int32, d Date, b Int32 TTL d + INTERVAL 1 DAY, INDEX i a * 2 TYPE bloom_filter(0.01) GRANULARITY 1) ENGINE = MergeTree ORDER BY a",
184
+ ]:
185
+ with self.subTest(q=q):
186
+ query.check_valid_write_query(q)
187
+
157
188
  def test_create_table_with_subqueries_in_alias_definition__is_ok(self):
158
189
  q = """
159
190
  CREATE TABLE visits4
@@ -263,6 +294,56 @@ class TestCreateTable(unittest.TestCase):
263
294
  ORDER BY id
264
295
  """)
265
296
 
297
+ def test_create_table_with_apply(self):
298
+ restricted = [
299
+ "CREATE TABLE t (a Int8, PROJECTION p (SELECT * APPLY(x -> hostName()))) ENGINE = MergeTree ORDER BY a",
300
+ "CREATE TABLE t (a Int8, PROJECTION p (SELECT * APPLY(sleepEachRow))) ENGINE = MergeTree ORDER BY a",
301
+ "CREATE TABLE t (a Int8) ENGINE = MergeTree ORDER BY tuple(* APPLY(x -> hostName()))",
302
+ ]
303
+ for q in restricted:
304
+ with self.subTest(q=q), self.assertRaisesRegex(ValueError, "Usage of function .* is restricted"):
305
+ query.check_valid_write_query(q)
306
+
307
+ subqueries = [
308
+ "CREATE TABLE t (a Int8) ENGINE = MergeTree ORDER BY tuple(* APPLY(x -> (SELECT 1 FROM system.tables)))",
309
+ "CREATE TABLE t (a Int8) ENGINE = MergeTree ORDER BY tuple(* APPLY(x -> x IN (SELECT 1 FROM system.tables)))",
310
+ ]
311
+ for q in subqueries:
312
+ with self.subTest(q=q), self.assertRaisesRegex(ValueError, "CREATE TABLE: Unsupported subquery: in ORDER BY declaration"):
313
+ query.check_valid_write_query(q)
314
+
315
+ with self.assertRaisesRegex(ValueError, "CREATE TABLE: Unsupported function dictGetString: in ORDER BY declaration"):
316
+ query.check_valid_write_query("CREATE TABLE t (a Int8) ENGINE = MergeTree ORDER BY tuple(COLUMNS('a') APPLY(dictGetString))")
317
+
318
+ def test_create_table_with_ttl_group_by(self):
319
+ restricted = [
320
+ "CREATE TABLE t (a Int32, d Date) ENGINE = MergeTree ORDER BY a TTL d GROUP BY a SET a = toInt32OrZero(hostName())",
321
+ "CREATE TABLE t (a Int32, d Date) ENGINE = MergeTree ORDER BY a TTL d GROUP BY a SET a = toInt32(sleep(3))",
322
+ ]
323
+ for q in restricted:
324
+ with self.subTest(q=q), self.assertRaisesRegex(ValueError, "Usage of function .* is restricted"):
325
+ query.check_valid_write_query(q)
326
+
327
+ query.check_valid_write_query(
328
+ "CREATE TABLE t (a Int32, b Int32, d Date) ENGINE = MergeTree ORDER BY a TTL d GROUP BY a SET b = max(b)"
329
+ )
330
+ query.check_valid_write_query(
331
+ "CREATE TABLE t (a Int32, d Date) ENGINE = MergeTree ORDER BY a TTL d RECOMPRESS CODEC(ZSTD(12))"
332
+ )
333
+ query.check_valid_write_query(
334
+ "CREATE TABLE t (a Int32, d Date) ENGINE = MergeTree ORDER BY a TTL d RECOMPRESS CODEC(Delta, LZ4)"
335
+ )
336
+
337
+ def test_create_table_with_ttl_recompress_codec_arguments(self):
338
+ with self.assertRaisesRegex(ValueError, "Usage of function .* is restricted"):
339
+ query.check_valid_write_query(
340
+ "CREATE TABLE t (a Int32, d Date) ENGINE = MergeTree ORDER BY a TTL d RECOMPRESS CODEC(ZSTD(toUInt64(hostName())))"
341
+ )
342
+ with self.assertRaisesRegex(ValueError, "CREATE TABLE: Unsupported subquery: in TTL declaration"):
343
+ query.check_valid_write_query(
344
+ "CREATE TABLE t (a Int32, d Date) ENGINE = MergeTree ORDER BY a TTL d RECOMPRESS CODEC(ZSTD((SELECT 1 FROM system.tables)))"
345
+ )
346
+
266
347
  def test_create_table_with_join_engine_is_forbidden(self):
267
348
  with self.assertRaisesRegex(ValueError, "Creation of tables with ENGINE Join is not supported"):
268
349
  query.check_valid_write_query("""
@@ -1,4 +1,5 @@
1
1
  import json
2
+ import sys
2
3
  import logging
3
4
  import re
4
5
  import shutil
@@ -9078,6 +9079,175 @@ class TestRowBinaryEncoder:
9078
9079
  outputs[type_name] = result
9079
9080
  assert outputs['Tuple(JSON, LowCardinality(String))'] == outputs['Tuple(JSON, String)']
9080
9081
 
9082
+ OBJECT_COLUMN_SCRATCH_CASES = [
9083
+ # Objects directly in the column: rows 1-2 share a shape (reuse), rows 3-4 don't (reset).
9084
+ ('JSON', True,
9085
+ [{'value': {'b': 1, 'a': 'x'}}, {'value': {'b': 2, 'a': 'y'}},
9086
+ {'value': {'other': [1, {'deep': True}]}}, {'value': {'b': 3, 'a': 'z'}}]),
9087
+ # Array lengths vary while the element shapes repeat.
9088
+ ('Array(JSON)', False,
9089
+ [{'value': [{'a': 1}]}, {'value': [{'a': 2}, {'a': 3}]}, {'value': []}, {'value': [{'a': 4}]}]),
9090
+ # Objects nested in a Tuple and in a Map: first two rows share a shape, the third doesn't.
9091
+ ('Tuple(JSON, String)', False,
9092
+ [{'value': [{'a': 1}, 't1']}, {'value': [{'a': 2}, 't2']}, {'value': [{'b': 3}, 't3']}]),
9093
+ ('Map(String, JSON)', False,
9094
+ [{'value': {'k': {'a': 1}}}, {'value': {'k': {'a': 2}}}, {'value': {'k': {'b': 3}}}]),
9095
+ # A LowCardinality column is reused only while its dictionary stays small, same rows still
9096
+ # have to encode identically.
9097
+ ('Tuple(JSON, LowCardinality(String))', False,
9098
+ [{'value': [{'a': 1}, 'lc1']}, {'value': [{'a': 2}, 'lc2']}, {'value': [{'b': 3}, 'lc3']}]),
9099
+ ]
9100
+
9101
+ @pytest.mark.parametrize("type_name, legacy_conversion_mode, rows", OBJECT_COLUMN_SCRATCH_CASES)
9102
+ def test_object_column_reuses_scratch_column_across_rows(self, type_name, legacy_conversion_mode, rows):
9103
+ """Object columns are written through a scratch column that is reused across rows.
9104
+
9105
+ Reuse is only a cache: rows must encode to exactly the same bytes as each row encoded on its
9106
+ own, when they share a shape (reuse), when they don't (reset), and across calls to the same
9107
+ encoder (which is how encoders are used in practice).
9108
+ """
9109
+ jsonpath = '$.value[:]' if type_name.startswith('Tuple') else '$.value'
9110
+ schema = json.dumps(get_schema([('value', type_name, jsonpath, False)]))
9111
+ encoded_rows = [json.dumps(row) for row in rows]
9112
+
9113
+ def encoder():
9114
+ return chquery.RowBinaryEncoder(schema, legacy_conversion_mode=legacy_conversion_mode, binary_json_as_string=True)
9115
+
9116
+ expected = b''
9117
+ for row in encoded_rows:
9118
+ with encoder() as fresh_encoder:
9119
+ result, quarantine, nrows, nquarantine = fresh_encoder.encode(row)
9120
+ assert (nrows, nquarantine, quarantine) == (1, 0, b'')
9121
+ expected += result
9122
+
9123
+ with encoder() as cached_encoder:
9124
+ result, quarantine, nrows, nquarantine = cached_encoder.encode('\n'.join(encoded_rows))
9125
+ assert (nrows, nquarantine, quarantine) == (len(encoded_rows), 0, b'')
9126
+ assert result == expected
9127
+
9128
+ # Same rows, but split over two calls on the same encoder (cross-call reuse).
9129
+ with encoder() as cached_encoder:
9130
+ first, _, first_rows, _ = cached_encoder.encode('\n'.join(encoded_rows[:2]))
9131
+ second, _, second_rows, second_quarantine = cached_encoder.encode('\n'.join(encoded_rows[2:]))
9132
+ assert (first_rows, second_rows, second_quarantine) == (2, len(encoded_rows) - 2, 0)
9133
+ assert first + second == expected
9134
+
9135
+ OBJECT_COLUMN_SCRATCH_RETENTION_CASES = [
9136
+ # ColumnLowCardinality keeps a dictionary of every value ever inserted and popBack() only
9137
+ # rewinds its index, so the reuse of this schema is bounded by that dictionary.
9138
+ ('Tuple(JSON, LowCardinality(String))', '$.value[:]'),
9139
+ # A plain String column keeps the inserted rows; they have to be dropped with popBack().
9140
+ ('Array(JSON)', '$.value'),
9141
+ ]
9142
+
9143
+ @pytest.mark.parametrize("type_name, jsonpath", OBJECT_COLUMN_SCRATCH_RETENTION_CASES)
9144
+ def test_object_column_scratch_column_does_not_retain_values(self, type_name, jsonpath):
9145
+ """The reused scratch column must not keep data from previous rows.
9146
+
9147
+ Its contents are dropped with popBack() after every row, and state that popBack() does not
9148
+ clear is bounded (the LowCardinality dictionary is given up once it grows past 1 MiB). Both a
9149
+ retained column and a missing popBack() show up as RSS growth proportional to the number of
9150
+ rows, so this is a coarse guard for that failure mode.
9151
+
9152
+ The measurement runs in a fresh process: ru_maxrss is the process-lifetime peak, so a high
9153
+ peak earlier in the test session would hide the growth of this loop.
9154
+ """
9155
+ script = f"""
9156
+ import json, resource, sys
9157
+ from chtoolset import query as chquery
9158
+
9159
+ schema = json.dumps([{{"name": "value", "type": {type_name!r}, "jsonpath": {jsonpath!r}, "has_default": False}}])
9160
+ value_size, calls = 200_000, 200
9161
+ make_row = (
9162
+ (lambda i, value: {{"value": [{{"a": 1}}, value]}}) if sys.argv[1] == "tuple"
9163
+ else (lambda i, value: {{"value": [{{"a": 1, "tag": value}}]}})
9164
+ )
9165
+
9166
+ # ru_maxrss is in bytes on macOS and in kilobytes on Linux
9167
+ def rss_mb():
9168
+ return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / (1e6 if sys.platform == 'darwin' else 1e3)
9169
+
9170
+ with chquery.RowBinaryEncoder(schema, legacy_conversion_mode=False, binary_json_as_string=True) as encoder:
9171
+ baseline = None
9172
+ for i in range(calls):
9173
+ payload = json.dumps(make_row(i, 'tag%06d' % i + 'x' * value_size))
9174
+ result, quarantine, nrows, nquarantine = encoder.encode(payload)
9175
+ assert (nrows, nquarantine, quarantine) == (1, 0, b''), (nrows, nquarantine, quarantine)
9176
+ if i == 5:
9177
+ baseline = rss_mb()
9178
+ print(rss_mb() - baseline)
9179
+ """
9180
+ family = 'tuple' if type_name.startswith('Tuple') else 'array'
9181
+ output = subprocess.check_output([sys.executable, '-c', script, family], text=True)
9182
+ growth_mb = float(output.strip().splitlines()[-1])
9183
+
9184
+ # Retaining the rows would grow RSS by ~calls * value_size (40 MB); allow for allocator noise.
9185
+ assert growth_mb < 20, f'scratch column retained ~{growth_mb:.0f} MB of previous rows'
9186
+
9187
+ @pytest.mark.parametrize(
9188
+ 'rows',
9189
+ [
9190
+ # One large row followed by a small one of the same shape, which keeps reusing the column.
9191
+ [{"a": "x" * 900_000}, {"a": "y"}],
9192
+ # A small row of a very wide object: each dynamic path keeps its own column.
9193
+ [{f"k{i}": i for i in range(1000)}] * 2,
9194
+ ],
9195
+ ids=['large_row', 'wide_object'],
9196
+ )
9197
+ def test_object_column_scratch_column_does_not_keep_large_row_buffers(self, rows):
9198
+ """popBack() keeps buffer capacity, so a reused scratch column would hold the buffers of the
9199
+ largest row (or the paths of the widest object) ever seen for the encoder's lifetime (Kafka
9200
+ agents keep one encoder for hours). Many live encoders that each saw one such row must not keep
9201
+ more memory than with binary_json_as_string=False, which doesn't use the scratch column. Each
9202
+ mode runs in its own process because the setting is global to the process.
9203
+ """
9204
+ script = """
9205
+ import ctypes, json, sys
9206
+ from chtoolset import query as chquery
9207
+
9208
+ # Bytes in use by malloc rather than RSS: RSS also counts freed memory the allocator hasn't returned yet,
9209
+ # which on macOS varies by more than the retention this test looks for.
9210
+ libc = ctypes.CDLL(None)
9211
+ if sys.platform == 'darwin':
9212
+ class Stats(ctypes.Structure):
9213
+ _fields_ = [('blocks_in_use', ctypes.c_uint), ('size_in_use', ctypes.c_size_t),
9214
+ ('max_size_in_use', ctypes.c_size_t), ('size_allocated', ctypes.c_size_t)]
9215
+ def used_mb():
9216
+ stats = Stats()
9217
+ libc.malloc_zone_statistics(None, ctypes.byref(stats))
9218
+ return stats.size_in_use / 1048576
9219
+ else:
9220
+ class Stats(ctypes.Structure):
9221
+ _fields_ = [(name, ctypes.c_size_t) for name in
9222
+ ('arena', 'ordblks', 'smblks', 'hblks', 'hblkhd', 'usmblks', 'fsmblks', 'uordblks', 'fordblks', 'keepcost')]
9223
+ libc.mallinfo2.restype = Stats
9224
+ def used_mb():
9225
+ stats = libc.mallinfo2()
9226
+ return (stats.uordblks + stats.hblkhd) / 1048576
9227
+
9228
+ schema = json.dumps([{"name": "value", "type": "JSON", "jsonpath": "$.value", "has_default": False}])
9229
+ # Rows come through stdin: a 900 KB argument is over Linux's 128 KB limit per argument.
9230
+ rows = [json.dumps({"value": value}) for value in json.load(sys.stdin)]
9231
+ encoders = []
9232
+ baseline = used_mb()
9233
+ for _ in range(200):
9234
+ encoder = chquery.RowBinaryEncoder(schema, legacy_conversion_mode=False, binary_json_as_string=sys.argv[1] == 'string')
9235
+ encoder.__enter__()
9236
+ for row in rows:
9237
+ encoder.encode(row)
9238
+ encoders.append(encoder)
9239
+ print(used_mb() - baseline)
9240
+ for encoder in encoders:
9241
+ encoder.__exit__(None, None, None)
9242
+ """
9243
+ def retained_mb(mode):
9244
+ output = subprocess.check_output([sys.executable, '-c', script, mode], input=json.dumps(rows), text=True)
9245
+ return float(output.strip().splitlines()[-1])
9246
+
9247
+ extra_mb = retained_mb('string') - retained_mb('binary')
9248
+ # Keeping the buffers costs ~0.5 MB (large row) or ~13 MB (wide object) per encoder; without them ~4 MB in total.
9249
+ assert extra_mb < 20, f'scratch columns of 200 encoders retained ~{extra_mb:.0f} MB after one large row or wide object each'
9250
+
9081
9251
  def test_getRaw_whitespace_trimming_for_integers(self):
9082
9252
  """Test that getRaw method properly trims whitespace from integers, especially when they are the last element in JSON objects."""
9083
9253
  # Schema with integer and string fields
@@ -100,6 +100,31 @@ class TestReplaceTables(unittest.TestCase):
100
100
  },
101
101
  "SELECT * FROM database.t_01010101 AS t WHERE (c1, c2) IN database.t_02020202",
102
102
  ),
103
+ (
104
+ "SELECT * APPLY(x -> (SELECT count() FROM tt)) FROM (SELECT 1 AS a)",
105
+ {("", "tt"): ("", "(select a from table2 where a > 1)")},
106
+ "SELECT * APPLY(x -> (SELECT count() FROM (select a from table2 where a > 1) AS tt)) FROM (SELECT 1 AS a)",
107
+ ),
108
+ (
109
+ "SELECT * APPLY(x -> x IN (SELECT a FROM tt)) FROM (SELECT 1 AS a)",
110
+ {("", "tt"): ("database", "t_01010101")},
111
+ "SELECT * APPLY(x -> x IN (SELECT a FROM database.t_01010101 AS tt)) FROM (SELECT 1 AS a)",
112
+ ),
113
+ (
114
+ "SELECT * APPLY(x -> x IN tt) FROM (SELECT 1 AS a)",
115
+ {("", "tt"): ("database", "t_01010101")},
116
+ "SELECT * APPLY(x -> x IN database.t_01010101) FROM (SELECT 1 AS a)",
117
+ ),
118
+ (
119
+ "SELECT sum(a) OVER (PARTITION BY (SELECT count() FROM tt)) FROM (SELECT 1 AS a)",
120
+ {("", "tt"): ("database", "t_01010101")},
121
+ "SELECT sum(a) OVER (PARTITION BY (SELECT count() FROM database.t_01010101 AS tt)) FROM (SELECT 1 AS a)",
122
+ ),
123
+ (
124
+ "SELECT sum(a) OVER w FROM (SELECT 1 AS a) WINDOW w AS (PARTITION BY a IN (SELECT a FROM tt))",
125
+ {("", "tt"): ("database", "t_01010101")},
126
+ "SELECT sum(a) OVER w FROM (SELECT 1 AS a) WINDOW w AS (PARTITION BY a IN (SELECT a FROM database.t_01010101 AS tt))",
127
+ ),
103
128
  ]
104
129
 
105
130
  def test_asterisks_no_database(self):
@@ -1017,6 +1042,37 @@ class TestDisabledFunctions(unittest.TestCase):
1017
1042
  ):
1018
1043
  chquery.replace_tables(q, replacements)
1019
1044
 
1045
+ def test_blocked_function_in_apply(self):
1046
+ queries = [
1047
+ "SELECT * APPLY(sleep) FROM (SELECT 2 AS a)",
1048
+ "SELECT * APPLY(x -> hostName()) FROM (SELECT 1 AS a)",
1049
+ "SELECT * APPLY(filesystemCapacity) FROM (SELECT 'default' AS a)",
1050
+ "SELECT COLUMNS('a') APPLY(x -> sleep(x)) FROM (SELECT 1 AS a)",
1051
+ "SELECT t.* APPLY(x -> toInt64(currentUser())) FROM (SELECT 1 AS a) AS t",
1052
+ ]
1053
+ for q in queries:
1054
+ with self.assertRaisesRegex(ValueError, "DB::Exception: Usage of function .* is restricted"):
1055
+ chquery.replace_tables(q, {})
1056
+
1057
+ def test_allowed_function_in_apply(self):
1058
+ for q in [
1059
+ "SELECT * APPLY(sum) FROM (SELECT 2 AS a)",
1060
+ "SELECT * APPLY(quantile(0.9)) FROM (SELECT 2 AS a)",
1061
+ "SELECT * APPLY(x -> toString(x)) FROM (SELECT 2 AS a)",
1062
+ ]:
1063
+ chquery.replace_tables(q, {})
1064
+
1065
+ def test_blocked_function_in_window(self):
1066
+ queries = [
1067
+ "SELECT sum(a) OVER (PARTITION BY sleep(1)) FROM (SELECT 1 AS a)",
1068
+ "SELECT sum(a) OVER (ORDER BY hostName()) FROM (SELECT 1 AS a)",
1069
+ "SELECT sum(a) OVER (ORDER BY a ROWS BETWEEN toUInt64(sleep(1)) PRECEDING AND CURRENT ROW) FROM (SELECT 1 AS a)",
1070
+ "SELECT sum(a) OVER w FROM (SELECT 1 AS a) WINDOW w AS (PARTITION BY sleep(1))",
1071
+ ]
1072
+ for q in queries:
1073
+ with self.subTest(q=q), self.assertRaisesRegex(ValueError, "DB::Exception: Usage of function .* is restricted"):
1074
+ chquery.replace_tables(q, {})
1075
+
1020
1076
  def test_sleep_in_replacements(self):
1021
1077
  sql = "SELECT * FROM a, a"
1022
1078
  replacement = {
@@ -27,6 +27,14 @@ class TestTables(unittest.TestCase):
27
27
  ('SELECT * FROM t WHERE event_date IN system.query_log', [('', 't', ''), ('system', 'query_log', '')]),
28
28
  ('SELECT * FROM t WHERE event_date GLOBAL NOT IN system.query_log', [('', 't', ''), ('system', 'query_log', '')]),
29
29
  ('SELECT * FROM t WHERE event_date IN (Select * FROM system.query_log)', [('', 't', ''), ('system', 'query_log', '')]),
30
+ ('SELECT * APPLY(x -> (SELECT count() FROM system.trace_log)) FROM (SELECT 1 AS a)', [('system', 'trace_log', '')]),
31
+ ('SELECT * APPLY(x -> x IN (SELECT count() FROM system.tables)) FROM (SELECT 1 AS a)', [('system', 'tables', '')]),
32
+ ('SELECT * APPLY(x -> x IN system.tables) FROM (SELECT 1 AS a)', [('system', 'tables', '')]),
33
+ ('SELECT COLUMNS(\'a\') APPLY(x -> (SELECT max(b) FROM t2)) FROM t', [('', 't', ''), ('', 't2', '')]),
34
+ ('SELECT * APPLY(x -> (WITH c AS (SELECT b FROM t) SELECT count() FROM c)) FROM (SELECT 1 AS a)', [('', 't', '')]),
35
+ ('SELECT sum(a) OVER (PARTITION BY (SELECT count() FROM system.trace_log)) FROM (SELECT 1 AS a)', [('system', 'trace_log', '')]),
36
+ ('SELECT sum(a) OVER (ORDER BY a IN system.tables) FROM (SELECT 1 AS a)', [('system', 'tables', '')]),
37
+ ('SELECT sum(a) OVER w FROM (SELECT 1 AS a) WINDOW w AS (PARTITION BY (SELECT count() FROM system.trace_log))', [('system', 'trace_log', '')]),
30
38
  ]
31
39
 
32
40
  def test_json_all_paths_is_allowed(self):