Skip to content

Fix logical error and memory tracking in PNG image output - #107537

Merged
alexey-milovidov merged 9 commits into
ClickHouse:masterfrom
Algunenano:png-image-dimension-limit-and-memory-tracking
Jun 16, 2026
Merged

alexey-milovidov merged 9 commits into
ClickHouse:masterfrom
Algunenano:png-image-dimension-limit-and-memory-tracking

Conversation

@Algunenano

@Algunenano Algunenano commented Jun 15, 2026 •

Copy link
Copy Markdown
Member

Two fixes to the PNG image output format, both found from a query that aborted in debug builds.

  1. Oversized image dimensions raised a LOGICAL_ERROR. libpng caps each dimension at 1000000 (its per-dimension user limit) and reports a larger value through an error callback we surfaced as a logical error, which aborts in debug builds. Our pre-validation only rejected values above the 31-bit PNG range, so a dimension between the libpng limit and that range slipped through to png_set_IHDR. Width and height are now validated up front against the libpng limit and rejected with a clear BAD_ARGUMENTS naming the output_format_image_width / output_format_image_height settings. The check covers every output mode (raw PNG, iTerm, Kitty, Sixel).

  2. The terminal-output paths allocated scratch buffers (the per-band color map, the encoded PNG, and its base64) through standard containers, which use the non-throwing memory tracker and so overshoot max_memory_usage instead of failing. Those buffers now use memory-tracked containers, and the base64 for iTerm/Kitty is streamed straight into the output buffer rather than materializing the whole encoded string plus a redundant copy of the PNG.

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

🤖 Generated with Claude Code

Version info

  • Merged into: 26.6.1.896

Algunenano and others added 2 commits June 15, 2026 18:24
libpng caps each image dimension at its per-dimension user limit
(1000000 by default) and reports a larger value through an error
callback that we surfaced as a `LOGICAL_ERROR`, which aborts in debug
builds. Our own pre-validation only rejected values above the 31-bit
PNG range, so any dimension between the libpng limit and that range
reached `png_set_IHDR` and tripped it.

Validate width and height against the libpng limit up front and throw
`BAD_ARGUMENTS` naming the `output_format_image_width` /
`output_format_image_height` settings, before allocating the buffer or
invoking libpng. The check at serializer construction covers every
output mode (raw PNG, iTerm, Kitty, Sixel).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The Sixel, iTerm, and Kitty paths allocated their scratch buffers (the
per-band color map, the encoded PNG, and its base64) through standard
containers. Those use the non-throwing memory tracker, so a single
large allocation overshoots `max_memory_usage` and completes instead
of being rejected.

Switch the Sixel scratch buffers and the encoded-PNG buffer to
memory-tracked containers that throw when the limit is reached, and
stream the base64 for iTerm/Kitty directly into the output buffer
rather than materializing the whole encoded string plus a redundant
copy of the PNG.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@Algunenano Algunenano mentioned this pull request Jun 15, 2026
1 of 21 tasks
@clickhouse-gh

clickhouse-gh Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bb1d4b2]

Summary: ✅


AI Review

Summary

This PR fixes oversized PNG image dimension validation and moves large terminal-output buffers onto memory-tracked allocations. The current memory accounting and regression coverage look consistent, but one compatibility regression remains: raw FORMAT PNG is now compiled out when ENABLE_BASE64 is disabled, even though the raw PNG path only requires libpng.

Findings

⚠️ Majors

  • [src/Processors/Formats/Impl/PNGOutputFormat.cpp:3] [dismissed by author -- https://github.com/Fix logical error and memory tracking in PNG image output #107537#discussion_r3417170109] FORMAT PNG should remain available whenever USE_LIBPNG is enabled for raw image output, but the whole formatter is guarded by USE_LIBPNG && USE_BASE64. In builds with -DENABLE_LIBPNG=ON -DENABLE_BASE64=OFF, registerOutputFormatPNG becomes a no-op, so FORMAT PNG disappears even when output_format_image_terminal_mode is empty and no base64 terminal protocol is used. This is still real in the current code because PNGOutputFormat.cpp, PNGOutputFormat.h, and PNGTerminalOutput.* all use the combined guard.
    Suggested fix: keep raw PNGOutputFormat and ImageTerminalMode::None under USE_LIBPNG, and gate or reject only the iterm and kitty terminal modes that require base64.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: restore FORMAT PNG for libpng-only builds, or make the new base64 dependency an explicit accepted compatibility change with matching metadata, docs, and tests.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jun 15, 2026
Comment thread src/Formats/PNGTerminalOutput.cpp Resolved
@alexey-milovidov alexey-milovidov self-assigned this Jun 15, 2026
Algunenano and others added 2 commits June 16, 2026 01:20
Replace the hand-rolled base64 routine with `Base64WriteBuffer`, a new
streaming buffer in `src/IO` built on libbase64. It encodes into the
underlying buffer without materializing the whole base64 string, and
unlike the compression write buffers it does not finalize the
underlying buffer, so callers can keep writing raw bytes after it (the
terminal control sequences that wrap the payload).

The iTerm path streams the whole payload through it; the Kitty path
encodes each protocol chunk with libbase64 directly, since its framing
interleaves control sequences between fixed-size base64 chunks. This
lowers the iTerm/Kitty peak memory by ~40% on large images, removing a
redundant copy of the PNG and the fully materialized base64 string.

`ch_contrib::base64` is now linked to `clickhouse_common_io`, and the
PNG output format is gated behind `USE_LIBPNG && USE_BASE64`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The native protocol formats the result on the client, so the test did
not exercise the server-side PNG encoder. Drive the queries over HTTP
so the server produces the image. The reference output is unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Algunenano and others added 2 commits June 16, 2026 01:47
The PNG output format requires libpng and base64. The fast-test build
enables libpng but not base64, so the format is unavailable there and
the tests produce empty output. Tag them `no-fasttest`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The Sixel encoder's per-band scratch buffer must be charged to the
memory tracker so it respects `max_memory_usage`. Over HTTP (server-side
encoding) a 1000000-wide one-row image makes that ~24 MB buffer the
dominant allocation; under a 10 MB limit it must be rejected with
`MEMORY_LIMIT_EXCEEDED`, and a generous limit still produces a Sixel
stream. Before the fix the allocation silently exceeded the limit.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/IO/Base64WriteBuffer.cpp Resolved
Algunenano and others added 3 commits June 16, 2026 01:59
Encode through a fixed local buffer and forward with `out.write` instead
of writing base64 straight into the wrapped buffer. The previous code
assumed the wrapped `WriteBuffer` could expose at least four contiguous
bytes; a buffer that never does (for example a `WriteBufferFromPointer`
over one to three bytes) would have spun forever. `out.write` copes with
any destination buffer size.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
clang-tidy's member-init check flags `state` as uninitialized in the
constructor, even though `base64_stream_encode_init` sets it in the body.
Zero-initialize the member to satisfy the check.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Extend the test with an iTerm case: the iTerm and Kitty modes build the
whole encoded PNG in a memory-tracked buffer, so an incompressible image
under a tight limit (with the response streamed, so HTTP buffering does
not mask it) must be rejected. The existing case only covered the Sixel
per-band scratch buffer.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.10% 85.20% +0.10%
Functions 92.30% 92.30% +0.00%
Branches 77.40% 77.40% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 68/73 (93.15%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 16, 2026
Merged via the queue into ClickHouse:master with commit 3926f40 Jun 16, 2026
327 of 328 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog 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.

3 participants