Skip to content

Surface real callback exceptions in ZipArchiveReader instead of "Code = -100" - #105103

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-104681-zip-archive-exception-laundering
Jun 26, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-104681-zip-archive-exception-laundering

Conversation

@groeneai

@groeneai groeneai commented May 16, 2026 •

Copy link
Copy Markdown
Collaborator

When reading a zip archive whose underlying SeekableReadBuffer throws (for example ReadBufferFromS3 with restricted_seek = true rejecting a backward seek during minizip's EOCD search), the exception was caught inside the StreamFromReadBuffer C callbacks, the callback returned an error code, and minizip's state machine then surfaced a generic MZ_END_OF_LIST (-100). The result was the unhelpful

Couldn't unpack zip archive 'X': Code = -100

reported in #104681, with the actual cause (e.g. CANNOT_SEEK_THROUGH_FILE) silently dropped.

What changed

  • HandleHolder::checkResult and showError now rethrow any stored stream exception before falling through to the cryptic minizip error formatter, so every post-open failure surfaces the underlying error instead of Code = -100.
  • StreamFromReadBuffer::open returns the captured exception when unzOpen2_64 fails. Minizip cleans up the stream during its own failure path, so the in-stream stored_exception is unreachable afterwards. The read/seek/tell callbacks therefore also write a copy of the exception into the shared Opaque struct (lives on the caller's stack), which acquireRawHandle rethrows instead of the generic Couldn't open zip archive message.

Testing

A new gtest ZipArchiveReaderTest.RethrowsCallbackExceptionOnOpen reproduces the issue with a SeekFailingReadBuffer that fails on the second seek after a read. With the fix the underlying CANNOT_SEEK_THROUGH_FILE is surfaced unchanged; without the fix the test fails (gets code 643 / "Couldn't open zip archive" instead of expected 87 / CANNOT_SEEK_THROUGH_FILE).

All 79 existing archive gtests continue to pass.

Closes #104681

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

Surface the real underlying exception when a zip archive cannot be unpacked because the input buffer (e.g. an S3 read buffer with restricted_seek = true) refuses a seek or read requested by minizip. Previously the actual error was hidden behind the generic Couldn't unpack zip archive: Code = -100 / Couldn't open zip archive message.

Version info

  • Merged into: 26.7.1.126

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (session cron:clickhouse-ci-task-worker:20260516-033000):

a) Deterministic repro? ✅ The new gtest ZipArchiveReaderTest.RethrowsCallbackExceptionOnOpen triggers the failure on demand using a SeekFailingReadBuffer that throws CANNOT_SEEK_THROUGH_FILE on the second seek after the first read — mirroring what ReadBufferFromS3 with restricted_seek = true does during minizip's EOCD lookup on archives that don't fit in a single working buffer.

b) Root cause explained? ✅ The minizip stream callbacks (readFunc, seekFunc, tellFunc) catch the C++ exception (mandatory: C++ exceptions must not unwind through C code) and return a numeric error to minizip. Minizip's state machine then reports a generic code (frequently MZ_END_OF_LIST = -100). Both error-formatting paths (HandleHolder::checkResult and acquireRawHandle's open-failed branch) drop the captured exception and emit the cryptic Code = -100 / Couldn't open zip archive text. The fix surfaces the captured exception in both paths.

c) Fix matches root cause? ✅ The captured exception is rethrown at exactly the two sites where it was being dropped: (1) HandleHolder::checkResult / showError before they format minizip's error, and (2) acquireRawHandle after unzOpen2_64 fails (the in-stream exception is gone by then because minizip's cleanup ran closeFileFunc, so the callbacks also copy it into the caller-owned Opaque struct that survives the open).

d) Test intent preserved / new tests added? ✅ All 79 existing archive gtests continue to pass. A new gtest specifically covers the laundering path the issue describes.

e) Both directions demonstrated? ✅ Without the fix the new gtest fails (got code 643 CANNOT_UNPACK_ARCHIVE with Couldn't open zip archive); with the fix it passes (gets code 87 CANNOT_SEEK_THROUGH_FILE unchanged). Verified by stashing the source change, rebuilding, and re-running.

f) Fix is general? ✅ The exception capture now happens in every callback that catches an exception (readFunc, seekFunc, tellFunc), not just one. Both the in-stream copy and the Opaque copy are populated, so the fix works regardless of whether minizip destroys the stream during cleanup or not. Both the open-time and post-open failure paths are covered by the unified rethrowStreamException() call inside checkResult / showError.

This is a defensive fix that improves the user-facing error message. It does not by itself change the underlying behavior of ReadBufferFromS3 with restricted_seek = true (issue #104681's underlying mechanism remains the same), but with this fix the user now sees the actual CANNOT_SEEK_THROUGH_FILE error instead of Code = -100, which makes the failure mode actionable.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @PedroTadim @rschu1ze @alexey-milovidov — could you review this? It surfaces the real underlying exception (e.g. CANNOT_SEEK_THROUGH_FILE from an S3 backward seek) when minizip's stream callbacks fail, instead of returning the generic Couldn't unpack zip archive: Code = -100 that masks the actual cause.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [19c58ef]

Summary: ✅


AI Review

Summary

This PR preserves ZipArchiveReader callback exceptions and pins the minizip callback Opaque state for the unzFile handle lifetime, so failures from SeekableReadBuffer callbacks surface as their original Exception instead of Code = -100. I did not find any unresolved correctness, lifetime, or test coverage concern in the current diff; the prior clickhouse-gh lifetime finding is addressed by the std::shared_ptr ownership threaded through OpenResult, RawHandleWithStream, and HandleHolder.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 16, 2026
Comment thread src/IO/Archives/ZipArchiveReader.cpp Resolved
groeneai added a commit to groeneai/ClickHouse that referenced this pull request May 16, 2026
…-scope

clickhouse-gh[bot] flagged on PR ClickHouse#105103 that the `Opaque` struct used by the
minizip stream callbacks was a stack-local in `StreamFromReadBuffer::open`.
Minizip stores the `opaque` pointer internally during `unzOpen2_64` and
dereferences it from every later callback (`readFileFunc`, `seekFunc`,
`tellFunc`); after `open` returned successfully, those callbacks dereferenced
freed stack memory whenever they took the exception-capture path through
`storeException(strm, opaque)`.

ASan confirms the bug:

    ERROR: AddressSanitizer: stack-use-after-return
    READ of size 8 at 0x... thread T0
    Address ... is located in stack of thread T0 at offset 88 in frame
      ...
      [64, 96) 'opaque' (line 74) <== Memory access at offset 88 is inside this variable

The fix heap-allocates `Opaque` via `std::shared_ptr` and pins it for the
lifetime of the `unzFile` handle:

  * `OpenResult` carries a `std::shared_ptr<Opaque>` owning the storage.
  * `RawHandleWithStream` (in the header) gains a `std::shared_ptr<void> opaque`
    field so the handle cache keeps the storage alive across acquire/release.
  * `HandleHolder` moves the opaque shared pointer with the handle and passes
    it back to the cache in `releaseRawHandle()`.

`closeFileFunc` already ignores the `opaque` parameter, so destruction order
during `unzClose()` in `~ZipArchiveReader` is safe: minizip releases the
handle first, then the shared pointers in `free_handles` drop the `Opaque`.

A new gtest, `ZipArchiveReaderTest.RethrowsCallbackExceptionAfterOpenSucceeded`,
opens the archive normally, then flips an externally-owned flag so the next
post-open callback throws. Under ASan, this test deterministically fails on
the pre-fix code (stack-use-after-return at line 74) and passes cleanly with
the heap-allocated `Opaque`.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed @clickhouse-gh[bot]'s memory-safety review in commit 49c0890.

Bot's concern (correct): Opaque was a stack-local in StreamFromReadBuffer::open. After unzOpen2_64 returned successfully, the stack frame was reclaimed, but minizip stored the opaque pointer internally and dereferenced it from every later callback (readFileFunc, seekFunc, tellFunc). Any post-open exception path through storeException(strm, opaque) wrote to freed stack memory — use-after-scope.

Confirmed with ASan. Wrote a regression test (ZipArchiveReaderTest.RethrowsCallbackExceptionAfterOpenSucceeded) that opens the archive normally, then flips an externally-owned flag so the next post-open callback throws. On the pre-fix code under ASAN_OPTIONS=detect_stack_use_after_return=1, the test reproduces the bug deterministically:

==4005143==ERROR: AddressSanitizer: stack-use-after-return on address 0x7a200601aa58
READ of size 8 at 0x7a200601aa58 thread T0
Address ... is located in stack of thread T0 at offset 88 in frame
  This frame has 8 object(s):
    [64, 96) 'opaque' (line 74) <== Memory access at offset 88 is inside this variable
    ...
SUMMARY: AddressSanitizer: stack-use-after-return

Fix. Moved Opaque to the heap via std::shared_ptr<Opaque> and pinned it for the entire lifetime of the unzFile handle:

  • OpenResult now carries a std::shared_ptr<Opaque> that owns the storage.
  • RawHandleWithStream (in the header) gains a std::shared_ptr<void> opaque field so the handle cache keeps Opaque alive across acquire/release cycles in free_handles.
  • HandleHolder moves the opaque shared pointer with the handle and passes it back to the cache in ~HandleHolder.

Destruction order is safe because closeFileFunc ignores the opaque parameter — unzClose() in ~ZipArchiveReader releases the handle first, then the free_handles vector drops the RawHandleWithStream entries and the Opaque shared pointers along with them.

Verification (both directions):

  • Without the fix + ASan: stack-use-after-return at 'opaque' (line 74) (deterministic, every run).
  • With the fix + ASan: all ZipArchiveReaderTest.* and ArchiveReaderAndWriterTest.* tests pass (80 + 2 = 82 cases, including the new regression test). Verified locally with build-asan/src/unit_tests_dbms.

Session: cron:clickhouse-ci-task-worker:20260516-060000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate (per TASK.md Phase 4 Step 9)

# Question Answer
a Deterministic repro? YES. ZipArchiveReaderTest.RethrowsCallbackExceptionAfterOpenSucceeded triggers the issue on every run. With ASan + detect_stack_use_after_return=1, the pre-fix code aborts with stack-use-after-return on 'opaque' (line 74).
b Root cause explained? YES. Opaque was a stack-local in StreamFromReadBuffer::open. unzOpen2_64 stored &opaque inside the unzFile handle. After open returned, that stack memory was reclaimed but minizip continued invoking readFileFunc / seekFunc / tellFunc with the saved pointer. Any callback that took the exception-capture path wrote to freed stack memory via storeException(strm, opaque).
c Fix matches root cause? YES. Heap-allocated Opaque (std::shared_ptr<Opaque>) is pinned for the entire unzFile lifetime: through OpenResult → RawHandleWithStream::opaque → HandleHolder::opaque → back into free_handles. Released only when unzClose() runs in ~ZipArchiveReader. This directly removes the lifetime mismatch the bot identified.
d Test intent preserved? YES. Existing RethrowsCallbackExceptionOnOpen still verifies that callback exceptions during open surface as CANNOT_SEEK_THROUGH_FILE instead of Code = -100. Added RethrowsCallbackExceptionAfterOpenSucceeded to cover the post-open path the bot was concerned about. No assertions weakened.
e Both directions demonstrated? YES. Without fix + ASan: deterministic stack-use-after-return at 'opaque' (line 74). With fix + ASan: 82/82 archive tests pass (80 existing + 2 ZipArchiveReaderTest).
f Fix is general, not narrow? YES. The fix covers ALL callback paths that use opaque (read/seek/tell/write), not just the one triggering the reported #104681 symptom. The same bug pattern is not present elsewhere in ZipArchiveReader.cpp because Opaque is the only stack-bound callback context.

Local verification:

  • build/src/unit_tests_dbms --gtest_filter="*Archive*" → 80/80 PASSED.
  • build-asan/src/unit_tests_dbms --gtest_filter="ZipArchiveReaderTest.*" with ASAN_OPTIONS=detect_stack_use_after_return=1 → 2/2 PASSED (with fix). Pre-fix → ASAN aborts on the new test.

Session: cron:clickhouse-ci-task-worker:20260516-060000

@alexey-milovidov

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

groeneai added 2 commits June 10, 2026 21:28
… = -100"

When reading a zip archive whose underlying `SeekableReadBuffer` throws (for
example `ReadBufferFromS3` with `restricted_seek = true` rejecting a backward
seek during minizip's EOCD search), the exception was caught inside the
`StreamFromReadBuffer` C callbacks, the callback returned an error code, and
minizip's state machine then surfaced a generic `MZ_END_OF_LIST` (-100). The
result was the unhelpful `Couldn't unpack zip archive 'X': Code = -100`
message reported in issue ClickHouse#104681, with the actual cause (e.g.
`CANNOT_SEEK_THROUGH_FILE`) silently dropped.

The fix:

* `HandleHolder::checkResult` and `showError` now rethrow any stored stream
  exception before falling through to the cryptic minizip error formatter, so
  every post-open failure surfaces the underlying error instead of
  `Code = -100`.
* `StreamFromReadBuffer::open()` returns the captured exception when
  `unzOpen2_64` fails. Minizip cleans up the stream during its own failure
  path, so the in-stream `stored_exception` is unreachable afterwards. The
  read/seek/tell callbacks therefore also write a copy of the exception into
  the shared `Opaque` struct (lives on the caller's stack), which
  `acquireRawHandle` rethrows instead of the generic
  `Couldn't open zip archive` message.

A new gtest reproduces the issue with a `SeekFailingReadBuffer` that fails on
the second seek after a read; with the fix the underlying
`CANNOT_SEEK_THROUGH_FILE` is surfaced unchanged.

Closes ClickHouse#104681
…-scope

clickhouse-gh[bot] flagged on PR ClickHouse#105103 that the `Opaque` struct used by the
minizip stream callbacks was a stack-local in `StreamFromReadBuffer::open`.
Minizip stores the `opaque` pointer internally during `unzOpen2_64` and
dereferences it from every later callback (`readFileFunc`, `seekFunc`,
`tellFunc`); after `open` returned successfully, those callbacks dereferenced
freed stack memory whenever they took the exception-capture path through
`storeException(strm, opaque)`.

ASan confirms the bug:

    ERROR: AddressSanitizer: stack-use-after-return
    READ of size 8 at 0x... thread T0
    Address ... is located in stack of thread T0 at offset 88 in frame
      ...
      [64, 96) 'opaque' (line 74) <== Memory access at offset 88 is inside this variable

The fix heap-allocates `Opaque` via `std::shared_ptr` and pins it for the
lifetime of the `unzFile` handle:

  * `OpenResult` carries a `std::shared_ptr<Opaque>` owning the storage.
  * `RawHandleWithStream` (in the header) gains a `std::shared_ptr<void> opaque`
    field so the handle cache keeps the storage alive across acquire/release.
  * `HandleHolder` moves the opaque shared pointer with the handle and passes
    it back to the cache in `releaseRawHandle()`.

`closeFileFunc` already ignores the `opaque` parameter, so destruction order
during `unzClose()` in `~ZipArchiveReader` is safe: minizip releases the
handle first, then the shared pointers in `free_handles` drop the `Opaque`.

A new gtest, `ZipArchiveReaderTest.RethrowsCallbackExceptionAfterOpenSucceeded`,
opens the archive normally, then flips an externally-owned flag so the next
post-open callback throws. Under ASan, this test deterministically fails on
the pre-fix code (stack-use-after-return at line 74) and passes cleanly with
the heap-allocated `Opaque`.
@groeneai
groeneai force-pushed the fix-104681-zip-archive-exception-laundering branch from 8aaf7e2 to 19c58ef Compare June 10, 2026 21:42
@groeneai

Copy link
Copy Markdown
Collaborator Author

Rebased onto current master to resolve a merge conflict in src/IO/Archives/ZipArchiveReader.h.

The conflict was trivial: master (#106849) switched the archive reader to Strings / VectorWithMemoryTracking and adjusted the include block; this PR adds #include <memory> for the std::shared_ptr<void> opaque field. Resolution keeps both. No functional change to the fix.

The history is now clean (2 commits, the stale merge commit was dropped). Verified locally with clang-21 debug:

  • ZipArchiveReader.cpp and gtest_archive_reader_and_writer.cpp compile against current master
  • unit_tests_dbms links
  • All 80 archive tests pass, including the post-open callback regression test ZipArchiveReaderTest.RethrowsCallbackExceptionAfterOpenSucceeded

Session: cron:clickhouse-worker-slot-7:20260610-212500

@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.60% 84.70% +0.10%
Functions 92.30% 92.30% +0.00%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 152/165 (92.12%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on `19c58efab5c0` with no test failures. Ready for review.

@alexey-milovidov
alexey-milovidov merged commit a20e164 into ClickHouse:master Jun 26, 2026
165 of 166 checks passed
@alexey-milovidov alexey-milovidov self-assigned this Jun 26, 2026
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 26, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…-scope

clickhouse-gh[bot] flagged on PR ClickHouse#105103 that the `Opaque` struct used by the
minizip stream callbacks was a stack-local in `StreamFromReadBuffer::open`.
Minizip stores the `opaque` pointer internally during `unzOpen2_64` and
dereferences it from every later callback (`readFileFunc`, `seekFunc`,
`tellFunc`); after `open` returned successfully, those callbacks dereferenced
freed stack memory whenever they took the exception-capture path through
`storeException(strm, opaque)`.

ASan confirms the bug:

    ERROR: AddressSanitizer: stack-use-after-return
    READ of size 8 at 0x... thread T0
    Address ... is located in stack of thread T0 at offset 88 in frame
      ...
      [64, 96) 'opaque' (line 74) <== Memory access at offset 88 is inside this variable

The fix heap-allocates `Opaque` via `std::shared_ptr` and pins it for the
lifetime of the `unzFile` handle:

  * `OpenResult` carries a `std::shared_ptr<Opaque>` owning the storage.
  * `RawHandleWithStream` (in the header) gains a `std::shared_ptr<void> opaque`
    field so the handle cache keeps the storage alive across acquire/release.
  * `HandleHolder` moves the opaque shared pointer with the handle and passes
    it back to the cache in `releaseRawHandle()`.

`closeFileFunc` already ignores the `opaque` parameter, so destruction order
during `unzClose()` in `~ZipArchiveReader` is safe: minizip releases the
handle first, then the shared pointers in `free_handles` drop the `Opaque`.

A new gtest, `ZipArchiveReaderTest.RethrowsCallbackExceptionAfterOpenSucceeded`,
opens the archive normally, then flips an externally-owned flag so the next
post-open callback throws. Under ASan, this test deterministically fails on
the pre-fix code (stack-use-after-return at line 74) and passes cleanly with
the heap-allocated `Opaque`.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…hive-exception-laundering

Surface real callback exceptions in ZipArchiveReader instead of "Code = -100"
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.

s3() fails to read parquet files embedded in zip when file exceeds a certain threshold

3 participants