tinybird-toolset 2.8.0__tar.gz → 2.8.3__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.8.0/src/tinybird_toolset.egg-info → tinybird_toolset-2.8.3}/PKG-INFO +2 -1
  2. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/README.md +10 -0
  3. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/conf.py +87 -19
  4. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/setup.py +2 -1
  5. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3/src/tinybird_toolset.egg-info}/PKG-INFO +2 -1
  6. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/src/tinybird_toolset.egg-info/requires.txt +1 -0
  7. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/tests/test_convert_to_row_binary.py +184 -0
  8. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/tests/test_replace_tables.py +38 -1
  9. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/LICENSE +0 -0
  10. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/MANIFEST.in +0 -0
  11. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/setup.cfg +0 -0
  12. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/src/chtoolset/__init__.py +0 -0
  13. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/src/chtoolset/query.py +0 -0
  14. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/src/tinybird_toolset.egg-info/SOURCES.txt +0 -0
  15. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/src/tinybird_toolset.egg-info/dependency_links.txt +0 -0
  16. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/src/tinybird_toolset.egg-info/top_level.txt +0 -0
  17. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/tests/test_check_compatible_types.py +0 -0
  18. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/tests/test_check_ttl_partition_compatibility.py +0 -0
  19. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/tests/test_check_write_query.py +0 -0
  20. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/tests/test_chquery.py +0 -0
  21. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/tests/test_explain_ast.py +0 -0
  22. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/tests/test_get_columns_from_create_query.py +0 -0
  23. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/tests/test_get_left_table.py +0 -0
  24. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/tests/test_internal_cache.py +0 -0
  25. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/tests/test_normalize_query_keep_names.py +0 -0
  26. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/tests/test_normalize_table_column.py +0 -0
  27. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/tests/test_parse_create_materialized_view_target_table.py +0 -0
  28. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/tests/test_replace_tables_backward_compat.py +0 -0
  29. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/tests/test_rewrite_aggregation_states.py +0 -0
  30. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/tests/test_tables.py +0 -0
  31. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/tests/test_validate_partition_key.py +0 -0
  32. {tinybird_toolset-2.8.0 → tinybird_toolset-2.8.3}/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.8.0
3
+ Version: 2.8.3
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.8.0'
4
+ VERSION = '2.8.3'
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.8.0
3
+ Version: 2.8.3
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
@@ -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,189 @@ class TestRowBinaryEncoder:
9078
9079
  outputs[type_name] = result
9079
9080
  assert outputs['Tuple(JSON, LowCardinality(String))'] == outputs['Tuple(JSON, String)']
9080
9081
 
9082
+ def test_binary_json_as_string_is_per_encoder(self):
9083
+ schema = json.dumps(get_schema([('v', 'JSON', '$.v', False)]))
9084
+ data = json.dumps({'v': {'a': 1}})
9085
+ outputs = {}
9086
+ for binary_json_as_string in (True, False):
9087
+ with chquery.RowBinaryEncoder(schema, binary_json_as_string=binary_json_as_string, legacy_conversion_mode=False) as encoder:
9088
+ outputs[binary_json_as_string] = encoder.encode(data)[0]
9089
+ assert outputs[True] != outputs[False]
9090
+
9091
+ with chquery.RowBinaryEncoder(schema, binary_json_as_string=True, legacy_conversion_mode=False) as string_encoder:
9092
+ with chquery.RowBinaryEncoder(schema, binary_json_as_string=False, legacy_conversion_mode=False) as binary_encoder:
9093
+ assert string_encoder.encode(data)[0] == outputs[True]
9094
+ assert binary_encoder.encode(data)[0] == outputs[False]
9095
+
9096
+ OBJECT_COLUMN_SCRATCH_CASES = [
9097
+ # Objects directly in the column: rows 1-2 share a shape (reuse), rows 3-4 don't (reset).
9098
+ ('JSON', True,
9099
+ [{'value': {'b': 1, 'a': 'x'}}, {'value': {'b': 2, 'a': 'y'}},
9100
+ {'value': {'other': [1, {'deep': True}]}}, {'value': {'b': 3, 'a': 'z'}}]),
9101
+ # Array lengths vary while the element shapes repeat.
9102
+ ('Array(JSON)', False,
9103
+ [{'value': [{'a': 1}]}, {'value': [{'a': 2}, {'a': 3}]}, {'value': []}, {'value': [{'a': 4}]}]),
9104
+ # Objects nested in a Tuple and in a Map: first two rows share a shape, the third doesn't.
9105
+ ('Tuple(JSON, String)', False,
9106
+ [{'value': [{'a': 1}, 't1']}, {'value': [{'a': 2}, 't2']}, {'value': [{'b': 3}, 't3']}]),
9107
+ ('Map(String, JSON)', False,
9108
+ [{'value': {'k': {'a': 1}}}, {'value': {'k': {'a': 2}}}, {'value': {'k': {'b': 3}}}]),
9109
+ # A LowCardinality column is reused only while its dictionary stays small, same rows still
9110
+ # have to encode identically.
9111
+ ('Tuple(JSON, LowCardinality(String))', False,
9112
+ [{'value': [{'a': 1}, 'lc1']}, {'value': [{'a': 2}, 'lc2']}, {'value': [{'b': 3}, 'lc3']}]),
9113
+ ]
9114
+
9115
+ @pytest.mark.parametrize("type_name, legacy_conversion_mode, rows", OBJECT_COLUMN_SCRATCH_CASES)
9116
+ def test_object_column_reuses_scratch_column_across_rows(self, type_name, legacy_conversion_mode, rows):
9117
+ """Object columns are written through a scratch column that is reused across rows.
9118
+
9119
+ Reuse is only a cache: rows must encode to exactly the same bytes as each row encoded on its
9120
+ own, when they share a shape (reuse), when they don't (reset), and across calls to the same
9121
+ encoder (which is how encoders are used in practice).
9122
+ """
9123
+ jsonpath = '$.value[:]' if type_name.startswith('Tuple') else '$.value'
9124
+ schema = json.dumps(get_schema([('value', type_name, jsonpath, False)]))
9125
+ encoded_rows = [json.dumps(row) for row in rows]
9126
+
9127
+ def encoder():
9128
+ return chquery.RowBinaryEncoder(schema, legacy_conversion_mode=legacy_conversion_mode, binary_json_as_string=True)
9129
+
9130
+ expected = b''
9131
+ for row in encoded_rows:
9132
+ with encoder() as fresh_encoder:
9133
+ result, quarantine, nrows, nquarantine = fresh_encoder.encode(row)
9134
+ assert (nrows, nquarantine, quarantine) == (1, 0, b'')
9135
+ expected += result
9136
+
9137
+ with encoder() as cached_encoder:
9138
+ result, quarantine, nrows, nquarantine = cached_encoder.encode('\n'.join(encoded_rows))
9139
+ assert (nrows, nquarantine, quarantine) == (len(encoded_rows), 0, b'')
9140
+ assert result == expected
9141
+
9142
+ # Same rows, but split over two calls on the same encoder (cross-call reuse).
9143
+ with encoder() as cached_encoder:
9144
+ first, _, first_rows, _ = cached_encoder.encode('\n'.join(encoded_rows[:2]))
9145
+ second, _, second_rows, second_quarantine = cached_encoder.encode('\n'.join(encoded_rows[2:]))
9146
+ assert (first_rows, second_rows, second_quarantine) == (2, len(encoded_rows) - 2, 0)
9147
+ assert first + second == expected
9148
+
9149
+ OBJECT_COLUMN_SCRATCH_RETENTION_CASES = [
9150
+ # ColumnLowCardinality keeps a dictionary of every value ever inserted and popBack() only
9151
+ # rewinds its index, so the reuse of this schema is bounded by that dictionary.
9152
+ ('Tuple(JSON, LowCardinality(String))', '$.value[:]'),
9153
+ # A plain String column keeps the inserted rows; they have to be dropped with popBack().
9154
+ ('Array(JSON)', '$.value'),
9155
+ ]
9156
+
9157
+ @pytest.mark.parametrize("type_name, jsonpath", OBJECT_COLUMN_SCRATCH_RETENTION_CASES)
9158
+ def test_object_column_scratch_column_does_not_retain_values(self, type_name, jsonpath):
9159
+ """The reused scratch column must not keep data from previous rows.
9160
+
9161
+ Its contents are dropped with popBack() after every row, and state that popBack() does not
9162
+ clear is bounded (the LowCardinality dictionary is given up once it grows past 1 MiB). Both a
9163
+ retained column and a missing popBack() show up as RSS growth proportional to the number of
9164
+ rows, so this is a coarse guard for that failure mode.
9165
+
9166
+ The measurement runs in a fresh process: ru_maxrss is the process-lifetime peak, so a high
9167
+ peak earlier in the test session would hide the growth of this loop.
9168
+ """
9169
+ script = f"""
9170
+ import json, resource, sys
9171
+ from chtoolset import query as chquery
9172
+
9173
+ schema = json.dumps([{{"name": "value", "type": {type_name!r}, "jsonpath": {jsonpath!r}, "has_default": False}}])
9174
+ value_size, calls = 200_000, 200
9175
+ make_row = (
9176
+ (lambda i, value: {{"value": [{{"a": 1}}, value]}}) if sys.argv[1] == "tuple"
9177
+ else (lambda i, value: {{"value": [{{"a": 1, "tag": value}}]}})
9178
+ )
9179
+
9180
+ # ru_maxrss is in bytes on macOS and in kilobytes on Linux
9181
+ def rss_mb():
9182
+ return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / (1e6 if sys.platform == 'darwin' else 1e3)
9183
+
9184
+ with chquery.RowBinaryEncoder(schema, legacy_conversion_mode=False, binary_json_as_string=True) as encoder:
9185
+ baseline = None
9186
+ for i in range(calls):
9187
+ payload = json.dumps(make_row(i, 'tag%06d' % i + 'x' * value_size))
9188
+ result, quarantine, nrows, nquarantine = encoder.encode(payload)
9189
+ assert (nrows, nquarantine, quarantine) == (1, 0, b''), (nrows, nquarantine, quarantine)
9190
+ if i == 5:
9191
+ baseline = rss_mb()
9192
+ print(rss_mb() - baseline)
9193
+ """
9194
+ family = 'tuple' if type_name.startswith('Tuple') else 'array'
9195
+ output = subprocess.check_output([sys.executable, '-c', script, family], text=True)
9196
+ growth_mb = float(output.strip().splitlines()[-1])
9197
+
9198
+ # Retaining the rows would grow RSS by ~calls * value_size (40 MB); allow for allocator noise.
9199
+ assert growth_mb < 20, f'scratch column retained ~{growth_mb:.0f} MB of previous rows'
9200
+
9201
+ @pytest.mark.parametrize(
9202
+ 'rows',
9203
+ [
9204
+ # One large row followed by a small one of the same shape, which keeps reusing the column.
9205
+ [{"a": "x" * 900_000}, {"a": "y"}],
9206
+ # A small row of a very wide object: each dynamic path keeps its own column.
9207
+ [{f"k{i}": i for i in range(1000)}] * 2,
9208
+ ],
9209
+ ids=['large_row', 'wide_object'],
9210
+ )
9211
+ def test_object_column_scratch_column_does_not_keep_large_row_buffers(self, rows):
9212
+ """popBack() keeps buffer capacity, so a reused scratch column would hold the buffers of the
9213
+ largest row (or the paths of the widest object) ever seen for the encoder's lifetime (Kafka
9214
+ agents keep one encoder for hours). Many live encoders that each saw one such row must not keep
9215
+ more memory than with binary_json_as_string=False, which doesn't use the scratch column. Each
9216
+ mode runs in its own process because the setting is global to the process.
9217
+ """
9218
+ script = """
9219
+ import ctypes, json, sys
9220
+ from chtoolset import query as chquery
9221
+
9222
+ # Bytes in use by malloc rather than RSS: RSS also counts freed memory the allocator hasn't returned yet,
9223
+ # which on macOS varies by more than the retention this test looks for.
9224
+ libc = ctypes.CDLL(None)
9225
+ if sys.platform == 'darwin':
9226
+ class Stats(ctypes.Structure):
9227
+ _fields_ = [('blocks_in_use', ctypes.c_uint), ('size_in_use', ctypes.c_size_t),
9228
+ ('max_size_in_use', ctypes.c_size_t), ('size_allocated', ctypes.c_size_t)]
9229
+ def used_mb():
9230
+ stats = Stats()
9231
+ libc.malloc_zone_statistics(None, ctypes.byref(stats))
9232
+ return stats.size_in_use / 1048576
9233
+ else:
9234
+ class Stats(ctypes.Structure):
9235
+ _fields_ = [(name, ctypes.c_size_t) for name in
9236
+ ('arena', 'ordblks', 'smblks', 'hblks', 'hblkhd', 'usmblks', 'fsmblks', 'uordblks', 'fordblks', 'keepcost')]
9237
+ libc.mallinfo2.restype = Stats
9238
+ def used_mb():
9239
+ stats = libc.mallinfo2()
9240
+ return (stats.uordblks + stats.hblkhd) / 1048576
9241
+
9242
+ schema = json.dumps([{"name": "value", "type": "JSON", "jsonpath": "$.value", "has_default": False}])
9243
+ # Rows come through stdin: a 900 KB argument is over Linux's 128 KB limit per argument.
9244
+ rows = [json.dumps({"value": value}) for value in json.load(sys.stdin)]
9245
+ encoders = []
9246
+ baseline = used_mb()
9247
+ for _ in range(200):
9248
+ encoder = chquery.RowBinaryEncoder(schema, legacy_conversion_mode=False, binary_json_as_string=sys.argv[1] == 'string')
9249
+ encoder.__enter__()
9250
+ for row in rows:
9251
+ encoder.encode(row)
9252
+ encoders.append(encoder)
9253
+ print(used_mb() - baseline)
9254
+ for encoder in encoders:
9255
+ encoder.__exit__(None, None, None)
9256
+ """
9257
+ def retained_mb(mode):
9258
+ output = subprocess.check_output([sys.executable, '-c', script, mode], input=json.dumps(rows), text=True)
9259
+ return float(output.strip().splitlines()[-1])
9260
+
9261
+ extra_mb = retained_mb('string') - retained_mb('binary')
9262
+ # Keeping the buffers costs ~0.5 MB (large row) or ~13 MB (wide object) per encoder; without them ~4 MB in total.
9263
+ assert extra_mb < 20, f'scratch columns of 200 encoders retained ~{extra_mb:.0f} MB after one large row or wide object each'
9264
+
9081
9265
  def test_getRaw_whitespace_trimming_for_integers(self):
9082
9266
  """Test that getRaw method properly trims whitespace from integers, especially when they are the last element in JSON objects."""
9083
9267
  # Schema with integer and string fields
@@ -125,6 +125,41 @@ class TestReplaceTables(unittest.TestCase):
125
125
  {("", "tt"): ("database", "t_01010101")},
126
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
127
  ),
128
+ (
129
+ "SELECT * FROM tt FINAL WHERE b = 1",
130
+ {("", "tt"): ("", "(select * from database.t_01010101 where a > 1)")},
131
+ "SELECT * FROM (select * from database.t_01010101 FINAL where a > 1) AS tt WHERE b = 1",
132
+ ),
133
+ (
134
+ "SELECT * FROM tt AS t FINAL",
135
+ {("", "tt"): ("", "(select * from (select * from database.t_01010101 where a > 1) where a > 1)")},
136
+ "SELECT * FROM (select * from (select * from database.t_01010101 FINAL where a > 1) where a > 1) AS t",
137
+ ),
138
+ (
139
+ "SELECT * FROM tt FINAL",
140
+ {("", "tt"): ("", "(select * from cluster(c, database.t_01010101) where a > 1)")},
141
+ "SELECT * FROM (select * from cluster(c, database.t_01010101) FINAL where a > 1) AS tt",
142
+ ),
143
+ (
144
+ "SELECT * FROM tt FINAL",
145
+ {("", "tt"): ("", "(select a from table2 group by a)")},
146
+ "SELECT * FROM (select a from table2 group by a) AS tt FINAL",
147
+ ),
148
+ (
149
+ "SELECT * FROM tt FINAL",
150
+ {("", "tt"): ("", "(select count() from table2 where a > 1)")},
151
+ "SELECT * FROM (select count() from table2 where a > 1) AS tt FINAL",
152
+ ),
153
+ (
154
+ "SELECT * FROM tt FINAL",
155
+ {("", "tt"): ("", "(select * apply(sum) from table2 where a > 1)")},
156
+ "SELECT * FROM (select * apply(sum) from table2 where a > 1) AS tt FINAL",
157
+ ),
158
+ (
159
+ "SELECT * FROM tt FINAL",
160
+ {("", "tt"): ("", "(select * from (select a from table2 limit 1) where a > 1)")},
161
+ "SELECT * FROM (select * from (select a from table2 limit 1) where a > 1) AS tt FINAL",
162
+ ),
128
163
  ]
129
164
 
130
165
  def test_asterisks_no_database(self):
@@ -1313,7 +1348,8 @@ class TestDisabledFunctions(unittest.TestCase):
1313
1348
  max_memory_usage = 1000000,
1314
1349
  max_execution_time = 60,
1315
1350
  use_query_condition_cache = 0,
1316
- prefer_column_name_to_alias = 1
1351
+ prefer_column_name_to_alias = 1,
1352
+ final = 1
1317
1353
  """
1318
1354
  replacement = {("default", "a"): ("", "(SELECT count() FROM system.numbers LIMIT 1)")}
1319
1355
  replaced = chquery.replace_tables(sql, replacement, default_database="default")
@@ -1325,6 +1361,7 @@ class TestDisabledFunctions(unittest.TestCase):
1325
1361
  "max_execution_time",
1326
1362
  "use_query_condition_cache",
1327
1363
  "prefer_column_name_to_alias",
1364
+ "final",
1328
1365
  ):
1329
1366
  self.assertIn(key, out)
1330
1367