Skip to content

Reopen closed stdin/stdout/stderr on /dev/null at startup - #736

Merged
fcostaoliveira merged 1 commit into
masterfrom
fix/733-reopen-std-fds
Oct 17, 2026
Merged

fcostaoliveira merged 1 commit into
masterfrom
fix/733-reopen-std-fds

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

If memtier is started with stdout closed (memtier_benchmark ... >&-), the fopen() of --json-out-file gets fd 1. The text results that go to stdout are written into the JSON file, mixed with the JSON. The file is invalid and the run exits 0. With stderr closed, the JSON file gets fd 2, so it starts with Json file ... created... and is invalid, also with exit 0. Even when the JSON happened to stay valid (--hide-histogram), the text results were lost (write(1) = EBADF) and the run still exited 0.

Root cause

Nothing made sure fds 0-2 were open before files were opened. main() uses outfile = stdout, then new json_handler() calls fopen(), which takes the lowest free fd. After that, stdout (or stderr) and the JSON FILE* write to the same file. The same applies to --out-file, --failed-keys-file and any other file opened while 0-2 are free.

Fix

  • reopen_closed_std_fds() runs first in main(). For fds 0, 1 and 2, if fcntl(fd, F_GETFD) fails with EBADF, it calls open("/dev/null", O_RDWR) (retrying on EINTR), which gets that fd. It returns a mask of the reopened fds. If the open fails or returns another fd, memtier prints an error (when stderr is open) and exits 1. This is the usual daemon/setuid idiom.
  • Then two checks run at startup, before connecting:
    • early, right after option parsing, before any file is opened or read: a path option that names a reopened fd is rejected with exit 1.
      • Outputs covered: --out-file, --json-out-file, --failed-keys-file.
      • Inputs covered: --data-import, --monitor-input, --cert, --key, --cacert. With stdin closed, /dev/stdin used to fail with "cannot open"; after the reopen it would read an empty /dev/null.
      • Names matched: /dev/stdout, /dev/fd/1, /proc/self/fd/1, /proc/thread-self/fd/1 and symlinks to them, and likewise for stdin and stderr.
      • The message is error: --out-file /dev/stdout resolves to stdout, which was closed at startup. With stderr closed it is not visible, only rc 1.
      • A --failed-keys-file that names a closed fd is fatal here, while a failed-keys path that cannot be opened only warns, as before. The difference is deliberate: an unopenable path prints an error, but a closed-fd path opens fine on /dev/null and the log would be lost without any message.
    • late, after all option validation and data import, just before the output files are opened (where Fail at startup on an unwritable --out-file; open output files only after option validation #717 opens --out-file): a closed stdout with no --out-file is rejected with exit 1 and error: stdout was closed at startup, so the results would not be written; use --out-file. Because it is late, a bad option (for example a jitter error) still reports its own error. To keep only the JSON, pass --out-file /dev/null.
    • a closed stdin or stderr does not fail the run by itself.
  • In every case that runs, the --json-out-file is valid. The exit-code tail of main() is unchanged from master.
  • path_is_closed_fd(path, fd) follows the path one symlink at a time. It resolves the directory part with realpath() and checks the name against /dev/<name>, /dev/fd/N, /proc/<getpid()>/fd/N and /proc/<getpid()>/task/<tid>/fd/N (is_task_fd_path()). Any spelling of /dev/null (/dev/./null, a symlink to it) is accepted. So is another process's fd, such as the Docker idiom --out-file /proc/1/fd/1.
  • --hdr-file-prefix and --client-stats are prefixes. memtier always appends a suffix (_FULL_RUN_1.txt, -1-0-0.csv, ...), so they never name a descriptor themselves and are not checked. With stdout closed, --hdr-file-prefix /dev/stdout --client-stats /dev/fd/1 opens /dev/stdout_FULL_RUN_1.txt (Permission denied) and /dev/fd/1-1-0-0.csv (No such file), as on master; reporting those errors in the exit code is the known gap Write errors on --hdr-file-prefix files, --client-stats CSVs and --failed-keys-file are ignored: a full disk leaves empty/truncated files and the run exits 0 #744, linked from the README.
  • README: new section "Closed stdin, stdout or stderr". Fail the run on write errors to --out-file, --json-out-file or stdout #729's "Output write errors" paragraph no longer lists "a closed stdout" and points to it.

Why fail at startup: with stdout closed and no --out-file, it is known as soon as the fds are reopened that the text results would go to /dev/null. Running the whole benchmark (possibly minutes with --test-time) just to exit 1 at the end gains nothing; the user has to rerun with --out-file (or --out-file /dev/null) anyway. This matches #717, and it removes the ordering logic an end-of-run check needed next to the connection-stage (2) and worker-failure (1) exits.

Why the path check: reopening fd 1 on /dev/null would itself cause a silent-loss regression. On master, --out-file /dev/stdout with stdout closed failed loudly (rc 1, "cannot open"). After the reopen the same path opens /dev/null, so the results would be lost with exit 0. The path check keeps those cases failing, now with a clearer message, while any spelling of /dev/null still works. An inode comparison cannot do this, since the reopened fd 1 is /dev/null.

Why exit 1 rather than a warning: stdout is the default results sink, and losing it silently with exit 0 is the failure mode of #719. #729 treats a failed results write as exit 1. This PR keeps that rule after the reopen hides the EBADF.

Interplay with #729 (merged as 2285b02)

Before this PR, #729 reported a closed stdout as a failed write (EBADF), but only after the whole run. Now fd 1 is /dev/null, so those writes would succeed. The startup check above covers that case with the same exit code (1). #729's stdout_reader_gone() exemption cannot apply to /dev/null.

Tests

New tests/test_closed_std_fds.py (23 tests), also added to the asan and tsan "misc" cells (single endpoint and TLS v1.3). Each test runs memtier through sh -c 'exec "$@" >&-' (or <&-, 2>&-), not preexec_fn, which is unsafe in a threaded parent. Each test uses its own TemporaryDirectory. The results go to stdout (Benchmark's default --out-file is removed), with --json-out-file. On master the closed-stdout case corrupts the JSON only intermittently, so the tests catch the bug through the exit code and the error message. The startup-rejection tests check that memtier stopped before opening files or connecting: no mb.json, no Json file ... created line and no Preparing benchmark client line.

test master 38dfbaa this PR
test_stdout_closed_json_out_file, ..._hide_histogram, ..._run_count_2 FAIL (rc 0 after the run; JSON sometimes invalid) PASS (rc 1 at startup)
test_stdout_closed_out_file_dev_stdout, ..._json_out_file_dev_stdout, ..._out_file_dev_fd_1, ..._out_file_proc_thread_self_fd_1, ..._out_file_symlink_to_dev_stdout FAIL (rc 1, "cannot open") PASS
test_stdin_closed_out_file_dev_stdin FAIL (rc 1, "cannot open") PASS
test_stdin_closed_data_import_dev_stdin, test_stdin_closed_monitor_input_dev_stdin, test_stdin_closed_cacert_dev_stdin FAIL on master ("cannot open") and on e08ac06 (reads an empty /dev/null) PASS
test_stderr_closed_failed_keys_file_dev_stderr FAIL (rc 0, log lost) PASS
test_stderr_closed_json_out_file_dev_stderr, test_stderr_closed_out_file_dev_fd_2 PASS (rc 1, "cannot open") PASS
test_stderr_closed_json_out_file FAIL (JSON starts with Json file ... created...) PASS
test_stdout_closed_failed_keys_file_does_not_take_fd_1 FAIL (rc 0) PASS
test_stdout_closed_with_out_file_succeeds (control) PASS PASS
test_stdout_closed_out_file_dev_null_is_allowed, ..._dev_dot_null_is_allowed, ..._symlink_to_dev_null_is_allowed (controls, rc 0) PASS PASS
test_stdin_closed PASS PASS
test_stdout_closed_bad_option_reports_its_own_error (min jitter > max jitter, stdout closed: the jitter error, not the stdout one) PASS PASS

The rc-2 precedence test from earlier revisions is gone: a closed stdout without --out-file now exits before connecting, so the run can no longer reach a connection-stage abort.

Measured rates (--env oss), on 43eea81 (rebased on master 38dfbaa, which includes #751):

  • test_closed_std_fds.py: 23/23 passed in 5/5 runs. The previous head e08ac06 fails the 3 new input-path tests.
  • Fail the run on write errors to --out-file, --json-out-file or stdout #729's 11 write-error tests plus test_json_output_integrity.py and test_json_percentile_key_collision.py: 36/36 passed.
  • Master 38dfbaa: 15 of the 23 tests fail in 3/3 runs (every test marked FAIL in the table above); the other 8 (controls, test_stdin_closed, the two stderr-path tests that master already rejects with "cannot open", and test_stdout_closed_bad_option_reports_its_own_error) pass.
  • Mutation check: moving the reopen after the failed-keys log is opened fails test_stdout_closed_failed_keys_file_does_not_take_fd_1 and 12 others.

Fixes #733

Affected versions

1.2.9 through 2.5.2 (latest) and master.

  • Introduced by fb6888d "add support for JSON output" (add support for JSON output #18), which opened the JSON file with a plain fopen() while the text results go to stdout, with no fd 0-2 guard. git tag --contains fb6888d gives 1.2.9.
  • Reproduced on master e09ee54 (see the issue; 2.5.2 also confirmed there).

🤖 Generated with Claude Code

@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

🤖 Automated first-pass review — a human maintainer's review is still required before merge.

Thanks for this. I went through the C++ and the tests, and only have a couple of small comments.

  • On compatibility: as far as I can tell, failing at startup on >&- without --out-file doesn't break anything new. Since Fail the run on write errors to --out-file, --json-out-file or stdout #729, master already exits 1 on the EBADF write, just at the end of the run. The README also documents --out-file /dev/null for anyone who only wants the JSON. So I think stopping early is the right tradeoff here, not a new break.
  • I traced path_is_closed_fd() through /dev/stdout, /dev/fd/1 (resolves to /proc/<pid>/fd/1), /proc/thread-self/fd/1, /dev/./null and a trailing-slash path. I couldn't find a spelling that gets past it, and I didn't see a loop that can run forever, since it stops after 40 hops. The readlink(..., sizeof(target) - 1) sizing also looks right.
  • Nitpicking: the PR description doesn't match the commit anymore. It says the path check runs "just before the failed-keys log is opened" and only lists output paths. In the diff (and the commit message), the check runs right after option parsing and also covers --data-import, --monitor-input, --cert, --key and --cacert. The description also says 20 tests and shows a table, but I count 23 in tests/test_closed_std_fds.py. The stdin input-path tests aren't in the table. Could you update it so whoever squash-merges doesn't pick up the old wording?
  • Just checking: the TLS input check sits under #ifdef USE_TLS, and test_stdin_closed_cacert_dev_stdin skips by looking for --cacert in the --help output. I think that's fine, but did you confirm the test really runs in the TLS asan/tsan cells you added it to, and isn't quietly skipped there?

The fix itself looks solid to me. I'd mainly want the description brought in line with what the code actually does before this merges.

(would file this as a comment, not a formal block)

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. On the exit-code question: a closed stdout with --json-out-file still exits 1, and that is deliberate.

Closed stdin now has a test too (test_stdin_closed). The tests close the fd with sh -c 'exec "$@" <&-' (or >&- / 2>&-) instead of preexec_fn.

The latest push also rejects an --out-file or --json-out-file that names stdout (/dev/stdout, /dev/fd/1, /proc/self/fd/1) when stdout was closed. That path now resolves to the reopened /dev/null, so it would have lost the results with exit 0. On master it failed with "cannot open". It now fails at startup with exit 1 and error: --out-file /dev/stdout is stdout, which was closed at startup. An explicit /dev/null is still accepted.

@fcostaoliveira
fcostaoliveira force-pushed the fix/733-reopen-std-fds branch 2 times, most recently from f11a150 to 12856ff Compare October 16, 2026 19:39
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks. Both are addressed in 12856ff (rebased on master 0fc29f4):

  • (b) the vacuous assertion: you were right that assertFalse("ALL STATS" in stderr) could not fail. The rejection tests now check that memtier stopped before it opened any output file or connected: mb.json does not exist, and stderr has neither the Json file ... created line nor Preparing benchmark client.
  • (c) other spellings of /dev/null: inodes cannot tell /dev/./null or a symlink to /dev/null apart from the reopened stdout. So the check no longer compares inodes. It follows the path one symlink at a time, resolves the directory part with realpath(), and rejects it only if it names fd 1 (/dev/stdout, /dev/fd/1, /proc/<pid>/fd/1, or a symlink to one of them).
    • Any spelling of /dev/null is accepted. New tests cover /dev/./null and a symlink to /dev/null (rc 0), plus /dev/fd/1 and a symlink to /dev/stdout (rc 1).
    • The message now reads error: --out-file PATH resolves to stdout, which was closed at startup.

On the exit-code question, the PR body now has a short "why exit 1 rather than a warning" paragraph. The reason holds without #729: losing the default results sink silently is #719's failure mode, and --out-file /dev/null is the explicit way to keep only the JSON with exit 0. Also, when the run fails for another reason too (a thread ended early), both errors are now printed.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Points 2 and 3a are addressed in 69f128c:

  • 2, the other reopened fds: the guard now covers every fd that was reopened, not just stdout. reopen_closed_std_fds() returns a mask, and path_is_closed_fd(path, fd) is checked for each reopened fd.
    • With stderr closed, --json-out-file /dev/stderr and --out-file /dev/fd/2 exit 1 instead of writing silently to /dev/null with exit 0. The same goes for closed stdin with --out-file /dev/stdin.
    • --failed-keys-file is checked too. The check moved before the failed-keys log is opened, so it runs before any of the three files is opened.
    • The message reads ... resolves to stdin/stdout/stderr, which was closed at startup. With stderr closed it is not visible, so the exit code is the signal there.
    • README no longer says that a closed stderr only loses the log lines.
  • 3a, another process's fd: the /proc match now accepts only this process: /proc/<getpid()>/fd/N and /proc/<getpid()>/task/<tid>/fd/N (/proc/self and /proc/thread-self resolve to these). The Docker idiom --out-file /proc/1/fd/1 is no longer matched.

New tests pin both: /dev/stderr and /dev/fd/2 with stderr closed, /dev/stdin with stdin closed, and --failed-keys-file /dev/stderr. Two more pin that a connection-stage abort keeps exit 2 with stdout closed, and that the reopen runs before the failed-keys log takes fd 1. The test file now also runs in the asan and tsan "misc" cells.

@fcostaoliveira
fcostaoliveira force-pushed the fix/733-reopen-std-fds branch 2 times, most recently from 34f9c03 to bce73c5 Compare October 16, 2026 21:24
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks. I've answered each point; the changes are in bce73c5, rebased on master 8ef3971.

Is path_is_closed_fd() worth keeping? I think so. See "Why the path check" in the PR description. The check guards against a regression that the reopen itself would cause, not a new edge case:

  • On master, --out-file /dev/stdout with stdout closed fails loudly (rc 1, "cannot open").
  • With the reopen and no path check, the same command opens /dev/null and exits 0 with the results lost. That is the silent loss this PR is meant to remove.

I kept it and did what you suggested: the /proc/<pid>/task/<tid>/fd/N match is now a small helper, is_task_fd_path(path, task_prefix, fd_suffix). It checks the prefix, then that <tid> is all digits, then the exact suffix, so the if in the loop is now a single call. /proc/thread-self/fd/1 is covered by test_stdout_closed_out_file_proc_thread_self_fd_1.

--hdr-file-prefix / --client-stats: agreed. The "Closed stdin, stdout or stderr" section now says these are not checked: pointed at a closed descriptor, they go to /dev/null without an error, as with the other write errors on those files. That matches #744.

What runs between reopen_closed_std_fds() and the path check: I went through main() from the reopen down to the check, which sits just before the failed-keys log is opened:

  • evthread_use_pthreads(), the signal handlers and setrlimit(): no fds.
  • setup_crash_handlers(): sigaltstack plus prewarm_crash_handler(). The prewarm opens /dev/null for a moment and calls backtrace(), which loads libgcc_s read-only.
  • config_init_defaults() / config_parse_args(): no file opens.
  • --monitor-input load_from_file(): opens the input read-only.

Everything else comes after the check:

  • statsd socket and Prometheus listener
  • init_openssl(), SSL_CTX_new(), and the cert/key/CA loads (SSL_CTX_use_certificate_chain_file, SSL_CTX_load_verify_locations)
  • --data-import
  • the failed-keys log
  • --out-file / --json-out-file

Since fds 0-2 are open by the time any of these runs, none of them can get fd 0-2. The "before any of those files is opened" claim depends only on the three checked output paths, and all three are opened after the check.

Nit: _benchmark() is now a context manager around tempfile.TemporaryDirectory(), so each test's directory is removed afterwards.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks. The changes are in ec232eb, rebased on master 8ef3971. Point by point:

  1. Fail at startup, not at the end: agreed, done. With stdout closed and no --out-file, memtier now exits 1 right after the closed-fd path check, before connecting and before any output file is opened. This is the same place and the same approach as Fail at startup on an unwritable --out-file; open output files only after option validation #717's unwritable --out-file. The message is error: stdout was closed at startup, so the results would not be written; use --out-file.
    • The results_lost logic at the end of main() is gone, so the exit-code tail is the same as on master again.
    • The JSON-only case is still --out-file /dev/null, which runs and exits 0 with a valid JSON.
    • The tests now check the early exit: rc 1, no mb.json, and neither the Json file ... created line nor Preparing benchmark client.
    • The rc-2 precedence test is dropped: a run that is rejected before connecting can no longer reach a connection-stage abort.
  2. Is the path walker worth its size? The reasoning is in "Why the path check" in the PR description. The reopen itself would otherwise create a regression: on master, --out-file /dev/stdout with stdout closed fails loudly ("cannot open", rc 1). With the reopen alone, it would open /dev/null and exit 0 with the results lost. An inode comparison cannot catch this, because the reopened fd 1 is /dev/null. I kept it, with the task-path check split out into is_task_fd_path(). Thanks for tracing the /dev/fd, thread-self, relative-symlink and loop cases.
  3. Comment placement: done. The paragraph that describes path_is_closed_fd() is now above that function. is_task_fd_path() keeps only its own comment.
  4. --hdr-file-prefix / --client-stats: I checked. Both are prefixes, and memtier always appends a suffix (%s_FULL_RUN_%d.txt, %s_<CMD>_command_run_%d.hgrm, %s-<run>-<cg>-<client>.csv). So the files they open can never be /dev/stdout or /dev/fd/N themselves. With stdout closed:

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks for the update. Both points are addressed in e08ac06, rebased on master a7881e0:

  • --failed-keys-file /dev/stderr with stderr closed is fatal, but an unopenable failed-keys path only warns. That difference is on purpose, and I kept it. A path that cannot be opened prints an error, so the user sees it, and the run is otherwise fine. A path that names a closed fd opens fine on /dev/null, so the log would be lost with no message at all, which is the silent loss this PR removes. The comment at the open site said a failure "is reported but doesn't abort". It now describes both rules and why they differ.
  • Ordering: the closed-stdout check (no --out-file) has nothing to do with the failed-keys log. I moved it next to where Fail at startup on an unwritable --out-file; open output files only after option validation #717 opens --out-file, after all option validation and data import and before connecting. A bad option now reports its own error first: with stdout closed and --thread-conn-start-min-jitter-micros greater than the max, you get the jitter error. That case is pinned by test_stdout_closed_bad_option_reports_its_own_error.
    • The closed-fd path check stays where it is, just before the failed-keys log is opened, because it has to run before any of those files is opened. Moving it later would mean moving the failed-keys open too, which I did not want to do in this PR.
    • So a bad --clients-start combined with --out-file /dev/stdout and a closed stdout still reports the path error first. Both exit 1.
  • The README note on --hdr-file-prefix / --client-stats now links Write errors on --hdr-file-prefix files, --client-stats CSVs and --failed-keys-file are ignored: a full disk leaves empty/truncated files and the run exits 0 #744 as the known gap.

When memtier was started with stdout (or stderr) closed, the fopen() of
--json-out-file got fd 1 (or 2). The text results (or the stderr log
lines) were then written into the JSON file, which became invalid, and
the run still exited 0. The same applied to --out-file and any other
file opened while 0-2 were free.

main() now reopens any closed fd 0-2 on /dev/null before it does
anything else, the usual idiom for this. A closed stdin or stderr does
not fail the run by itself.

With stdout closed, the text results would now go to /dev/null. So if
no --out-file is given, memtier fails at startup with exit 1 and an
error, after the option checks and before connecting or opening any
output file, like an --out-file that cannot be opened. After #729 a write to the reopened /dev/null
succeeds, so its write-error check would no longer catch this.

An --out-file, --json-out-file or --failed-keys-file that names a
closed fd (/dev/stdout, /dev/fd/1, /proc/self/fd/1, or a symlink to one
of them; likewise for stdin and stderr) would now resolve to the
reopened /dev/null and lose its output with exit 0, where master failed
with "cannot open". It is rejected at startup with exit 1 too. The path
is followed one symlink at a time, because an inode comparison cannot
tell it from /dev/null itself, which is accepted however it is spelled.
Another process's fd (/proc/1/fd/1) is not matched. The same check
covers the input paths --data-import, --monitor-input, --cert, --key and
--cacert: with stdin closed, /dev/stdin would now read an empty
/dev/null. All path checks run right after option parsing, before any
of these files is opened or read.

The new tests also run in the asan and tsan "misc" cells.

Fixes #733

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

Copy link
Copy Markdown
Collaborator Author

Thanks for the re-edit. Point by point (changes in 43eea81, rebased on master 38dfbaa, which includes #751):

  1. Input paths with stdin closed: good catch. --data-import /dev/stdin and --monitor-input /dev/stdin used to fail with "cannot open"; after the reopen they would quietly read an empty /dev/null. I went through every option that takes a path:

    • The inputs are --data-import, --monitor-input, --cert, --key and --cacert.
    • The outputs are --out-file, --json-out-file and --failed-keys-file.
    • --hdr-file-prefix and --client-stats are suffixed prefixes (see the README).

    All eight path options now go through path_is_closed_fd() in one check. I moved that check to right after config_parse_args(), so it runs before monitor_commands->load_from_file() (the first file read in main()), before the data import and TLS loads, and before the failed-keys log is opened. The message is the same form, e.g. error: --monitor-input /dev/stdin resolves to stdin, which was closed at startup. New tests for --data-import, --monitor-input and --cacert with /dev/stdin fail on master and on e08ac06, and pass now.

  2. Ordering wording: the README now states the two checks exactly.

    • The path check is early: right after option parsing, before any file is opened or read.
    • The closed stdout without --out-file check is late: after all option validation and data import, just before the output files are opened. That is why a bad option still reports its own error.

    With the path check moved up, the failed-keys open no longer has to move; it stays where it was.

  3. readlink() nit: done. The comment now says that a realpath() or readlink() failure such as ENOENT or EACCES deliberately counts as "not a closed fd", so the later open()/fopen() reports the real error.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks. On the two open points:

  • Description vs commit: the description was updated after this review ran. It now says the path check runs right after option parsing, before any file is opened or read. It lists the input paths (--data-import, --monitor-input, --cert, --key, --cacert) as well as the outputs, says 23 tests, and the table includes the three stdin input-path tests. Master 38dfbaa fails 15 of the 23.
  • test_stdin_closed_cacert_dev_stdin in the TLS cells: confirmed it runs and is not skipped. In the ASAN and TSAN "Single Endpoint: TCP TLS (misc)" job logs at 43eea81, the test starts its TLS redis (--tls-port), runs memtier with --tls --cert ... --cacert ... --key ..., and asserts rc 1 with error: --cacert /dev/stdin resolves to stdin, which was closed at startup.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant