Repository navigation
Build and run natively on Windows (MSYS2 / MinGW-w64) - #553
Conversation
|
🤖 Automated first-pass review — a human maintainer's review is still required before merge. Thanks for this, it's a big one. I read most of it, and the POSIX paths look carefully kept as they were. The commits are split well, which helps a lot. A few comments:
The description says native Windows validation for the current head is still pending. I'd want that run green, plus the full cross-platform CI, before this merges. I'd also like a maintainer to explicitly agree to support Windows long-term, since that's more of a project decision than a code question. |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 133c58e. Configure here.
133c58e to
ac0598b
Compare
|
Pushed. I rebased onto the updated #552 and force-pushed, per CONTRIBUTING.
Re-tested:
|
ac0598b to
c08faaa
Compare
Several non-void functions (the unsupported-command stubs of the memcache protocols and the mbulk/bulk element accessors) ended in `assert(0)` with no return. Under NDEBUG the assert compiles away and control falls off the end of a non-void function, which is undefined behaviour. Return an explicit -1/false/NULL after each assert(0), and initialise `key_len` in the multi-get loops so it is never read uninitialised. Also pass the AUTH argument lengths to evbuffer_add_printf() as `%llu` with an explicit `unsigned long long` cast instead of `%zu`: MinGW checks evbuffer_add_printf() formats as ms_printf, which does not know `%zu`. The bytes written are unchanged.
Detect a MinGW host in configure.ac and, there only: define _WIN32_WINNT/WIN32_LEAN_AND_MEAN/NOMINMAX/__USE_MINGW_ANSI_STDIO, link ws2_32, skip the libevent_pthreads check (libevent's Windows thread backend lives in libevent_core), and default to static libraries so libtool does not wrap the program in a launcher exe that loses the exit status on Ctrl+C. Expose the result as the MEMTIER_WINDOWS automake conditional. In Makefile.am, skip socket_options_test on MinGW and give prometheus_metrics_test the feature macro that makes mingw-w64 declare rand_r(). Ignore *.exe and /.libs/ in .gitignore. No change for other hosts.
Add platform_compat.h, which pulls in the Winsock/AF_UNIX headers on Windows and the existing POSIX socket headers elsewhere, and use it in place of the scattered <sys/socket.h>/<netdb.h>/<arpa/inet.h> includes. Switch socket descriptors to evutil_socket_t and replace fcntl(O_NONBLOCK), close() and errno-based socket error reporting with libevent's evutil_make_socket_nonblocking(), evutil_closesocket() and EVUTIL_SOCKET_ERROR()/evutil_socket_error_to_string(), which are plain fcntl()/close()/errno/strerror() on POSIX. Cast setsockopt() option pointers to const char * as Winsock requires, build struct timeval values field by field, initialize Winsock with WSAStartup() and select libevent's Windows thread backend in main(). Gate the remaining POSIX-only pieces behind _WIN32: the crash handler, per-thread/rusage CPU accounting (reported as zero on Windows for now), RLIMIT_NOFILE/core-dump handling, SIGPIPE, ucontext and utsname. --unix-socket is rejected with an error on Windows, and --randomize derives its seed without srandom()/random(). Other fixes: provide a getline() fallback for --monitor-input, open import/export files in binary mode (identical to text mode on POSIX), supply a jrand48() equivalent for the HAVE_DRAND48 code path when neither random_r nor jrand48 exist, use gmtime_s(), and use hdr_timespec (a typedef of struct timespec on POSIX) for the HDR log timestamps. POSIX code paths are unchanged.
CPU accounting was compiled out on Windows (RUSAGE_THREAD is not defined there) and the live sampler read 0 because winpthreads' pthread_getcpuclockid is an ENOTSUP stub. Provide a file-local struct rusage / RUSAGE_THREAD / getrusage() shim built on GetThreadTimes(GetCurrentThread()) so the existing RUSAGE_THREAD blocks compile unchanged, drop the "&& !defined(_WIN32)" guards they carried, and read other threads' CPU in get_thread_cpu_usec() with GetThreadTimes() on the winpthreads handle. Update the comments that described CPU accounting as Linux-only. GetThreadTimes() is scheduler-tick accounted (~15.6 ms resolution), so very short intervals read as zero; this is advisory data like on the other platforms. POSIX code paths are unchanged.
The POSIX crash handler is compiled out on Windows. Install an unhandled exception filter via SetUnhandledExceptionFilter() that prints the same report: START banner, exception code, fault address (and the access violation target), raw return addresses with the image base for addr2line, then the INFO OUTPUT section with the Windows version and the CLIENT LIST. It returns EXCEPTION_CONTINUE_SEARCH so Windows Error Reporting (LocalDumps) still gets the crash, and the report points at LocalDumps instead of ulimit/core_pattern. The INFO OUTPUT / CLIENT LIST / footer part moves unchanged into print_crash_report_tail(), shared by both handlers; the POSIX report text is byte-for-byte the same. print_client_list() and print_all_threads_stack_trace() are no longer POSIX-only. abort() and assert() failures do not go through the exception filter and are not covered.
Build with MSYS2 UCRT64 on windows-latest, failing on any compiler warning outside deps/, then run make check, verify --version reports a real commit hash and bits=64, and run tests/windows_smoke.py. The job has a 30 minute timeout and refreshes the git index before building so version.sh does not report a dirty tree. The smoke test needs only the Python standard library: it drives memtier_benchmark against the RESP sink in tests/fuzz and checks a fixed-request-count run, the JSON CPU section of a timed run, a clean non-crashing failure against a closed port, and the rejection of --unix-socket.
Add a Windows (MSYS2 / MinGW-w64) section to DEVELOPMENT.md with the package list, build commands, how to ship the executable (DLL list, or an example static link recipe), the Windows 10 minimum, and the known limitations of the Windows build. Point to it from the README's build-from-source section.
The MinGW "default to static" tweak called AC_DISABLE_SHARED inside an
AS_CASE. Where libtool is not installed (the Debian CI containers install
only build-essential autoconf automake pkg-config libevent-dev zlib1g-dev
libssl-dev) that is an undefined AC_ macro, so autoreconf fails with
"possibly undefined macro: AC_DISABLE_SHARED". An undefined LT_INIT is
tolerated, an undefined AC_ macro is not.
Worse, with libtool installed, AC_DISABLE_SHARED expands LT_INIT inside the
mingw case branch, so on every other host libtool was left uninitialised
("whether to build shared libraries..." printed an empty result).
Pre-seed enable_shared=no on mingw instead, which LT_INIT's
--enable-shared handling honours. This needs no libtool macros, keeps
LT_INIT unconditional, and an explicit --enable-shared still wins.
config_range used strtoul(), whose result is 32 bits wide on LLP64 hosts (Windows) and saturates for large input, while on LP64 hosts it is 64 bits and narrows to int. --data-size-range=1-9999999999 therefore failed argument validation on Windows (exit 2) instead of behaving as on Linux/macOS, which test_426_8_data_size_range_too_large relies on. Parse with strtoull() so every platform sees the same value; on LP64 hosts unsigned long and unsigned long long are the same width, so behaviour there is unchanged.
…ories RLTest test names look like "file.py:test_name" and RunConfig used the name verbatim as a directory name; ':' is not allowed in Windows paths, so every test that builds a RunConfig failed in ensure_clean_benchmark_folder() there. Replace the reserved characters with '_'. Names on POSIX hosts that contain none of them (which is every other character) are unaffected, but the colon-containing RLTest names now map to "file.py_test_name".
On Windows, bufferevent_socket_connect() follows the expected WSAEWOULDBLOCK from a non-blocking connect() with getsockopt(SO_ERROR) (libevent's evutil_socket_geterror()). While the connect is still in flight that call blocks for 10-15 ms, even on loopback. All connections are opened one after another before the worker threads start, so setup took about 15.6 ms * threads * clients: -t4 -c50 spent ~3.1 s connecting and -t4 -c250 ~15.5 s, and every reconnect paid it again. Issue the non-blocking connect() in shard_connection and pass libevent the in-flight socket (a NULL address), which bufferevent_socket_connect() documents as "assume the socket is already connecting". libevent then arms the write event exactly as it does after its own WSAEWOULDBLOCK, so completion, refusal and TLS handshakes are reported through the event callback as before. connect() errors other than "in progress" are left to libevent, which retries the connect and reports them as before. The change is Windows-only; POSIX builds call bufferevent_socket_connect() with the same arguments as before.
When the non-blocking connect() fails immediately with an error other than "in progress", the Windows path used to call bufferevent_socket_connect() with the address, which makes libevent issue connect() a second time on the same socket, and Winsock is not guaranteed to report the original error for that second call. Return -1 instead so the caller logs the error from the failed connect(). The caller now reads the socket error before disconnect(), which frees the bufferevent and could otherwise overwrite it.
The gate grepped build.log for the bare word "warning", which also matches
"libtool: warning: ..." lines and any path containing "warning". Match the
compiler diagnostic format ("file:line:col: warning:") instead; the deps/
exclusion is unchanged.
DEVELOPMENT.md claimed the suite had never been run on Windows. State what is true: it is not run in CI there, it can be run locally against a Windows Redis-compatible server such as Memurai with a small RLTest shim, and the tests that need POSIX signals or /proc cannot pass.
The RLTest note listed the crash-handler and SIGPIPE tests, but the SIGINT test (test_interrupt_signal_handling) also needs a POSIX signal, and running against Memurai needs a shim for its --version output as well.
c08faaa to
5a29a0e
Compare
--hdr-file-prefix builds per-command file names from the display name, so --scan-incremental-iteration writes "<prefix>_SCAN <cursor>_command_run_1.hgrm". '<' and '>' are reserved file-name characters on Windows (fopen() fails and the histogram is silently lost once the native build from #553 lands), and actions/upload-artifact rejects them, so CI jobs cannot upload these files. Replace spaces, control characters and < > : " / \ | ? * with '_' in the command part of the HDR file names. The prefix, the stderr messages, the .hgrm header and the JSON keys keep the display name. Sanitizing runs before the #587 duplicate-name pass, so names that map to the same string (e.g. "A:" and "A?") still get distinct "_N" suffixes. The suffix pass now also skips an ordinal whose label is already taken by another name (e.g. a literal "A__1"), so a suffixed label can no longer overwrite another command's file. This changes user-visible file names: "SCAN <cursor>" becomes SCAN__cursor_, "SCAN 0" becomes SCAN_0, and --command-stats-breakdown=line names such as "GET (Line 1)" become GET_(Line_1). Fixes #627 Co-Authored-By: Claude Opus 5.5 <[email protected]>
--hdr-file-prefix builds per-command file names from the display name, so --scan-incremental-iteration writes "<prefix>_SCAN <cursor>_command_run_1.hgrm". '<' and '>' are reserved file-name characters on Windows (fopen() fails and the histogram is silently lost once the native build from #553 lands), and actions/upload-artifact rejects them, so CI jobs cannot upload these files. Replace spaces, control characters and < > : " / \ | ? * with '_' in the command part of the HDR file names. The prefix, the stderr messages, the .hgrm header and the JSON keys keep the display name. Sanitizing runs before the #587 duplicate-name pass, so names that map to the same string (e.g. "A:" and "A?") still get distinct "_N" suffixes. The suffix pass now also skips an ordinal whose label is already taken by another name (e.g. a literal "A__1"), so a suffixed label can no longer overwrite another command's file. This changes user-visible file names: "SCAN <cursor>" becomes SCAN__cursor_, "SCAN 0" becomes SCAN_0, and --command-stats-breakdown=line names such as "GET (Line 1)" become GET_(Line_1). Fixes #627 Co-authored-by: Claude Opus 5.5 <[email protected]>
|
Addressed in eed9262 and the integration commits:
Native Windows at 9b0997e passed the warning-free build, all 14 unit programs and all 8 smoke tests. The new detached-process case is being checked on eed9262. Linux controls pass all 14 units and 34 focused closed-fd/crash-handler/import regressions (the three valid-import cases used a local AUTH adapter for the private password-protected Redis). |
|
The follow-up is now at 8736d8b:
The PR body now lists these final behaviors and measured results. All historical Cursor threads are resolved. |
|
Addressed the crash timestamp point in 2c75aca: Windows caches The normal master merge includes #257 and preserves its exact Unix sockaddr length alongside Windows's connect wrapper. All 14 Linux unit programs and all five Unix address regressions pass. Help and the man page now label Native Windows on 8736d8b did pass all 14 unit programs (including retry drain/sibling tests) and all nine smoke tests: https://github.com/redis/memtier_benchmark/actions/runs/39013454099 . The new 2c75aca head is rerunning CI; the description now distinguishes those results. The scope items remain in their separate commits within this port. The fallback matrix is now also on merged master through #257; its existing comment identifies the upstream repository variable, whose defined value takes precedence. Independent connection/reconnect reviews are in progress before any merge. |
|
Follow-up for the 07:34 and 07:47 edits, now at 972d454 (runtime 7cf8437): The independent dispatch review found a narrower real compatibility bug: libevent returns success and defers an error event for synchronous ECONNREFUSED, while the Windows wrapper had returned -1. Fixed with a connection-owned event using event_new/event_active (available at the existing libevent 2.0.10 minimum). It delivers one deferred error with the original Winsock code, enters existing reconnect policy, and is canceled before disconnect/destruction or bufferevent replacement. TLS keeps the same owning bufferevent. There is no inline callback or second connect on the failed socket. EADDRNOTAVAIL/ENETUNREACH were checked separately: original libevent also returns -1 immediately for those, so that behavior remains unchanged. Native Windows runtime 7cf8437 passed all 14 units and 9 smoke tests: https://github.com/redis/memtier_benchmark/actions/runs/39014863571 . The socket unit now injects synchronous WSAECONNREFUSED in six plain/TLS cases, checking normal dispatch, disconnect-before-dispatch, and destruction-before-dispatch, including error preservation, retry scheduling and socket closure. This is an injected dispatch/lifetime regression, not a claim of reproducing a natural Windows network failure. The earlier 2c75aca crash timestamp follow-up also passed native 14/9. The production compiler-warning gate passes; unit compilation separately still has an existing -Wsign-compare diagnostic, now qualified in the description. 972d454 adds the requested getline coverage: the native smoke reads a 1024-byte quoted monitor command with no final newline and completes three requests. It crosses several reallocations and covers EOF handling. That focused smoke passes on Linux; its native follow-up is running: https://github.com/redis/memtier_benchmark/actions/runs/39015091236 . The platform policy remains explicit: native Windows10+ through MSYS2 UCRT64 is the implementation scope; no branch-protection settings or release promises changed. Maintainers own whether to require the job. I considered a larger platform_compat.cpp extraction, but kept this review to the existing focused portability changes; centralizing those implementations can be a separate cleanup. The generic fixes remain separate dependency commits within this port rather than introducing additional PR dependencies. Drive-relative C:hist preflight is a known narrow limitation; the actual output open/write error checks remain in force. The POSIX Unix fixtures still select their Unix socket despite the harmless TCP address initialization. |
|
For the 07:50:59 edit: the deferred callback owns the current bufferevent association for its whole queued lifetime: setup_event(), disconnect(), and destruction cancel it before replacing/freeing the bufferevent. The six native tests cover dispatch and both teardown paths with plain/TLS bufferevents, and the independent reconnect/lifetime reviewer is rechecking the exact runtime commit. I considered pinning MSYS2 or removing the production warning gate. This job deliberately tracks the supported rolling UCRT64 environment so its dependency/compiler changes become visible; a pinned package snapshot would need a separate update policy. The 30-minute timeout is a cap, not the measured job duration (the last successful run took about 3.5 minutes). Required-check and release-support policy remain with maintainers; this PR does not alter them. Generic fixes remain separate dependency commits as described above. The config_range narrowing remains the existing int conversion, so this is not new range validation. Also, --randomize is timestamp-seeded and already does not promise comparable seeds between runs or platforms; the Windows seed-generation path is different. I will leave these explanatory nits and reading EVUTIL_SOCKET_ERROR once to follow-up cleanup rather than change the runtime after the completed native dispatch validation. |
|
Follow-up to the review edited at 08:13:42 UTC, on final head fa1e304:
The owner pass and all seven independent review lenses have converged, including focused checks of both master integrations. Exact-head native Windows CI passed production compilation, 15/15 units and 10/10 smoke tests: https://github.com/redis/memtier_benchmark/actions/runs/39016446081 . Full cross-platform CI is still required before merge. |
|
Reply to the review edited at08:43:56 UTC:
After #25 merged, we normally integrated masterb6e9d78 as6f82fda. All15 Linux units pass, and integrated native Windows run39018356290 passed the production warning gate,15/15 units and10/10 smoke tests: https://github.com/redis/memtier_benchmark/actions/runs/39018356290 . The final documentation-only head has an identical build/runtime/test tree and its own CI is running. All seven review lenses have converged, with the focused BUILD integration check; final-head full CI and fresh bot/thread gates remain required before squash merge. |
|
Follow-up to the 08:46:36 review edit:
The POSIX fixture continues to select its configured Unix socket; the address fields provide the Windows TCP fallback and are harmless on POSIX. The retained Unix address/path tests and independent integration checks pass. We are leaving this cosmetic fixture suggestion unchanged. The scoped platform/CI decision remains native Windows 10+ with MSYS2 UCRT64, the production warning gate, unit tests and smoke coverage described above. This accepts the rolling-toolchain maintenance cost within the authorized merge workflow; it does not claim an additional human maintainer endorsement or change branch protection. Full RLTest remains POSIX-only. Exact final head |
A worker delayed inside a callback could arm its final reconnect before the --test-time deadline: next_reconnect_delay() subtracted a fresh wall-clock sample from the deadline, while event_add() counts from libevent's cached loop time. If that early retry completed a never-started client's setup, the client ran a whole extra interval (a 3 s run reported 6 s and exited 0). Compute the remaining delay from event_base_gettimeofday_cached(), the origin event_add() uses, falling back to gettimeofday() only on an API error. libevent 2.0.10 returns monotonic uptime through that call, so require 2.0.11 (core, OpenSSL and pthreads) and say so in the docs. Building against the real 2.0.11 minimum exposed two #553 details: the connect address pointer stays mutable for the older evutil API, and the unit test compares sockets against static_cast<evutil_socket_t>(-1) rather than EVUTIL_INVALID_SOCKET. Fixes #811 Co-Authored-By: Claude Opus 5.5 <[email protected]>

Problem
Native Windows clients need WSL or another machine to run memtier because the build and runtime assume POSIX sockets, process facilities and time helpers.
Root cause
Winsock uses different socket handles, errors, initialization and nonblocking-connect behavior. UCRT also differs in CPU accounting, standard handles, file paths, binary I/O and integer widths.
Fix
Support native Windows10+ with MSYS2 UCRT64 and the existing autotools build. Use libevent socket types/helpers and Windows thread initialization; provide CPU/crash reporting and missing-library shims; reject unsupported Unix sockets. Preserve explicit AC_PROG_CC and the libtool-free build.
The Windows path starts nonblocking connect directly, then hands the socket to libevent. A synchronous WSAECONNREFUSED queues one connection-owned deferred error callback so existing reconnect policy applies. Disconnect/destruction cancels it; other immediate hard errors retain libevent's failure behavior. APIs remain compatible with the existing libevent2.0.10 floor. POSIX keeps its libevent path and Unix backlog retry timer.
Restore missing standard handles before opening outputs. Preserve POSIX Unix fixtures while using private TCP fixtures on Windows. All15 unit programs run on Windows. Crash timestamps use a UTC offset prepared before the exception filter; the fault path avoids localtime/strftime. Portable integer formatting/conversion changes support LLP64 without changing the reviewed LP64 behavior.
Current head
14a284cincludes the normal merge of masterb6e9d78as6f82fda, including meta protocol, Unix backlog retries, JSON fatal summaries and debug-only JSON lifecycle notices. Existing output/import validation, reconnect deadlines, completion policy and crash watchdog fixes remain present.Tests and measured results
fa1e304: production build/warning gate, all15 units, version/hash checks and all10 smoke tests pass: https://github.com/redis/memtier_benchmark/actions/runs/39016446081 .6f82fdapassed the production warning gate,15 units and10 smoke tests: https://github.com/redis/memtier_benchmark/actions/runs/39018356290 . Final14a284conly removes a stale documentation count; its exact-head native run also passed the production warning gate,15 units and10 smoke tests: https://github.com/redis/memtier_benchmark/actions/runs/39018544725 . Other cross-platform CI is pending.Affected versions
This is a new platform feature, not a regression in a released Windows build. No released-version introducer applies. MSVC and32-bit Windows are outside this implementation.
Limitations
Windows uses libevent's select backend, has coarse scheduler-accounted CPU samples, and does not support Unix sockets. Crash reporting is best effort for unhandled SEH exceptions and raw addresses, not abort/assert failures; fprintf/CRT stream locks can still prevent output. RLTest's POSIX signal and /proc cases remain outside native Windows CI. Full static/no-TLS native deployment is not claimed validated.
The rolling MSYS2 toolchain and blocking production warning gate intentionally expose new compiler diagnostics and can require maintenance on unrelated PRs. Repository branch protection is unchanged.
Note
High Risk
Large changes to networking, threading, crash handling, and startup paths on a new platform; POSIX behavior is mostly preserved but Windows-specific connect and error-deferral logic is security- and reliability-sensitive.
Overview
Adds native Windows 10+ builds with MSYS2 UCRT64 / MinGW-w64: new GitHub Actions workflow (warning-free build,
make check, version hash check,tests/windows_smoke.py), developer docs, and.gitignorefor*.exe.Portability layer: new
platform_compat.hconsolidates Winsock vs POSIX networking includes;configure.acdetects MinGW, linksws2_32, sets Windows API macros, and skipslibevent_pthreadson Windows. Call sites move to libevent socket/timer helpers (evutil_*),evthread_use_windows_threads(), andWSAStartupinmain.Runtime behavior on Windows:
--unix-socketis rejected; CPU accounting usesGetThreadTimes(); crash reporting uses an SEH unhandled-exception filter (shared tail with POSIX) instead of alt-stack signal handlers; stdio fd reopening and output-prefix checks handle Win32 paths and detached CRT handles. Connections: nonblockingconnect()bypasses libevent’s blockinggetsockopt(SO_ERROR)path; synchronousWSAECONNREFUSEDis deferred via a connection-owned libevent callback so reconnect policy matches POSIX. Shims addgetline,jrand48, LLP64-safestrtoullparsing, and binary-mode file I/O.Unit tests gain Windows TCP fixtures, Winsock startup, and injected refusal cases; RLTest result dirs sanitize
:on NT.Reviewed by Cursor Bugbot for commit 14a284c. Bugbot is set up for automated code reviews on this repo. Configure here.
🤖 Generated with Claude Code