Skip to content

Cross-compile ClickHouse for Windows - #112824

Open
alexey-milovidov wants to merge 396 commits into
masterfrom
windows-cross-build
Open

alexey-milovidov wants to merge 396 commits into
masterfrom
windows-cross-build

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 31, 2026 •

Copy link
Copy Markdown
Member

Draft. Cross-compiles clickhouse.exe for x86_64-w64-windows-gnu (mingw-w64 + clang + lld → a native PE, no emulation layer and no MSVC licence). The goal is clickhouse-client and clickhouse-local running natively on Windows.

State: it links, and CI runs it under Wine — clickhouse.exe --version and clickhouse.exe local --query "SELECT 1", which is the whole startup path and one pipeline. Nothing past that has been executed: no client against a real server, no clickhouse-local over actual files, no test suite, and nothing on a real Windows machine rather than on Wine. The Wine run happens on the CI runner because the development host is aarch64 and Wine on ARM ships no x86 emulator.

programs/clickhouse.exe: PE32+ executable for MS Windows 6.00 (console), x86-64
520 MB · imports ADVAPI32, IPHLPAPI, KERNEL32, USER32, WS2_32, dbghelp, msvcrt

Every import ships with Windows, so the binary is a single self-contained file. Linux builds and links clickhouse unchanged after every commit in the branch. CI builds clickhouse for Windows on every pull request and then executes it under Wine, so the port cannot silently regress.

What is here

The runtime (libc++/libc++abi/libunwind with SEH, compiler-rt builtins), 117 contribs behind a self-maintaining CI gate, all of Poco — whose Windows layer had been deleted from this fork and is restored from upstream 1.9.3 — every library under src, and programs. Roughly 900 of the changed lines are one mechanical class: std::filesystem::path used where a String is wanted, which compiles on POSIX through an implicit conversion that does not exist on Windows.

Implemented natively rather than stubbed, because a client needs them: terminal size and console encoding, raw console mode and keystroke reading, Ctrl+C and Ctrl+Break, socket liveness, statvfs via GetDiskFreeSpaceEx, file mapping, pread, per-thread CPU time, setThreadName, isLocalAddress, readpassphrase, and a WakeupFd built on a loopback socket pair (a Windows pipe cannot be waited on alongside sockets).

Compiled out with the reason recorded at each site, all server-side or POSIX-only: the sampling profiler and signal handlers (Windows reports faults through SEH), ThreadFuzzer, the fork-based watchdog, ShellCommand and everything built on it, the pseudo-terminal features, and the su/docker-init/install tools.

Known gaps

  • Executed only as far as a trivial clickhouse-local query under Wine, as above.
  • -g0 on Windows: a PE image cannot exceed 4 GiB and the DWARF alone is several times that, and PE has no .gnu_debuglink equivalent to carry it separately. A crash symbolizes to module and offset, not file and line.
  • No Epoll backend, so nothing that polls sockets through it works yet.
  • Local syslog, archives (libarchive needs a hand-written Windows config.h), conditional writes to the local object storage (they need flock on a directory and sub-second modification times), and the web terminal report NOT_IMPLEMENTED.

docs/resources/develop-contribute/build/build-cross-windows.mdx has the build instructions and a per-subsystem inventory of what remains.

Related: #112185
Related: #112767

Changelog category (leave one):

  • Build/Testing/Packaging Improvement

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

Added a cross-compilation target for Windows (x86_64-w64-windows-gnu), producing a native clickhouse.exe. The port is not finished: CI runs the binary under Wine over a trivial clickhouse-local query, and nothing beyond that has been executed.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

🤖 Generated with Claude Code


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

@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e46add2]

Summary: ❌

job_name test_name status info comment
Build (arm_tidy, 2/4) FAIL
Build ClickHouse FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL
Build (amd_asan_ubsan) DROPPED
Build (arm_asan_ubsan) DROPPED
Integration tests (amd_asan_ubsan, db disk, targeted) DROPPED
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) DROPPED

AI Review

Summary

Adds a native Windows cross-build, platform implementations for file I/O, sockets and console handling, and Wine smoke coverage. The current code contains two Linux regressions and Windows file-identity, durability and console-lifecycle defects. Three new safety findings require blocking approval. Previously dismissed findings that remain valid are recorded below without renewed inline discussion.

Missing context / blind spots
  • ⚠️ No ClickHouse binary is available in this review job. Reproductions are source-derived. At head e46add2331cc5b7f4d49a33d1107dff8caaab68e, the Windows job and runtime suites are skipped following the clang-tidy failure. Current-head CI execution and a native console check would close the runtime-validation gap.
Findings

❌ Blockers

  • StorageFile.cpp:2194: A failed second metadata lookup resets current_file_cache_version, but the split-file comparison at line 2210 dereferences it unconditionally. Removing a parallel-read Parquet file between the successful getFileStat and platformFileVersion produces undefined behavior on Linux too. Reject the missing token with FILE_CHANGED_DURING_READ before comparing it.

  • PlatformFileIO.cpp:428: DeletePending describes deletion of the open handle's link, independently of remaining accessible hard links, per the Windows filesystem algorithm. After a failed sync through hard link A, deleting A while B remains makes FailedFiles::releaseUnlinked forget the durability failure. Require zero accessible names before releasing the marker.

  • StorageReplicatedMergeTree.cpp:976: collectFileIds still compares CRT (st_dev, st_ino) values on Windows, although those fields identify a drive and a zero inode. Independent parts with matching filename sets therefore compare equal; checkPartsImpl can delete an unexpected part instead of preserving it in detached. Local attachment reaches this check before replica activation. Use reliable file identities or skip destructive deduplication when unavailable. The CRT documentation confirms that these fields cannot identify individual Windows files.

  • src/Backups/registerBackupEnginesFileAndDisk.cpp:112 — [dismissed by author -- https://github.com/Cross-compile ClickHouse for Windows #112824#discussion_r4228573877] Both backup containment checks remain lexical. An existing symlink below an allowed directory can direct a backup outside backups.allowed_path or a local disk root. The author's decision to preserve existing behavior does not remove the sandbox escape; use symlink-aware containment or track the security issue explicitly.

⚠️ Majors

  • Common.cpp:40: IcebergMetadata::drop passes the absolute table path twice to listFiles. String concatenation now doubles that path, whereas the old filesystem join selected the absolute second operand. DROP TABLE with iceberg_delete_data_on_drop = 1 consequently leaves an absolute-path IcebergLocal table's data behind on Linux. Pass an empty prefix and assert physical cleanup.

  • programs/main.cpp:640: Console restoration relies on std::atexit, but controlled cancellation and external-table option errors use _exit, which skips those callbacks. Starting under code page 437 and exiting an idle local session with Ctrl+Break leaves the shared console at 65001. Restore saved console state before controlled immediate exits.

  • programs/disks/DisksClient.h:29 — [dismissed by author -- https://github.com/Cross-compile ClickHouse for Windows #112824#discussion_r4174994349] DiskWithPath still applies Windows filesystem semantics to virtual paths. A remote object named with a literal backslash is addressed as a different slash-separated key. Use /-only virtual-path operations; the acknowledged redesign remains unfinished.

  • MetadataStorageFromStaticFilesWebServer.cpp:221 — [dismissed by author -- https://github.com/Cross-compile ClickHouse for Windows #112824#discussion_r4321747169] Raw projection directory names still become URL syntax at index/data reader boundaries. A legal projection p#q uploads successfully but cannot be read back. Encode reader directory components consistently with the uploader; ordinary-name coverage does not prove this round trip.

  • programs/local/LocalServer.cpp:429 — [dismissed by author -- https://github.com/Cross-compile ClickHouse for Windows #112824#discussion_r4170809834] An explicit missing --config-file still silently selects embedded configuration plus the current directory's merge files. This can run with different configuration from the one requested. Restrict the fallback to implicit discovery, or explicitly track the existing behavior.

  • programs/extract-from-config/ExtractFromConfig.cpp:132 — [dismissed by author -- https://github.com/Cross-compile ClickHouse for Windows #112824#discussion_r4170809846] A relative users configuration is anchored beside the main configuration only if that sibling already exists. Otherwise --users can read a different file in the current directory. Resolve the relative path against its intended base before checking existence.

  • src/Client/ClientApplicationBase.cpp:334 — [dismissed by author -- https://github.com/Cross-compile ClickHouse for Windows #112824#discussion_r4256151591] The uncaught-C++-exception portion is fixed, but access violations still lack an SEH fatal-reporting path. Windows client/local faults can therefore terminate without ClickHouse fatal diagnostics. This acknowledged follow-up also covers the duplicate second thread.

💡 Nits

  • src/Storages/MergeTree/checkDataPart.cpp:30: CI already reports the unused fs namespace alias through clang-tidy. No inline finding was posted for this build-check failure.
Tests
  • ⚠️ Add focused Linux coverage for the failed split-file version lookup and physical cleanup after dropping an absolute-path IcebergLocal table.
  • ⚠️ Verify Windows identities distinguish independent files with identical relative names while recognizing hard links. Test that removing one of two links preserves the failed-file marker and removing the last permits cleanup. The existing selftest checks identity equality/difference, but not this deletion-state contract; the author's reply explicitly identifies that gap.
  • ⚠️ Check shared console state after controlled child-process cancellation. Extend the existing web-disk round trip with URL-special/escaped projection names when the reader is corrected; the serialization fix has no such regression case, as acknowledged.
Final Verdict

Status: ❌ Block

Correct the three new safety defects, the absolute-path Iceberg deletion regression and console cleanup, with focused regression evidence. The dismissed findings remain recorded for maintainer disposition; no dismissed thread was replied to or reopened.

@clickhouse-gh clickhouse-gh Bot added pr-build Pull request with build/testing/packaging improvement submodule changed At least one submodule changed in this PR. labels Jul 31, 2026
@mintlify

mintlify Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Nov 24, 2026, 6:00 AM

Comment thread src/Client/ClientApplicationBase.cpp Resolved
alexey-milovidov added a commit that referenced this pull request Aug 4, 2026
The  job failed to compile libc++'s `filesystem/path.cpp`:
Ubuntu 24.04 ships mingw-w64 11, whose headers and `libmsvcrt.a` lack the
`_l`-suffixed per-locale CRT functions (`_iswctype_l`, ...) that the libc++ 22
locale support calls. The failure only surfaced now because the job previously
built `clickhouse-windows-ported`, which never compiled that translation unit.

Install `mingw-w64-common` and `mingw-w64-x86-64-dev` 13.0.0 from Launchpad's
permanent per-file archive instead: both are data-only `all`-architecture
packages (headers and import libraries, no host binaries) depending only on
each other, verified by SHA-256. Compiling the failing translation unit against
a sysroot extracted from exactly these two packages was verified locally.

Also sync `docs/resources/develop-contribute/build/build-cross-windows.mdx`
(the published tree) with the rewritten `docs/en` page, which had gone stale,
and document the mingw-w64 version requirement in both.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112824&sha=8e2d398de135f758d71a3c1709aad95a51634042&name_0=PR&name_1=Build%20%28amd_windows%29
PR: #112824

Co-Authored-By: Claude Fable 5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Aug 4, 2026
Two changes on master do not compile for the Windows target:

- The frozen-clone fsync (#111426) passes an `fs::path` to
  `fsyncFrozenCloneTree`, relying on the implicit `path`/`std::string`
  conversion that only exists on POSIX. Route it through
  `pathToGenericString`, like every other disk-path construction site.

- The directory-name length check for async distributed INSERT moved from
  `Cluster.cpp` to `DistributedSink::checkDirectoryNameLengths`, bringing
  back a bare `NAME_MAX`, which Windows does not define. Reintroduce the
  `max_path_component_length` constant this branch had used in `Cluster.cpp`
  (where master removed the check) at the new site.

PR: #112824

Co-Authored-By: Claude Fable 5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Aug 4, 2026
The Windows branch of `setupSignalHandler` assumed the interactive loop
installs `InterruptListener`, but the client never does - only `benchmark`
and `keeper-bench` use it - so Ctrl+C fell through to the default console
behavior and ended the process instead of stopping the query. Install a
console control handler mirroring `interruptSignalHandler`: the first
Ctrl+C (or Ctrl+Break) requests a stop through `tryStopQuery`, a repeated
one exits.

`ENABLE_PROCESSED_INPUT` in the keystroke interceptor is deliberately kept
on and now documented: it is the counterpart of `ISIG`, which the POSIX raw
mode keeps on as well, so Ctrl+C reaches the new console control handler
instead of becoming a key event that no registered callback would consume.
The embedded client's `0x03` callback is fed by an SSH stream that never
passes through a Windows console.

PR: #112824

Co-Authored-By: Claude Fable 5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Aug 4, 2026
Turning the traversal paths from `fs::path` into plain strings for the
Windows port also changed the user-visible output of `delete_stale_backups`:
streaming an `fs::path` prints it quoted, streaming a `String` does not.
`test_keeper_client/test.py::test_delete_stale_backups` pins the quoted
form and failed on every integration shard. Restore the quotes explicitly.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112824&sha=8e2d398de135f758d71a3c1709aad95a51634042
PR: #112824

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

Copy link
Copy Markdown
Member Author

🕵 Status of this pass (commits bb2ae1379e1..81fa5c25b65):

  • Merged master (352 commits behind). Conflicts in .github/workflows/pull_request.yml (took master's, re-ran python3 -m ci.praktika yaml), Cluster.cpp (master removed the path-length check, so the branch's max_path_component_length went with it) and DDLWorker.cpp (kept pathToGenericString, added master's new max_tries_exceeded_path in the same style). Two master changes did not compile for Windows and were fixed: the frozen-clone fsync passing fs::path to fsyncFrozenCloneTree, and the moved NAME_MAX check in DistributedSink.
  • Build (amd_windows) failure fixed: Ubuntu 24.04's mingw-w64 11 lacks the _l-suffixed per-locale CRT functions (_iswctype_l, ...) that libc++ 22's locale support calls — in both the headers and libmsvcrt.a — so the binary-builder image now installs the data-only mingw-w64 13 packages from Launchpad, pinned by SHA-256. Verified locally by compiling the failing translation unit against a sysroot extracted from exactly those two packages; the full clickhouse.exe links.
  • AI review Majors addressed (37241dcaf98): setupSignalHandler now installs a console control handler so Ctrl+C cancels the running query; the ENABLE_PROCESSED_INPUT choice is documented — see the replies on the two threads. The requested native-Windows smoke run is not possible yet: there is no Windows runner in CI and the development host is aarch64 with no x86 emulation; running the binary is recorded as the first item of "Remaining work" in the build doc.
  • test_keeper_client/test.py::test_delete_stale_backups (all five integration shards) was caused by this PR — streaming a String instead of an fs::path dropped the quotes from the delete_stale_backups output. Fixed by restoring the quotes explicitly (81fa5c25b65).
  • AST fuzzer (amd_tsan) Logical error: '!database_name.empty()' in StorageMerge::getDatabaseIterator is unrelated (this PR's only StorageMerge change is 1UL → 1uz); a fix is already in progress: Fix a logical error when the merge table function is used in a mutation #113185
  • Stress test (amd_msan) "Hung check failed" shows a fuzzer-mutated query stuck CPU-bound in the analyzer's resolveQuery — unrelated to this PR's mechanical portability changes; possibly the same class as Uninterruptible CPU-bound function evaluation over a large value #112203. @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112824&sha=8e2d398de135f758d71a3c1709aad95a51634042&name_0=PR&name_1=Stress%20test%20%28amd_msan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

Comment thread src/Common/checkStackSize.cpp Resolved
Comment thread src/IO/PlatformFileIO.cpp Resolved
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

I read the hung_check.log artifact for 8e2d398de135f758d71a3c1709aad95a51634042. There is one hung query, not a convoy:

SELECT * FROM (SELECT toString(number) AS user_id FROM system.numbers LIMIT 20000, 10000) AS t1
LEFT JOIN (SELECT DISTINCT * FROM merge(REGEXP('^system$'), '.+') AS i1
           ANY LEFT JOIN (SELECT * FROM join_block_test) AS i2 ON i1.id = toString(i2.num)) AS t2
ON t1.user_id = t2.id

elapsed = 733.42, is_cancelled = 1, single-threaded, log_comment = 02033_join_engine_deadlock_long.sh-test_3.

One correction on the frame. The resolveQuery chain visible in CIDB is not this query's stack. CIDB keeps only the trailing 32 KiB of the log, which for this artifact starts at line 697, and those frames sit inside the Top messages not matching their format strings section (from line 528). The hung query's own stack is at line 61:

QueryPlan::optimize -> optimizeTreeSecondPass -> optimizePrimaryKeyConditionAndLimit
-> SourceStepWithFilterBase::applyFilters -> ReadFromMerge::applyFilters
-> filterTablesAndCreateChildrenPlans -> createChildrenPlans -> getModifiedQueryInfo
-> QueryAnalysisPass::run -> ... -> AnalysisTableExpressionData::ensureColumnMembershipSetsArePopulated

So this is plan-time per-child re-analysis inside StorageMerge, not analysis of the top-level query. Your CPU-bound reading is right: QueryProfilerRuns = 1411, and there is no futex or condition-variable frame, so the thread was running rather than blocked.

Two separate defects sit behind that row, and one of them is already yours.

Cost. The query has a JOIN, so getModifiedQueryInfo takes the replaceTableExpressionAndRemoveJoin path, and the leaf frame is exactly the per-column AnalysisTableExpressionData rebuild that #113140 makes linear. That PR is the fix for this half.

Interruptibility. #113140 does not add a cancellation point, and src/Storages/StorageMerge.cpp has none at all: on master 91687a7d610e6e, grep -c 'isCancelled\|is_cancelled\|checkTimeLimit\|throwIfKilled' returns 0. The harness issued four KILL QUERY ... ASYNC statements for this query_id, at 20:00:22, 20:01:42, 20:02:26 and 20:03:18, each returning one row, so each matched a live query. max_execution_time was 10. The query kept running through all of it. This half has no fixing PR yet; a fix task owns it and I will post the fixing-PR link here when it opens.

On #112203: same class, different site. That issue is per-value function evaluation during constant folding, whereas this is the per-child loop inside QueryPlan::optimize, so a fix there would not reach this path.

Separately, this report lost its server-side system.stack_trace dump: the collection command is assembled with duplicated client options and exits with Bad arguments: option '--max_untracked_memory' cannot be specified more than once (line 95 of the same artifact). #112845 fixes that.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status of this pass (commits fb0ee5124bd..cb89628950f):

  • Merged master (324 commits behind). All conflicts were of one shape: the branch's OS_WINDOWS cases vs master's new OS_WASM cases in the same places (cmake/target.cmake, CMakeLists.txt, getThreadId.cpp, c-ares, setThreadName.cpp) — kept both. Master's new OS_HAS_SIGNAL_HANDLERS macro now also excludes OS_WINDOWS (mingw-w64 has no sigaction; faults arrive through SEH), which lets ThreadStatus.cpp use master's condition unchanged.
  • Build (amd_windows) red fixed: master's ENABLE_BUILD_PROFILING adds -Wl,--time-trace, which lld's MinGW driver does not implement (only the ELF driver does), so the final link of clickhouse.exe failed with "unknown argument". The flag is no longer passed for the Windows target; verified locally with -DENABLE_BUILD_PROFILING=1 — the full clickhouse.exe links again.
  • AI review blockers addressed: checkStackSize is no longer a no-op on Windows — it feeds the shared check from GetCurrentThreadStackLimits, so TOO_DEEP_RECURSION fires again; platformOpenDirectory now opens with GENERIC_WRITE so _commit/FlushFileBuffers can flush directory metadata for LocalDirectorySyncGuard.
  • CI Tests red is unrelated: all 20 failures were ci/tests/test_lsan_ptrace_probe_filter.py, which master deleted in aa4d71aa820 (Resolve the settings-history patch against the PR head file, not the merged checkout #113227) for exactly this breakage; the merge pulls the deletion in.
  • The review's remaining ask — a native Windows / Wine smoke run — is still infeasible here: the development host is aarch64 and its Wine has no x86-on-ARM emulator, and CI has no Windows runner. The binary compiles and links; first execution still needs an x86-64 Windows machine.

Comment thread src/IO/PlatformFileIO.cpp Resolved
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator

Fixing PR for the ReadFromMerge::createChildrenPlans plan-time cancellation hung check on my
CI finish ledger: #113415 (external, open).

I had a fix for this on a local branch, but @alexey-milovidov opened #113415 with the identical
guard at the identical call site, so I dropped mine rather than open a duplicate. My analysis and
the one coverage gap I measured are in
#113415 (comment).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status of this pass (commits 5b93563ea31..21906972bd6):

  • Addressed the review on PlatformFileIO.cpp: platformRead now treats ERROR_BROKEN_PIPE / ERROR_NO_DATA as end-of-stream (0), matching POSIX read for a pipe whose writer closed, so piped stdin works on Windows.
  • Merged master (655 commits behind). Conflicts: the workflow YAMLs (took master's, re-ran python3 -m ci.praktika yaml — it re-adds the amd_windows job) and StorageReplicatedMergeTree.cpp (kept the branch's pathToGenericString wrapper plus master's new query_cancelled check in stop_waiting).
  • The merge broke the Windows build once: MySQL: accept TLS credentials as contents, allow paths only in the configuration file #112070's new TemporarySecretFile assigns std::filesystem::path to std::string, which does not compile where path::value_type is wchar_t. Fixed with pathToGenericString.
  • Verified locally: full Windows cross-build links (clickhouse.exe, 520 MB), and the touched translation units compile on Linux.
  • The single red at the previous sha (test_memory_context_in_trace_log, container-start timeout, retry_ok) is an infra flake unrelated to this PR; CI re-runs on the new sha.

Comment thread base/poco/Net/src/Net.cpp Resolved
Comment thread src/Client/ReplxxLineReader.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1d180ebdc with master 0161ed02a (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 679267cc9; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

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 ⚠️

4636 object files changed (-571.06 MiB total), 5 added.

Object file Master PR Δ
src/Dictionaries/CMakeFiles/clickhouse_dictionaries.dir/HashedDictionary.cpp.o 19.77 MiB 4.14 MiB -15.63 MiB (-79.06%)
src/Dictionaries/CMakeFiles/clickhouse_dictionaries.dir/SparseHashedDictionary.cpp.o 21.09 MiB 5.80 MiB -15.29 MiB (-72.50%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/polygonsSymDifference.cpp.o 17.39 MiB 6.62 MiB -10.77 MiB (-61.93%)
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion.cpp.o 24.64 MiB 14.21 MiB -10.43 MiB (-42.35%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionsNumericIndexedVector.cpp.o 19.51 MiB 9.31 MiB -10.21 MiB (-52.31%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/modulo.cpp.o 17.43 MiB 9.59 MiB -7.84 MiB (-45.00%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/polygonsIntersection.cpp.o 10.80 MiB 4.08 MiB -6.72 MiB (-62.25%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/polygonsUnion.cpp.o 10.73 MiB 4.06 MiB -6.66 MiB (-62.12%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/polygonsDistance.cpp.o 9.25 MiB 2.80 MiB -6.46 MiB (-69.75%)
src/CMakeFiles/dbms.dir/Functions/if.cpp.o 11.51 MiB 5.95 MiB -5.56 MiB (-48.31%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/intDiv.cpp.o 11.61 MiB 6.26 MiB -5.35 MiB (-46.11%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/arrayElement.cpp.o 10.20 MiB 5.08 MiB -5.12 MiB (-50.19%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/arrayDistance.cpp.o 10.11 MiB 5.25 MiB -4.87 MiB (-48.13%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/geometryIntersect.cpp.o 7.04 MiB 2.23 MiB -4.81 MiB (-68.31%)
src/Dictionaries/CMakeFiles/clickhouse_dictionaries.dir/HashedArrayDictionary.cpp.o 8.08 MiB 3.35 MiB -4.73 MiB (-58.51%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/arraySort.cpp.o 7.29 MiB 2.76 MiB -4.53 MiB (-62.14%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionsRound.cpp.o 8.64 MiB 4.21 MiB -4.42 MiB (-51.22%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/divide.cpp.o 9.61 MiB 5.19 MiB -4.42 MiB (-45.96%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/plus.cpp.o 8.74 MiB 4.57 MiB -4.17 MiB (-47.70%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/greaterOrEquals.cpp.o 8.56 MiB 4.45 MiB -4.11 MiB (-48.05%)

719 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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.68, programs/clickhouse-keeper ×0.64 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::SettingsTraits::Accessor::instance()::$_0::operator()() const 10.5 s 17.7 s +10.5 s (+146%)
Compile time of recompiled translation units

16491 translation units recompiled, 33934 s compile time in total, 15985 of them have a recent master baseline.

Translation unit Master PR Δ vs median
contrib/arrow-cmake/__/arrow/cpp/src/arrow/compute/api_scalar.cc 6.7 s 12.5 s +6.1 s (+94%)
contrib/arrow-cmake/__/arrow/cpp/src/arrow/compute/kernels/scalar_nested.cc 9.5 s 15.1 s +5.9 s (+64%)
contrib/arrow-cmake/__/arrow/cpp/src/arrow/compute/kernels/scalar_cast_numeric.cc 12.2 s 17.5 s +5.6 s (+47%)
contrib/arrow-cmake/__/arrow/cpp/src/arrow/compute/kernels/aggregate_mode.cc 7.6 s 12.9 s +5.5 s (+75%)
contrib/arrow-cmake/__/arrow/cpp/src/arrow/compute/kernels/vector_run_end_encode.cc 5.9 s 11.2 s +5.5 s (+95%)
contrib/arrow-cmake/__/arrow/cpp/src/arrow/compute/kernels/scalar_compare.cc 10.4 s 15.4 s +5.3 s (+52%)
contrib/arrow-cmake/__/arrow/cpp/src/arrow/compute/kernels/hash_aggregate.cc 11.7 s 16.5 s +5.1 s (+45%)

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.9 s

Job report

alexey-milovidov added a commit that referenced this pull request Aug 6, 2026
Winsock startup lived only in a static initializer in `Net.cpp`, a translation unit of the
static library `_poco_net` that nothing references, so the linker could drop it and the first
socket call would fail with `WSANOTINITIALISED`. Call `Poco::Net::initializeNetwork` from
`main` on Windows: the reference forces `Net.cpp` into the link (its initializer then runs
before `main`) and starts Winsock even if the initializer were compiled out.

Addresses the AI review blocker on #112824

Co-Authored-By: Claude Fable 5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Aug 6, 2026
`history_file_path` is UTF-8, but the history code interpreted it through the active code
page on Windows: `open` in the `ReplxxLineReader` constructor, the `std::ifstream` /
`std::ofstream` in `convertHistoryFile`, and replxx's own file opens inside
`history_load(std::string)` / `history_save(std::string)`. A profile directory containing a
character outside the code page silently lost history load and save.

Add `platformOpenReadWrite` (`_wopen` on Windows) to `PlatformFileIO`, open the conversion
streams by `std::filesystem::path` - wide on Windows - and use replxx's stream overloads on
Windows, reproducing the merge-then-write behavior of `history_save(std::string)` under the
exclusive lock the reader already holds.

Addresses the AI review Major on #112824

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

Copy link
Copy Markdown
Member Author

🕵 Status of this pass (commits 858fee6c6df..3faa7d0c25b):

  • Addressed the AI review blocker (Winsock startup): main now calls Poco::Net::initializeNetwork on Windows, which forces Net.cpp into the link (nothing else references that translation unit of the static library _poco_net, so the linker was free to drop it together with the WSAStartup static initializer) and starts Winsock even if the initializer were compiled out. Verified the symbol is now present in the linked clickhouse.exe.
  • Addressed the AI review Major (history file on narrow path APIs): the history path stays wide end-to-end on Windows — a new platformOpenReadWrite in PlatformFileIO (_wopen), convertHistoryFile streams opened by std::filesystem::path, and replxx's std::istream/std::ostream overloads for history_load/history_save, reproducing the merge-then-write of history_save(std::string) under the exclusive lock addToHistory already holds. POSIX behavior is unchanged.
  • Both touched translation units compile for Linux in build/; the full Windows build links, clickhouse.exe 520 MB.
  • The review's remaining ask — a native Windows or Wine smoke run — is still infeasible here: the development host is aarch64 and there is no x86-64 Windows CI runner. That is the first thing to do once one is available.
  • CI was fully green ✅ at the previous commit 21906972bd6.

alexey-milovidov and others added 3 commits November 10, 2026 04:50
The parent of a root path such as `X:/` (or `/`) is the root itself, so when
the volume is unavailable `getStatVFS` and `enoughSpaceInDirectory` retried the
same failing call forever. Stop when the parent equals the current path and
surface the error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	.github/workflows/master.yml
#	CMakeLists.txt
#	programs/benchmark/Benchmark.cpp
#	src/Backups/BackupMetadataFinder.cpp
#	src/Common/AlignedBuffer.cpp
#	src/Common/EnvironmentChecks.cpp
#	src/Common/ZooKeeper/KeeperClientCLI/KeeperClient.cpp
#	src/Common/memory.h
#	src/Disks/LocalDirectorySyncGuard.cpp
#	src/Processors/QueryPlan/Optimizations/RuntimeDataflowStatistics.cpp
#	src/Storages/MergeTree/MergeTreeData.cpp
#	src/Storages/MergeTree/MergeTreeMutationEntry.cpp
#	src/Storages/StorageStripeLog.cpp
The split reading path that came from master computed the file cache version token
from a `struct stat`, but this branch builds the token from `PlatformFileVersion`
(the CRT `stat` on Windows has whole-second timestamps and a zero `st_ino`). Read the
version with `platformFileVersion` and the metadata with `platformStat`, as the other
call sites do.

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

Copy link
Copy Markdown
Member Author

🕵 Merged master and resolved the conflicts. Head is now fbdebc9a352.

  • b9cdae7c698: merged master. There were conflicts in 13 files:
    • CMakeLists.txt: kept master's --time-trace-granularity and this PR's NOT OS_WINDOWS guard.
    • Benchmark.cpp: master moved the signal masking into blockSigint, so the OS_WINDOWS guard is now inside it.
    • AlignedBuffer.cpp: kept master's cache-line rounding and this PR's alignedPosixMemalign.
    • memory.h: kept master's je_mallocx / jemallocFlags path. alignmentForAlignedNew and the Windows zero-size and charging logic are now used only when jemalloc is off.
    • EnvironmentChecks.cpp: master's printErrorAndExit now sits under this PR's _putenv_s / setenv switch.
    • LocalDirectorySyncGuard.cpp: master's failpoint, then this PR's platformFDataSync.
    • MergeTreeMutationEntry.cpp: master's writeRecord refactoring, with this PR's pathToGenericString applied.
    • MergeTreeData.cpp: master removed loadDataPartForRemovalIfExists, so this PR's edit to it is dropped.
    • RuntimeDataflowStatistics.cpp: master's nullptr format settings plus this PR's 8192uz.
    • KeeperClient.cpp: kept this PR's string-space ZooKeeper path normalization, which covers master's lexically_normal change.
    • BackupMetadataFinder.cpp, StorageStripeLog.cpp: kept the includes from both sides.
    • master.yml: regenerated with praktika yaml.
  • fbdebc9a352: master's new split reading in StorageFile used the old stat-based computeFileCacheVersionToken. It now uses PlatformFileVersion / platformStat, like the other call sites.

The Linux build passes, and a parallel CSV read through file gives correct results. The Windows build will be checked by CI. The four open review threads already have replies and are left for the maintainer to decide.

alexey-milovidov and others added 4 commits November 12, 2026 10:54
Conflict resolutions:
- `checkStackSize.cpp`: keep the platform-split includes of the branch, add `Common/Silk/FiberScheduler.h` from master.
- `ICatalog.cpp`: take the endpoint-path-segment check from master, keep the key-space joins of the branch.
- `MetadataStorageFromStaticFilesWebServer.cpp`: keep `makeRemotePath` of the branch.
- `MMappedFileDescriptor.cpp`: the new `MADV_DONTNEED` before `munmap` goes into the POSIX branch.
- `DataLakes/Common/Common.cpp`: take `listPrefixImpl` / `listPrefixNonRecursive` from master, joining the
  directory key in key space via a new `keyDirectory` helper instead of `std::filesystem::path`.
- `test_disk_over_web_server/test.py`: keep the tests from both sides.
The `fs::path` to `String` conversion does not exist on Windows, where the native string is wide.
Convert with `pathToGenericString`, like the other paths in this file.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112824&sha=fbdebc9a3520e2786d5baa92ebe25a05e82cfb0d&name_0=PR&name_1=Build%20%28amd_windows%29
PR: #112824

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…cache

On current `master` `SELECT sum(a), count()` from the table is answered without reading any column, so no
file segment was cached and the test saw an empty `system.filesystem_cache`. Reproduced with a
`master`-based binary; also reading `sum(length(b))` makes the query go through the cache again.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112824&sha=fbdebc9a3520e2786d5baa92ebe25a05e82cfb0d&name_0=PR&name_1=Fast%20test
PR: #112824

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

Copy link
Copy Markdown
Member Author

🕵 Merged master and fixed the red checks. Head is now d94bd7a2358.

  • ccbf903c248: merged master. There were conflicts in 6 files:
    • checkStackSize.cpp: kept this PR's platform-split includes and added master's Common/Silk/FiberScheduler.h.
    • ICatalog.cpp: took master's endpoint-path-segment check for Azure and kept this PR's key-space joins.
    • MetadataStorageFromStaticFilesWebServer.cpp: kept makeRemotePath.
    • MMappedFileDescriptor.cpp: master's new MADV_DONTNEED before munmap now sits in the POSIX branch.
    • DataLakes/Common/Common.cpp: took master's listPrefixImpl / listPrefixNonRecursive. The directory key is now built in key space by a new keyDirectory helper, so it no longer goes through std::filesystem::path.
    • test_disk_over_web_server/test.py: kept the tests from both sides.
  • ba66712d1a2: fixes Build (amd_windows). Master's new code in StorageMergeTree::loadMutations converted an fs::path to a String implicitly. It now uses pathToGenericString.
  • c5fc19865fd: fixes Build (arm_tidy). gtest_keeper_path_normalize called .string() on the String that getAbsolutePath now returns.
  • d94bd7a2358: fixes 05565_filesystem_cache_unicode_path in Fast test. On current master, SELECT sum(a), count() is answered without reading any column, so nothing reached the filesystem cache. I reproduced this with a master-based binary. The query now also reads sum(length(b)), and the test passes locally.

The Windows cross build was not verified locally, so the next Build (amd_windows) run will show whether the newly merged master code builds there.

Conflicts resolved:
- `contrib/replxx`: point at ClickHouse/replxx 6650850 (merge of #54), which contains both the Windows `Terminal::read_unicode_character` from this branch and the synchronized refresh from master.
- `src/Client/ClientBase.cpp`: keep the `use_replxx` structure of this branch and add the `.vim` option from master.
- `src/Formats/FormatSchemaInfo.cpp`: keep the `pathFromString` / `pathToGenericString` conversion of this branch.
- `src/Interpreters/FileCache/FileCache.cpp`: take master's `fiu_do_on`, which also builds without libfiu.

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

Copy link
Copy Markdown
Member Author

🕵 Merged master and resolved the conflicts. Head is now 8229587134d.

  • contrib/replxx: both sides moved the submodule. Pointed it at ClickHouse/replxx 6650850 (the merge of Declare Terminal::read_unicode_character on Windows too replxx#54), which has both this branch's Windows Terminal::read_unicode_character and master's synchronized refresh.
  • ClientBase.cpp: kept this branch's use_replxx structure and added master's new .vim option to the ReplxxLineReader options.
  • FormatSchemaInfo.cpp: kept this branch's pathFromString / pathToGenericString conversion.
  • FileCache.cpp: took master's fiu_do_on, which also builds without libfiu, so the #if USE_LIBFIU guard is no longer needed.

The Linux (aarch64) clickhouse build passes locally. I could not build the Windows cross-build here, so Build (amd_windows) in CI is the check for that. There are no unresolved review threads.

alexey-milovidov and others added 2 commits November 15, 2026 23:07
Conflicts:
- `ci/workflows/pull_request.py`: master moved part of the special builds to the merge
  queue (`special_build_pr_jobs`); `SPECIAL_BUILD_JOBS_EXCEPT_WINDOWS` now filters that list.
- `programs/local/LocalServer.cpp`: took master's persistent `system` database logic, with
  `path` kept as `fs::path` and the warning formatted through `pathToString`.
- `src/Backups/BackupIO_Default.cpp`: kept both sides' includes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hen stdout is not a console

The Windows backend of replxx renders through the console screen buffer of the output handle
and does not check that it is one. `ClientBase` already fell back to the basic `LineReader`
then, but `DisksApp` and `KeeperClient` built `ReplxxLineReader` unconditionally. The check is
now `ReplxxLineReader::canRenderTo`, shared by all three users.

Address review: #112824 (comment)

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

Copy link
Copy Markdown
Member Author

🕵 Merged master and resolved the conflicts. Head is now 6bcfee47ba2.

  • a81957c3292: merged master. There were conflicts in 3 files:
    • ci/workflows/pull_request.py: master moved some special builds to the merge queue (special_build_pr_jobs). SPECIAL_BUILD_JOBS_EXCEPT_WINDOWS now filters that list, so Build (amd_windows) still runs separately.
    • LocalServer.cpp: took master's persistent system database logic. path stays an fs::path, and the new warning formats it through pathToString.
    • BackupIO_Default.cpp: kept the includes from both sides.
  • 6bcfee47ba2: the open review thread on redirected stdout. clickhouse-disks and keeper-client now fall back to the basic LineReader when stdout is not a console, through the shared ReplxxLineReader::canRenderTo.

The changed files build on Linux. The Windows build was not run locally; CI will build it.

alexey-milovidov and others added 4 commits November 21, 2026 01:35
Conflicts in 27 files. Resolutions that are more than taking both sides:

- `ReplxxLineReader.cpp`: master replaced `skim` with the built-in `pickFromHistory`
  and creates the history file in `open` with `O_CREAT`. The file is now opened
  through `platformOpenFile` with `O_RDWR | O_CREAT`, the unused
  `platformOpenReadWrite` is removed, and the picker is not bound on Windows,
  where the console is not a byte stream (as before, when `skim` was not built there).
- `DisksApp.cpp`, `KeeperClient.cpp`: took master's removal of the separate
  history file creation.
- `SocketPeerClosed.cpp`: master moved `ScopedNonBlocking` to its own header.
- `UTF8Helpers.cpp`, `widechar_width.h`: took master's rewrite; it takes `uint32_t`,
  so the `char32_t` change of this branch is no longer needed.
- `isLocalAddress.cpp`, `MetadataStorageFromStaticFilesWebServer.h`: master only
  added `[[nodiscard]]` to code that this branch removed.
- `IObjectStorage.h`: master's `stripQueryAndFragment` with the string
  `last_component` of this branch instead of `std::filesystem::path`.
- The rest keep master's changes with the path helpers of this branch
  (`pathToGenericString`, `pathFromString`, `zkutil::joinZooKeeperPath`,
  `zkutil::zooKeeperNodeName`) and the `OS_WINDOWS` guards.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…erge

Master updated `contrib/llvm-project` and made the minimal Thrift library a part of every build:

- `locale_win32.cpp` tests a `std::from_chars_result` as a `bool`, which is C++26,
  so it is compiled with `-std=c++26`, like `text_encoding.cpp`.
- `cxa_thread_atexit.cpp` takes the secret for the `thread_local` destructor pointers
  from `getentropy` everywhere but on Linux. Windows has none, so a force-included header
  provides it through `RtlGenRandom`.
- `_thrift_minimal` is now built with `ENABLE_LIBRARIES=OFF` too, and the generated
  `thrift/config.h` claimed the POSIX socket headers (`netinet/in.h` and others)
  on every platform. They are not set on Windows anymore.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…lows

`ci/workflows/master.py` took its special builds from `SPECIAL_BUILD_JOBS_EXCEPT_WINDOWS`,
which, since the merge queue got some of them, is the list of the pull request workflow only.
So the generated `master.yml` lost `Build (amd_darwin)` and the other cross-compiled builds,
and `Check Workflows` failed with "workflows are outdated": .github/workflows/master.yml.
`MasterCI` now takes every special build except the Windows one, which it starts separately.

The previous commit also picked up three workflow files regenerated before this fix.
That was a mistake: this commit puts them back as they were, and the regenerated
`master.yml` is now the same as the committed one.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112824&sha=6bcfee47ba2bfd6e0b4497668620f714aa541a3b&name_0=PR&name_1=Config%20Workflow
#112824

Co-Authored-By: Claude Fable 5.2 <[email protected]>
New code on master that does not compile for Windows:

- `BackupIO_Disk.cpp`, `MergeCheckpoint.cpp`, `MergeTask.cpp`, `MergeTreeDataPartBuilder.cpp`:
  a `std::filesystem::path` was converted to a `String` implicitly. It goes through
  `pathToGenericString` now.
- `ObjectStorageQueueOrderedFileMetadata.cpp`: ZooKeeper paths were joined
  as `std::filesystem::path`. They use `zkutil::joinZooKeeperPath` now.
- `ParallelSyncFiles.cpp`: `fdatasync` and `open` are replaced with `platformFDataSync`
  and `platformOpenFile`.
- `retryTransientStoreError.cpp`: the Windows CRT has no `EDQUOT`.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and fixed the Windows build. Head is now e6570037466.

  • 27c67809acc: merged master. There were conflicts in 27 files. The ones that needed more than keeping both sides:
    • ReplxxLineReader.cpp: master replaced skim with the built-in pickFromHistory and creates the history file in open with O_CREAT. The file is now opened through platformOpenFile with O_RDWR | O_CREAT, and the unused platformOpenReadWrite is removed. The picker is not bound on Windows, because it reads the terminal as a byte stream. Ctrl-R stays the incremental search of replxx there, as before, when skim was not built for Windows.
    • DisksApp.cpp, KeeperClient.cpp: took master's removal of the separate history file creation.
    • UTF8Helpers.cpp, widechar_width.h: took master's rewrite. It takes uint32_t, so this branch's char32_t change is no longer needed.
    • SocketPeerClosed.cpp: master moved ScopedNonBlocking to its own header.
    • The rest keep master's changes with this branch's path helpers and OS_WINDOWS guards.
  • ba75090c2e3: master updated contrib/llvm-project and builds the minimal Thrift library always. locale_win32.cpp is compiled with -std=c++26, cxa_thread_atexit.cpp gets getentropy through RtlGenRandom, and Thrift's generated config.h no longer claims the POSIX socket headers on Windows.
  • 522b705b0b1: fixes Check Workflows ("workflows are outdated", master.yml). master.py used SPECIAL_BUILD_JOBS_EXCEPT_WINDOWS, which is the pull request list since some special builds moved to the merge queue, so MasterCI would have lost Build (amd_darwin) and the other cross-compiled builds. It now takes every special build except the Windows one. ba75090c2e3 picked up three workflow files regenerated before this fix by mistake; this commit puts them back, so the net change to .github/workflows is empty.
  • e6570037466: new code on master that did not compile for Windows: implicit std::filesystem::path to String conversions (BackupIO_Disk.cpp, MergeCheckpoint.cpp, MergeTask.cpp, MergeTreeDataPartBuilder.cpp), ZooKeeper paths joined as std::filesystem::path (ObjectStorageQueueOrderedFileMetadata.cpp), fdatasync (ParallelSyncFiles.cpp) and EDQUOT (retryTransientStoreError.cpp).

Built locally: clickhouse for Linux (aarch64), and clickhouse clickhouse-windows-ported clickhouse-windows-selftest for Windows, both link. The Linux binary answers a query. The Windows binary was not run: this host is aarch64, so Wine cannot execute it, and Build (amd_windows) in CI is the check for that.

The five open review threads have no new comments since the last replies. Three of them (backslashes in clickhouse-disks paths, URL syntax in projection names on the web disk, a Structured Exception Handling fault handler) are left for the maintainer to decide.

alexey-milovidov and others added 6 commits November 24, 2026 04:20
Conflicts:
- `.github/workflows/master.yml`: took master's version and regenerated it with
  `python3 -m ci.praktika yaml`, which adds `Build (amd_windows)` back.
- `programs/CMakeLists.txt`: master removed the `install` steps and renamed
  `clickhouse_program_install` to `clickhouse_program_link`. Kept this branch's
  `NOT OS_WINDOWS` guards around the symlink aliases and its optional programs.
- `DiskLocal.cpp`, `DatabaseCatalog.cpp`: master removed `DiskLocal::chmod` and
  the cleanup of the `store` directory, so the Windows adaptations of them go away.
- `FormatSchemaInfo.cpp`: took master's `fs::rename`, which replaces the
  `renameExchange` / `renameNoReplace` pair.
- `FormatParserSharedResources.cpp`, `Parquet/Reader.cpp`: master's logic with `uz`
  literals instead of `ul`, because `size_t` is not `unsigned long` on Windows.
- `FsSnapshot.cpp`, `MetadataStorageFromPlainRewritableObjectStorage.cpp`: master's
  changes with `pathToGenericString`; the new `materializeVirtualDirectory`
  converts its path the same way.
- `StorageObjectStorageSource.cpp`: kept the includes from both sides.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
The code that came with the merge does not compile for `x86_64-w64-windows-gnu`:

- `ReadBufferFromFileDescriptor.cpp`: the failpoint `file_read_corrupt_data_without_direct_io`
  asks `fcntl` for `O_DIRECT`. It goes through `isOpenedForDirectIO`, which is `false` on Windows.
- `ClientBase.cpp`: `getStdinStateNonBlocking` uses `poll` on stdin. On Windows it decides by the
  kind of the handle: a file has data, a pipe is asked with `PeekNamedPipe`, a console is ambiguous.
- `FilesystemIsolationPaths.cpp`: `getpwuid_r` and `pwd.h` are not available on Windows.
- `StorageReplicatedMergeTree.cpp`, `checkDataPart.cpp`: `std::filesystem::path` was passed where
  a `String` is expected.
- `StorageObjectStorageQueue.cpp`: the ZooKeeper path is a `String` in this branch, so it is
  joined with `zkutil::joinZooKeeperPath`.

Also remove `platformChmod`: its only user, `DiskLocal::chmod`, was removed in `master`.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…esWebServer.cpp`

`Build (arm_tidy)` failed with `modernize-use-nodiscard` on `Socket::isValid`, `Socket::poll` and
`Socket::toDescriptor`, and with `performance-string-view-conversions` on a `String` built
from a `std::string_view` only to be passed to `escapeForFileName`, which takes a `std::string_view`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112824&sha=e6570037466deabae14c1ece001978cb3c4c7688&name_0=PR&name_1=Build%20%28arm_tidy%2C%201%2F4%29
#112824

Co-Authored-By: Claude Fable 5.2 <[email protected]>
- `syncPath` opens the file for writing on Windows, because `FlushFileBuffers` fails on a handle
  without `GENERIC_WRITE`. Otherwise every `INSERT` with `fsync_after_insert` failed with
  `CANNOT_FSYNC`.
- The registry of the files whose fsync failed identifies a file by `PlatformFileVersion` (the
  volume serial number and the file index on Windows) instead of the `st_dev` and `st_ino` of
  `fstat`, which are zero for every file there, so one failed file made all later syncs fail.
- The registry releases a file when `platformIsDescriptorUnlinked` reports that it has no names
  left: `st_nlink == 0` on POSIX, no links or a pending delete on Windows.

The Wine step of `Build (amd_windows)` runs two inserts into a persistent `MergeTree` table with
`fsync_after_insert`, and `clickhouse-windows-selftest` checks the file identity and the sync
through a write-only descriptor.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…sk-uploader`

`MetadataStorageFromStaticFilesWebServer::loadFiles` reads the name with `readEscapedString`,
so the uploader writes it with `writeEscapedString`. It matters since the uploader descends into
projection directories, whose names are not escaped with `escapeForFileName` and can contain
a backslash, a tab or a newline.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…of `master`

Regenerating the workflows for the merge of `master` rewrote these two files as well,
with an incomplete result. This branch does not change them, so take them from `master`.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master, fixed the red checks and addressed the new review. Head is now e46add2331cc.

  • e95311cb759f: merged master. There were conflicts in 10 files. The ones that needed more than keeping both sides:
    • programs/CMakeLists.txt: master removed the install steps and renamed clickhouse_program_install to clickhouse_program_link. The NOT OS_WINDOWS guards around the symlink aliases stay.
    • DiskLocal.cpp, DatabaseCatalog.cpp: master removed DiskLocal::chmod and the cleanup of the store directory, so their Windows adaptations (and platformChmod) are gone.
    • FormatSchemaInfo.cpp: took master's fs::rename instead of renameExchange / renameNoReplace.
    • MetadataStorageFromPlainRewritableObjectStorage.cpp: master's new materializeVirtualDirectory converts its path with pathToGenericString, as the rest of the file.
    • .github/workflows/master.yml: regenerated. The regeneration also rewrote create_release.yml and release_branches.yml incorrectly, and that went into the merge commit; e46add2331cc restores both to the state of master.
  • 0aba868fd920: code that came from master did not compile for Windows in six files (fcntl in a failpoint of ReadBufferFromFileDescriptor, poll on stdin in ClientBase.cpp, pwd.h in FilesystemIsolationPaths.cpp, and fs::path passed as String in three more). On Windows getStdinStateNonBlocking now decides by the kind of the handle: a file has data, a pipe is asked with PeekNamedPipe, a console is ambiguous.
  • df5449a56c05: fixes Build (arm_tidy): [[nodiscard]] in Socket.h and a redundant String conversion.
  • 07a9664c62a5, dccaa3cf03bd: the three review threads from 2026-11-21, with replies in each. Two of them stay open because the requested tests are not added.

Checked locally: clickhouse.exe and clickhouse-windows-selftest.exe build and link for x86_64-w64-windows-gnu, the Linux clickhouse builds, and the four failpoint tests of the fsync registry pass on Linux. Not run: anything under Wine (the new smoke step and selftest run first in CI), clang-tidy, and the integration tests.

if (file_version_known)
current_file_cache_version = computeFileCacheVersionToken(file_version);
else
current_file_cache_version.reset();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Blocker] Check for a missing version before comparing split-file generations

The new failure branch disengages current_file_cache_version, but the split-file path unconditionally dereferences it at line 2210. A parallel Parquet read can successfully run getFileStat at line 2180, then have an external writer remove the file before platformFileVersion performs its second metadata lookup. That takes this reset and then dereferences an empty std::optional<String> instead of reporting FILE_CHANGED_DURING_READ. This affects Linux as well as Windows; previously the token was built from the already successful file_stat.

For a split file, reject an unavailable token before dereferencing it, and cover failure of the second metadata lookup. This trace is source-derived; I could not execute a ClickHouse binary here.

Comment thread src/IO/PlatformFileIO.cpp
errno = EIO;
return -1;
}
return info.DeletePending || info.NumberOfLinks == 0;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Blocker] Keep the failed-fsync marker while another hard link remains accessible

DeletePending does not establish that the file has no remaining names. The Windows filesystem algorithm derives that flag from deletion of the particular link used by the open handle, independently of the count of other accessible links.

With hard links A and B, let syncPath(A) fail and retain its descriptor, then delete A while B remains. This returns 1 because A is delete-pending, so FailedFiles::releaseUnlinked closes the descriptor and erases the file's error marker. A later sync through B can now succeed despite the earlier durability failure. Hard-linked part files must retain that failure across removal of just one name.

Only report unlinked when no accessible links remain. Add a Windows check that deleting one of two hard links returns 0, and deleting the last returns 1. This is a source/specification trace, not a Windows runtime result.

const auto st = disk.stat(dir / file);
ids.emplace(file.string(), std::pair<UInt64, UInt64>{st.st_dev, st.st_ino});
const auto st = disk.stat(pathToString(dir / file));
ids.emplace(pathToGenericString(file), std::pair<UInt64, UInt64>{st.st_dev, st.st_ino});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Blocker] Use real Windows file identities before deleting a supposed duplicate part

DiskLocal::supportsStat remains true on Windows, but DiskLocal::stat delegates to the CRT, whose st_ino is zero and whose st_dev identifies the drive, not the individual file. The PR already handles this distinction in PlatformFileVersion and createHardLink; the CRT field contract also documents it.

Consequently, an unexpected part and an independent detached part on the same drive compare equal whenever their relative filename sets match, even if their contents differ. checkPartsImpl then adds the unexpected part to parts_already_detached and removes it at line 2280 instead of preserving it as detached/ignored_*. This can lose the only copy of those contents. A local attach with external Keeper reaches this check before replica activation checks the interserver address.

Use reliable volume/file identities for this comparison, or skip the destructive duplicate-removal optimization when the disk cannot supply them. Cover distinct files with matching relative names as well as genuine hard links.

/// would append `\` on Windows, where it is an ordinary character in a key.
String keyDirectory(const String & path, const String & prefix)
{
String key = appendObjectStorageKeySegment(path, prefix);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Major] Preserve the existing absolute-path Iceberg drop behavior

The new concatenation changes the absolute-suffix behavior relied on by IcebergMetadata::drop at IcebergMetadata.cpp:2238: it passes persistent_components.table_path as both path and prefix to listFiles. For an IcebergLocal table at /data/user_files/lake, the old filesystem join produced /data/user_files/lake/, whereas this helper produces /data/user_files/lake//data/user_files/lake/.

LocalObjectStorage::listObjects returns an empty listing for that nonexistent directory, so DROP TABLE succeeds while iceberg_delete_data_on_drop = 1 leaves all the table data behind. This is a Linux regression too; existing stateless Iceberg tests already use absolute table paths.

Update the drop caller to pass an empty prefix, and add a focused assertion that dropping an absolute-path table actually removes its metadata and data files.

Comment thread programs/main.cpp
/// on exit. Redirected output has no console code page and receives the bytes as they are.
static const UINT original_console_output_code_page = GetConsoleOutputCP();
if (original_console_output_code_page != 0 && original_console_output_code_page != CP_UTF8 && SetConsoleOutputCP(CP_UTF8))
std::atexit([] { SetConsoleOutputCP(original_console_output_code_page); });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Major] Restore shared console state on controlled immediate exits

These restorations run only through std::atexit, but the Windows console handler calls safeExit on an idle interrupt or repeated cancellation (ClientApplicationBase.cpp:93), and safeExit calls _exit, which skips these callbacks. The client's external-table option error path also calls _exit directly.

The code pages belong to the shared console, so starting from chcp 437, launching clickhouse.exe local, and pressing Ctrl+Break at the idle prompt leaves the parent console at 65001. The input-code-page and output-mode restorations below are skipped as well, affecting subsequent commands after ClickHouse exits.

Restore the saved console state explicitly before controlled immediate exits, while retaining the immediate-exit behavior needed by the cancellation path. Cover the child-process exit with a real-console test when available. This reproduction is source-traced, not executed on Windows.

This branch was successfully deployed

1 active deployment
staging - docs — e46add23 Deployed Nov 24, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-build-system Build system (CMake, compilation, platform builds). pr-build Pull request with build/testing/packaging improvement submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants