Skip to content

Fail at startup on an unwritable --out-file; open output files only after option validation - #717

Merged
fcostaoliveira merged 5 commits into
masterfrom
fix-716-out-file-open
Oct 16, 2026
Merged

fcostaoliveira merged 5 commits into
masterfrom
fix-716-out-file-open

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

Decisions:

  • An --out-file that cannot be opened is now a fatal startup error (exit 1), matching what Handle SIGTERM like Ctrl+C so --json-out-file stays valid #706 did for --json-out-file. Previously memtier printed the fopen error, ran the benchmark, and then crashed.
  • --out-file and --json-out-file are now both opened only after all option validation, so a startup error leaves existing output files untouched.
  • --out-file is truncated only after the --json-out-file has been opened, so an open error on either file leaves the other untouched.

Problem

  1. --out-file with an unwritable path segfaults after the run instead of failing at startup #716. With an unwritable --out-file (for example, a missing directory or no permission), memtier printed PATH: No such file or directory, ran the whole benchmark (the full --test-time), and then crashed with SIGSEGV (rc 139) while writing the results.
  2. Startup validation errors after --json-out-file is opened leave a truncated, invalid JSON file (and clobber an existing one) #718. --json-out-file was opened, truncated, and given the config block before most option validation. Any usage() or exit(1) after that left a truncated, invalid JSON file in place of whatever was there before. A rerun with a typo destroyed the previous results.

Root cause

  • A failed fopen(cfg.out_file, "w") in main() was only perror()'d. outfile stayed NULL until the first fprintf(outfile, ...) after the run.
  • new json_handler(cfg.json_out_file) and config_print_to_json() ran right after the TLS setup, before the getrlimit, protocol, data-size, key-range and data-import checks. Those exit directly, so ~json_handler() never closed the object.

Fix

Both opens now happen where --out-file used to be opened: after every usage check, the server_addr DNS resolution and the data-import loading, and before any connection or worker thread starts.

  • --out-file is opened first, with open(O_WRONLY | O_CREAT) + fdopen(), so it is not truncated yet. open() is retried on EINTR (as in json_handler), and on failure memtier prints error: cannot open --out-file PATH: REASON and calls exit(1). The JSON file has not been touched at that point.
  • Then the json_handler is created and config_print_to_json() runs. If the JSON open fails, memtier exits 1 and the existing --out-file is left as it was.
  • Only then is the results file ftruncate()d. This is done only for regular files, so /dev/stdout, /dev/null and FIFOs work as before.
  • The stderr notes keep their old order: "Json file ... created" before "Writing results to ...". Both now print after the usage checks.
  • One edge case: if --out-file did not exist before and the JSON open then fails, an empty --out-file is left behind. An existing file is never modified.

JSON configuration block. I compared the parsed block before and after this change for several option sets:

  • default
  • Z:Z
  • Z:Z --key-zipf-exp 0.5
  • G:G --key-stddev 10
  • --data-size-range
  • an arbitrary command with --command-key-pattern=Z
  • -t 2 -c 3 --ratio 1:3 --pipeline 4
  • --data-import
  • --key-prefix / --randomize

The only difference: with a Zipf key pattern and no --key-zipf-exp, "key_zipf_exp" is now 1.000000, the exponent actually used, instead of the unset 0.000000. Every other field is identical.

A shared open/retry/error helper for JSON_handler.cpp and memtier_benchmark.cpp was considered and declined: they are separate translation units, and it would need a new header for four lines.

Not covered (pre-existing): the --statsd client and the --prometheus-port exporter are set up earlier in main(), before validation. That is unchanged by this PR.

Tests

All tests are in tests/tests_oss_simple_flow.py, run with --env existing-env against a local redis:

test master bc7320a 92ffb0b this PR (c0f8842)
test_out_file_unwritable: rc 1, full message with : No such file or directory, no Launching threads, < 20 s, existing JSON untouched FAIL (still running at 20 s, killed) pass pass
test_json_out_file_unwritable_keeps_out_file: unwritable JSON path, existing --out-file byte-identical pass FAIL (--out-file emptied) pass
test_out_file_replaces_existing: a longer existing --out-file is fully replaced, and stderr order is "Json file" then "Writing results" pass FAIL (order) pass
test_startup_error_keeps_output_files_data_size (--data-size 10 --data-size-list 10:1) FAIL (JSON clobbered) pass pass
test_startup_error_keeps_output_files_select_db (-P memcache_text --select-db 1) FAIL pass pass
test_startup_error_keeps_output_files_data_import (missing --data-import file) FAIL pass pass

At 75b0c5e, the three test_startup_error_* tests also fail, because both files were clobbered.

  • Repeat runs: these six tests plus test_json_out_file_unwritable passed 35/35 across 5 repeated runs with this PR.
  • Cluster: they also pass with --env oss-cluster --shards-count 3. In cluster mode the select-db and data-import cases fail earlier, with the cluster-mode message, and the test expects that.
  • Special files: --out-file /dev/null and --out-file /dev/stdout still work (rc 0).
  • No regressions:
    • test_json_output_integrity.py passes (17/17).
    • The SIGINT/SIGTERM JSON tests pass: test_sigterm_closes_json, test_sigterm_stops_run_count, test_interrupt_* and test_valid_json_using_debug_command.
    • test_json_out_file_unwritable, test_default_set and test_default_set_get pass.

Manual repro, -n 10 -t 1 -c 1 --out-file /nonexistent-memtier-dir/o.txt:

  • master: crashed by signal: 11 ... SIGSEGV, rc 139
  • this PR: error: cannot open --out-file /nonexistent-memtier-dir/o.txt: No such file or directory, rc 1

Fixes #716
Fixes #718

Release notes

  • An unwritable --out-file or --json-out-file now fails at startup with an error and exit code 1. It no longer crashes, and no longer leaves an empty or invalid JSON file behind.
  • Output files are opened only after the options are validated, so an invalid option no longer truncates an existing --out-file.
  • JSON configuration: with a Zipf key pattern (Z) and no --key-zipf-exp, "key_zipf_exp" now reports the exponent actually used (1.000000), not the unset 0.000000.

Affected versions

#716: 1.0.0 through 2.5.2 (latest) and master.

  • Introduced by 833a8df, "First memtier_benchmark version". The fopen / perror / continue block has been there since then.
  • Confirmed by running: master 0370514 and bc7320a (rc 139); f308ed6 and 2.5.2 (rc 139, from the issue).
  • Derived from history: 1.0.0 through 2.5.1.

#718: 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 created the json_handler before the validation.
  • Confirmed by running: master 0370514 (from the issue) and bc7320a (the tests above); 2.5.2 (from the issue).
  • Derived from history: 1.2.9 through 2.5.1.

🤖 Generated with Claude Code


Note

Medium Risk
Changes when and how benchmark results are written at startup; behavior is well-tested but affects all runs using --out-file or --json-out-file.

Overview
Fixes startup handling for --out-file and --json-out-file so bad paths fail immediately and do not destroy prior results.

Output opens move to the end of startup validation (after option checks, DNS, and data import). JSON config is no longer written before validation, so early exit/usage leaves existing JSON and text output files intact.

--out-file behavior changes: unwritable paths now exit with a clear error instead of running the benchmark and crashing on write. The file is created with open(O_WRONLY|O_CREAT) first; ftruncate runs only after --json-out-file opens successfully, and only for regular files (stdout/FIFOs unchanged). Failed JSON open no longer wipes an existing --out-file.

Integration tests cover unwritable outputs, truncation on success, stderr message order, and that validation errors preserve both output files.

Reviewed by Cursor Bugbot for commit a673611. Bugbot is set up for automated code reviews on this repo. Configure here.

@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

🤖 Automated first-pass review. A human maintainer still needs to review this before merge.

Thanks, I read through the whole thing. Moving both opens below the validation looks right to me. Nothing reads jsonhandler or outfile between the old and new locations, so the move is self-contained. Each of the new tests is shown failing on bc7320a and passing here, which is the same bar tests/test_json_output_integrity.py set in #364.

A few small things, none blocking:

  • The configuration block is now written from the post-validation cfg. I think key_zipf_exp showing the exponent actually used (1.0 instead of 0.0) is an improvement, and you already called it out. It's still a visible change in JSON output, though, so it's probably worth a line in the release notes for anyone diffing configs across versions.
  • --out-file /dev/stdout with stdout redirected to a regular file: fstat sees a regular file and ftruncates it. As far as I can tell that's the same as the old fopen("w") truncation, so there's no behavior change. Just confirming that's intended.
  • Nitpicking: the new comment block above the opens is fairly long. The bit about truncating only after the JSON open could sit next to the ftruncate() call instead. Also, since the // We allways print... line is being moved anyway, the typo could be fixed while you're there.

The core fix looks solid to me.

(I'd file this as an approval-leaning comment, not a block.)

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. Point by point:

  1. Opening --out-file before the JSON handler. Agreed, done in 75b0c5e. --out-file is now opened just before json_handler is created. That is still after the TLS setup and before any connection or thread, so an unwritable --out-file no longer touches --json-out-file. test_out_file_unwritable now writes a valid JSON file first and asserts it is byte-for-byte unchanged afterwards. At d6f1dcd that assertion fails (5/5), and at 75b0c5e the test passes (5/5). The trade-off is that a usage error found later in main() now leaves an empty --out-file. It is empty, not corrupt, and I noted it in the PR description. The test also now asserts the full message, including : No such file or directory.

  2. Shared helper. Declined. The two call sites are in different translation units (JSON_handler.cpp and memtier_benchmark.cpp), so one small static function can't serve both. Sharing it would need a new header and declaration for four lines of logic, and the messages name different options. Both copies carry the same comment and wording, so drift is easy to spot.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

Comment thread memtier_benchmark.cpp Resolved
fcostaoliveira and others added 3 commits October 16, 2026 14:56
main() only perror()'d a failed fopen() of --out-file and carried on with
outfile == NULL. The whole benchmark ran (the full --test-time), and then
the first fprintf(outfile, ...) of the results crashed with SIGSEGV
(rc 139), losing the run and printing the crash-handler bug report.

Treat it as a fatal configuration error, the same way #706 now handles an
unopenable --json-out-file: print "error: cannot open --out-file PATH:
REASON" and exit 1. The open still happens before any connection or
thread is started, so no run is wasted. fopen() is retried on EINTR, as
json_handler does.

Regression test test_out_file_unwritable in tests_oss_simple_flow.py
uses a path in a non-existent directory with --test-time 60 and expects
exit 1, the message, no "Launching threads", and an exit within 20 s.

Fixes #716

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

json_handler truncates --json-out-file and writes the config as soon as
it is constructed, so failing on --out-file after that left a valid JSON
file from an earlier run replaced by a partial one. Open --out-file just
before the JSON handler instead. It is still before any connection or
thread starts. A usage error found after this point now leaves an empty
--out-file behind, which is empty rather than corrupt.

The test now also checks that an existing --json-out-file is untouched,
and asserts the full message including the strerror() reason.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Opening the output files early meant that any later startup error
(usage(), a failed data-import, ...) had already truncated an existing
--out-file and replaced an existing --json-out-file with an unterminated
config block. A rerun with a typo destroyed the previous results.

Move both opens to just before the run, after all option validation and
the data-import loading. --out-file goes first, so its open error still
leaves the JSON file untouched. No connection or worker thread has
started at that point.

The only visible change in the JSON "configuration" block: with a Zipf
key pattern and no --key-zipf-exp, "key_zipf_exp" now shows the value
actually used (1.0) instead of the unset 0.0.

Tests cover the three #718 cases (--data-size with --data-size-list,
-P memcache_text --select-db, a missing --data-import): each leaves an
existing --out-file and --json-out-file byte-identical.

Fixes #718

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

Copy link
Copy Markdown
Collaborator Author

Thanks. I went the way you suggested, in 92ffb0b. Rebased on bc7320a.

  1. Placement. Both opens now sit where --out-file used to be opened. That is after every usage() check, the server_addr DNS resolution and the data-import loading, and before any connection or worker thread. --out-file is opened first (EINTR retry, then error: cannot open --out-file PATH: REASON and exit 1). Then json_handler is created and config_print_to_json() runs.

    You were right that nothing in between uses jsonhandler. A startup error now leaves both an existing --out-file and an existing --json-out-file byte-identical, so this also fixes Startup validation errors after --json-out-file is opened leave a truncated, invalid JSON file (and clobber an existing one) #718. I tested all three Startup validation errors after --json-out-file is opened leave a truncated, invalid JSON file (and clobber an existing one) #718 cases, and each has a test in tests_oss_simple_flow.py:

    case master 75b0c5e 92ffb0b
    --data-size 10 --data-size-list 10:1 (rc 2) JSON clobbered both files clobbered both untouched
    -P memcache_text --select-db 1 (rc 2) JSON clobbered both files clobbered both untouched
    --data-import <missing> (rc 1) JSON clobbered both files clobbered both untouched

    In cluster mode, the first two cases fail earlier, with a different message, but are still checked.

    One side effect: config_print_to_json() now runs after main() fills in key_zipf_exp. I compared the parsed configuration block before and after for these runs:

    • default
    • Z:Z
    • Z:Z --key-zipf-exp 0.5
    • G:G --key-stddev 10
    • --data-size-range
    • an arbitrary command with --command-key-pattern=Z
    • -t 2 -c 3 --ratio 1:3 --pipeline 4
    • --data-import
    • --key-prefix/--randomize

    The only difference: with a Zipf key pattern and no --key-zipf-exp, "key_zipf_exp" is now 1.000000, the exponent actually used, instead of the unset 0.000000. I kept that, since it is more accurate.

  2. "Writing results to ..." nit. That line now prints after the usage checks, so it no longer shows up right before a usage error.

@fcostaoliveira fcostaoliveira changed the title Fail at startup when --out-file cannot be opened Fail at startup on an unwritable --out-file; open output files only after option validation Oct 16, 2026
Opening --out-file with fopen("w") before the JSON handler truncated an
existing results file even when the --json-out-file open then failed and
memtier exited 1, so the previous results were lost.

Open --out-file with open(O_WRONLY | O_CREAT) and fdopen(), create the
json_handler, and only then ftruncate() the results file. ftruncate() is
done only for regular files, so /dev/stdout, /dev/null and FIFOs still
work. An error opening either file now leaves the other untouched, and
the stderr notes are back in their old order ("Json file ... created"
before "Writing results to ...").

New tests: an unwritable --json-out-file leaves an existing --out-file
byte-identical, and a successful run fully replaces a longer existing
--out-file and keeps the note order.

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

Copy link
Copy Markdown
Collaborator Author

Thanks. Point by point:

  1. Unwritable --json-out-file with an existing --out-file. Good catch. Fixed in c0f8842, rebased on bc7320a. --out-file is now opened with open(O_WRONLY | O_CREAT) + fdopen(), so there is no truncation at that point. Then the json_handler is created. Only after both opens have succeeded is the results file ftruncate()d. That only happens for regular files, so /dev/stdout, /dev/null and FIFOs still work.

    So an open error on either file leaves the other one byte-identical. That holds in both directions:

    • test_json_out_file_unwritable_keeps_out_file (the test you suggested) fails at 92ffb0b ('' == 'previous results\n') and passes now.
    • test_out_file_unwritable already covers the mirror case, an existing JSON file, and passes at both.

    test_out_file_replaces_existing checks that a successful run still fully replaces a longer existing --out-file. It also checks the stderr order, which is back to "Json file ... created" before "Writing results to ...". At 92ffb0b it fails on the order.

  2. key_zipf_exp. It is already called out in the PR description under "JSON configuration block". I also mentioned it in the commit message so it ends up in the squashed message.

  3. Title and body. Both were updated after 92ffb0b: the title now mentions the option-validation change, the body has Fixes #718, and the stale empty---out-file trade-off paragraph is gone. I have now updated the body again for c0f8842.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit c0f8842. Configure here.

Comment thread memtier_benchmark.cpp Resolved
If ftruncate() of --out-file failed (e.g. EIO), memtier exited after the
json_handler had already written the config block, skipping its
destructor and leaving an unterminated JSON file. Delete the handler
before exiting so the nesting is closed and the JSON stays valid.

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

Copy link
Copy Markdown
Collaborator Author

Thanks. Point by point:

  1. key_zipf_exp in the JSON configuration block: agreed. I added a "Release notes" section to the description covering it, together with the startup-failure behaviour for unwritable --out-file / --json-out-file and the fact that an invalid option no longer truncates an existing --out-file.
  2. --out-file /dev/stdout with stdout redirected to a regular file: yes, that's intended. fstat() sees a regular file and truncates it, which matches the old fopen("w"). Character devices, /dev/null and FIFOs aren't truncated, the same as before.
  3. Comment placement and the allways typo: fair nits. I'm leaving them as they are in this PR so the reviewed and CI-green head doesn't change for comment-only edits. They can go into the follow-up for Write errors on --out-file and --json-out-file are ignored: a run whose results could not be written exits 0 #719 (write errors on the out and JSON files), which touches the same block.

@fcostaoliveira
fcostaoliveira merged commit ec4e6fa into master Oct 16, 2026
129 checks passed
fcostaoliveira added a commit that referenced this pull request Oct 16, 2026
main() closed the results file with an unchecked fclose(), and
~json_handler() did the same for the JSON file and then logged
"Json file closed.". A buffered ENOSPC/EDQUOT/EIO was lost, so a run
whose results were missing or truncated exited 0, and scripts that
check the exit code accepted it.

Flush and close both files through a new finish_output_file() helper
that checks fflush(), ferror() and fclose(). json_handler gets a
close() method that returns the error; main() calls it instead of
relying on the destructor. On failure memtier prints
"error: failed writing --out-file PATH: REASON" (or --json-out-file)
and exits 1, the code already used for a run that did not complete.

The default stdout output is checked too (`> /dev/full` exited 0), but
EPIPE on stdout is not an error: SIGPIPE is ignored, so `| head` makes
the writes fail with EPIPE, and that run used to and still exits 0.
An explicit --out-file is held to the stricter rule.

Also tidy two nits from the #717 review: move the
truncate-after-JSON note next to the ftruncate() call, and fix the
"allways" typo.

Fixes #719

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Oct 16, 2026
main() closed the results file with an unchecked fclose(), and
~json_handler() did the same for the JSON file and then logged
"Json file closed.". A buffered ENOSPC/EDQUOT/EIO was lost, so a run
whose results were missing or truncated exited 0, and scripts that
check the exit code accepted it.

Flush and close both files through a new finish_output_file() helper
that checks fflush(), ferror() and fclose(). json_handler gets a
close() method that returns the error; main() calls it instead of
relying on the destructor. On failure memtier prints
"error: failed writing --out-file PATH: REASON" (or --json-out-file)
and exits 1, the code already used for a run that did not complete.

The default stdout output is checked too (`> /dev/full` exited 0), but
EPIPE on stdout is not an error: SIGPIPE is ignored, so `| head` makes
the writes fail with EPIPE, and that run used to and still exits 0.
An explicit --out-file is held to the stricter rule.

Also tidy two nits from the #717 review: move the
truncate-after-JSON note next to the ftruncate() call, and fix the
"allways" typo.

Fixes #719

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Oct 16, 2026
main() closed the results file with an unchecked fclose(), and
~json_handler() did the same for the JSON file and then logged
"Json file closed.". A buffered ENOSPC/EDQUOT/EIO was lost, so a run
whose results were missing or truncated exited 0, and scripts that
check the exit code accepted it.

Flush and close both files through a new finish_output_file() helper
that checks fflush(), ferror() and fclose(). json_handler gets a
close() method that returns the error; main() calls it instead of
relying on the destructor. On failure memtier prints
"error: failed writing --out-file PATH: REASON" (or --json-out-file)
and exits 1, the code already used for a run that did not complete.

The default stdout output is checked too (`> /dev/full` exited 0), but
EPIPE on stdout is not an error: SIGPIPE is ignored, so `| head` makes
the writes fail with EPIPE, and that run used to and still exits 0.
An explicit --out-file is held to the stricter rule.

Also tidy two nits from the #717 review: move the
truncate-after-JSON note next to the ftruncate() call, and fix the
"allways" typo.

Fixes #719

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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