Skip to content

capnp-rust-serde-json - #8410

Merged
mikea merged 1 commit into
mainfrom
maizatskyi/2026-11-11-capnp-serde
Nov 25, 2026
Merged

mikea merged 1 commit into
mainfrom
maizatskyi/2026-11-11-capnp-serde

Conversation

@mikea

@mikea mikea commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

This PR contains a capnpc plugin that genrates:

  • serde json definition that matches JsonCodec schema for a given capnp file
  • C++ ffi that mimics capnp API and gives access to the typed serde parser to C++

The plugin does not implement all features of JsonCodec, but only the ones that are actively used.
Generator fails if unsupported features are used.

The generator code itself is probably not worth reviewewing, but generated code is: https://gist.github.com/mikea/c930fd84098ec641a2c3123c1e6cb529 contains generated files for r2 api.
Of note is the use of Option everywhere since everything is optional in capnp.

While this change tests r2 api, it has no production impact whatsoever. This will be done in follow up PRs.

@codecov-commenter

codecov-commenter commented Nov 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 67.64%. Comparing base (263efdf) to head (c72e48a).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #8410      +/-   ##
==========================================
- Coverage   67.64%   67.64%   -0.01%     
==========================================
  Files         880      880              
  Lines      221875   221875              
  Branches    33220    33220              
==========================================
- Hits       150080   150078       -2     
- Misses      52146    52148       +2     
  Partials    19649    19649              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@mikea
mikea force-pushed the maizatskyi/2026-11-11-capnp-serde branch 3 times, most recently from 9f9de68 to f0b316f Compare November 18, 2026 18:38
@mikea mikea changed the title capnp serde capnp-rust-serde-json Nov 18, 2026
@mikea
mikea marked this pull request as ready for review November 18, 2026 18:53
@mikea
mikea requested review from a team as code owners November 18, 2026 18:53
@mikea
mikea force-pushed the maizatskyi/2026-11-11-capnp-serde branch from f0b316f to ff0405e Compare November 18, 2026 18:54

@clanky-the-clanker clanky-the-clanker 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.

Superseded by the review of 70e6504c.

This review, of ff0405e8

💬 Approved with comments — No correctness, security or performance problems found. The only findings are small cleanup items (INFO/SUGGESTION): a stale include path, a dangling comment reference, a broken README anchor and a missing license header.

Findings: 3 info · 1 suggestion (4 are inline comments on the diff)

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


📋 Code Quality: 💬 2 info · 1 suggestion

No correctness bugs. Minor cleanups: a stale compile_flags entry, a comment naming a nonexistent target, untested rejection paths, and a missing license header.

Recommendation: 💬 Optional Nits

  • [INFO] compile_flags.txt lists an include path for a json_codec.rs@cxx bridge that no target generates (compile_flags.txt:41)
  • [INFO] Comment cites a nonexistent r2-api-serde-json-test; the ffi::parseR2* path is never checked for correctness (src/workerd/tests/r2-json-serde/bench-r2-json.c++:110)
  • [SUGGESTION] fixtures-test.rs is missing the Copyright/License header (src/workerd/tests/r2-json-serde/fixtures-test.rs:1)
View full review
  • compile_flags.txt:41 adds an include path for a json_codec.rs@cxx bridge that no target generates. The tests package builds only test_serde_json_ffi.rs@cxx.
  • bench-r2-json.c++:109-110 says r2-api-serde-json-test checks what the bridge parses. No such target exists: wd_rust_capnp_serde_json_library creates no test target. The ffi::parseR2* functions the benchmark calls are never checked against the fixtures.
  • The plugin's many bail! rejection paths and duplicate-name checks in codegen.rs have no negative tests. If an unsupported construct started being accepted by mistake, nothing would catch it.
  • fixtures-test.rs is missing the Copyright/License header that the other new files have.

📝 Documentation: 💬 1 info

The README has a broken internal anchor.

Recommendation: 💬 Optional Nits

  • [INFO] README links to #decoding, which has no matching heading (src/rust/capnp-serde-json/README.md:76)
View full review
  • src/rust/capnp-serde-json/README.md:76 links to #decoding, but the document has no Decoding heading.

✅ All other checks passed

🔒 Security: ✅ LGTM

No security issues. The new code is a build-time generator plus test and benchmark targets that only handle static fixture JSON.


📖 AGENTS.md: ✅ LGTM

The src/rust/AGENTS.md addition is fine.


⚡ Performance: ✅ LGTM

No performance issues found.


Reviewed commit: ff0405e8

Comment thread compile_flags.txt Resolved
Comment thread src/rust/capnp-serde-json/README.md Resolved
@mikea
mikea force-pushed the maizatskyi/2026-11-11-capnp-serde branch from ff0405e to 70e6504 Compare November 18, 2026 19:03

@clanky-the-clanker clanky-the-clanker 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.

Superseded by the review of 22f03b9e.

This review, of 70e6504c

💬 Approved with comments — No correctness, security or performance problems found. Four small cleanup notes from the last review are still open: a stale include path, a comment that names a test target that doesn't exist, a broken README anchor and a missing license header.

Findings: 3 info · 1 suggestion (1 is an inline comment on the diff)

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


📋 Code Quality: 💬 2 info · 1 suggestion

No correctness defects. Three small cleanup notes from the last review are still open.

Recommendation: 💬 Optional Nits

  • [INFO] compile_flags.txt lists an include path for a json_codec.rs@cxx bridge that no target generates (compile_flags.txt:41)
  • [INFO] Comment names a nonexistent r2-api-serde-json-test; nothing checks the ffi::parseR2* output against the fixtures (src/workerd/tests/r2-json-serde/bench-r2-json.c++:112)
  • [SUGGESTION] fixtures-test.rs is missing the Copyright/License header (src/workerd/tests/r2-json-serde/fixtures-test.rs:1)
View full review
  • compile_flags.txt:41 adds an include path for a json_codec.rs@cxx bridge that no target generates. The tests package builds only test_serde_json_ffi.rs@cxx, and the next line already covers it.
  • bench-r2-json.c++:111-112 says r2-api-serde-json-test checks what the bridge parses, but no such target exists. The benchmark only confirms that the ffi::parseR2* functions don't throw, so nothing checks their output against the fixtures.
  • fixtures-test.rs has no Copyright/License header. The other new files in that directory have one.

📝 Documentation: 💬 1 info

One broken README anchor remains.

Recommendation: 💬 Optional Nits

  • [INFO] README links to #decoding, which has no matching heading (src/rust/capnp-serde-json/README.md:76)
View full review
  • src/rust/capnp-serde-json/README.md:76 links to #decoding, but the README has no Decoding heading.

✅ All other checks passed

🔒 Security: ✅ LGTM

The new code is a build-time generator plus a runtime helper crate and test/benchmark targets. JSON parsing goes through serde_json with its default recursion limit. The hex, base64 and Int64 decoders return errors on bad input instead of panicking.


📖 AGENTS.md: ✅ LGTM

The src/rust/AGENTS.md addition is fine.


⚡ Performance: ✅ LGTM

No performance issues found.


Reviewed commit: 70e6504c

@mikea
mikea force-pushed the maizatskyi/2026-11-11-capnp-serde branch from 70e6504 to 22f03b9 Compare November 18, 2026 19:19

@clanky-the-clanker clanky-the-clanker 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.

Superseded by the review of c72e48ac.

This review, of 22f03b9e

✅ Approved — The earlier cleanup notes are all fixed, and nothing new came up in the files changed since the last review or in the rest of the change.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

JSON parsing goes through serde_json with its default recursion limit. The hex, base64 and Int64 decoders return errors on bad input instead of panicking. The plugin runs at build time and only reads the CodeGeneratorRequest the schema compiler sends it, and its output paths come from schema file names.


📖 AGENTS.md: ✅ LGTM

The src/rust/AGENTS.md addition is fine.


📋 Code Quality: ✅ LGTM

The earlier notes are fixed. compile_flags.txt:41 now points at test_serde_json_ffi.rs@cxx, which src/rust/capnp-serde-json/tests/BUILD.bazel generates. The bench-r2-json.c++ header no longer names a test target that doesn't exist, and the benchmark checks the decoded fields of each fixture before it measures. fixtures-test.rs starts with the Copyright/License header. The fixtures match the r2-api.capnp field names and UInt64 defaults, and the testonly/cxx_bridge_src wiring matches wd_rust_crate.bzl.


⚡ Performance: ✅ LGTM

No performance issues found.


📝 Documentation: ✅ LGTM

The README no longer links to the missing #decoding anchor. No other documentation issues.


Reviewed commit: 22f03b9e

capnpc-rust-serde-json generates Rust types with serde derives from
Cap'n Proto schemas. It covers JSON only, not the Cap'n Proto wire
format: the types' JSON is that of the C++ capnp::JsonCodec with
handleByAnnotation(), the codec workerd uses for the R2 binding, so
Rust can exchange JSON with that C++ code and the services it talks to.

The types are idiomatic serde, not a port of every behaviour of
JsonCodec. JSON that JsonCodec writes decodes to the same values in
Rust, and JSON that Rust writes decodes to the same message in C++;
JSON that only other writers produce may decode differently.

- Structs become structs, and unions become enums: internally tagged
  with $Json.discriminator, externally tagged without, and flattened
  into their struct. $Json.name, $Json.flatten (without a prefix),
  $Json.base64 and $Json.hex map onto serde attributes.
- Serialize and Deserialize are derived. Missing fields take the
  schema defaults through #[serde(default)] and a generated Default
  impl. Fields that hold their schema defaults are left out, as with
  HasMode::NON_DEFAULT, which the R2 binding sends its requests with.
- 64-bit integers are decimal strings, and numbers are read too.
- A union member of a pointer type is never null in Rust, where C++ may
  leave it null; both read and write the same.

The plugin supports what r2-api.capnp needs and fails with an error
naming the declaration for the rest, rather than reproduce constructs
nothing uses: floats, enum fields, Void fields, Data without
$Json.base64 or $Json.hex, lists other than of integers, Text and
structs, Json.Value, schema defaults of pointer fields and union
members, groups other than flattened named unions, tagged union
members other than Void and flattened structs, valueName, flatten
prefixes, structs that contain themselves, interfaces, AnyPointer and
generics. Enum declarations are skipped, and constants are generated
for Bool and integer types.

The runtime crate //src/rust/capnp-serde-json holds the serde adapters
the generated code uses (Int64, Base64, Hex and the skip_serializing_if
predicates), and capnp_serde_json::from_slice(), which decodes JSON
bytes with the results of serde_json::from_slice() but checks their
UTF-8 once rather than string by string, which takes longer for the
short strings and keys of Cap'n Proto messages. Hex decodes through a
table, with no early exit, so that it vectorizes; data_encoding's
decoder made R2's head responses, which carry five checksums, about 10%
slower to decode.

wd_rust_capnp_serde_json_library() runs the plugin and wraps its output
in a crate. //src/workerd/api:r2-api-serde-json is the crate for
r2-api.capnp, with the C++ bridge below; no production code uses it.

With ffi = True, the macro also generates, for each schema foo.capnp, a
cxx bridge (module foo_serde_json_ffi of the crate, header
<pkg>/foo_serde_json_ffi.rs.h) through which C++ decodes JSON into the
generated types and reads them in place, without copying them into a
Cap'n Proto message. The API follows capnp's C++ readers:

- parseFoo(json) decodes a document into a rust::Box<Foo>, and throws
  if it is not one of Foo.
- Bool and integer fields have getX(). Text, Data and list fields have
  getX(), a rust::Str or rust::Slice into the value (empty if null),
  and hasX(). Struct fields' getX() returns a reference, to a static
  default if null.
- Unions have which(), isX() and getX(), which returns the member's
  default if another member is set. A struct's unnamed union has them
  on the struct.
- Every struct and named union is an opaque Rust type in the file's
  $Cxx.namespace followed by ::serde, so that the names do not clash
  with those of capnpc-c++.

C++ cannot read types that other schema files declare; the bridge has
a comment in place of each such accessor.

The bridge must be in the crate of the types, since cxx implements its
traits for them and the getters are their inherent methods (private to
the bridge's module). The compiler passes plugins no options, so
:capnpc-rust-serde-json-ffi is the plugin built with
CAPNPC_RUST_SERDE_JSON_FFI, which makes it write the bridges too.
rust_cxx_bridge() gets a testonly argument for testonly schema crates.

The parse functions decode with capnp_serde_json::from_codec_input(),
which, like JsonCodec::decode(), takes the input to end at its first
NUL byte, so that it may be a kj::String's array with its terminator.
It finds that byte with memchr, a new direct dependency (already in
the lock file through other crates).

tests/test.capnp has every construct the plugin supports, and both
tests hold the same hardcoded JSON documents. capnp-serde-json-test
decodes, in Rust, documents as JsonCodec writes them by default, checks
the values and the JSON the Rust types write, and checks what Rust
rejects. capnp-serde-json-ffi-test reads every construct from C++
through the bridge, against JsonCodec: each document the bridge
decodes, JsonCodec must decode to a message whose fields read the same,
and JsonCodec with HasMode::NON_DEFAULT must write the JSON the Rust
test expects of the Rust types. The tests run no tools; Bazel builds
every crate the plugin generates.

bench-r2-json measures decoding the R2 binding's JSON with capnp's
JsonCodec, as r2-bucket.c++ uses it, against the generated types of
r2-api-serde-json. The documents in r2-json-serde/fixtures.rs are R2
responses and requests in the forms R2 exchanges them in. Each gets four
cases: JsonCodec with one codec and with a new codec per message,
capnp_serde_json::from_slice() through r2-json-serde's own bridge, whose
types wrap r2-api-serde-json's, and the parse function of
r2-api-serde-json's bridge, which C++ code would call. Before it
measures, each case but from_slice() checks fields of one decoded
document, through capnp's readers or through the bridge's getters;
r2-json-serde's Rust tests check what from_slice() decodes. In an
optimized build serde_json decodes these documents several times as fast
as JsonCodec, and the bridge's parse functions are about as fast as
from_slice(). Requests, which only tests decode, go through serde's
buffering of flattened and internally tagged values.

wd_cc_benchmark() executables get their own main(), which under
`bazel test` adds --benchmark_dry_run=true, so that the test runs each
benchmark once, to check that it works, and measures nothing;
recordAllocationStats() does nothing in a dry run. `bazel run`, and
so CodSpeed, still measures.

src/rust/capnp-serde-json/README.md gives an overview of the plugin,
the runtime crate, the C++ bridge and the tests, and has compatibility
tables: every schema construct, whether the plugin supports or rejects
it, and every way the JSON that Rust reads and writes differs from
JsonCodec's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mikea
mikea force-pushed the maizatskyi/2026-11-11-capnp-serde branch from 22f03b9 to c72e48a Compare November 25, 2026 18:12

@clanky-the-clanker clanky-the-clanker 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.

✅ Approved — No issues in the files changed since the last review or in the rest of the change. The JSON parser keeps serde_json's default nesting limit.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

from_slice() in src/rust/capnp-serde-json/lib.rs parses with serde_json's default deserializer, which limits nesting to 128 levels. The unbounded_depth feature already enabled in deps/rust/Cargo.toml:96 only makes disable_recursion_limit() available, and this crate never calls it. The hex, base64 and Int64 decoders return errors on bad input instead of panicking.


📖 AGENTS.md: ✅ LGTM

The line added to src/rust/AGENTS.md is fine.


📋 Code Quality: ✅ LGTM

The new testonly parameter on rust_cxx_bridge in build/wd_rust_crate.bzl reaches both the genrule and the cc_library. It defaults to False, and wd_rust_capnp_serde_json_library passes it through. The new memchr 2.8.3 entry is the same in Cargo.toml, Cargo.lock and cargo-bazel-lock.json.


⚡ Performance: ✅ LGTM

No performance issues found.


📝 Documentation: ✅ LGTM

No documentation issues found.


Reviewed commit: c72e48ac

@mikea
mikea merged commit aea9e5c into main Nov 25, 2026
24 checks passed
@mikea
mikea deleted the maizatskyi/2026-11-11-capnp-serde branch November 25, 2026 18:30
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.

3 participants