Skip to content

Add fatal JSON summaries and make lifecycle notices debug-only - #25

Merged
fcostaoliveira merged 6 commits into
masterfrom
add-json-error
Oct 17, 2026
Merged

fcostaoliveira merged 6 commits into
masterfrom
add-json-error

Conversation

@elad-ash

@elad-ash elad-ash commented Mar 30, 2017 •

Copy link
Copy Markdown
Contributor

Problem

With --json-out-file, a failed run can leave configuration or partial results without a structured indication of failure. JSON creation/finalization notices also clutter ordinary stderr.

Root cause

The current writer preserves and closes partial JSON, but does not record the failure category. The original PR predates the current output and shutdown handling and cannot safely replace those paths wholesale.

Fix

Add an optional top-level FATAL_ERROR string after JSON initialization, retaining configuration and results already emitted. Fixed summaries distinguish connection setup, worker, verification, other output, and early termination failures; detailed diagnostics remain on stderr and existing exit codes remain authoritative. Close the failed-key log before finalizing JSON so its late failures are included. Move JSON lifecycle notices behind --debug.

Successful runs, recovered errors and graceful interrupts do not gain the field unless another failure occurs. Pre-initialization validation leaves existing JSON untouched. JSON write failure, crashes and forced termination cannot guarantee a complete artifact. The writer escapes error text, closes existing nesting and records only the first summary.

Tests

  • Before/after: on current master, four of the five new focused cases fail; all five pass with this change. They cover success, debug lifecycle, setup timeout, verification failure with retained results, and another output failing on /dev/full.
  • All 14 unit programs and six early-exit JSON integration cases pass.
  • A direct writer probe under ASan/LSan/UBSan preserves nested content, escapes quotes/control characters, replaces malformed UTF-8, avoids duplicate summaries, and tolerates repeated close and post-close writes.
  • Private explicit test endpoints and dummy credentials were used. A further Unix-peer test completes four benchmark operations, removes the listener before verification, and confirms the completed results survive with the verification-failure category. Two existing synchronous early-exit tests also pass with the clarified generic finalization wording. All seven independent reviews pass. A combined tree with PR258/363/129/553 passes 15 unit programs and 11 focused integration executions; final CI is still running.

Affected versions

This adds a new JSON failure-summary field; no released version provides this contract. The comparison baseline is current master 21a7879802a6a901a2f4079868e67c70e4da9a0b. Consumers should continue checking the process exit status and accept the optional top-level field.


Note

Low Risk
Adds optional JSON metadata and stderr noise reduction on shutdown paths; behavior for successful runs is unchanged aside from quieter stderr.

Overview
Failed runs with --json-out-file now get a top-level FATAL_ERROR string in the JSON artifact while keeping configuration and any results already written. json_handler::write_error() records one escaped summary (connection setup, worker stop, output write failure, verification failure, or generic early termination); stderr and exit codes stay the source of detail.

Shutdown in main() picks the category in fixed priority and closes the failed-keys log before finalizing JSON so late log failures count as output errors. The atexit JSON closer writes the generic early-termination message when the process exits without normal finalization.

JSON create/close/save notices move behind --debug via benchmark_debug_log. README documents the contract; tests cover success (no field), each failure class with retained stats, and updated early-exit expectations.

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

Release note

JSON creation, saving and close notices now require --debug. Error diagnostics and exit statuses are unchanged; failed JSON results may include the optional FATAL_ERROR summary.

🤖 Generated with Claude Code

fcostaoliveira added a commit that referenced this pull request Jun 2, 2026
…and tracking (#435)

* fix(resp3): accept push frames; count nil _ as miss in arbitrary command tracking

Two RESP3 correctness bugs surfaced by the 2.4 readiness review.

#27: aggregate_type() lacked '>'. A server-pushed message (pubsub,
keyspace notifications, client tracking invalidation) on a RESP3
connection hit the "unsupported response" path and dropped the
connection. Now accepts and drains push frames inline.

#25: SingleNullBulk and ArrayPerElementNulls miss sentinels only
recognised RESP2 nil shapes ($-1/*-1/*0). RESP3 nil (_\r\n) was
miscounted as a hit, silently understating miss rate and
suppressing --miss-rate-threshold warnings.

Refs: 2.4 review findings #25 + #27

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(resp3): flag RESP3 null at construction; distinguish from literal "_"

Bugbot flagged that the ArrayPerElementNulls walker used a content
heuristic (value_len==1 && value[0]=='_') that couldn't tell a
RESP3 null parsed via single_type from a real bulk value of literal
"_" parsed via blob_type. Both produce identical bulk_el.

Added bulk_el::is_resp3_null flag, set only when single_type
constructs the element for type byte '_'. Walker now reads the flag
directly instead of inferring from content. Test added that stores
"_" values and asserts they are NOT counted as misses.

Refs: bugbot LOW on PR #435

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(resp3): drain server-pushed frames without delivering as reply

Reviewer caught that the prior commit accepted RESP3 push (>) into
aggregate_type() but didn't suppress its effect on m_last_response.
The push frame fully parsed AS a reply, response_ended() returned 1,
and memtier dequeued the push as the reply to the next in-flight
command -- corrupting latency attribution + hit/miss accounting.

Adds an m_push drain-mode flag:
- Set when a push aggregate is encountered at top level
- Suppresses every mutation to m_last_response while true
- Cleared in response_ended(), which returns false so the parser
  continues to read the actual reply
- Reset on rs_initial transition

Refs: 2.4 review of PR #435 (R1 CRITICAL).

* fix(resp3): reset m_response_len when draining push frame

Bugbot caught that response_ended()'s m_push drain returned false
without resetting m_response_len. The accumulated push frame bytes
stayed in the counter and contaminated set_total_len() for the
actual reply, skewing bandwidth and per-op size statistics.

Resetting m_response_len to 0 at the push-drain-complete site
matches the behaviour at rs_initial (the only other site where
m_response_len is reset).

Refs: bugbot LOW on PR #435 (follow-up).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(resp3): clear both m_push and m_attribute together in response_ended()

Bugbot caught that if an attribute (|) appears nested inside a push
frame (>), and both complete at the same response_ended() call,
the m_attribute branch fired first and returned false, leaving
m_push set. The parser then consumed the actual command reply as
push-drain data, desynchronizing the connection.

response_ended() now clears whichever flags are set in a single
call and returns false if either was set.

Refs: bugbot LOW on PR #435 (follow-up).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

---------

Co-authored-by: Claude Sonnet 4.6 <[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 bringing this old one up to date against current master. I went through the writer, the finalization reordering and the tests, and left a few comments below.

  • The JSON schema change is additive. It's a single optional top-level key, appended after everything else, and successful runs don't get it. That's about as low-risk as an output-format change gets here (it's the "push it to the end" shape from PR#60). I think the stderr change matters more for compatibility: Json file ... created... / Json file closed. / Saving JSON output file: stop printing by default, and the existing test_out_file_replaces_existing assertion had to be flipped to cover that. Moving them to --debug is reasonable, since we've pushed back on noisy default output before. Still, did you consider whether anyone's wrapper scripts look for these lines? Either way, I'd call it out in the release notes rather than leave it buried in the PR body.

  • On early exits, every path ends up with the same generic "Benchmark terminated before normal finalization". That includes reconnect failure mid-run and the MGET allocation failure, which is exactly where a structured category would help a consumer most. I wonder if the exit(failure_exit_code()) sites could set a category (a static fixed string, like the normal path uses) for the atexit hook to write, instead of the hook always guessing. Not a blocker if the answer is "follow-up", but as it stands the README's "distinguishes connection setup, worker, ... failures" only holds on the normal path.

  • Just checking the precedence on the normal path: if a run has both worker/connection failures and failed verification, only the first is recorded. The README documents this, so I'm fine with it. I just want to confirm it's intentional that a consumer can't tell verification also failed without parsing stderr. "client verifications results" is still in the document, so maybe that's enough.

  • JSON_handler.cpp now includes memtier_benchmark.h just for benchmark_debug_log, so the writer depends on the main binary's logging symbol. Today that's fine because it's only linked into memtier_benchmark, but it would bite a unit test that links JSON_handler.cpp on its own (your ASan writer probe presumably had to stub this). Is that dependency acceptable to whoever owns the output code, or would a small logging hook be preferable?

  • Moving the failed-keys logger close ahead of the JSON close looks right to me, since workers are joined by then. The old comment explained why the early-exit paths skip that close, though, and it got dropped. I'd keep a line of that in the new comment.

  • Tests: thanks for the fails-on-master/passes-with-fix cases and the /dev/full output case. That's the bar PR#364 set for JSON-integrity fixes. Nitpicking: test_json_fatal_error.py introduces a new pattern, a unittest.TestCase wrapped by an _adapt shim into RLTest functions, with its own socketserver peer. The rest of the suite uses env directly (as test_json_early_exit.py does). The fake peer is needed for the silent/zzz replies, but I wonder if the shim could be dropped in favor of plain env-style functions so failures report the way the rest of the suite does.

  • Nitpicking: the branch has the two original 2017 commits plus a master merge and three follow-ups, so I'd squash on merge. Also, the PR body mentions "seven independent reviews are still pending", which reads like leftover generated text and is probably worth trimming.

The core change looks sound to me. I'd mainly like an answer on the early-exit category question and a release-note mention of the quieter stderr before this merges.

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

@fcostaoliveira fcostaoliveira changed the title Add json error Add structured fatal summaries to JSON results Oct 17, 2026
@fcostaoliveira fcostaoliveira changed the title Add structured fatal summaries to JSON results Add fatal JSON summaries and make lifecycle notices debug-only Oct 17, 2026
@fcostaoliveira

Copy link
Copy Markdown
Collaborator

Thanks. The output decisions are explicit now:

  1. Debug-only JSON lifecycle notices were part of this PR's original request, alongside structured fatal errors. I am retaining that behavior and have made both changes visible in the title, body and README. Detailed error diagnostics and exit statuses remain unchanged. Wrappers should use the process status and artifact, rather than these informational notices; --debug retains the notices.
  2. I am retaining the requested FATAL_ERROR string contract. It is an optional failure-only root member, documented as such; consumers must branch on known members/types. An object would still require consumers to distinguish this new non-statistics member, so it would not make arbitrary iteration over root statistics safe. No existing root member changes type.
  3. I changed the generic category to “Benchmark terminated before normal finalization,” which makes no claim about how much result data exists. The new targeted test completes four SETs, removes the listener and then fails verifier connection setup: current code follows normal cleanup with “Data verification failed or did not complete” and preserves all four operations. The two synchronous early-exit tests pass with the clarified generic category. The earlier comment suggesting verification necessarily exits was also corrected.
  4. The peer deliberately makes these schema/lifetime tests independent of RLTest topology and transport; repeated matrix execution does not establish TLS or cluster coverage. Retaining the common self-contained harness keeps ordinary and failure assertions on the same output path. Existing integration tests continue to exercise real servers. The Unix early-exit tests explicitly document their standalone plaintext endpoint too.
  5. Merge will be squash-only after seven independent lenses, fresh final-head CI, and current comment/thread gates.

Published followup: 521c16b31206d0997cf2399a80fc6b4f71ae58f3.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator

Follow-up on the07:53:15 edit:

  • The title, README and PR body explicitly call out debug-only JSON lifecycle notices as a separate visible behavior. This remains within the original PR request; error diagnostics and process statuses are preserved.
  • 17e65dd now runs the early-exit helper with --debug and retains the exact one-close-notice assertion. All six early-exit tests pass. A notice counts successful closure, not every invocation of an idempotent close(); independent sanitizer probes also exercise repeated close and post-close writes directly. Default quiet behavior remains tested separately.
  • Generic atexit categorization is intentional, including early output-open/truncate failures. I found no successful exit(0) after registration: version/help/validation handling precedes JSON initialization. The normal successful path closes/deletes the writer and clears the global pointer. Exit status and stderr remain authoritative.
  • README now states the summary is not an exhaustive failure list and documents setup > worker > other output > verification precedence. Independent process tests cover simultaneous setup/output and output/verification failures.
  • The unittest adapter lets the same self-contained cases run directly against an installed binary without RLTest dependencies and through the normal suite. BUILD independently ran the installed cases with Python site imports disabled. The peer is deliberately plaintext/standalone in every matrix cell; repeated execution is not additional transport coverage. Retaining the originally requested FATAL_ERROR spelling avoids introducing an unrelated API redesign.
  • The extra blank line is removed. All changes after521c16b are documentation/test-only; runtime is unchanged. SEM, OUT, TEST and BUILD reviews approve, with LIFE/INTER/MAINT finishing. Squash-only merge remains gated on all reviews and final CI.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator

Replying to the07:59:44 revision:

The early-exit category is deliberately generic in this change. The README explicitly limits specialized categories to normal finalization. Adding category assignment to every historical exit site would broaden this patch; it can be a follow-up without weakening the existing exit status or detailed stderr. The documented priority is intentional, and verification's existing result object is retained when emitted.

The writer is an internal executable component. Its debug logging dependency is acceptable here; BUILD independently compiled and linked a direct writer consumer with the normal logging callback stub, alongside the full no-TLS VPATH build/install and14 unit programs. A new public logging hook is unnecessary for the current use.

The early-exit failed-key-logger lifetime explanation remains at global_failed_keys_logger() in retry_policy.cpp: those paths can still have live workers, so the process-lifetime logger is not destroyed/closed there. Only main's joined-worker normal path was reordered. The new nearby comment says workers have joined; no early-exit logger ownership changed. Independent LIFE and TEST checks cover concurrent failure logging, early exits and a late fclose-only error.

There is no tracked release-notes/changelog file in this repository. I have added an explicit release-note paragraph to the PR body for the next release: “JSON creation, saving and close notices now require --debug. Error diagnostics and exit statuses are unchanged; failed JSON results may include the optional FATAL_ERROR summary.” This makes the stderr change reviewable as a release-facing compatibility note.

The unittest adapter intentionally keeps the same cases runnable directly against an installed binary and in RLTest; failures propagate full test details. All six early-exit cases pass with the debug close check. The final merge will be a squash. Body counts and review status are being refreshed; no further runtime change is needed for these points.

@fcostaoliveira
fcostaoliveira merged commit b6e9d78 into master Oct 17, 2026
131 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.

2 participants