Skip to content

Add Memcached meta-command protocol support (memcache_meta) - #363

Merged
fcostaoliveira merged 10 commits into
redis:masterfrom
sam-obeid:feature/memcache-meta-protocol-v2
Oct 17, 2026
Merged

fcostaoliveira merged 10 commits into
redis:masterfrom
sam-obeid:feature/memcache-meta-protocol-v2

Conversation

@sam-obeid

@sam-obeid sam-obeid commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Memtier cannot benchmark Memcached's meta text protocol. Add --protocol=memcache_meta for SET, GET and multi-GET against Memcached 1.6.10+ while retaining the existing Redis, text and binary protocols.

Root cause

There is no meta protocol factory/CLI implementation. The original unmerged parser also accepts malformed value lengths and framing as completed operations, and unsupported WAIT/arbitrary-command options can reach inherited assertions.

Fix

Add meta ms/mg requests and a response parser. Each logical request ends with mn, and its reply ends at MN; a multi-GET groups its individual mg requests before one terminator. An ordered expectation queue validates each reply kind and exact section count, while the terminator detects excess sections before an operation completes. Mixed pipelined replies do not depend on a mutable write-side mode. The extra terminator costs four request and four response bytes per logical operation; relative overhead depends on the workload, and no universal throughput improvement is claimed.

Validate unsigned value lengths against the parser's representable range, complete status/number tokens and value CRLF. Reject a bare terminator without a reply. Retain valid empty values and response flags. Defined ERROR, CLIENT_ERROR and SERVER_ERROR replies consume one expected section and complete at MN through normal error accounting/retry policy. Keep the first error status even after earlier MGET hits; truly malformed replies remain parser failures. Reset partial value state, accumulated response bytes and pending expectations when reconnecting. Reject unsupported WAIT/arbitrary commands at startup; authentication, database selection, cluster and offset validation also cover meta mode. Report memcache_meta in structured configuration, help/man and completion. Existing protocols retain their implementations.

Original author commits are preserved, with a normal merge of upstream 0bb7fc5. Test reports use separate temporary directories so parallel invocations cannot overwrite each other's JSON.

Tests

  • Original integrated feature: its existing 13 tests pass. New malformed-response regression fails on eight subcases before the fix; each wrongly accepted input completes successfully rather than failing verification of the response. The newly added unsupported-option test also fails on both WAIT and arbitrary commands, reproducing their assertion exits.
  • Final head: 18/18 Python integration tests and 15/15 unit programs pass. Cases include SET/GET/MGET, hit/miss accounting, fragmented values, mixed pipelines, nine malformed replies, empty/flagged valid values, six startup rejection controls, and JSON protocol identity. Format and staged-format checks pass.
  • Malformed response kinds/counts previously completed successfully, including extra hits, missing MGET sections and GET/SET response swaps. The ordered validator rejects them; unit cases cover each mismatch and mixed pipelines. The unit also splits valid zero/binary/MGET replies at every byte boundary, including incomplete value CRLF, and checks signed libevent length bounds.
  • The new deterministic reset test covers five partial-response states with value retention enabled and disabled. It fails against the previous parser and passes after the fix. Independent socket reproductions change from a hang or inflated RX bytes to two completed misses with exactly 16 RX bytes.
  • Real Memcached 1.6.24, on an owned private Unix socket: meta/text/binary each pass 100 SETs followed by 100 GETs with no misses; meta/text multi-GET(4) each completes 100 operations with all requested keys found. These are correctness controls, not performance measurements.
  • Missing test binaries and skipped RLTest adapters now fail explicitly. The unknown-response integration test checks exit2 as well as the diagnostic. A CI matrix fallback keeps fork builds from failing before distro jobs are created when repository variables are unavailable.
  • Defined server errors after the first successful operation previously hung finite runs: all three error forms and a retry case timed out against the previous head. New cases complete three logical operations, record one terminal error or one successful retry as appropriate, and preserve following reply alignment.
  • Independent seven-lens review and fresh CI are in progress. Protocol references: official meta guide and protocol specification. The minimum follows the 1.6.10 syntax/status changes.

Affected versions

This is a new feature with no released introducing commit. Upstream 0bb7fc5 has no memcache_meta protocol. The parser and unsupported-option defects fixed during review were confined to this unmerged feature branch.

Every logical meta operation includes one extra mn server command, with 4 request and 4 response bytes. The ordered expectation queue could support omitting it for single-key operations, but this implementation deliberately retains a uniform explicit boundary. Results describe that wire workload; no throughput equivalence with clients that omit mn is claimed.

🤖 Generated with Claude Code


Note

Medium Risk
New protocol path touches connection I/O, parsing, and retry replay; mistakes could mis-account hits/misses or mishandle pipelined replies, though scope is limited to Memcached meta mode with added validation and tests.

Overview
Adds --protocol=memcache_meta so memtier can benchmark Memcached 1.6.10+ meta text commands (ms SET, mg GET/MGET) with every logical request terminated by mn and replies validated through an ordered expectation queue until MN.

The new memcache_meta_protocol in protocol.cpp implements wire encoding, strict response parsing (value lengths, CRLF, defined errors vs parse failures), and reset_state on reconnect. prepare_request_replay on abstract_protocol restores reply expectations when serialized requests are resent from shard_connection. Startup rejects --wait-ratio and --command for this mode; docs, man page, bash completion, and README document the option.

Tests: C++ memcache_meta_test (wired in Makefile.am) and a large Python suite with an in-process mock server. CI: smoke-test matrix falls back to a default image list when vars.SMOKE_TEST_IMAGES is missing on fork PRs.

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

Adds a new value 'memcache_meta' to the -P/--protocol flag, enabling
benchmarking of the Memcached meta protocol (memcached 1.6+).

Wire format
-----------
Every command is wire-terminated by 'mn\r\n' so every response is
uniformly terminated by 'MN'. This eliminates write-time/parse-time
mode-attribution races under pipelined / mixed-command workloads:

    SET:        ms <k> <l> T<e>\r\n<value>\r\n mn\r\n  -> HD\r\n MN\r\n
    GET:        mg <k> v\r\n mn\r\n                    -> VA <n>\r\n<data>\r\n MN\r\n
                                                            (or EN MN on miss)
    multi-GET:  pipelined 'mg ... v\r\n' + 'mn\r\n'      -> ...VA/EN..., MN

The wire cost is +4 request +4 response bytes per command; at typical
value sizes (>= 64B) this is < 1% of bandwidth.

Implementation
--------------
The new memcache_meta_protocol class inherits from memcache_text_protocol
to reuse the buffer plumbing and the seven assert(0) stubs for operations
not supported by either Memcached path (auth, select_db, cluster_slots,
wait, arbitrary_command). Only the four wire-touching methods are
overridden: write_command_set / write_command_get / write_command_multi_get
/ parse_response.

Performance touches:
- mg / multi-get write paths use raw evbuffer_add (no vsnprintf in the
  per-key hot path), matching the existing memcache_text multi-get pattern.
- VA <size> parsing uses strtoul (not sscanf) on the GET hot path.
- Response state machine has a single termination rule (read until MN),
  removing all conditional branches on external state in the hot loop.

Validation against memcached 1.6.41 (4 clients x 2 threads x 10K ops):
  meta SETs            135K ops/sec  (text: 131K)
  meta GETs            130K ops/sec  (text: 133K, ~3.5x less response bandwidth)
  meta multi-get(4)    256K keys/sec
  mixed --pipeline=4   246K ops/sec

Tests
-----
13 unit tests in tests/test_memcache_meta_protocol.py exercise the
parser via an in-process mock TCP server that speaks the meta protocol,
so the suite runs without requiring memcached or Redis. Coverage:

  Happy path:       single SET, single GET (hit / miss), GET against
                    pre-loaded data, multi-get with mn terminator,
                    SET -> GET roundtrip
  Status codes:     NS / EX / NF responses do not error
  Async / partial:  fragmented VA delivery (header and value across
                    two TCP sends -> rs_read_value 'need more data' path)
  Error path:       unknown server response classified as parse error
  Pipelining:       --pipeline=4 SET, mixed --pipeline=2 SET +
                    multi-get (regression for write-time/parse-time race)
  Multi-get:        deterministic VA + EN mix within a single pipeline

Tests are also discoverable by RLTest via top-level test_meta_*
adapters so they ride along with ./tests/run_tests.sh.

Documentation
-------------
Updated --help text, error message for invalid -P, manpage
(memtier_benchmark.1), README.md feature bullet, and bash completion.
@jit-ci

jit-ci Bot commented Apr 30, 2026

Copy link
Copy Markdown

Hi, I’m Jit, a friendly security platform designed to help developers build secure applications from day zero with an MVS (Minimal viable security) mindset.

In case there are security findings, they will be communicated to you as a comment inside the PR.

Hope you’ll enjoy using Jit.

Questions? Comments? Want to learn more? Get in touch with us.

Comment thread memtier_benchmark.cpp Resolved
Comment thread memtier_benchmark.cpp Resolved
Addresses two issues found in code review (PR redis#363):

1. get_protocol_name() had no case for PROTOCOL_MEMCACHE_META, causing
   --show-config and the JSON output file to report 'protocol = none'
   instead of 'memcache_meta'. Add the missing branch.

2. The --authenticate validation only rejected PROTOCOL_MEMCACHE_TEXT.
   Passing --authenticate with --protocol=memcache_meta hit the inherited
   memcache_text_protocol::authenticate() assert(0), producing a confusing
   crash report instead of the same clean usage error the text path emits.
   Extend the guard to reject memcache_meta as well.

Verified manually:
- '-P memcache_meta --show-config' now prints 'protocol = memcache_meta'
- The JSON output reports 'protocol: memcache_meta'
- '-P memcache_meta --authenticate=foo' now exits with the clean error
  'authenticate can only be used with redis or memcache_binary' instead
  of crashing.
- Existing text / binary / redis auth paths unchanged.
- All 13 meta unit tests still pass.
@sam-obeid

Copy link
Copy Markdown
Contributor Author

cursor review

@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.

@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, and for extending --protocol rather than adding a new flag. Help text, man page, completion and get_protocol_name() are all covered, and turning WAIT/--command into startup errors instead of hitting the inherited assert(0) is a nice touch. I went through the parser and the tests and have a few comments below.

  • Per-op mn cost on a benchmark tool. Every single-key ms/mg now carries an extra mn, so the server runs two commands per measured op. The code comment says the expectation queue already validates reply kinds and section counts, and that "Single-key operations could omit mn in another mode." If that's true, why keep mn on single-key ops at all instead of only on multi-get? The meta numbers we report would include a no-op that real meta clients generally don't send. The original commit's own figures show meta GETs a bit below text (130K vs 133K). I wonder if that's partly the mn. For a tool whose output people compare across protocols, I think this tradeoff deserves an explicit answer, not just a mention in the docs.

  • MN / status detection relies on pointer identity. done = m_last_response.get_status() != line and the similar check in the error branch both work out "was this the first line?" by comparing the adopted status pointer with line. I think it's correct as written, but it's subtle and easy to break in a later refactor. A small bool m_seen_section (reset in rs_initial and reset_state()) would make the intent obvious. Nitpicking, not blocking.

  • Shared replay path. prepare_request_replay() is called from shard_connection::replay_request() for every protocol. It's a no-op by default, so the risk is low, but this is the retry/reconnect path. Just checking: does req->m_keys always hold 1 for single-key rt_get requests (not 0)? Otherwise a replayed GET would push {true, 0} and the next reply would be rejected. This may be worth a second look from whoever owns the retry/replay code.

  • CI change bundled in. The ci.yml fallback for fork PRs isn't related to meta protocol support. The hardcoded image list will also quietly drift from SMOKE_TEST_IMAGES the next time someone changes the variable. Would you mind moving it to its own PR?

  • Test placement. tests/test_memcache_meta_protocol.py uses its own mock server and ignores env. Since RLTest picks it up, I think it will also run in every OSS cluster / replicas / TLS pass of run_tests.sh, bringing up a Redis env each time for tests that never touch it. Is that intended, or should it run only once, e.g. via pytest the way cli_fuzz.py does?

  • The unit-level coverage looks solid: byte-boundary splits, malformed VA lengths, the reconnect reset and replayed expectations. That's the kind of regression test that fails before the fix and passes after, which we want for parser changes. Thanks for including the failing-before evidence.

The parser itself looks careful to me. I'd mainly want the single-key mn question answered, and the CI change split out, before this merges.

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

@fcostaoliveira

Copy link
Copy Markdown
Collaborator

Owner follow-up at 1a4d0a5:

  1. Considered using mn only for MGET. Correct pipelined attribution would require an ordered per-request reply-kind queue; a mutable write-side flag is insufficient when SET/GET/MGET overlap. This feature keeps one framing rule. Help and the man page now explicitly say that each meta operation includes an mn terminator. The PR body quantifies the extra four request/four response bytes and makes no throughput or small-overhead claim.
  2. The legacy text/binary unsupported-option assertions predate this feature. I am keeping this guard scoped to the new protocol and tracking the legacy behavior separately so that its compatibility change gets its own reproducer and review. The existing shared authentication/database/cluster/offset validation already includes meta.
  3. Removed the stale review-history/state comments and unused _meta_tmp/ ignore entry.
  4. Retaining the RLTest adapters ensures the existing CI discovers these tests. They also run directly through Python unittest without RLTest. Avoiding unused Redis environments is a worthwhile harness optimization, but changing the suite discovery policy is separate from adding this protocol.

The missing quote is fixed. Independent semantic review also found partial parser state surviving reconnect: the new reset override clears that state and byte accumulation. A deterministic regression fails before the fix and passes afterward; two socket reproductions now finish with the correct counts and RX bytes. Final local validation: 16 integration cases and 15 unit programs pass. Minimum Memcached version is now accurately documented as 1.6.10, when the implemented ms syntax and HD status were introduced.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator

Follow-up at cd1f799 (runtime176fbb6):

  1. Keeping mn per logical operation is a deliberate framing tradeoff. The ordered expectations added below could support a different bare-single-op design, but the explicit terminator also lets us reject excess sections before declaring an operation complete. Help/man and the body disclose the extra no-op and its eight wire bytes; no throughput advantage or negligible-overhead claim is made.
  2. Fixed. The parser now queues expected reply kind and count in issue order: one VA/EN for each non-quiet mg, one storage status for ms, then MN. Too few/many sections or wrong-kind responses fail. Reconnect clears the expectations together with partial state. The new unit fails before the fix and passes afterward, including mixed pipelined requests. Independent end-to-end recheck is running.
  3. A missing binary now fails the unittest setup, and RLTest adapters also fail on skipped cases. The module keeps an explicit MEMTIER_BINARY override plus a source-relative default so direct standard-library execution stays available without importing the Redis/RLTest dependencies. CI supplies the override. Repeated matrix adapters retain existing discovery for now.
  4. The unknown-response case now asserts exit2 from the setup-stage guard and the parser diagnostic, with a bounded subprocess timeout.
  5. Restored tests/.gitignore to the base contents and placed the new unit target with the existing program list, keeping the metrics comment adjacent to its own target.

The expanded unit additionally checks every byte split of valid replies (including incomplete value CRLF) and the signed libevent length boundary. All15unit programs and16integration cases pass. The fork CI matrix fallback is the same independently reviewed change required by #257/#258; repository overrides retain precedence.

@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

Reviewed by Cursor Bugbot for commit 5460d2a. Configure here.

Comment thread protocol.cpp Resolved
@fcostaoliveira

Copy link
Copy Markdown
Collaborator

Follow-up at 47b0a08:

  1. Considered passing pending-request context into parse_response. The protocol parser validates sections before it can return a completed logical response, and currently owns wire framing independently of shard_connection. Keeping the small expectation queue avoids changing every parser invocation/API for this feature. The code now explicitly documents that raw serialized replay must restore the metadata. The sole raw replay path does so; independent GET/SET/MGET/mixed/verifier replay tests distinguish the missing-hook failure and pass with the hook. Metadata is copied by value, with no request-pointer ownership.
  2. The CI fallback is the same prerequisite repair in shard_connection: Support abstract Unix socket clients #257/Retry full Unix socket listen queues without blocking the event loop #258: fork context omitted the repository variable and prevented jobs from being created. Keeping it here lets this fork head run all required distro checks. An explicit repository variable still wins.
  3. Retaining the existing RLTest adapters keeps CI discovery; direct standard-library unittest execution also works. Missing binaries and skipped adapters fail now. Running the mock suite once is a possible harness optimization, not required for protocol correctness.
  4. Fixed as a merge blocker. ERROR/CLIENT_ERROR/SERVER_ERROR now consume an expected section and complete at MN as error replies. They use normal error accounting and retry policy, and preserve the first error status after earlier valid MGET sections. All three forms previously hung after one successful SET; the new regression cases now complete with exact counts and one failed-key record. A transient SERVER_ERROR retry succeeds without a failure record. Malformed reply types/lengths still fail parsing.
  5. The debug message now prints the actual rejected line before it is released.

Final local validation:18integration cases and15unit programs pass. The defined-error fix is awaiting the independent focused maintainer recheck; other protocol, replay, lifetime, output and integration reviews are recorded.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator

The expectation queue now makes single-key mn optional in principle. I considered omitting it, but retained one explicit MN boundary per logical request for this first implementation, including errors and multi-get. This is a deliberate wire workload, not a parser requirement. It adds one server command per operation as well as 4 request + 4 response bytes, so it must not be described as representative of a client that omits mn. The protocol comment now states that tradeoff explicitly; the help/man/README and PR describe the terminator overhead. Optimizing single-key framing can be a separately measured mode rather than silently changing this reviewed wire format.

For a limited sanity check, I ran three rotated repeats of 30,000 GET hits, one thread/client, 32-byte values, against the same private Unix Memcached 1.6.24 server. Median ops/s at pipeline1: initial integrated meta76.1k, final meta77.5k, final text77.5k. At pipeline32: initial meta763.7k, final meta845.6k, final text861.3k. All runs completed exactly30,000 hits. Pipeline32 meta samples ranged716.1–920.1k on this shared host; these short runs neither isolate the added checks nor establish a speedup/parity claim. They show no obvious throughput collapse in this sanity workload. No performance claim was restored.

The replay ordering was independently reviewed and exercised: five real GET/SET/MGET/mixed/verifier retries failed before the metadata hook and pass after it; LIFE also covered reset/replay ownership under sanitizers. The hook is at the existing central serialized replay path. The expectation queue remains strict, so missing metadata is rejected instead of silently assigning a reply to an unrelated request.

The CI fallback is the shared #257 prerequisite: fork context otherwise fails matrix expansion before the seven distro jobs exist. Configured values retain precedence; after #257 merges it leaves this PR’s base diff. In 3f2d0b0 I also removed the unused hit-key preload from the all-miss test (focused test passes) and rewrote the parser comment around both the expectation queue and MN boundary. Runtime is unchanged from47b0a08, which now has all seven independent lens approvals.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator

Following up on the07:21:14 revision: the single-key and verifier GET constructors both set m_keys=1; multi-get sets the requested key-list count. Setup requests with zero keys are not replayed as workload GETs. The independently exercised single-key GET/verifier replay cases confirm that contract.

MN framing is the deliberate first-version workload choice described in the previous reply: an explicit logical-operation boundary retained for all operations, with an extra server command disclosed and no claim of equivalence to clients that omit it. The pointer comparison tracks ownership of the first status line, not content equality; boundary/retained-value/error tests exercise this. I kept that reviewed state representation rather than introduce a second mutable boolean for the same state.

The self-contained mock cases intentionally remain available through the existing RLTest adapter so normal suite execution cannot omit them. They do not claim to exercise the Redis/cluster/TLS environment that launches them. This can repeat the same mock coverage in full-suite cells; moving those cases to a single dedicated job is a CI-runtime optimization, not required for parser correctness. The focused standalone invocation also remains available.

The shared CI prerequisite has now landed separately with #257 (21a7879), so it is no longer a feature-specific matrix change here. Repository-variable overrides still take precedence over the fork fallback.

@fcostaoliveira
fcostaoliveira merged commit b515485 into redis: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