Skip to content

Parse numeric 1/0 as Bool inside containers - #109976

Merged
Avogar merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-array-bool-csv-numeric-109882
Jul 30, 2026
Merged

Avogar merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-array-bool-csv-numeric-109882

Conversation

@groeneai

@groeneai groeneai commented Jul 10, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #109882

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):

Fix parsing of numeric 1/0 as Bool values inside container types (e.g. Array(Bool), Tuple(Bool, ...)). Previously [1,0] failed with CANNOT_READ_ARRAY_FROM_TEXT while [true,false] worked.

Description

SerializationBool::deserializeTextQuoted (the element reader used by Array/Tuple text parsing and by CSV array elements) handled the numeric forms 1/0 by inserting the value without advancing the read position, unlike the true/false and quoted-value branches. The container reader then saw the same digit where it expected a comma or closing bracket:

Cannot read array from text, expected comma or end of array, found '1' (CANNOT_READ_ARRAY_FROM_TEXT)

Scalar Bool was unaffected. The one-line fix advances the position for the 1/0 cases like every other branch. Verified [1,0], mixed [true,0,1,false], Array(Nullable(Bool)), Tuple(Bool,Bool) text, and CSV all parse correctly while true/false, the quoted '1' form, and scalar Bool remain unchanged. Regression test added in 04510_bool_numeric_in_containers.

Version info

  • Merged into: 26.8.1.448 (included in 26.8 and later)

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. SELECT CAST('[1,0]', 'Array(Bool)') and printf '"[1,0]"\n' | clickhouse local --input-format CSV --structure "x Array(Bool)" fail every time with CANNOT_READ_ARRAY_FROM_TEXT.
b Root cause explained? SerializationBool::deserializeTextQuoted inserts the value for the '1'/'0' cases without advancing istr.position() (unlike the true/false and quoted branches). The container element reader then sees the same digit where it expects a comma or ], so it throws. Scalar Bool uses a different path and is unaffected.
c Fix matches root cause? Yes. Adds the missing ++istr.position() to the '1'/'0' branches, exactly mirroring the other cases. No behavior widening.
d Test intent preserved / new tests added? New regression test 04510_bool_numeric_in_containers (parallel-safe .sql). No existing test weakened.
e Demonstrated in both directions? Fails on pristine build (Build ID 8d6f...), passes after fix (Build ID a771...).
f Fix general, not a narrow patch? Single shared element path deserializeTextQuoted — one fix covers Array, Tuple text, CSV array elements, and Nullable wrapping. Verified all.
g Generalizes across inputs / wrappers? Verified: [1,0], mixed [true,0,1,false], Array(Nullable(Bool)) with NULL, Tuple(Bool,Bool) text; word form true/false, quoted '1' form, and scalar Bool all still correct.
h Backward compatible? Yes. Only makes a previously-erroring input parse; no format/default/setting change.
i Invariants preserved? deserializeTextQuoted postcondition (position must be left after the consumed token) is now upheld on the 1/0 paths, matching every other branch.

Session id: cron:clickhouse-worker-slot-0:20260710-100400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Avogar for review. One-line fix in SerializationBool::deserializeTextQuoted: the '1'/'0' cases inserted the value without advancing the read position, so [1,0] inside Array(Bool)/Tuple(Bool,...) and CSV array elements failed with CANNOT_READ_ARRAY_FROM_TEXT. Fixes #109882.

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

clickhouse-gh Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dfdee5a]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_tsan, 3/6) FAIL
test_replicated_database/test.py::test_replicated_table_structure_alter FAIL cidb, issue

AI Review

Summary

This PR fixes the CANNOT_READ_ARRAY_FROM_TEXT failure for numeric 1 / 0 inside Bool containers by advancing the read position in deserializeTextQuotedImpl, and the new 04510 regression file covers the affected Array / Tuple / Map paths well. I do not think the current head is safe to merge, because the same shared helper is also used by Variant / Dynamic, and this change re-enables bare numeric 1 / 0 as Bool there even when allow_special_bool_values_inside_variant = 0.

Findings

❌ Blockers

  • [src/DataTypes/Serializations/SerializationBool.cpp:409-417] The container fix is applied in a helper that Variant / Dynamic also use. SerializationVariant::tryDeserializeVariantFromField deliberately copies allow_special_bool_values_inside_variant into allow_special_bool_values before it tries Bool, but after the new ++istr.position() the bare 1 / 0 branch now reaches EOF and wins over the integer variants anyway. The 03158_dynamic_type_from_variant.reference update in this PR is the visible regression: values that used to stay UInt32 / String now become Bool by default.
    Suggested fix: either honor settings.allow_special_bool_values in the bare 1 / 0 quoted-path branches, or keep the position-advance change out of the shared quoted parser so only the container readers get the delimiter fix.
Final Verdict

Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fix update — Fast test regression on 03158 addressed (head 0aba3a7)

The first attempt (++istr.position() on the 1/0 branches of deserializeTextQuotedImpl) fixed container parsing but changed Variant/Dynamic type inference: bare 0/1 were greedily read as Bool instead of falling through to wider numeric types, changing 03158_dynamic_type_from_variant.

Root cause: deserializeTextQuotedImpl accepted numeric 1/0 unconditionally, bypassing the allow_special_bool_values gate that deserializeImpl already honors. SerializationVariant::tryDeserializeVariantFromField intentionally sets allow_special_bool_values = allow_special_bool_values_inside_variant (default false) so 1/0 are NOT consumed as Bool during inference.

Fix: gate the 1/0 branches on settings.allow_special_bool_values, mirroring deserializeImpl.

Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro Yes: CAST('[1,0]','Array(Bool)') failed with CANNOT_READ_ARRAY_FROM_TEXT; 03158 diff reproduced on branch HEAD
b Root cause explained 1/0 accepted without honoring allow_special_bool_values; Variant inference disables that flag so tokens must fall through to numeric types
c Fix matches root cause Gates the two numeric branches on the same flag deserializeImpl uses
d Test intent preserved 03158 now byte-matches committed reference; scalar Bool CSV 1/0 unchanged; word form unchanged
e Both directions 04510 fails on ungated HEAD, passes with gate; 03158 fails on ungated HEAD, matches reference with gate
f Fix general, not narrow Single shared quoted-text path used by Array/Tuple/Map/Nullable element readers and Variant; all covered
g Generalizes across inputs Verified Array(Bool), Array(Nullable(Bool)), Tuple(Bool,Bool), Map(String,Bool), mixed word/numeric; allow_special_bool_values_inside_variant=1 still opts numeric-in-Variant back in
h Backward compatible Restores pre-existing Variant/Dynamic inference behavior (no on-disk/wire/setting-default change); container 1/0 was already broken (CANNOT_READ_ARRAY_FROM_TEXT), so no regression
i Invariants preserved Quoted-text reader contract unchanged; position always advanced on accept; error path unified via parse_error

Session id: cron:clickhouse-worker-slot-0:20260710-110300

@groeneai

Copy link
Copy Markdown
Collaborator Author

Added Map(String, Bool) cases to 04510_bool_numeric_in_containers (ef84bd9): Values (text) and CSV, both numeric {'a':1,'b':0} and word {'a':true,'b':false}, all parsing to {'a':true,'b':false}. Confirms the shared deserializeTextQuoted contract now holds across Array, Tuple, and Map.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Added opt-in-direction coverage in 03365_variant_bool_parsing: numeric 1/0 under allow_special_bool_values_inside_variant = 1 now assert to Bool, and stay String in the default/off sections. Both directions of the gate are pinned. Pushed 25b50f4.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The Bugfix validation failure was PR-caused: the check runs every changed 5-digit test file against master HEAD and requires each to FAIL there (proving it catches the bug). 04510_bool_numeric_in_containers correctly fails on master (the [1,0] container case throws), but 03365_variant_bool_parsing is a pre-existing test I had extended, and its added numeric 1/0 cases pin the pre-existing allow_special_bool_values_inside_variant behavior, which does not depend on the SerializationBool fix. It passes on master, so the validation inverter flipped OK to FAIL.

Fixed in 2afe737: reverted 03365 to master and folded the opt-in-direction Variant coverage into 04510 instead. 04510 fails on master via the container case, so it stays a valid regression test while still pinning the gate in both directions:

  • allow_special_bool_values_inside_variant = 0 (default): 1/0 -> String
  • allow_special_bool_values_inside_variant = 1: 1/0 -> Bool

Verified with clickhouse-local against the fixed binary.

@Avogar Avogar self-assigned this Jul 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Good catch — the JSON path was still ungated. Fixed in 339f658.

SerializationBool::deserializeTextJSON / tryDeserializeTextJSON ignored FormatSettings and unconditionally read bare 1/0. Since Variant gives Bool higher priority than the integer types, SerializationVariant::tryDeserializeTextJSONImpl forwarding allow_special_bool_values_inside_variant into the nested call had no effect on JSON, so {"v":1} for Variant(Bool, UInt32) landed in Bool even with the setting off.

The numeric 1/0 branch now requires settings.allow_special_bool_values, mirroring the text/CSV gate. Word form true/false is unchanged, and a plain Bool JSON column (where the base setting defaults to true) still accepts 1/0.

Verified against Variant(Bool, UInt32):

  • setting off (default): {"v":1} -> 1 UInt32, {"v":0} -> 0 UInt32
  • setting on: {"v":1} -> true Bool, {"v":0} -> false Bool

04510_bool_numeric_in_containers now covers both JSON directions alongside the existing text/CSV cases.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 339f658

All checks finished (Finish Workflow success). The PR's own numeric-1/0 Bool-parsing tests all pass on this head: 03158_dynamic_type_from_variant, 03365_variant_bool_parsing, and 04510_bool_numeric_in_containers are OK across Fast test, amd_debug/asan/tsan/msan/llvm_coverage and arm variants. The earlier 03158/03365 failures were on superseded commits (1656abf / 25b50f4), before the revert and the JSON gate; they no longer reproduce.

The remaining red checks are pre-existing/unrelated to this PR. Each has an owner:

Check / test Reason Owner
Stress test (arm_tsan) / Block structure mismatch in JoinStep (STID 0993-308a) pre-existing trunk fuzzer bug (102 hits / 83 PRs / 9 master, 30d) — issue #109215 a full-effort fix task tracks it (fixing-PR link to follow)
Stress test (arm_tsan) / Hung check failed, possible deadlock chronic trunk deadlock family (1970 hits / 699 PRs / 390 master, 30d) a full-effort fix task tracks it (fixing-PR link to follow)
Stateless (amd_asan_ubsan, distributed plan, parallel) / 04401_distributed_with_fill_const_to_scalar trunk regression under --prefer_localhost_replica 0 (22 hits / 17 PRs / 6 master, all 2026-07-10) a fix task is in progress (fixing-PR link to follow)
Integration tests (amd_tsan, 1/6) / test_rename_distributed_parallel_insert_and_select pre-existing flaky (7 hits / 7 PRs / 0 master, 30d) a full-effort fix task tracks it (fixing-PR link to follow)

None of these touch Bool serialization; they are not caused by this PR's diff.

Session id: cron:clickhouse-worker-slot-12:20260710-210200

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 339f658

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. All three failures are pre-existing / unrelated to this PR's diff (SerializationBool.cpp + 04510 regression test); confirmed by 30-day cross-PR spread.

Check / test Reason Owner / fixing PR
Stateless tests (amd_asan_ubsan, distributed plan, parallel) / 04401_distributed_with_fill_const_to_scalar flaky (randomized prefer_localhost_replica) a fix task is created (investigating at full effort — fixing-PR link to follow here)
Integration tests (amd_tsan, 1/6) / test_rename_column::test_rename_distributed_parallel_insert_and_select flaky (concurrent rename + merge race) a fix task is created (investigating at full effort — fixing-PR link to follow here)
Stress test (arm_tsan) / Block structure mismatch in JoinStep (STID 0993-308a) crash / logical error (decorrelated correlated subquery, duplicate column name) #109114 (ours, open)

Session id: cron:our-pr-ci-monitor:20260710-213000

@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.

It's 2 complitely different fixes. One - bug in not advancing position during parsing of 1/0 as Bool in deserializeTextQuotedImpl. Second - not gating 1/0 as under allow_special_bool_values. The PR description and changelog mention that this a fix for the first issue, and changes were very confusing to me. Split changes with allow_special_bool_values into a separate PR.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed, splitting. #109976 will keep only the position-advance fix in deserializeTextQuotedImpl (the CANNOT_READ_ARRAY_FROM_TEXT bug for [1,0]) plus its container regression tests. The allow_special_bool_values gating (JSON/Variant/quoted paths) moves to a separate PR, which I'll link here.

SerializationBool::deserializeTextQuoted handled the numeric forms 1/0
by inserting the value without advancing the read position, unlike the
true/false and quoted-value branches. The container reader then saw the
same digit where it expected a comma or closing bracket and failed with
CANNOT_READ_ARRAY_FROM_TEXT for inputs like [1,0]. Advance the position
in the 1/0 cases like every other branch.

Closes: ClickHouse#109882

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

Copy link
Copy Markdown
Collaborator Author

Split done. The allow_special_bool_values JSON/Variant gating now lives in #110835. This PR (#109976) keeps only the position-advance fix in deserializeTextQuotedImpl (the [1,0] CANNOT_READ_ARRAY_FROM_TEXT bug) plus its container regression tests.

The position-advance fix in deserializeTextQuotedImpl lets Bool consume bare
1/0 to EOF, so the Variant deserializer (Bool has higher priority than
integers) now selects Bool instead of falling through to UInt32.

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

Copy link
Copy Markdown
Collaborator Author

The bot's analysis is correct and I want to surface the tension it creates with the split.

deserializeTextQuotedImpl is the single quoted entry point for both containers (Array/Tuple/Map) and Variant/Dynamic (SerializationVariant::tryDeserializeVariantFromField calls the same tryDeserializeTextQuoted). There is no container-only quoted path, so the position-advance fix cannot be "moved out of the shared parser" (bot option b) without a hack.

The one signal that separates the two contexts is the setting itself: tryDeserializeVariantFromField lowers allow_special_bool_values to allow_special_bool_values_inside_variant (default 0) before trying Bool, while containers keep the base default (1). So gating the 1/0 quoted branches on settings.allow_special_bool_values (bot option a):

The catch: that gate is an allow_special_bool_values change, which you asked to move into #110835. But without it (or without accepting the 03158 change), the container fix here silently widens the default Variant/Dynamic contract.

Which split do you prefer?

I lean A: it makes #109976 a pure container fix with zero Variant/Dynamic behavior change.

@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.00% 86.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 78.20% 78.20% +0.00%

Changed lines: Changed C/C++ lines covered: 10/11 (90.91%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — dfdee5a

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
Integration tests (amd_tsan, 3/6) / test_replicated_database/test.py::test_replicated_table_structure_alter flaky cross-replica structure convergence: assert "1\t2\t3\n" == competing_node.query(...) at test.py:1421. Not reachable from this diff, which only changes Bool parsing inside containers #111029 (external, merged 2026-07-24)
Sync - CH Inc sync (private, not actionable)

#111029's merge commit 78515f491816b6 is not on this branch and this head's CI ran 2026-07-17, a week
before that merge, so the failure predates the fix. The daily failure rate for that test collapsed from
83-176 rows/day up to 2026-07-24 to a single row on 2026-07-25 and a single row on 2026-07-27, which is
the fix taking effect on master. Merging master into this branch picks it up.

Session id: cron:our-pr-ci-monitor:20260727-170000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Cross-reference from #110835, where the AI reviewer raised the ungated quoted carrier. Recording it here because this is the PR that makes those branches reachable.

On origin/master the two numeric branches in deserializeTextQuotedImpl (:409 / :412) never advance istr.position(), so every caller's end-of-value check rejects them and they are unreachable-as-accepting:

SELECT v FROM format(CustomSeparated, 'v Bool', '1\n') SETTINGS format_custom_escaping_rule = 'Quoted';
-- Code: 27 ... text "1<LINE FEED>" is not like Bool

That is the bug this PR fixes. The side effect is that the branches become accepting while still ungated, so bare 1 / 0 inside a Variant resolve to Bool at the default allow_special_bool_values_inside_variant = 0. Measured on master with this PR's own 03158 insert shape and no bool setting:

-- origin/master today
0  UInt32
1  UInt32
-- this PR's updated 03158 reference
0  ->  false  Bool
1  ->  true   Bool

The dfdee5a commit message already states this, and the split into #110835 was per the request above, so this is a known consequence rather than a new finding. Two things worth doing here:

  1. The description currently documents only the container fix and says true/false, the quoted '1' form and scalar Bool are unchanged. It does not mention that Variant / Dynamic inference changes for bare 1 / 0 at the default setting, which is the part a reviewer is most likely to question given the 03158 reference diff. Adding a sentence for it would make the diff self-explaining.
  2. Since Gate numeric 1/0 JSON Bool parsing on allow_special_bool_values #110835 gates only the JSON carrier, gating the quoted branches has to land with the change that makes them accept, i.e. here, or the invariant is left open for this carrier after both merge. Gating them in Gate numeric 1/0 JSON Bool parsing on allow_special_bool_values #110835 instead would be a no-op today, because they do not accept until this PR lands.

No change pushed for this comment.

@Avogar
Avogar added this pull request to the merge queue Jul 30, 2026
Merged via the queue into ClickHouse:master with commit d4f94c2 Jul 30, 2026
175 of 177 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 30, 2026
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 pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Array(Bool) CSV parsing fails for numeric literals "1"/"0" (works for "true"/"false")

4 participants