Skip to content

Read compressed debug sections in the built-in symbolizer - #131722

Open
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:dwarf-compressed-debug-sections
Open

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:dwarf-compressed-debug-sections

Conversation

@groeneai

@groeneai groeneai commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #126943

Changelog category (leave one):

  • Improvement

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

Stack traces, addressToLine and addressToLineWithInlines now show file names, line numbers and inlined frames when the debug sections are compressed with zstd or zlib (objcopy --compress-debug-sections). The sections are decompressed once per process, on the first symbolization.

Description

Asked in #126943 (comment). Dwarf::getSection treated every SHF_COMPRESSED section as absent, so a compressed debug file gave no file:line. The companion PR that compresses the packaged clickhouse.debug with zstd should merge after this one or together with it; otherwise installed packages lose file:line in between.

Elf::getSectionsData returns the named sections together. It decompresses zlib and zstd sections once and keeps them for the lifetime of the Elf, which SymbolIndex holds for the whole process. The Dwarf ELF constructor makes one such call. A set is kept only if every section decompresses. A broken header, an unknown type, a size over 1024 times the payload, a truncated section or a decompression error disables Dwarf (no file:line, as today) instead of throwing during symbolization. The memory is charged to the server, not to the query that symbolizes first, and the decompression is refused, for the rest of the process, when it would exceed max_server_memory_usage. .debug_loclists is no longer read: its index was resolved into a value nothing reads. Fuzzer builds keep skipping compressed sections because of libFuzzer's RSS limit.

Cost: on the first symbolization, the sections needed from the 26.11 amd64 clickhouse.debug decompress to 3.48 GiB in about 4 s; that memory stays allocated for the life of the process and counts toward max_server_memory_usage.

Validation: a new gtest builds ELF images with a DWARF 4 unit (uncompressed, zlib, zstd) and fails on master for the compressed ones; it also covers the rejection and caching cases. A debug build compressed with llvm-objcopy --compress-debug-sections=zstd or zlib, and the package layout with a separate compressed .debug, show the same file:line in addressToLine and exception stack traces as the uncompressed binary; a master binary compressed the same way shows none.


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

`Dwarf::getSection` returned an empty view for every SHF_COMPRESSED section, so a
debug file written by `objcopy --compress-debug-sections` (zlib or zstd) disabled
`Dwarf` and stack traces, `addressToLine` and `addressToLineWithInlines` lost file
names, line numbers and inlined frames. ClickHouse#126943 compresses the packaged
`clickhouse.debug` with zstd, so this has to work first.

The decompressed bytes live in `Elf`, not in `Dwarf`: `StackTrace::forEachFrame`
builds a fresh `Dwarf` for every trace, which is why the per-`Dwarf` decompression
of ClickHouse#109306 (c8de703) was reverted (2c5f535). `SymbolIndex` keeps its `Elf`
objects for the whole process, so the sections are decompressed once.

`Elf::getSectionsData(names)` handles the whole set in one call:
- the headers are scanned by name; a named section that runs past the end of the
  file fails the call (`findSectionByName` would skip it, and a later unguarded
  `substr` on a DWARF 5 side table would throw);
- with no compressed section among the names it returns the raw views without
  locking or allocating, as before;
- otherwise, under the `Elf`'s mutex, it checks every pending header (type ZLIB or
  ZSTD, size at most 1024 times the payload, the same bound as
  `decompressGNUDebugData`), checks the summed size against the hard limit of
  `total_memory_tracker` explicitly (the tracker does not throw while an exception
  is being formatted, `getExceptionStackTraceString`), decompresses into local
  `Memory<>` buffers (`ZSTD_decompress`; chunked `inflate`, because the one-shot
  `uncompress` fails above 2 GiB) and publishes them with a noexcept swap only if
  all succeed. Any failure erases the placeholders and marks the sections
  unreadable for good: the symbolization results are cached anyway
  (`StackTraceCache`, `AddressToLineCache`), so a retry could not reach them.
  Nothing throws out of it.

The `Dwarf` ELF constructor makes that one call under a `User`-level
`MemoryTrackerBlockerInThread`, so the memory is charged to the server and not to
the query that happens to symbolize first; on nullopt `Dwarf` is disabled (fail
closed). Fuzzer builds keep skipping compressed sections: libFuzzer's RSS limit
(2-8 GiB) would turn every finding into an out-of-memory report, and the fuzzer
binaries are linked with `--compress-debug-sections=zlib`.

`.debug_loclists` (380 MiB decompressed in the 26.11 amd64 file) is no longer read:
`DW_FORM_loclistx` was resolved into a `DW_AT_location` value that nothing reads.

Measured on the 26.11 amd64 `clickhouse.debug`: the needed sections decompress to
3.48 GiB in about 4 s; on a debug build 4.86 GiB.

Related: ClickHouse#126943

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; 2 findings), plus my own review (4 nits).

# Sev Finding Verdict Evidence / action
1 ❌ SymbolIndex sets an object's address_end from the separate .debug file size, so compressing that file could drop high addresses (SymbolIndex.cpp:771-794) DISAGREE Measured on the 26.11.1.2315 amd64 package: the zstd-compressed clickhouse.debug is 1,320,653,480 B, the last PT_LOAD ends at 769,058,512 B (1.72x margin; debug-build split layout 1.9x). The range code is unchanged by this PR.
2 ⚠️ The uncompressed path now allocates two small vectors, against the Dwarf.h no-heap note DISAGREE Every caller allocates more around the constructor in the same call (StackTrace.cpp:596,598,621, AddressToLineCache.cpp:61, addressToLine.h:107). The note describes the record parser, which already allocates in FULL_WITH_INLINE (Dwarf.cpp:1163,1234).
3 💡 The ratio bound (size <= payload * 1024) is not pinned by a test noted, not blocking An absurd size is still rejected by the allocation or by the exact-size check.
4 💡 The gtest is long (273 lines), mostly the ELF and DWARF builders noted, not blocking none

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

Session id: cron:clickhouse-review-slot-9:20261115-015200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. unit_tests_dbms --gtest_filter='DwarfCompressedSections*' fails on master for the zlib and zstd images (the uncompressed control passes); a master binary compressed with llvm-objcopy --compress-debug-sections=zstd prints stack traces without file:line every run.
b Root cause explained? Dwarf::getSection returned an empty view for every SHF_COMPRESSED section and nothing decompressed them, so Dwarf disabled itself. The earlier per-Dwarf decompression was reverted because a Dwarf is rebuilt for every stack trace.
c Fix matches root cause? Yes. Elf, which owns the bytes for the process lifetime, decompresses the requested set once (zlib, zstd); Dwarf reads through one call.
d Test intent preserved / new tests added? New gtest: lookup through Dwarf for uncompressed, zlib and zstd, plus the rejection, caching, all-or-nothing, memory-limit and concurrency cases. Each guard was removed in turn and a case failed, except the ratio bound, which only prevents an allocation attempt. No SQL test: no CI binary has compressed debug sections.
e Both directions demonstrated? Gtest: master FAIL, fix PASS (50/50 repeats). Debug binary: master + zstd shows no file:line; fix + zstd, zlib and the split .debug layout show throwIf.cpp:177:23, the same as uncompressed.
f Fix is general across code paths? All Dwarf users go through the ELF constructor (stack traces, addressToLine*, trace_log, jemalloc profiles). Mach-O has no compressed sections. Fuzzer builds keep skipping them (libFuzzer RSS limit).
g Fix generalizes across inputs (params/datatypes/wrappers)? zlib, zstd, uncompressed, mixed; in-binary and separate .debug; unknown type, absurd or wrong size, short header, corrupt stream, truncated section, NOBITS, absent; a 2.70 GB zlib .debug_info (past the one-shot uncompress limit).
h Backward compatible? (maintainer-approved exception only) Yes: no settings, formats or on-disk changes; uncompressed sections return the same views. A debug section whose header points past the end of the file now disables Dwarf instead of reading as absent.
i Invariants and contracts preserved? Views live as long as the Elf; a set is published entirely or not at all; failures are final, so the symbolization caches stay consistent; one mutex guards the cache; nothing throws out of symbolization. The memory is charged to the server and refused above max_server_memory_usage.

Session id: cron:clickhouse-impl-slot-7:20261115-005700

@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [308984d]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 3/6) ERROR

AI Review

⚠️ Review sessions stopped as a cybersecurity risk

The model provider stopped these review sessions as a possible cybersecurity risk:

  • attempt 1: gpt-6.1-sol

This summary comes from a session with gpt-5.4. A session is typically stopped when it reaches a memory-safety finding, and the finding is lost with it, so this review can miss a real defect. Please review the change in detail, and run the review internally with a model that has cyber access.

Summary

This PR teaches the built-in symbolizer to read SHF_COMPRESSED DWARF sections and cache the decompressed bytes in Elf, which is the right direction and is covered by focused unit tests. I am still requesting changes because the end-to-end split-*.debug path the PR claims to support is not actually validated, and it still depends on SymbolIndex using the separate debug file's byte size as the loaded object's address range.

Findings
  • ⚠️ Majors
    • [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/131722#issuecomment-6887931346] [src/Common/tests/gtest_dwarf_compressed_sections.cpp:159] The new tests only construct Dwarf directly from an in-memory Elf, but real split-*.debug symbolization still goes through SymbolIndex::collectSymbols, which sets object.address_end from object.elf->size() of the separate debug file in src/Common/SymbolIndex.cpp:793. That invariant does not hold for genuine split-debug ELFs: a local objcopy --only-keep-debug reproduction on /bin/ls produced a 2856-byte ls.debug file for a binary whose PT_LOAD span is 0x30540, so addresses above base + 2856 would fail findObject before Dwarf is even consulted. The author's measurement on the packaged clickhouse.debug shows that one file happens to be large enough; it does not make the object-range calculation correct in general.
    • Suggested fix: derive address_end from the loaded object's runtime range (for example the PT_LOAD coverage from info->phdr) and add an end-to-end test through SymbolIndex, not only a direct Dwarf test.
Tests
  • ⚠️ Add one focused end-to-end test that exercises the SymbolIndex path with a real split *.debug file and proves that addresses near the end of the mapped object still symbolize when the debug file itself is smaller than the object's runtime span.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: fix the split-*.debug object-range calculation in SymbolIndex, or explicitly track that gap in a linked issue and narrow the PR's claim/tests so the unsupported end-to-end case is not presented as working.

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements can be tested Allows running workflows for external contributors comp-logging Logging/monitoring/observability (logs, metrics, tracing, instrumentation). labels Nov 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 308984db8 with master 6ea176fa3 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

11 object files changed (+48.23 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/clickhouse_common_io.dir/Common/Elf.cpp.o 59.62 KiB 102.48 KiB +42.86 KiB (+71.89%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

27 translation units recompiled, 97 s compile time in total, 27 of them have a recent master baseline.

Job report

groeneai and others added 2 commits November 15, 2026 04:29
The memory-limit case set the global hard limit to `total_memory_tracker.get() + 1024`.
`unit_tests_dbms` runs every suite in one process, and by the time this test runs in
`Unit tests (amd_debug)` the tracked amount is negative (measured in gdb with the
suites registered before it: amount -1460216, RSS 310010171), so the limit became
negative, which `getSectionsData` treats as "no limit", and the section decompressed.
The asan, msan and tsan unit-test jobs passed on the same head.

Set the limit just above `max(get(), getRSS())`, which is what `decompressSections`
compares against (as `gtest_memory_tracker.cpp` does). Disabling that check still
fails the test, both alone and after the preceding suites.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`decompressSections` checked the server limit once, then allocated each buffer just
before decompressing it, so other threads could use the headroom during the codec work
(seconds for a real `clickhouse.debug`). The memory tracker does not throw while an
exception is formatted, so the later buffers were charged past `max_server_memory_usage`.
Allocate every buffer first and check the limit again with them charged; if other
allocations got there first, free them and refuse.

Measured with a two-thread experiment (zstd sections of 256 and 64 MiB, hard limit =
both + 32 MiB, a competing 64 MiB allocation once the first buffer is charged): before,
10/10 runs had both allocations succeed and ended 32 MiB over the limit; after, 30/30
runs refused the decompression and stayed under it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Common/Elf.cpp Resolved
groeneai and others added 2 commits November 15, 2026 09:43
The sections were allocated by the thread that symbolizes, under a
`MemoryTrackerBlockerInThread(VariableContext::User)` in the `Dwarf` constructor. Buffers
smaller than `max_untracked_memory` stayed in the untracked memory of that thread and were
flushed when the blocker ended, and since 8de7e8b every such flush counts toward
`untracked_memory_flushed_unchecked`. Once that passes `untracked_memory_limit`, each enforced
allocation of the thread checks the limit of its query, until one check passes. So the first
stack trace through a frame whose separate debug file is compressed (libc's from libc6-dbg
here: about 2 MB of sections) made an `INSERT ... SETTINGS max_memory_usage = 1000` and the
next ones on the same pooled TCP thread fail with `MEMORY_LIMIT_EXCEEDED`;
`test_failed_async_inserts` counted 1 failed async insert instead of 4.

A thread without a `ThreadStatus` charges its allocations to the server tracker directly, and
with no `LockMemoryExceptionInThread` there, the tracker checks every buffer against the server
limit as it is allocated. So the `Dwarf` constructor needs no blocker, and the second explicit
check, made after allocating every buffer, is dropped.

Measured with the four `INSERT`s of the test against a debug server: 1 of 4 counted and 7
`MEMORY_LIMIT_EXCEEDED` log lines on the previous head, 4 of 4 and none on master and with this
change; libc frames keep their file:line. With a zstd or zlib compressed binary, a query capped
at 1 GB still resolves `addressToLine` while `MemoryTracking` grows by 4.9 GiB, and with
`max_server_memory_usage = 4G` the decompression is refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A thread with its own `ThreadStatus` reads a 1 MiB zstd section and measures what its tracker
was charged. Decompressing on the calling thread, as before the previous commit, charges it
1,048,719 bytes and fails the test; on a thread of its own it is charged a few small vectors.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 308984d

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
Performance Comparison (arm_release, master_head, 3/6) infra, not from this PR: killed at the 7200 s job timeout, because the coverage-based test selection picked a coverage run that collected no test (cohort 79929b2c), so every test of the shard ran in full (--max-queries 0 on all 142 tests). The tested tree (run created 11:44Z) predates the fix #131772 (mine, merged)
Mergeable Check, PR praktika rollups of the row above #131772 (mine, merged)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261115-153013

This branch has not been deployed

No deployments
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-logging Logging/monitoring/observability (logs, metrics, tracing, instrumentation). pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant