Skip to content

Check for cancellation while serializing values to String - #109257

Closed
groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:fix-toString-serialize-cancellation
Closed

groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:fix-toString-serialize-cancellation

Conversation

@groeneai

@groeneai groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

toString and CAST(... AS String) of a composite value (Dynamic, Array, JSON, ...) now check for query cancellation while serializing, so KILL QUERY and max_execution_time are honored during the conversion instead of only between pipeline blocks.

Description

toString/CAST(... AS String) of a composite value goes through ConvertImplGenericToString::execute, which loops over all rows in the current block calling serializeText per row. The query's time and cancellation limits are only checked between pipeline blocks (in PipelineExecutor), so a single large block kept a thread serializing for a long time after KILL QUERY or max_execution_time, with no way to interrupt it.

The server-side AST fuzzer (serverfuzz stress test) repeatedly hit this and tripped Hung check failed, possible deadlock found. The processlist showed a cancelled query (is_cancelled = 1) still running for hundreds of seconds, with the worker thread stuck in:

SerializationDynamic::serializeTextQuoted
  -> SerializationArray::serializeText
    -> ConvertImplGenericToString (toString)
      -> ExpressionTransform::transform -> PipelineExecutor

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108788&sha=a4eed43b831dbeebcc63925d98d9e95f1ef36d89&name_0=PR&name_1=Stress%20test%20%28amd_asan_ubsan%29

Fix: the per-row loop now calls QueryStatus::throwIfKilled() (a cheap atomic load that throws QUERY_WAS_CANCELLED / TIMEOUT_EXCEEDED once the query is cancelled; max_execution_time flips the flag via CancellationChecker). This mirrors the existing pattern for the base58 conversion (FunctionBaseXXConversion). The QueryStatus is taken from the query context in FunctionConvertSettings and is null for the context-less castColumn() path, where there is nothing to cancel.

Verified locally on a Debug build: KILL QUERY ... SYNC on a single-block toString(<Dynamic>) dropped from ~8.7s (blocked until the loop finished) to ~0.2s. The regression test 04401_to_string_dynamic_serialize_honors_cancellation fails without the fix (KILL blocks for the full serialization time) and passes with it.

This is a runtime value-serialization fix and is independent of #108863, which caps parser/AST-depth settings in the CI fuzzer/stress harness and does not bound this path.

toString/CAST to String of a composite value (Dynamic, Array, JSON, ...)
runs a per-row loop in ConvertImplGenericToString that calls serializeText
for every row. The query time and cancellation limits are only checked
between pipeline blocks, so a single large block kept a thread serializing
for a long time after KILL QUERY or max_execution_time, which the
server-side AST fuzzer repeatedly hit as "Hung check failed, possible
deadlock found" (SerializationDynamic::serializeTextQuoted ->
SerializationArray::serializeText -> ConvertImplGenericToString).

The loop now checks for cancellation per row via QueryStatus::throwIfKilled
(a cheap atomic load that throws QUERY_WAS_CANCELLED / TIMEOUT_EXCEEDED once
the query is cancelled; timeouts flip the flag via CancellationChecker), so
the query stops promptly. The QueryStatus is taken from the query context
in FunctionConvertSettings and is null for the context-less castColumn()
path, where there is nothing to cancel.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. KILL QUERY ... SYNC on a single-block SELECT toString(arrayMap(...)::Dynamic) FROM numbers(8000000) SETTINGS max_block_size=8000000, max_threads=1 blocks ~8.7s (until the serialize loop finishes) instead of returning promptly. Same shape with max_execution_time=1 returns TIMEOUT only after the full loop.
b Root cause explained? ConvertImplGenericToString::execute loops over all rows in the block calling serializeText per row (FunctionsConversion.h). The query's time/cancellation limits are only polled between pipeline blocks (PipelineExecutor), never inside a single action, so one big block keeps serializing after cancellation → the AST-fuzzer stress hung check fires with is_cancelled=1 still running.
c Fix matches root cause? Yes. Adds a per-row QueryStatus::throwIfKilled() inside that exact loop, so cancellation is observed during serialization, not only between blocks.
d Test intent preserved / new tests added? New test 04401_to_string_dynamic_serialize_honors_cancellation.sh added: launches a large single-block toString(Dynamic), KILLs it mid-loop, and asserts KILL ... SYNC returns in under 2s.
e Both directions demonstrated? Yes. Test FAILS on the no-poll binary (KILL blocked for 4.3s) and PASSES on the fixed binary (cancelled promptly, ~0.2-0.7s). KILL SYNC latency 8.7s → 0.17s.
f Fix is general across code paths? The fix covers all three ConvertImplGenericToString::execute call sites (FunctionConvert::executeImpl x2 and FunctionCast::createStringWrapper) via the shared FunctionConvertSettings. Sibling generic-serialize loops (concat, concatWithSeparator, format) have the same structural gap but are separate functions with no observed hang; noted as follow-up rather than speculatively expanded (no repro).
g Fix generalizes across inputs? Yes. The check is type-agnostic: it fires for any composite value routed through generic text serialization (Dynamic, Array, Map, Tuple, JSON, Nullable/LowCardinality wrappers). Correctness spot-checked unchanged across Int/String/Array/Map/Tuple/NULL Dynamic.
h Backward compatible? Yes. No setting/format/behavior change; the only observable difference is that a cancelled query now stops sooner. No SettingsChangesHistory entry needed.
i Invariants and contracts preserved? Yes. throwIfKilled() is a noexcept-clean atomic load that throws only when the query is already cancelled (an existing, expected exception path in this loop). query_status is null on the context-less castColumn() path, where there is nothing to cancel, so that path is unchanged. No data-structure or concurrency invariant is touched.

Session id: cron:clickhouse-worker-slot-6:20260703-042500

@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @rschu1ze — could you review this? It makes the per-row serializeText loop in toString/CAST(... AS String) (ConvertImplGenericToString) check for query cancellation, so KILL QUERY and max_execution_time are honored while serializing a large single block of composite values (Dynamic/Array/JSON). The AST-fuzzer serverfuzz stress test repeatedly hit the uninterruptible loop as a hung check.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f6a1ad2]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) FAIL
01666_merge_tree_max_query_limit FAIL cidb
Integration tests (amd_tsan, 1/6) ERROR
test_postgresql_replica_database_engine/test_1.py::test_restart_server_while_replication_startup_not_finished FAIL cidb
test_postgresql_replica_database_engine/test_1.py::test_abrupt_server_restart_while_heavy_replication FAIL cidb
test_postgresql_replica_database_engine/test_1.py::test_quoting_1 FAIL cidb
test_postgresql_replica_database_engine/test_1.py::test_quoting_2 FAIL cidb
test_postgresql_replica_database_engine/test_1.py::test_user_managed_slots FAIL cidb
test_postgresql_replica_database_engine/test_1.py::test_bool_and_bool_array FAIL cidb
test_postgresql_replica_database_engine/test_1.py::test_merge_table_over_materialized_postgresql FAIL cidb
Timeout FAIL cidb

AI Review

Summary

This PR adds per-row timeout and cancellation polling to the generic composite-to-text conversion loops used by toString / CAST(... AS String) and the serialize/parse-back path for CAST(... AS JSON), so large single-block conversions do not run until block end before noticing KILL QUERY or max_execution_time. The current head still has one unresolved contract gap around timeout_overflow_mode = 'break': the implementation turns the soft timeout into an exception inside the row loop, and the regression only checks timing under FORMAT Null, so the visible partial-result behavior is still not demonstrated.

Findings

⚠️ Majors

  • [src/Functions/FunctionsConversion.cpp:56-62, src/Functions/FunctionsConversion.h:937-941, src/Functions/FunctionsConversion.cpp:1855-1863, src/Functions/FunctionsConversion.h:2852-2857, tests/queries/0_stateless/04401_to_string_dynamic_serialize_honors_cancellation.sh:47-86] timeout_overflow_mode = 'break' promises a partial result, but throwIfQueryCancelled converts the soft false from checkTimeLimit() into a thrown TIMEOUT_EXCEEDED. In all three loops the output column/string is built in a local buffer and is only published on normal return, so there is no code here that preserves the already-converted row prefix when the soft timeout fires; the current block can only be dropped. 04401 cannot disprove that because it runs under FORMAT Null and checks only duration / exit status. Suggested fix: either preserve break explicitly (stop the loop without throwing and return a coherently truncated result), or add a non-Null regression that proves the current observable break behavior is intentionally acceptable.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Clarify or preserve the timeout_overflow_mode = 'break' contract for these row-wise conversion loops.
    • Add focused coverage that checks the visible break result, not just timing under FORMAT Null.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 3, 2026
bc is not installed on the Fast test runner, so the elapsed-time
comparison wrote 'bc: command not found' to stderr and the test failed.
awk already runs on that line and does the float subtraction natively,
so drop the external bc dependency. The prompt-vs-blocked discrimination
(d < 2) is unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

Fix-up pushed (2986e0f): the new test 04401_to_string_dynamic_serialize_honors_cancellation.sh used bc for the elapsed-time comparison, but bc is not installed on the Fast test runner (line 38: bc: command not found), which broke the test. awk already runs on that line and does the float subtraction natively, so I dropped the external bc dependency. Re-posting the validation gate since the .sh changed.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Under a bc-less PATH the old line (`awk -v d="$(echo "$end - $start"
b Root cause explained? The .sh shelled out to bc to subtract two $EPOCHREALTIME floats. The Fast test runner image has no bc → the command substitution fails, writes to stderr, and passes empty/garbage into awk. The C++ cancellation behavior worked (CI stdout already showed cancelled promptly); only the bc call broke the check.
c Fix matches root cause? Yes. Remove the sole external dependency: awk (already invoked on that line, present in all CI images) does d = e - s natively. No bc, no other tool.
d Test intent preserved / new tests added? Preserved byte-for-byte. The discrimination d < 2 → cancelled promptly else KILL blocked for %.1fs is unchanged; .reference (cancelled promptly) unchanged. The test still proves KILL QUERY SYNC returns promptly only when per-row cancellation is honored.
e Both directions demonstrated? Yes, at shell level under a bc-less PATH: OLD line → broken (bc: command not found, wrong output); NEW line → stdout cancelled promptly, empty stderr; NEW line with a slow 8.7s delta → KILL blocked for 8.7s. Verified awk float precision matches bc to microseconds on the real ~1.78e9 $EPOCHREALTIME magnitudes.
f Fix is general across code paths? N/A (test-only shell fix, not a code bug). bc was the only external-tool dependency in the script; $EPOCHREALTIME is a bash builtin (already worked in CI).
g Fix generalizes across inputs? N/A (test-only shell fix). awk e - s handles the same float range bc did; checked fast/slow/boundary (exactly 2.0s, 1.999s) cases.
h Backward compatible? N/A (test-only shell fix).
i Invariants and contracts preserved? N/A (test-only shell fix). No source, format, or setting change; only removes an unavailable external binary from one test.

Session id: cron:clickhouse-worker-slot-6:20260703-083300

Comment thread src/Functions/FunctionsConversion.h Resolved
…test

The per-row cancellation check in ConvertImplGenericToString used
QueryStatus::throwIfKilled(), which only observes state set by cancelQuery()
(KILL QUERY and the `throw` timeout overflow mode). For
timeout_overflow_mode = 'break', CancellationChecker::cancelTask() calls
checkTimeLimit() and never sets is_killed, so the per-row poll stayed a no-op
for the whole serialize loop and max_execution_time was not honored in that
mode. Switch to QueryStatus::checkTimeLimit(), which throws for KILL/`throw`
and returns false for `break`; turn the `break` result into a hard stop since
a half-serialized value is not a useful partial result (same pattern as
FunctionBaseXXConversion and sleep()).

Rewrite 04401 to gate on a phase-specific signal instead of assuming a fast
KILL means success. It measures the natural (unlimited) run time, sets
max_execution_time to ~45% of it (past input building, inside serialization),
and asserts from query_log that the query stopped near the limit rather than
running to natural completion; it fails loudly if the query finished early
(e.g. a randomized limit or an unrelated failure) or ran to the end
(cancellation not observed inside serialization). Covers both `throw` and
`break` modes and adds no-random-settings since the assertion is timing-based.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate for the review-fix commit ae3bdc2 (honor break-mode timeout + harden the test).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Single 8M-row block, toString(...::Dynamic), max_block_size covering all rows, max_threads=1. max_execution_time=3, timeout_overflow_mode='break' → runs to full serialization (~7s) on a no-per-row-check baseline; throw mode → exception reports elapsed ~7.7s. Deterministic every run.
b Root cause explained? throwIfKilled() only acts on is_killed, which cancelQuery() sets (KILL QUERY, throw overflow mode). For timeout_overflow_mode='break', CancellationChecker::cancelTask() calls checkTimeLimit() and never sets is_killed, so the per-row poll was a no-op and max_execution_time was ignored for the whole (single-block) serialize loop.
c Fix matches root cause? Yes. Switched the per-row poll to QueryStatus::checkTimeLimit(), which evaluates the time limit directly (throws for KILL/throw, returns false for break); the false is turned into a hard TIMEOUT_EXCEEDED. Directly targets the missed break path.
d Test intent preserved / new tests added? Test rewritten to be stronger: it now gates on a phase-specific query_log signal proving cancellation was observed inside serialization, and fails loudly if the query finished early or ran to natural completion. Covers both throw and break.
e Both directions demonstrated? Yes. The rewritten test PASSES with the fix and FAILS loudly against a baseline binary with no per-row check (throw duration=7140ms, break duration=6987ms, both outside the [2800,5398]ms window). Stable over 5 repeats with the fix.
f Fix is general across code paths? ConvertImplGenericToString is the single generic composite→String serialization path; all three call sites (toString, CAST AS String, custom-serialization) already thread settings.query_status through. No sibling path has the same loop. Not a defensive guard: it interrupts at the real cost site.
g Fix generalizes across inputs (params/datatypes/wrappers)? The check is type-agnostic (per row, before serializeText), so it applies uniformly to any composite type (Dynamic/Array/JSON/Map/Tuple/Nullable/LowCardinality...). It now honors both timeout overflow modes and KILL. query_status is null on the context-less castColumn() path (nothing to cancel) → safe no-op.
h Backward compatible? Yes. No setting default, format, or protocol change. Purely makes an already-cancellable operation also honor max_execution_time in break mode. A query that previously ran to completion despite an exceeded limit now respects the limit — the documented contract.
i Invariants and contracts preserved? Yes. checkTimeLimit() is the same primitive used by FunctionBaseXXConversion/sleep()/ReadProgressCallback; calling it per row adds one cheap clock_gettime+atomic. break mode has no valid partial-column result (would violate block equal-column-size invariant), so the hard stop is required, not optional. Throwing mid-loop is exception-safe (RAII WriteHelper/buffers).

Session id: cron:clickhouse-worker-slot-5:20260703-092800

Comment thread src/Functions/FunctionsConversion.h Resolved
The per-row cancellation check only polls between rows, so a single row
holding one huge Array/Map/JSON/Dynamic value stays inside one
serializeText() call (the container serializer's own inner loops) and was
still uninterruptible by KILL QUERY / max_execution_time.

Interpose a small fixed-size cancellation-checking WriteBuffer between the
serializer and the column buffer. Every byte the (arbitrarily nested)
serializer emits flushes through it at a fixed cadence, where it checks
the query time/cancellation limit before forwarding to the real buffer.
This needs no changes to any Serialization class and gives a bounded,
value-size-independent latency (the existing WriteBufferFromVector doubles
its buffer, so a check there would leave a gap of ~half the value's size).

04401 now also covers a single giant composite value with max_block_size=1,
asserting it stops near the limit instead of running to natural completion,
in both throw and break modes.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate for dbc4f6a (interrupt serialization of a single huge composite value).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT toString(arrayMap(x -> arrayMap(y -> range(y % 8), range(x % 40)), range(6000000))::Dynamic) FROM numbers(1) FORMAT Null SETTINGS max_block_size=1, max_threads=1, max_memory_usage=0, max_execution_time=2 runs one row holding one huge value. On a local Debug build it takes ~5s to serialize; with the fix it stops at ~2s, without it runs the full ~5s.
b Root cause explained? The per-row throwIfQueryCancelled only runs between rows. A single row can hold one huge Array/Map/JSON/Dynamic value; serialization->serializeText() for that one value runs the container serializer's own inner loops and never returns control to the per-row loop, so KILL QUERY / max_execution_time are ignored until the whole value is rendered (the between-block pipeline check only fires afterwards).
c Fix matches root cause? Yes. A fixed-size CancellationCheckingWriteBuffer is interposed between the serializer and the column buffer. Every byte the (nested) serializer emits flushes through it, and it calls checkTimeLimit() on each flush, so cancellation is observed inside a single serializeText(). It targets the exact mechanism, not a symptom.
d Test intent preserved / new tests added? Both shapes are now asserted in 04401: the existing many-rows-in-one-block case is unchanged, and a new max_block_size = 1 single-giant-value case asserts the query stops near the limit (not at natural completion) in both throw and break modes. Nothing was weakened.
e Both directions demonstrated? Yes, through clickhouse-test. With the fix: [ OK ], stable 6/6. Against a build with only the per-row check: [ FAIL ] with duration=5009ms/5028ms ... (cancellation not observed inside serialization) on the single-value case (the multi-row case still passes there).
f Fix is general across code paths? The check sits on the WriteBuffer, which every recursive text serializer (SerializationArray/Map/JSON/Dynamic/Tuple, ...) writes through, so all nesting is covered by one hook rather than patching each serializer. Both ConvertImplGenericToString instantiations (ColumnString, ColumnFixedString) go through it.
g Fix generalizes across inputs? Correctness re-checked (unchanged output) for Array, Map, Tuple, Dynamic, JSON, CAST(... AS String) and CAST(... AS FixedString) including the padding invariant, plus edge cases: empty array, empty string, NULL. The cancellation cadence is byte-based, so it is independent of value type and size.
h Backward compatible? Yes. No setting default, on-disk/wire format, or user-visible behavior change. toString/CAST output is byte-identical; the only new behavior is that an already-supported cancellation/timeout is now honored sooner.
i Invariants and contracts preserved? Yes. CancellationCheckingWriteBuffer follows the standard forwarding-WriteBuffer contract (nextImpl forwards to out, finalizeImpl flushes, destructor cancels if not finalized). WriteHelper::finishRow() still sees the correct count() because each row is flushed down to the underlying buffer before finishRow(). Verified no WriteBuffer is neither finalized nor canceled dtor assertion and no LOGICAL_ERROR across repeated mid-value timeouts on a Debug build.

Session id: cron:clickhouse-worker-slot-10:20260703-115000

Comment thread src/Functions/FunctionsConversion.cpp Resolved
…ON cast

The Tuple/Map/Object -> JSON fallback serializes each row into an intermediate
ColumnString and then parses that string back into a JSON column. Both loops ran
uninterrupted for a whole block, so CAST(... AS JSON) still ignored KILL QUERY and
max_execution_time one conversion over.

Reuse the existing hook in the serialize loop (per-row throwIfQueryCancelled plus
the shared CancellationCheckingWriteBuffer for a single huge value), and add the
same per-row check to the generic from-String parse loop, which dominates the cost
of this cast. Extend 04401 with a many-rows CAST(Map AS JSON) case that fails loudly
without the parse-back check.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CAST(map('id', number, 'vals', arrayMap(x -> x, range(number % 30))) AS JSON) FROM numbers(6000000) in one block with max_execution_time at ~45% of natural runs to natural completion (~8.5s) without the parse-back check; a KILL QUERY ... SYNC mid-parse-back returns in ~7s (query stuck in one deserializeObject).
b Root cause explained? CAST(Tuple/Map/Object AS JSON) has two per-row loops in createObjectWrapper: serialize each row to a JSON string, then parse it back into a JSON column (ConvertImplGenericFromString). Time/cancellation limits are only checked between pipeline blocks, so for one big block both loops ran to the end; the parse-back half dominates the cost, so a limit was ignored for the whole block.
c Fix matches root cause? Yes. Serialize loop reuses the existing hook (per-row throwIfQueryCancelled + shared CancellationCheckingWriteBuffer); parse-back loop gets the same per-row throwIfQueryCancelled. No new mechanism, no serialization-interface change.
d Test intent preserved / new tests added? Added a many-rows CAST(Map AS JSON) case (json_many) to 04401, alongside the existing to-String cases. Phase-gated (asserts stop near limit vs natural), no-random-settings.
e Both directions demonstrated? Yes. Local Debug: passes with the fix (stops at limit, both modes); the json_many case fails loudly with the parse-back check disabled (duration=8612ms limit=4000ms ... cancellation not observed). To-String cases pass in both builds. Build IDs verified distinct.
f Fix is general across code paths? Yes. This is exactly the sibling-path generalization the finding asked for: the same uninterruptible per-row loop existed one conversion over, in both the serialize and parse-back halves of the JSON cast. Both are now covered. The one remaining shape (single huge value whose parse-back stays inside one deserializeObject) is documented in-thread as out of scope, as covering it needs a callback through the shared JSONExtractTree hierarchy (the blast radius this PR avoids); the serialize half of such a value is already interruptible and the common many-rows case is fully covered.
g Fix generalizes across inputs (params/datatypes/wrappers)? The per-row check is type-agnostic (fires before each row regardless of value type). Correctness verified unchanged for Map/Tuple/Array/Nullable/NULL/empty-map/FixedString-padding to-String and to-JSON.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format, or default changes. Behavior change is limited to honoring already-existing KILL QUERY / max_execution_time sooner; a query within its limit is unaffected.
i Invariants and contracts preserved? Yes. CancellationCheckingWriteBuffer forwards every byte to the real buffer and flushes per row before finishRow() reads its count (offsets stay correct); its destructor cancels on unwind. Verified no dangling-buffer chassert / LOGICAL_ERROR over repeated mid-conversion timeouts on a Debug build. The parse-back check is placed before per-row work and does not alter parse results.

Session id: cron:clickhouse-worker-slot-10:20260703-142100

The new test failed CI two ways: a deterministic TOO_MANY_ROWS_OR_BYTES on
arm_binary (the queries build results larger than CI's default max_result_bytes
before FORMAT Null discards them), and a process-group Timeout in the flaky check
(a multi-second wall-clock timing test run 50x under sanitizers).

Add max_result_bytes = 0 to the queries, tag no-flaky-check (running a latency test
50x validates nothing and risks the timeout), and shrink the datasets so each run is
a few seconds. The natural-time-relative assertion is unchanged; verified it still
fails loudly against a build without the parse-back cancellation check.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up (b640b21): fixed two CI failures the new test 04401 caused on the previous head.

  • TOO_MANY_ROWS_OR_BYTES on Stateless tests (arm_binary, parallel): the queries build results larger than CI's default max_result_bytes before FORMAT Null discards them. Added max_result_bytes = 0 to the queries.
  • Process-group Timeout! in the flaky check: this is a wall-clock latency test (measures that a query stops near its max_execution_time rather than running to natural completion). Running it 50x under sanitizers validates nothing about output determinism and risks the timeout, so it is tagged no-flaky-check; the datasets were also shrunk so each run is a few seconds.

The natural-time-relative assertion is unchanged and still fails loudly against a build without the parse-back cancellation check.

Comment thread src/Functions/FunctionsConversion.h Resolved
@Avogar Avogar self-assigned this Jul 3, 2026
The per-case max_execution_time was ceil(0.45 * natural) seconds. For the
single-value case (natural ~2.3s) that rounded a ~1s intent up to 2s, leaving
only ~300ms between the limit and the natural time. Run-to-run variance then
occasionally pushed an execution below the 2s limit, so no TIMEOUT_EXCEEDED
fired and the two single-case lines went missing (flaky on the fast
arm_binary runner).

Use floor(natural * 0.35) seconds (min 1s) so the limit stays at ~0.35x the
natural time with a wide margin, and widen the acceptance window upper bound
to 0.7 * natural. Verified in both directions on a local debug build: with the
fix all shapes stop at ~1s (8/8 harness runs pass, output unchanged); with the
cancellation checks reverted all shapes run to their natural time and the test
fails loudly.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 78466d5 to fix the remaining arm_binary, parallel flakiness of the new test (the two single-case TIMEOUT_EXCEEDED lines were dropping on fast runners). Test-only change.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CIDB diagnosis on b640b21: Stateless tests (arm_binary, parallel), "Runs 3, Failed 2", diff @@ -1,12 +1,10 @@ (the two single-case TIMEOUT_EXCEEDED lines missing). Reproduced the mechanism locally: single-case natural=2317ms -> limit=ceil(0.45*natural)=2s -> only ~300ms margin -> a run below 2s skips the timeout.
b Root cause explained? max_execution_time is integer seconds. ceil(0.45*natural) rounded a ~1.04s intent up to 2s for the single case (natural ~2.3s), leaving margin (natural-limit) ~300ms, smaller than run-to-run variance. Some executions then finish below the 2s limit, no TIMEOUT_EXCEEDED fires, and the expected lines are missing.
c Fix matches root cause? Yes. Use floor(natural*0.35) seconds (min 1s) so the limit sits at ~0.35x natural with a wide margin, and set the window upper bound to 0.7*natural. This directly removes the thin-margin/round-up mechanism from (b).
d Test intent preserved / new tests added? Yes. Still asserts the query stops near the limit (not at natural completion) in both throw and break modes across all three shapes; .reference is unchanged. No assertion weakened.
e Both directions demonstrated? Yes, local debug. FIX (build 1a31f57d): 8/8 harness runs pass, output matches .reference, empty stderr. BASELINE (cancellation checks reverted, build fe9ef923): all shapes run to their natural time (~2.2-3.3s), landing outside the window, and the test fails loudly.
f Fix is general across code paths? N/A (test-only change; the C++ cancellation fix and its code-path coverage are unchanged from the earlier commits).
g Fix generalizes across inputs? N/A (test-only). The limit/window are now derived from each case's measured natural time, so the same logic adapts across all three shapes and build types.
h Backward compatible? N/A (test-only, no product behavior or setting changed).
i Invariants and contracts preserved? Yes. limit >= 1 is enforced (max_execution_time must be a positive integer); the window [0.5*limit*1000, 0.7*natural] is non-empty whenever natural > ~1.4*limit, which holds for all three shapes (natural >= ~2x the limit).

Session id: cron:clickhouse-worker-slot-14:20260703-161800

@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 78466d5

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, parallel) / 04061_spilling_hash_join_overflow_limits flaky (CI randomizes query_plan_join_swap_table -> tiny left table becomes build side -> join size limit never hit -> expected error 191 not thrown) #109334 (ours, open)
CH Inc sync — CH Inc sync (private, not actionable)

PR-caused gate: ZERO. This PR adds a cancellation check while serializing values to String; the failing test is an unrelated hash-join spilling flaky owned by the open fixing PR above.

Session id: cron:our-pr-ci-monitor:20260703-210000

@Avogar Avogar left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Using CancellationCheckingWriteBuffer to check the query cancellation or timeout per string reallocation sounds like an overkill to me, can we leave just check per row?

@rschu1ze

rschu1ze commented Jul 7, 2026

Copy link
Copy Markdown
Member

Agree with @Avogar. I find it even doubtful to check per row if the query was cancelled. If we really want to do this consistently across the code base, then hundreds, probably over one thousand SQL function implementations need to be changed.

Per @Avogar and @rschu1ze review: checking cancellation per string
reallocation via a CancellationCheckingWriteBuffer is overkill. Drop it
and keep only the per-row QueryStatus::throwIfKilled() poll in the
generic to-String and to-JSON serialize loops and the from-String parse
loop. This covers the common many-rows-in-one-block hang, which is the
shape the server-side fuzzer hit. The 04401 regression keeps the two
multi-row shapes (both interrupted by the per-row check); the
single-huge-value shape that needed the write buffer is dropped.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

@Avogar @rschu1ze agreed, simplified in fbe3e73. Dropped CancellationCheckingWriteBuffer entirely; the only cancellation hook now is the per-row throwIfQueryCancelled at the top of the generic to-String and to-JSON serialize loops and the from-String parse loop. This is the shape the server-side fuzzer actually hit (many rows in one block after KILL QUERY / max_execution_time), and it is one cheap atomic load per row.

On rschu1ze's wider point: this does not try to make every serialization consistently interruptible, it only adds the per-row poll to the three generic-serialization loops in FunctionsConversion that are reached by toString/CAST(... AS String|JSON) of a composite value, which is where the fuzzer parked a cancelled query for hundreds of seconds. Diff is now +150/-4 (was +224/-6).

The 04401 regression is trimmed accordingly: the two remaining shapes (many, json_many) are multi-row and are interrupted by the per-row check; the single-huge-value shape that only the write-buffer could interrupt is removed. Verified locally both directions on a Build-ID-matched debug binary (fails without the per-row check, passes with it).

@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 04401 shape many/json_many: one block of many rows, max_execution_time set to floor(0.35*natural) with timeout_overflow_mode throw/break; without the per-row check the query runs to natural completion (no cancellation observed inside the loop), with it the query stops near the limit.
b Root cause explained? The generic serialize/parse loops in ConvertImplGenericToString, the Tuple/Map/Object->JSON serialize loop, and ConvertImplGenericFromString iterate a whole block with no time/cancellation check (limits are only checked between pipeline blocks), so a big single block keeps a thread working after KILL QUERY / max_execution_time and trips the hung check.
c Fix matches root cause? Yes. A per-row throwIfQueryCancelled(query_status) (cheap atomic load) at the top of each loop makes it interruptible between rows, which is exactly the many-rows-in-one-block shape the fuzzer hit.
d Test intent preserved / new tests added? Preserved. The regression asserts the query stops near its limit (duration window), not merely that TIMEOUT is thrown; the two multi-row shapes still fail loudly without the fix. The single-huge-value shape (only interruptible by the removed write buffer) is dropped since the write buffer is dropped.
e Both directions demonstrated? Yes. Debug binary (Build ID verified against the running server): with the per-row check 04401 [ OK ]; with the check no-op'd the multi-row shapes run to ~natural and FAIL the duration-window assertion.
f Fix is general across code paths? Yes. The per-row poll is applied to all three generic conversion loops (to-String, to-JSON serialize, from-String parse) reached by composite toString/`CAST(... AS String
g Fix generalizes across inputs? Yes. The check is per-row and value-type-independent (Array/Map/Tuple/Dynamic/JSON/Nullable/LowCardinality/FixedString all take the same loop). The one shape it does NOT cover, a single row whose one huge value serializes without returning control, was investigated earlier in this PR (bounded for FixedString by MAX_FIXEDSTRING_SIZE; the deeper composite case needs cancellation plumbed through the shared recursive serializers, the large blast radius the maintainers asked to avoid).
h Backward compatible? Yes. No setting, format, or default changed. query_status is null when there is no query context (e.g. castColumn()), so the check is a no-op there.
i Invariants and contracts preserved? Yes. throwIfQueryCancelled only reads QueryStatus and throws; it does not touch the write buffer, block structure, or column sizes. Removing the interposing buffer restores serialization to write directly into write_buffer exactly as before the PR, so WriteHelper::finishRow() sees the same byte count.

Session id: cron:clickhouse-worker-slot-0:20260707-160200

/// checkTimeLimit() honors KILL QUERY and max_execution_time in both timeout overflow modes; it returns
/// false (instead of throwing) for `break`, which we turn into a hard stop since a half-converted value
/// is not a useful partial result. Mirrors FunctionBaseXXConversion.
if (query_status && !query_status->checkTimeLimit())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

timeout_overflow_mode = 'break' is documented to return a partial result, but this helper turns the soft-timeout false from checkTimeLimit() into a thrown TIMEOUT_EXCEEDED. That "throw on false" pattern is fine in places like arrayFold / FunctionBaseXXConversion, where there is no meaningful partial value, but here the loop already has a prefix of fully converted rows.

In other words, after the simplification to row-level polling only, the break behavior for these conversions is no longer obviously "return the partial result" so much as "let the pipeline absorb an exception and drop the current block". 04401 cannot distinguish those outcomes because it runs under FORMAT Null and only checks exit status / duration. Please either preserve the soft-break semantics for these row-wise loops, or add a non-Null regression that proves the observable break result is still acceptable.

@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — fbe3e73

CI is complete (Finish Workflow passed; only the private "CH Inc sync" check remains, which does not run for fork PRs). Every failure below has an owner (a fixing PR or a full-effort fix task). None are caused by this PR's diff (this PR only touches FunctionsConversion.{cpp,h} + test 04401).

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / Inconsistent AST formatting (STID 1941-1bfa) pre-existing trunk LOGICAL_ERROR (function used as a data-type argument) #109713 (ours, open)
Performance Comparison (arm_release, master_head, 5/6) unstable query (aggregate_functions_of_group_by_keys #1), all rows report success a fix task is investigating the arm_release perf-comparison "unstable queries / errors while building the report" class at full effort
Mergeable Check / PR aggregators of the above same
CH Inc sync private ClickHouse-Inc sync CH Inc sync (private, not actionable by us)

Session id: cron:our-pr-ci-monitor:20260707-220000

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.40% -0.10%

Changed lines: Changed C/C++ lines covered: 34/35 (97.14%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — f6a1ad2

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit the per-table concurrency throttle is keyed on query id, and secondary parallel-replica reads are sent with an empty query id, so the holder query competes against itself and the 202 assertion gets code 0 #112385 (mine, open)
Integration tests (amd_tsan, 1/6) / test_postgresql_replica_database_engine/test_1.py (7 tests) + Timeout one server death cascading through the module's autouse setup_teardown fixture (Code: 210 Connection refused / Code: 209 SOCKET_TIMEOUT), not 8 independent test failures a fix task is created (investigating at full effort — fixing-PR link to follow here)

The 01666 line is a lane-reachability regression, not a defect in this PR: the test became
reachable on the ParallelReplicas lane when #111230 removed its parallel_replicas_blacklist.txt
entry, and it fails the same way on master.

The integration cascade is a trunk defect in the MaterializedPostgreSQL database engine
(materialized_tables is mutated without holding tables_mutex, so the async-metrics thread
iterates storages while a DROP destroys them). It reproduces on master and across many
unrelated PRs on the same shard. This PR's diff is src/Functions/FunctionsConversion.{cpp,h}
plus one stateless test, which cannot reach PostgreSQL replication.

Session id: cron:our-pr-ci-monitor:20260729-060000

@Avogar

Avogar commented Jul 29, 2026

Copy link
Copy Markdown
Member

I don't think we want this implementation. Because as Robert said, If we really want to do this check per row, we would need to change quite a lot of code across the database for consistency.

@Avogar Avogar closed this Jul 29, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Understood, withdrawn. I will not reopen this or push a variant.

The signature that motivated it (a cancelled query parked in SerializationDynamic::serializeTextQuoted under toString of a composite value) has not recurred in the last 45 days, and master still has no check on that path, so closing this regresses nothing. If it does recur I will add a checkpoint to the single loop that actually hangs rather than a per-row poll in the generic conversion path, which is the shape you and Robert asked for.

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-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants