Skip to content

Report which destination made the macOS self-extracting copy fail - #115236

Closed
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:impl-arm-darwin-se-copyfile-diagnostic
Closed

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:impl-arm-darwin-se-copyfile-diagnostic

Conversation

@groeneai

@groeneai groeneai commented Aug 18, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

...

Description

Fast test (arm_darwin) fails a few times a day on unrelated PRs with
Permission denied on ci/tmp/clickhouse:
job 95461613722
(report),
also jobs 95537845886, 95306463154, 95222719292, across three unrelated PRs.

The binary is the self-extracting bundle and it destroys itself. In
decompressor.cpp unlink(self) succeeds, the Darwin-only
std::filesystem::copy_file(tmp -> self) then fails EEXIST, and the error
return happens before the chmod restoring the executable bit, so the process
exits having removed its own binary. The progress dots appear exactly once in
the log, immediately followed by that copy_file's File exists.

Why the destination exists after a successful unlink is not established, and I
could not reproduce it: this is macOS-only and I have no macOS host. Two
mechanisms remain possible (path resolution through
_NSGetExecutablePath/realpath/APFS naming a different entry than unlink
removed, or a symlink-following equivalence match); an unlabelled File exists
cannot tell them apart.

So instead of guessing at a fix, this reports the destination's identity and
keeps the failure closed: lstat and symlink-following stat for destination
and source, the equivalence flag from the followed pair (what libc++ compares
before returning EEXIST), and the original wrapper's dev/inode. It is confined
to that failure branch plus an OS_DARWIN-only helper; one real occurrence
identifies the mechanism.

Two candidate fixes were dropped on measurement: copy_options::overwrite_existing
is a no-op against the equivalence case and truncates an unknown object
otherwise; staging the temp file executable would publish a partial executable.

Validated by an oracle harness compiling this code verbatim over three
destination shapes that must differ (they collapse without the change), a
-DOS_DARWIN type-check with an injected-error control, byte-identical Linux
.text, and a standalone self-extracting round trip unchanged before and after.

A green Fast test (arm_darwin) here is not evidence the diagnostic works, since
it only fires on failure: this makes the next occurrence diagnosable, not rarer.


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

Fast test (arm_darwin) fails a few times a day, on unrelated PRs, with
Permission denied on ci/tmp/clickhouse. The binary is the self-extracting
bundle and it destroys itself: unlink(self) succeeds, the Darwin-only
std::filesystem::copy_file(tmp -> self) then fails EEXIST, and the error
return happens before the chmod that restores the executable bit, so the
process exits having removed its own binary. Every later invocation of that
path is Permission denied. The decompressor's progress dots appear exactly
once in the failing log, immediately followed by File exists, which is that
copy_file's message.

Why the destination exists after a successful unlink is not established and
could not be reproduced: this is macOS-only and no macOS host was available.
Two mechanisms remain possible, path resolution through
_NSGetExecutablePath/realpath/APFS naming a different directory entry than
unlink removed, or a symlink-following source-destination equivalence match,
and the current bare File exists carries no label and no path, so it cannot
tell them apart.

Rather than guess at a fix, report the destination's identity at the abort and
keep the failure closed. Both lstat and the symlink-following stat are emitted
for destination and source, because they answer different questions: lstat
gives the directory entry, while libc++ compares the FOLLOWED pair before
returning EEXIST (operations.cpp stat_equivalent), so the equivalence flag is
computed from the followed stats. An lstat-only comparison would report "not
equivalent" in exactly the case libc++ reports as EEXIST. The original
wrapper's dev/inode is included so a path-resolution divergence shows up as a
mismatch against what unlink was expected to have removed.

Two candidate fixes were dropped on measurement rather than opinion.
copy_options::overwrite_existing is a no-op against the equivalence case,
since libc++ short-circuits before consulting options, and it truncates an
unknown object otherwise. Making the staged temp file executable before the
copy would publish a partially copied executable, inverting the deliberate
publish-executable-last ordering of the final chmod.

Behaviour is unchanged everywhere: the edit lives inside the existing failure
branch or in an OS_DARWIN-only helper, and the compiled Linux .text is
byte-identical to before.

Validated by an oracle harness that compiles this code verbatim over three
destination shapes whose reports must differ (they collapse to the same bare
message without the change), a -DOS_DARWIN type-check with an injected-error
control, and a standalone self-extracting round trip that behaves identically
before and after.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (independent cold review + second-model gate, 0 blockers)

Before publishing I reviewed this diff cold, without reading the authoring
session's own write-up, and then had an independent second model re-review the
full change. Findings and verdicts:

# Finding Verdict
💡 1 errno is read after ostream inserts in the same full expression, so a stream operation could in principle clobber it DISAGREE. The same file already relies on this in 33 places via perror(), and in the stat-failure branch nothing is streamed between the failing call and the errno read. Not worth churn on a diagnostic path.
💡 2 Two added lines are 121-122 columns DISAGREE. .clang-format sets ColumnLimit: 140 and check_cpp.sh has no line-length rule. I ran the repo's own style regex, tab and trailing-whitespace checks over the file: zero hits.
⚠️ 3 The description linked two unrelated PRs by number for the breadth count AGREED, fixed. Bare #NNNNN back-references would falsely connect PRs that merely share a flaky failure; replaced with the count plus the job ids.
⚠️ 4 The description said "one line in one existing failure branch", understating a 45-line diff that adds a 32-line helper AGREED, fixed.

Second-model gate (independent engine, full scope): 0 findings. Its coverage
was the full decompressor, the callers and build wiring, the libc++ copy_file
implementation, the Darwin fast-test flow and the CI failure log.

Two things I checked specifically because they would have made the change wrong
or dead, and which hold:

  • The lstat / following-stat pair is not redundant. libc++ stats the
    destination with the following stat (posix_stat -> detail::stat) and
    short-circuits to EEXIST at operations.cpp:403-404 before consulting
    copy_options. So the emitted equivalent= flag reproduces libc++'s own
    st_dev/st_ino predicate, and an lstat-only comparison would have printed
    "not equivalent" in exactly the symlink case libc++ reports as EEXIST.
  • The code is compiled on the lane it targets. Both darwin builds pass
    -DENABLE_UTILS=0, but utils/CMakeLists.txt gates
    self-extracting-executable on ENABLE_CLICKHOUSE_SELF_EXTRACTING (=1 there),
    not on ENABLE_UTILS.

I also confirmed the root cause from the job log rather than from the authoring
analysis: the decompressor's progress dots occur exactly once in the whole log,
File exists follows immediately, and the first Permission denied is the next
invocation. File exists is the message of the only error_code reported in
that translation unit.

No test can redden on revert here, by construction: the path is macOS-only and
fires only on a failure that could not be reproduced without a macOS host. The
substitute is an oracle harness that compiles this code verbatim over three
destination shapes, with a negative control in which all three collapse to the
same bare message.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Of the diagnostic: yes, on demand. An oracle harness compiles the changed code verbatim (extracted from decompressor.cpp, byte-compared before each run) and drives the abort site over three destination shapes. Of the CI failure itself: no, and stated as such in the description. It is macOS-only and I have no macOS host, which is exactly why this reports identity instead of proposing a fix.
b Root cause explained? The abort is established: unlink(self) succeeds, the Darwin-only copy_file(tmp -> self) fails EEXIST, and the error return precedes the chmod that restores the executable bit, so the process exits having deleted its own binary. File exists is provably that copy_file's message (it was the only ec.message() in the TU), and the progress dots appear exactly once in the failing log. Why the destination exists after a successful unlink is NOT established - two mechanisms remain possible, two are refuted.
c Fix matches root cause? This does not claim to fix the abort; it makes the abort's cause identifiable and keeps the failure closed (return 1 unchanged). Two candidate fixes were dropped on measurement: copy_options::overwrite_existing is a no-op against the equivalence case (libc++ short-circuits at operations.cpp:403-404 before consulting options; measured ec=17 with and without the flag) and truncates an unknown object otherwise; making the staged temp file executable early would publish a partially copied executable, inverting the deliberate publish-executable-last ordering.
d Test intent preserved / new tests added? No test weakened (none touched). No stateless/integration test: this is build tooling with no SQL surface. The test surface is the oracle harness plus a -DOS_DARWIN type-check, and each has a control that fails when the thing it measures is absent.
e Both directions demonstrated? Yes. With the change, three arms (hard link / symlink / distinct file) emit pairwise-distinct reports and 12/12 assertions pass. Without it (same harness, pre-fix abort body) all three collapse to the identical bare File exists and the oracle fails. The symlink arm is the discriminator: lstat ino 2942813 (type link) vs followed stat ino 2942812 == source ino, equivalent=1 - the two disagree, so an lstat-only design would have contradicted the very failure it explains.
f Fix is general across code paths? The invariant is "when the Darwin self-replacement aborts, the report identifies the destination that caused it". The Darwin copy_file abort was the only site with an unlabelled diagnostic (confirmed: no other ec.message() in the TU). The Linux/FreeBSD link abort is untouched because it is already labelled by perror("link"), no failure is observed there, and Linux additionally has the lockf+inode guard macOS lacks. The same decompressor is embedded in the clickhouse, clickhouse-stripped and clickhouse-keeper bundles, so all three gain the diagnostic.
g Fix generalizes across inputs (params/datatypes/wrappers)? The helper's input is a path; its boundary cases are the ways a path can fail to resolve. Regular file (type=reg) and symlink (type=link, stats disagree) are both exercised by the arms; type=other is handled but not constructible here (copy_file returns not_supported for a non-regular destination before ever reporting EEXIST); a failing lstat or stat reports its errno. Notably equivalent= is emitted only when both followed stats succeeded, so a failed stat cannot yield a bogus flag computed from zero-initialised structs.
h Backward compatible? (maintainer-approved exception only) Yes, nothing to break. No format change (old and new decompressors read each other's bundles), no public interface, no setting, hence no SettingsChangesHistory.cpp entry. Output changes only on a path that already returned 1, and no CI script parses that text (grep -rn "File exists" ci/ tests/ci and the sibling decompressor messages: 0 hits).
i Invariants and contracts preserved? followed is written only on the success return and the caller gates on that return before reading it. All struct stat are zero-initialised, matching the file's existing style. No allocation, ownership, fd, lock or signal handler; the up-to-four added syscalls run only on an already-failing, about-to-return 1 path. errno is read immediately after the failing call. Failure semantics are unchanged - still return 1, still before the chmod. Single-threaded at this point (the decompressor's forks are all reaped earlier), so strerror is safe and is marked // NOLINT(concurrency-mt-unsafe) explicitly. Linux .text is byte-identical to master (b00815f9bf544daf, 7297 B both), and a full standalone self-extracting round trip behaves identically before and after (wrapper replaces itself, stays mode 755, second run execs the payload).

Session id: cron:clickhouse-impl-slot-5:20260818-015500

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [51208e7]


AI Review

Summary

This PR adds Darwin-only diagnostics around the self-extracting copy_file failure path so a future EEXIST/Permission denied incident records the destination and source identities. I did not find a new correctness, safety, or performance regression in the code change itself.

Missing context / blind spots
  • ⚠️ The 2026-09-05 PR discussion argues that the original Fast test (arm_darwin) symptom may already be obsolete after https://github.com/ClickHouse/ClickHouse/pull/115169, while the current tree still contains Darwin self-extracting artifacts and Darwin fast-test wiring. I could not prove from repo state alone whether this failure path is still exercised in production CI today; confirming that would settle whether the PR is still worth merging.
Final Verdict

✅ No inline findings on the current diff. The code change itself looks safe; the remaining question is whether the PR is still needed operationally.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @thevar1able @azat, could you review this? On the arm_darwin runner the self-extracting wrapper deletes itself: unlink(self) succeeds, the Darwin-only copy_file(tmp -> self) then fails EEXIST, and the error return precedes the chmod that restores the executable bit, so every later exec of that path is Permission denied. Why the destination exists after the unlink is not established and is not reproducible without a macOS host, so this reports the destination's identity at the abort instead of guessing at a fix.

@groeneai groeneai added the groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-build-system Build system (CMake, compilation, platform builds). label Sep 4, 2026
@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

Flagging this before it costs anyone a review: I think the defect this PR diagnoses has been
addressed from a different direction, and the check that would print the diagnostic is no longer
running.

The user-facing report is already closed. Issue #75921 describes this exact symptom, that
self-modification drops the execute permission and leaves a non-executable clickhouse. It was
closed as completed on 2026-08-20 pointing at #115169 (merged 2026-08-18) and
Homebrew/homebrew-cask#282010, i.e. signed plain macOS artifacts rather than a decompressor
change.

The CI signal is gone as well. Fast test (arm_darwin) is the only job that consumes the
self-extracting macOS binary (ci/defs/job_configs.py:317, requires=[CH_ARM_DARWIN_BIN]), and it
has produced no rows at all since 2026-09-01 16:34:24 UTC:

SELECT toDate(check_start_time) AS d,
       countIf(check_name = 'Build (arm_darwin)')     AS build_rows,
       countIf(check_name = 'Fast test (arm_darwin)') AS fast_test_rows
FROM default.checks WHERE check_start_time > now() - INTERVAL 10 DAY GROUP BY d ORDER BY d DESC
2026-09-05    926     0
2026-09-04   2500     0
2026-09-03   2126     0
2026-09-02   1903     0
2026-09-01   2165 27746
2026-08-31   2602 3516210

Consistent with that, the three completed PR workflow runs from today that I sampled (170 jobs each)
contain Build (arm_darwin) and Build (amd_darwin) but no darwin fast test job.

So the failure branch this PR instruments is currently unreachable in CI, and the report it adds
would never be printed. My suggestion is to close this PR. It is your call though: if the macOS fast
test is coming back, or the self-extracting macOS binary is still shipped somewhere I have not
found, the labelled report is still the cheapest way to separate the two candidate mechanisms, and I
will leave it open.

One code fact worth recording either way, since it was not in the original description. The
decompressor's whole concurrency protection is compiled out on macOS: the
/tmp/<name>.decompression.<inode>.lock file, the lockf(F_LOCK) mutual exclusion, and the check
that spots that another process already replaced the binary and execvs it instead of unlinking,
all sit inside #if !defined(OS_DARWIN) && !defined(OS_FREEBSD)
(utils/self-extracting-executable/decompressor.cpp:445-497). On Linux the loser of a race exits
without touching the file; on macOS both processes run unlink(self) and then
copy_file(tmp, self). That is a candidate explanation for a destination that exists after a
successful unlink, and it is one my earlier note did not cover: that note reasoned from a single
job log, but these macOS runners are reused between jobs. If the self-extracting path stays, that
gap is what I would fix, and it can be exercised on Linux by building with those two guards
excluded.

@thevar1able thevar1able added the can be tested Allows running workflows for external contributors label Sep 7, 2026
@thevar1able thevar1able self-assigned this Sep 7, 2026
@thevar1able

Copy link
Copy Markdown
Member

@groeneai so let's close this if it is not necessary anymore?

@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Yes, please go ahead and close it.

I re-measured before answering. Fast test (arm_darwin) has produced no CIDB rows since 2026-09-01 16:34:24 UTC, while the build that feeds it kept running the whole time (Build (arm_darwin) covered 258 PR commits today; the fast test covered 241 on 08-31 and none since), and it has not been renamed: the only %darwin% check names in the last 5 days are Build (arm_darwin), Build (amd_darwin) and the new Sign macOS binary (arm_darwin|amd_darwin). Since that job is the only consumer of CH_ARM_DARWIN_BIN (ci/defs/job_configs.py:317), the failure branch this PR instruments can no longer be reached, and #75921 is closed via #115169 plus Homebrew/homebrew-cask#282010.

One pointer worth keeping if the macOS fast test comes back, from my comment above: the decompressor's whole concurrency protection (the .decompression.<inode> lock file, the lockf(F_LOCK) mutual exclusion, and the "another process already replaced this binary, so execv instead of unlinking" inode check) sits inside #if !defined(OS_DARWIN) && !defined(OS_FREEBSD), so on macOS both racers run unlink(self) and then copy_file(tmp, self). That gap is testable on Linux by building the bundle with those guards excluded.

@thevar1able thevar1able closed this Sep 7, 2026
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-build-system Build system (CMake, compilation, platform builds). groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants