Skip to content

Fail fast on malformed --data-import files (hang, crashes) - #767

Merged
fcostaoliveira merged 3 commits into
masterfrom
fix/data-import-parse-error-hang
Oct 17, 2026
Merged

fcostaoliveira merged 3 commits into
masterfrom
fix/data-import-parse-error-hang

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Oct 17, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

Malformed --data-import files can hang at 100% CPU while flooding stderr, crash on truncated keys or overflowing lengths, or reach a worker and abort after connecting. --generate-keys previously skipped startup validation entirely.

Root cause

imported_keylist::read_keys() retried until EOF, but a failed fscanf() does not consume the invalid bytes. A NULL item also conflated an input error with EOF. Length arithmetic could underflow or wrap, and allocations and truncated strings were not checked.

Fix

  • Stop the startup scan on the first NULL item and fail with exit 1 on a parse error or zero complete items. Both stored-key and --generate-keys paths in main() use imported_keylist::read_keys(); the generated-key path uses a temporary keylist and read_keys(false) to validate without storing keys. Generated-key errors say invalid --data-import file.
  • Check bounded decimal length tokens before narrowing. Reject empty keys/values, keys or values over 512 MiB, numeric overflow, mismatched lengths and allocation failures before connecting. The 512 MiB per-field cap is a memtier import safety limit: protocol writers take signed int key/value lengths and add both payloads and framing into an int byte count. UINT_MAX - 2 would permit negative narrowed lengths; independent INT_MAX limits could still overflow combined accounting. A looser limit needs coupled length/framing validation and wider protocol accounting. This intentionally rejects some formerly accepted large files even when a server is configured for larger payloads; Redis's configurable default is precedent for the chosen cap, not the safety argument.
  • Preserve size-capped dump compatibility: a cut-off final item after at least one complete item warns premature end of file and acts as EOF. Earlier complete items still load, including when the worker wraps around. A file containing only a cut-off item fails. Missing-final-newline and missing-closing-quote warnings retain their existing behavior.
  • Reset line numbers and reader status when reopening. A short key column now fails instead of loading uninitialized trailing key bytes; this intentional behavior change is documented in the README.
  • --generate-keys adds one sequential startup scan without storing imported keys. The previous session measured approximately +3.9 s on a 488 MiB / two-million-item file; README documents this cost.

Tests

tests/test_data_import_parse_errors.py runs 114 invalid-input cases across ordinary import, --verify-only, and --generate-keys, including each malformed item both alone and between valid items. Subprocesses have a five-second timeout, bounded stderr and a distinct sanitizer exit code (86). Valid-file tests use the shared TLS helpers, request more items than the file contains, parse JSON operation counts, check Redis values and require no warnings for valid CRLF files. Truncated-final-item tests perform real imports and wrap around in both stored-key and generated-key modes.

Local owner validation on the final code:

  • ASan + UBSan plaintext and TLS: 5/5 integration tests pass in each; ordinary TLS/plaintext also passed before the extra overflow-token cases were added.
  • make check: 13/13 executables pass, including new reader reopen/error/EOF tests; sanitizer build passes too.
  • All six independent mutants deleting an error-flag assignment are killed. The valid/bad/valid cases catch dropped errors that an empty-file fallback otherwise hides.
  • Forced allocation failure returns NULL with a diagnostic, without dereferencing the allocation.
  • make format and make format-check pass.

Measured before/after from the initial reproduction (retained from the previous session):

Input Before (master 3fcbfbc) Fixed
reported repro, verify-only killed at 20 s; 395 MB stderr exit 1 in 7 ms; 325 B stderr
reported repro, ordinary import killed at 20 s; 325 MB stderr exit 1 in 7 ms
reported repro, generated keys SIGABRT after connecting exit 1 in 9 ms before connecting

Fixes #766

Affected versions

The faulty read loop and unchecked import parser originate in 833a8df (First memtier_benchmark version., 2013). git tag --contains 833a8df includes every release from 1.0.0 through 2.5.2, plus affected master. The previous session reproduced the hang on master 3fcbfbc and 2.5.2; older releases are identified by source history.

🤖 Generated with Claude Code


Note

Medium Risk
Changes startup behavior for all --data-import runs and tightens accepted file shapes (including rejecting some formerly tolerated inputs), but limits risk by validating before connections and preserving truncated-tail compatibility.

Overview
Hardens --data-import so malformed or empty dump files exit 1 at startup (before connecting), including --generate-keys and --verify-only.

The import reader now stops on the first bad item (fixing infinite CPU loops), tracks has_error(), validates bounded key/value lengths (max 512 MiB, no empty fields, length/column mismatches are errors), and handles OOM on column reads. A truncated final item after at least one complete row still warns and is treated as EOF for size-capped dumps; short keys no longer load garbage bytes.

imported_keylist::read_keys(bool keep_keys) supports a validation-only scan for generated-key mode; memtier_benchmark wires that path in main(). Adds file_io_test plus tests/test_data_import_parse_errors.py (timeouts, sanitizer exit code) and README notes on validation cost for large files.

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

A --data-import item line that read_item() could not parse made memtier
spin forever at 100% CPU while loading keys, printing the same "error
parsing item values." line hundreds of MB at a time. read_keys() looped on
!is_eof(), but read_item() returns NULL without consuming the bad input,
so the stream never reached EOF. The first SIGTERM only requests a
graceful stop, which the run loop checks and this loop does not, so it
looked as if SIGTERM was ignored.

Other bad lines crashed instead: a truncated key dereferenced a NULL
read_string() result (SIGSEGV), nbytes < 2 underflowed `nbytes - 2` into
a heap overflow, and errors that were dropped ("0 keys read") or only hit
at run time with --generate-keys aborted in read_next_item() after
connecting.

read_item() now records a malformed item in an error flag (has_error())
and returns NULL. A partial fscanf() match at EOF counts as an error, not
a clean end. It also rejects nbytes < 2, a NULL key/data from
read_string(), and a key whose length does not match nkey. read_keys()
stops at the first NULL and fails on an error or an empty file. With
--generate-keys, import_object_generator::open_file() runs the same
validation scan at startup. Every bad file now prints its error once,
with file:line, and exits 1 before connecting. Valid files load the same
data as before.

Fixes #766

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

github-actions Bot commented Oct 17, 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 reader changes and the tests, and I only have a few comments.

The core fix looks right to me. Stopping at the first NULL instead of looping on !is_eof() closes the spin, since fscanf() never consumed the bad bytes. Reading the length columns as bounded tokens and running them through strtoul before narrowing deals with the %u wrap at the root. The bad/good/bad cases in test_data_import_parse_errors.py, plus the 5s timeout and the separate sanitizer exit code, mean these tests would actually hang or fail on master, which is the bar I'd want for a parser fix like this.

  • Short key column is now a hard error where it used to warn and load. I agree the old behaviour was a bug, since key[s_nkey] left uninitialized bytes in the key. Did you consider the less-breaking option of warning and using key_actlen as the key length? Then old dumps that happened to load would keep loading, just with the key that's really in the file. I may be missing a reason it can't work (memcache_item taking nkey from somewhere else?). If it can't, the README note is fine. The data-column mismatch already returned NULL before this PR, so that one isn't really a compat change.

  • The 512 MiB cap: you've already laid out why independent INT_MAX limits aren't enough, given the combined int accounting in the protocol writers. That's the kind of reasoning I'd want for a stricter limit, so no objection from me. It might still be worth a second look from whoever owns the protocol layer, in case someone relies on 512 MiB–2 GiB values with a raised proto-max-bulk-len.

  • Truncated last item at run time: import_object_generator::read_next_item() reopens the file on every wrap, and bad_item() prints the premature end of file warning each time. With a small capped dump and a large --requests, I think that's one warning per wrap per client. The existing "end of line expected" warning already behaves this way, so it's not new, but did you consider warning only on the first open, e.g. from the startup scan?

  • Nitpicking: the new OOM message in read_string() prints m_line with %d. The other messages use %u.

None of this blocks the fix. I'd like an answer on the short-key question before this merges, though.

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

Recover the interrupted owner pass on top of the published PR head. Share startup validation, keep TLS test setup consistent, and reject overflowing length tokens before allocation. Exercise wrap-around and good/bad/good inputs with sanitizer exits distinct from parse failures.
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Addressed all three points in e7229f9:

  1. Keys and values are capped at 512 MiB, empty keys/values are rejected at startup, and read_string checks malloc before writing. The length fields are now parsed as bounded decimal tokens with checked conversion before narrowing, so even values above UINT_MAX that would otherwise wrap back to 3 or 5 cannot bypass the cap. Tests cover huge, negative and overflowing lengths alone and after a good item; a forced malloc-failure probe returns NULL cleanly. ASan+UBSan passes all five integration tests on plaintext and TLS.
  2. The PR body and README now explicitly say that a short key column is an error: the old warning path imported uninitialized trailing key bytes. A cut-off LAST item after complete items retains the compatible warning/EOF behavior, exercised by real imports and wrap-around; zero complete items still fails.
  3. The generated-key startup validation now calls the same imported_keylist::read_keys(false) scan as the stored-key path, without retaining keys. It reports invalid --data-import file rather than failed-to-open on parse errors. Its extra sequential-scan cost is documented (previous session: approximately +3.9 s for 488 MiB / two million items).

The previously red valid-file test now uses the shared TLS arguments and env.getConnection(). Six independent mutants deleting the reader's error assignments are all caught, including by the new good/bad/good cases. Full CI and the remaining independent review lenses are still pending; this is not a merge claim.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

On the latest edit:

  • We considered UINT_MAX-2, but the allocation arithmetic is not the only limit. protocol::write_command_set and its Redis/text/binary implementations accept signed int key/value lengths; the Redis implementation asserts they are positive, then accumulates key length, value length and framing into an int byte count. The proposed unsigned bound permits negative narrowed arguments, and even separate INT_MAX field bounds can overflow the combined count. Keeping 512 MiB per field provides headroom for both fields and framing without expanding this parser fix into a protocol-accounting change. This is an explicit memtier import limit, not a claim that Redis always enforces 512 MiB or that memcache has the same server limit. It does reject some previously accepted large files; supporting larger imports safely needs coupled accounting validation. The PR body now explains this tradeoff.
  • The description now names the final implementation: both startup paths in main use imported_keylist::read_keys(), and the generated-key path calls read_keys(false) on a temporary keylist. It does not validate in import_object_generator::open_file(). The squash message will describe this final behavior, not the recovery commit history.
  • Keeping the established failed to read keys summary for stored-key imports minimizes message changes. Both paths already emit the same precise file:line parser diagnostic first; the generated-key summary now correctly says invalid input instead of failed to open.
  • Agreed that replacement of the file after startup remains a separate TOCTOU issue; it is recorded in the handoff candidates.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks for the updated review. I considered replacing the declared key length with key_actlen: it is technically possible, but it repairs a structurally inconsistent dump by choosing a key identity the file did not declare. That can collapse distinct corrupt records onto an existing shorter key and overwrite it. The old path also sent uninitialized suffix bytes, so there is no deterministic old key identity to preserve. I am retaining the documented hard error for key-length mismatch; complete valid records stay compatible. A physically cut-off final record remains the separate warning/EOF exception, as requested.

The repeated truncated-tail warning is acknowledged. Startup validation and each client reader are independent, and runtime reopening can encounter a changed file. Suppressing all later diagnostics based on the startup scan would hide that change; per-reader warning deduplication would be a separate behavior change. This fix preserves the existing warning behavior and does not add suppression state.

The 512 MiB limits remain for the signed per-field and combined protocol accounting reasons in the previous reply. The %d line-number formatting follows adjacent legacy diagnostics in read_string(); I agree it could be made consistently unsigned in a separate diagnostic cleanup. No functional change is needed for this review, and the squash description will describe the final strict-length/truncated-tail policy.

@fcostaoliveira
fcostaoliveira merged commit bc8e316 into master Oct 17, 2026
129 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

--data-import: a malformed item line hangs at 100% CPU, flooding stderr (and other bad lines crash)

1 participant