Skip to content

Add FORMAT PNG support - #74691

Merged
alexey-milovidov merged 114 commits into
ClickHouse:masterfrom
m7kss1:generate_png_pictures_support
Jun 14, 2026
Merged

alexey-milovidov merged 114 commits into
ClickHouse:masterfrom
m7kss1:generate_png_pictures_support

Conversation

@m7kss1

@m7kss1 m7kss1 commented Jan 16, 2025 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • New Feature

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

Added the PNG output format support, allowing query output results to be directly rendered as PNG images

Documentation entry for user-facing changes

  • Motivation: This feature is useful as a built-in visualization tool

  • Documentation is written (mandatory for new features).

Information about CI checks: https://clickhouse.com/docs/en/development/continuous-integration/

CI Settings (Only check the boxes if you know what you are doing):

  • Allow: All Required Checks
  • Allow: Stateless tests
  • Allow: Stateful tests
  • Allow: Integration Tests
  • Allow: Performance tests
  • Allow: All Builds
  • Allow: batch 1, 2 for multi-batch jobs
  • Allow: batch 3, 4, 5, 6 for multi-batch jobs

  • Exclude: Style check
  • Exclude: Fast test
  • Exclude: All with ASAN
  • Exclude: All with TSAN, MSAN, UBSAN, Coverage
  • Exclude: All with aarch64, release, debug

  • Run only fuzzers related jobs (libFuzzer fuzzers, AST fuzzers, etc.)
  • Exclude: AST fuzzers

  • Do not test
  • Woolen Wolfdog
  • Upload binaries for special builds
  • Disable merge-commit
  • Disable CI cache

Note

Medium Risk
Introduces a new output format backed by a new third-party dependency (libpng) and new format settings, which can affect build/link behavior and output correctness across platforms.

Overview
Adds FORMAT PNG to render query results directly as PNG images, including support for RGB/RGBA/grayscale/binary modes and optional explicit x/y pixel coordinates.

Introduces new format settings output_format_image_width/output_format_image_height (wired through FormatFactory into FormatSettings) and documents the format.

Integrates libpng as a new contrib submodule with CMake plumbing/feature flags (ENABLE_LIBPNG/USE_LIBPNG), updates CI fast-test configuration, adds stateless coverage tests, and extends license detection and spellcheck dictionaries for new terminology.

Reviewed by Cursor Bugbot for commit 3ae65c2. Bugbot is set up for automated code reviews on this repo. Configure here.

Version info

  • Merged into: 26.6.1.779

@m7kss1

m7kss1 commented Jan 29, 2025

Copy link
Copy Markdown
Member Author

#57834

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Mar 4, 2025
@m7kss1
m7kss1 force-pushed the generate_png_pictures_support branch from fbffa70 to 0fcfe5e Compare April 7, 2025 17:38
@clickhouse-gh

clickhouse-gh Bot commented Apr 7, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f06fb4c]

@clickhouse-gh clickhouse-gh Bot added pr-feature Pull request with new product feature submodule changed At least one submodule changed in this PR. labels Apr 10, 2025
@groeneai

groeneai commented Jun 7, 2026

Copy link
Copy Markdown
Collaborator

@alexey-milovidov filed the fix as #106667.

Both 00906_low_cardinality_cache and 00945_bloom_filter_index failed in the same run at 15:39:56 UTC on Stateless tests (arm_asan_ubsan, azure, parallel) with global-tracker MEMORY_LIMIT_EXCEEDED (RSS 50.39 GiB / 53.69 GiB max), and both passed on every rerun. The mechanism is shared-runner memory pressure, not anything specific to FORMAT PNG. Fix pins max_threads = 1 and enable_parallel_replicas = 0 to keep the two tests light enough to coexist with heavier siblings under load.

…racked per-row pointer table

Two issues raised by the automated reviewer in the `FORMAT PNG` output path:

- `PNGOutputFormat` accumulates rendered pixels and the implicit coordinate cursor in its
  `serializer`, but did not override `resetFormatterImpl`. Reusable output paths such as
  `MessageQueueSink` finalize one image, restart the buffer, and call `resetFormatter` for the
  next message; without a reset the next image carried over stale pixels and could throw
  `TOO_MANY_ROWS`. Override `resetFormatterImpl` to call the existing `PNGSerializer::reset`.

- `PNGWriter::writeImage` built a `std::vector<png_bytep>` table of one pointer per row before
  encoding. Its size is proportional to the user-controlled `output_format_image_height`, and it
  was allocated outside the tracked ClickHouse allocator. Write the image one row at a time with
  `png_write_row` instead, pointing directly into the tightly packed pixel buffer, so no per-row
  pointer table is materialized.

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

Copy link
Copy Markdown
Member

Addressed the two remaining automated-review findings in 032b952e70e:

  • PNGOutputFormat now overrides resetFormatterImpl to call PNGSerializer::reset. Reusable output paths (e.g. MessageQueueSink) that finalize one image and reuse the formatter for the next message no longer carry over stale pixels or the implicit coordinate cursor.
  • PNGWriter::writeImage no longer builds a std::vector<png_bytep> table of one pointer per row (its size was proportional to the user-controlled output_format_image_height and was allocated outside the tracked allocator). It now encodes the image one row at a time with png_write_row, pointing directly into the tightly packed pixel buffer.

Both changed translation units compile cleanly. Did not merge master (branch is only 4 days behind and CI is green; trial merge is conflict-free).

alexey-milovidov and others added 3 commits June 8, 2026 14:42
… call

The `arm_tidy` build failed with `readability-ambiguous-smartptr-reset-call`:
calling `serializer->reset()` is ambiguous because both the
`std::unique_ptr` and the pointee `PNGSerializer` expose a `reset` method.
Dereference explicitly with `(*serializer).reset()` to call the pointee's
`reset`, as suggested by the linter.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
After merging `master`, the `04305`/`04306`/`04307` prefixes were taken by
unrelated tests. Renumber the `PNG` format tests to `04326`/`04327`/`04328`
(next free numbers) and update the in-test temp-directory names accordingly.

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

Copy link
Copy Markdown
Member

Merged latest master and pushed (f948cce5ace):

  • Merged master (branch was ~1483 commits behind): conflict-free. This brings in the fixes for the failures the previous CI run hit, all of which were unrelated to this PR:
    • Server died / 01018_ddl_dictionaries_special / Virtual row boundary violated in MergingSortedAlgorithm (STID 2651-3359) — the read-in-order virtual-row flake #106664, fixed on master by 28c01518689 (now in this branch).
    • 04295_04278_materialized_cte_in_union_runtime_set — its fix was reverted on master (0e3fa217240) and the test was removed along with it.
  • Renumbered the PNG tests to 04326/04327/04328 — after the merge the 04305/04306/04307 prefixes were taken by unrelated tests added on master.
  • Resolved the memory-tracking review thread: the terminal-mode encoders do not allocate outside the tracked allocator — ClickHouse globally overrides operator new (src/Common/AllocationInterceptors.cpp) so the base64Encode / Sixel scratch buffers are accounted by the MemoryTracker and bounded by the already-tracked pixel buffer.

Built with ENABLE_LIBPNG=ON and ran the three PNG tests locally — all pass.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, investigate "Logical error: 'this->visited_views == right->visited_views' (STID: 1288-3e19)" and provide a fix.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, check the message above ^

@groeneai

Copy link
Copy Markdown
Collaborator

Reproduced and root-caused the 'this->visited_views == right->visited_views' abort. (The STID 1288-3e19 is a hash-collision bucket spanning several unrelated stacks; the relevant one here is DeduplicationInfo::mergeSelf at InsertDeduplication.cpp:1066.)

Deterministic repro on current master (debug build), no fuzzing needed:

CREATE TABLE source (a Int32) ENGINE=MergeTree ORDER BY tuple();
CREATE TABLE source_null AS source ENGINE=Null;
CREATE TABLE dest (c UInt64, cs UInt64) ENGINE=MergeTree ORDER BY tuple();
CREATE MATERIALIZED VIEW mv1 TO source_null AS SELECT * FROM source;
CREATE MATERIALIZED VIEW mv2 TO source_null AS SELECT * FROM source;   -- 2nd MV, same target
CREATE MATERIALIZED VIEW mv_a TO dest AS
    SELECT count() AS c, (SELECT count() FROM source_null) AS cs FROM source_null;
INSERT INTO source SELECT number FROM numbers(2000)
    SETTINGS min_insert_block_size_rows=1500, max_insert_block_size=1500;

Aborts with the identical CI stack: mergeSelf -> merge -> CollectionOfDerived.h:114 -> Squashing.cpp:88 -> ApplySquashingTransform.cpp:33. With materialized_views_squash_parallel_inserts=0 the same scenario does not abort, which pins the trigger to the parallel-insert squashing path.

Root cause: when two materialized views write to the same target table, parallel-insert squashing (keyed per target table) merges their output chunks in Squashing::squash. Those chunks carry different visited_views chains by design ([source, mv1] vs [source, mv2]). mergeSelf asserts visited_views equality unconditionally, but visited_views is only meaningful for the deduplication path, and dedup is disabled on the squash-parallel-inserts path. So the assertion is over-strict for the dedup-disabled case. The merge of the two chunks for the same target is itself correct behavior.

Fix is being finalized (restrict the equality check to the dedup-enabled path, plus a regression test covering the two-MVs-to-same-target + chained-scalar-subquery scenario). Separate PR to follow shortly.

@alexey-milovidov

Copy link
Copy Markdown
Member

The fix for the Stress test (arm_debug) failure (Logical error: 'this->visited_views == right->visited_views', unrelated to this PR — it is in the insert-deduplication path for parallel materialized view squashing) is now up: #107027.

Status of this PR otherwise: all 30 review threads are resolved, the branch has master merged as of 2026-06-09, and all other CI checks are green. The remaining blockers are the known stress flake above and review approval.

@clickhouse-gh

clickhouse-gh Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 3 query(s) improved out of 38 analysed

This PR adds a PNG output format (libpng) and ALTER ADD ENUM VALUES syntax, plus documentation — none of which touches the query-execution path that ClickBench or TPC-H exercise. The measured improvements (Q22 -24%, Q23 -33%, Q7 -36%, Q20 -50%) therefore cannot be attributed to this change. The largest, most consistent deltas (Q23, Q7, Q20) are large enough to stand as measured, but are most plausibly build or environment differences rather than a query-logic effect; Q22 falls below that threshold and is downgraded to not-sure. TPC-H Q4 is borderline and trending on master, so treat it as inconclusive.

clickbench

🟢 1 improved · ⚠️ 1 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
🟢 23 improvement 297 198 -33.3% <0.0001 Off-path for a PNG/enum PR, but -33% clears the strong-signal trust gate so the verdict stands as measured
⚠️ 22 not_sure 334 254 -23.8% <0.0001 PNG/enum PR can't touch this ClickBench SELECT; -24% sits below the strong-signal floor, treat as build/env variance

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 2 improved · ⚠️ 1 inconclusive

Flagged queries (3 of 22)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
🟢 7 improvement 113 72 -36.3% <0.0001 join_operator: Off-path PR (PNG/enum); -36% clears the strong-signal gate so it stands, but likely build/env not query logic
🟢 20 improvement 248 124 -50.0% <0.0001 join_operator: -50% clears the strong-signal gate so it stands; query is intrinsically noisy and PR is off-path — read cautiously
⚠️ 4 not_sure 3015 2706 -10.2% 0.0412 aggregation: Borderline with mixed test signals; trending on master; PR is off-path so this is not a PR effect

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: a96fa4d9-73bc-4278-8dd8-27fdd6158a47
  • MIRAI run: fce11a45-8de4-4ab2-8da4-bbc1694a0ea7
  • PR check IDs:
    • clickbench_75419_1781411053
    • clickbench_75425_1781411053
    • clickbench_75431_1781411053
    • tpch_adapted_1_official_75437_1781411053
    • tpch_adapted_1_official_75443_1781411053
    • tpch_adapted_1_official_75965_1781411251

alexey-milovidov and others added 3 commits June 13, 2026 11:41
…ngjmp

The libpng error and warning callbacks ran `writer->error_message = error_msg`,
where `error_message` was a `std::string`. That assignment may allocate, and on
allocation failure it throws `std::bad_alloc`. Because the callbacks are invoked
from libpng's C frames and finish with `png_longjmp`, an exception escaping the
callback is undefined behavior.

Store the message in a fixed-size `char` buffer instead and copy into it with a
bounded `memcpy`, so the callbacks no longer allocate before `png_longjmp`.
libpng's own messages are bounded (`PNG_MAX_ERROR_TEXT` is 196); a longer
message is silently truncated.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Fast test now checks out contrib/libpng and configures the build with
-DENABLE_LIBPNG=1 (see ci/jobs/fast_test.py), so the FORMAT PNG feature
is available there. The no-fasttest tag on the PNG tests, whose stated
rationale was "requires libpng (not built in fast test)", is no longer
accurate and only removes these tests from the fastest CI signal.

The tests rely only on standard utilities (python3 stdlib, od, file,
base64, md5sum), all present in the Fast Test image.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
pull Bot pushed a commit to Haofei/ClickHouse that referenced this pull request Jun 14, 2026
`GH.get_changed_files` fetches the list of files a PR touches via
`gh api .../pulls/<n>/files`. The result is stored once into the job
KV data by the `store_data` pre-hook and read back by several other
workflow hooks (`pr_labels_and_category`, `team_notifications`,
`feature_docs`, ...).

The function had a `for attempt in range(3)` retry loop, but for the PR
path it was dead code: an `assert exit_code == 0` ran right after the
`gh api` call, so the very first transient failure raised before any
retry could happen. When the GitHub API hiccupped (rate limiting, a
5xx, or a GraphQL "Something went wrong" error), `store_data` aborted
without populating `changed_files`, and every downstream hook then read
`None` from the KV data and died far away with an opaque
`TypeError: 'NoneType' object is not iterable` / `can only join an
iterable`, with nothing in the report pointing at the real cause.

Changes:

- Make the retry actually retry: drop the premature `assert`, unify the
  PR and commit code paths into a single command, and retry every
  non-zero exit code (this is an idempotent read, so a spurious retry is
  cheap and the exit code alone does not reliably distinguish transient
  from permanent errors). Five attempts with a small linear backoff.
- On final failure, print and (when `strict`) raise a message that
  includes the command, exit code, stderr and stdout, so the failure is
  diagnosable directly from the report. The non-strict contract of
  returning `None` is preserved for callers that tolerate it
  (`Runner` and the master/release path of `store_data`).
- In the three consumer hooks, assert `changed_files is not None` with
  an actionable message instead of letting a missing value surface as a
  bare `TypeError`.

Observed on PR ClickHouse#74691 (commit 8e08fc0), which blocked the whole
pipeline because the failing pre-hooks were never able to dispatch the
real jobs:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=74691&sha=8e08fc02490688916fb3bffe4e897cbe50f2702a&name_0=PR&name_1=Config%20Workflow

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

clickhouse-gh Bot commented Jun 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.80% 84.80% +0.00%
Functions 92.40% 92.40% +0.00%
Branches 77.30% 77.40% +0.10%

Changed lines: Changed C/C++ lines covered by tests: 419/512 (81.84%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov merged commit 36275c2 into ClickHouse:master Jun 14, 2026
165 of 166 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 14, 2026
Comment thread src/Formats/PNGWriter.cpp
void PNGWriter::writeImage(const unsigned char * pixels)
{
if (initialized)
throw Exception(ErrorCodes::LOGICAL_ERROR, "PNG writer can encode only one image");

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 LOGICAL_ERROR unnecessarily leads to aborts in debug:

SELECT toUInt8(number % 256) AS v
FROM numbers(10000000)
SETTINGS output_format_image_width = 10000000, output_format_image_height = 1
FORMAT PNG

}

/// Sixels encode 6 vertical pixels at a time, so the image is processed in horizontal bands of 6 rows.
std::vector<int> band_colors(width * 6);

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.

This should be tracked. It can allocate GBs of memory. Same for line

@Algunenano

Copy link
Copy Markdown
Member

Follow up: #107537

Comment thread ci/jobs/fast_test.py
"contrib/StringZilla",
"contrib/rust_vendor",
"contrib/clickstack",
"contrib/libpng",

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.

😢 #108512

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 comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). manual approve Manual approve required to run CI pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants