Skip to content

Fix out-of-bounds write in query highlighting on malformed UTF-8 - #127906

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-highlight-malformed-utf8-bracket-oob
Oct 29, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-highlight-malformed-utf8-bracket-oob

Conversation

@groeneai

@groeneai groeneai commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #127899

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

Fixed an abort of clickhouse-client, clickhouse-local and clickhouse-format --hilite when highlighting a query whose string literal ends with an incomplete UTF-8 sequence, for example SELECT length(x'E2'). Such a query is now highlighted without reading past its end, and the closing bracket gets its own color.

Description

On 26.3.42.3, clickhouse format --hilite --query "SELECT length(x'E2')" aborts with libc++ Hardening assertion __n < size() failed: vector[] index out of bounds, and the interactive clickhouse-client aborts the same way when it echoes that query. On master the same abort takes down the server in Stress test (amd_tsan) (report), where 02426_pod_array_overflow_3 runs through the web terminal.

The highlighter maps bytes to entries of colors (one per code point) by stepping UTF8::seqLength bytes. The formatter writes string-literal bytes above 0x7F raw, so the query is echoed as SELECT length('<E2>'), and the 3-byte lead E2 swallows the closing '). The ) then maps to colors.size(), and the unguarded bracket write indexes past the end. The same walk makes the render loop read past the end of the string (SELECT x'F0') and, when text follows the bracket, puts the bracket color on the next character.

The fix changes the partition itself: a lead byte now spans only the continuation bytes that actually follow it, capped by the end of the text. Every walk in the file uses that one helper, so every index stays in bounds. For valid UTF-8 the partition, and so the highlighted output, is unchanged.

Validation: the new test fails on master (four aborts, plus the over-read) and passes with the fix, 50 runs. The interactive client and the CI query from 02426_pod_array_overflow_3 behave the same way. The existing highlighting tests pass.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/127906]

Version info

  • Merged into: 26.11.1.885-master (included in 26.11 and later)

groeneai and others added 2 commits October 27, 2026 01:55
The highlighter partitions the text into code points by stepping
`UTF8::seqLength` bytes, and sizes `colors` by the same walk. The AST
formatter writes string-literal bytes above 0x7F raw, so
`SELECT length(x'E2')` is echoed as `SELECT length('<E2>')`, and the
3-byte lead `E2` swallows the closing `')`. The `)` then maps to
`colors.size()`, and the unguarded bright-bracket write in `highlight()`
(always taken from `highlighted()`, which passes cursor 0) indexes past
the end: a libc++ hardening abort, or an out-of-bounds write without
hardening. Through the web terminal this aborts the server (Stress test,
`02426_pod_array_overflow_3`). The same walk made the render loop in
`highlighted()` read past the end of the string (`SELECT x'F0'`) and,
when text follows the bracket, put the bracket color on the next
character.

Fix the partition itself instead of guarding the write sites: a lead byte
spans only the continuation bytes that follow it, capped by its declared
length and by the end of the text. Every walk in the file uses this one
helper, so every position the highlighter indexes is a code-point start
before the end and all `colors` writes are in bounds. For valid UTF-8 the
partition equals the `seqLength` one, so the replxx callback (which always
passes valid UTF-8) highlights exactly as before.

Clamping `seqLength` to the remaining bytes would not be enough: `E2 ' )`
fits exactly in 3 bytes.

Closes ClickHouse#127899

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the codePointLength comment to one line.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings), plus my own cold review of the same head (0 findings).

# Sev Finding Verdict Evidence / action
- - No findings - none

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261027-015800

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse format --hilite --query "SELECT length(x'E2')" aborts every time on master (RC 134, libc++ Hardening assertion __n < size() failed: vector[] index out of bounds), and on official 26.3.42.3 and 26.9.19.9. The CI query from 02426_pod_array_overflow_3 aborts the same way.
b Root cause explained? Yes. The highlighter partitions the text by UTF8::seqLength. The formatter writes the raw byte E2, whose declared length 3 swallows the closing '), so the ) maps to colors.size(). highlighted() passes cursor 0, so the bright-bracket write is taken and it is unguarded.
c Fix matches root cause? Yes. The partition is fixed (a lead byte spans only the continuation bytes that follow it, capped by the end), not the write site. This also fixes the render over-read and the misplaced bracket color. No guard is added.
d Test intent preserved / new tests added? Yes. New 05453_highlight_malformed_utf8_before_bracket.sh checks no abort, output bytes equal to the plain format, and the bracket color. The existing highlighting tests pass.
e Both directions demonstrated? Yes. The new test and the repro fail on the base build (aborts and mismatches) and pass with the fix, on Build-ID-verified binaries. The interactive client aborts on base and answers with the fix. 50/50 runs pass.
f Fix is general across code paths? Yes. Every walk in ClientBaseHelpers.cpp uses the helper: lexer fallback, parser ranges, matching identifiers, bracket and error positions, render loop. That covers echoQuery (client, local, embedded client) and clickhouse-format --hilite. The replxx callback receives valid UTF-8 and is unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. 2/3/4-byte leads truncated before ) and at the end of the query, stray continuation bytes (CI query), and valid Cyrillic/CJK/Latin text checked byte-identical before and after. Type wrappers do not apply (client-side text).
h Backward compatible? (maintainer-approved exception only) Yes. No settings or protocol change. Valid UTF-8 output is byte-identical. For malformed UTF-8 only the color placement changes, and bytes past the end of the query are no longer emitted.
i Invariants and contracts preserved? Yes. Every index into colors is a code-point index of the same partition that sized it, and is below colors.size(), on all paths including the error highlight and the lexer fallback. The helper requires pos < end, which every caller satisfies, and returns at least 1, so every walk terminates.

Session id: cron:clickhouse-impl-slot-40:20261027-013700

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @azat @alexey-milovidov, could you review this and add the can be tested label so CI runs? The highlighter stepped through the query by UTF8::seqLength, so a truncated lead byte (for example SELECT length(x'E2')) swallowed the closing ) and the bracket color write indexed past colors; a code point now spans only the continuation bytes that actually follow its lead byte, capped by the end of the text.

@clickhouse-gh

clickhouse-gh Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9e79841]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

PR #127906 fixes out-of-bounds access when highlighting malformed UTF-8 by using a bounded, consistent byte partition for color allocation, position mapping, and rendering. Reviewed head 9e798410fd9fbb074f567f5cd62bf0ca15aa02d3, the surrounding code, callers, and all prior discussion. No actionable findings. The new regression test and 18 existing highlighting tests passed in the Fast test report.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-cli clickhouse-client (interactive CLI) and client library. labels Oct 27, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9e79841

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
Build profile diff infra, not from this PR: the CI logs cluster never passed the readiness probe, so the job ended with LogClusterNotReady: the endpoint never became ready before comparing anything. 282 of 286 runs since 2026-10-26 22:00 UTC are red, on 236 PRs #126200 (mine, open)
PR praktika rollup of the row above #126200 (the owner of the row above)

The first run of this head stopped at Config Workflow / Pre Hooks (and its Finish Workflow / Post Hooks) because the can be tested label was not set yet; the run after the label was added is the one above. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261027-203012

@alexey-milovidov alexey-milovidov added the blocker This issue / pr blocks a new release label Oct 29, 2026
@alexey-milovidov alexey-milovidov self-assigned this Oct 29, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors comp-cli clickhouse-client (interactive CLI) and client library. 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.

highlight() out-of-bounds colors[] write aborts on truncated UTF-8 before ')'

3 participants