Skip to content

refactor(derive): serialize tagged WireEnum variants as structs - #1096

Merged
jlucaso1 merged 1 commit into
mainfrom
claude/wireenum-tagged-struct-serialize-f9i0z4
Jul 24, 2026
Merged

jlucaso1 merged 1 commit into
mainfrom
claude/wireenum-tagged-struct-serialize-f9i0z4

Conversation

@jlucaso1

Copy link
Copy Markdown
Collaborator

The tagged branch emitted its payload as a map, so every field name went through the serializer's value path even though each one is a compile-time constant. Serializers that intern struct keys could not intern them and had to materialize a fresh key per field per value; in a host-object backend that is a new string plus a UTF-8 decode on every event, while the #[derive(Serialize)] structs alongside them cost nothing after the first.

Switch to serialize_struct with an exact field count computed per variant (constant fields plus the discriminator, then one per present Option), so length-prefixed formats stay valid. #[wire(skip)] filtering, the omission of None fields and Deserialize are unchanged, and self-describing formats produce byte-identical output.

The new tests pin the exact JSON for the tagged enums in the repo, covering all-fields-present, omitted None, skipped and unit variants, and the fallback tag.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@coderabbitai

coderabbitai Bot commented Jul 24, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@jlucaso1, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 10 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 86d5edf2-1a20-4152-937e-b2cb239e9be3

📥 Commits

Reviewing files that changed from the base of the PR and between b8d1437 and 23f1187.

📒 Files selected for processing (2)
  • wacore/derive/src/lib.rs
  • wacore/tests/wire_enum_serde_test.rs
📝 Walkthrough

Walkthrough

The WireEnum derive macro now generates tagged enums with SerializeStruct, including conditional optional fields and skipped-field handling. Tests cover exact JSON shapes and round trips for GroupNotificationAction and Usync types.

Changes

Tagged enum serialization

Layer / File(s) Summary
Generate SerializeStruct output
wacore/derive/src/lib.rs
Tagged-mode serialization now writes discriminators and fields through SerializeStruct, computes exact field counts, omits absent options, and excludes skipped fields.
Validate tagged JSON shapes
wacore/tests/wire_enum_serde_test.rs
Tests verify complete and sparse payloads, unit and skipped variants, adjacent Usync data, and serialization round trips.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant WireEnumDerive
  participant SerializeStruct
  participant serde_json
  WireEnumDerive->>SerializeStruct: generate tagged discriminator and fields
  SerializeStruct->>serde_json: serialize JSON object
  serde_json-->>SerializeStruct: provide serialized representation
Loading

Possibly related PRs

Suggested labels: api-design

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: tagged WireEnum serialization now uses struct-style output.
Description check ✅ Passed The description accurately describes the tagged serialization refactor and the added tests.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/wireenum-tagged-struct-serialize-f9i0z4

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@wacore/derive/src/lib.rs`:
- Around line 1652-1671: Update the optional-field detection used by the
serialized length accounting around is_option_type so only fields explicitly
proven to be Option<T> are treated as optional. Avoid relying solely on the
final path-segment name; use the existing type-resolution mechanism or an
explicit optional marker, then ensure constant_count and per-field increments
apply consistently to the resolved classification.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 1ec13c9c-e6aa-44df-b7d2-7b4f0f57666d

📥 Commits

Reviewing files that changed from the base of the PR and between 040ca13 and b8d1437.

📒 Files selected for processing (2)
  • wacore/derive/src/lib.rs
  • wacore/tests/wire_enum_serde_test.rs

Comment thread wacore/derive/src/lib.rs
@greptile-apps

greptile-apps Bot commented Jul 24, 2026

Copy link
Copy Markdown

Greptile Summary

This refactor switches tagged WireEnum serialization from SerializeMap (with field names passed as runtime string values) to SerializeStruct (with field names as &'static str compile-time keys), enabling key interning in host-object backends and keeping the output byte-identical for self-describing formats.

  • wacore/derive/src/lib.rs: Replaces the single shared serialize_map call with per-variant serialize_struct calls; introduces a constant_count formula (non-skipped non-optional fields + 1 discriminator) and a len_prelude that increments __len at runtime for each Some optional field, keeping the declared length exact for length-prefixed formats.
  • wacore/tests/wire_enum_serde_test.rs: Adds a field_count::CheckFieldCount serializer that intercepts serialize_struct(len) and asserts the declared count matches the number of serialize_field calls; uses it to pin GroupNotificationAction across all variant shapes, and separately pins JSON output for tagged and adjacent-representation enums.

Confidence Score: 5/5

Safe to merge — purely a serialization-path change with byte-identical output for self-describing formats and a correct exact field count for length-prefixed ones.

The field-count formula is correct, all pattern bindings used in __len increments are in scope, the compile_error arm is properly scoped to avoid shadowing, and the new CheckFieldCount serializer validates declared-vs-written counts across all variant shapes including edge cases.

No files require special attention.

Important Files Changed

Filename Overview
wacore/derive/src/lib.rs Serialization path refactored from SerializeMap to SerializeStruct; field-count formula and Option-aware len_prelude are correct; tuple-variant compile_error! fix properly scopes the pattern to avoid shadowing.
wacore/tests/wire_enum_serde_test.rs Adds a purpose-built field-count-checking serializer that validates declared vs. written counts, JSON-pins all variant shapes, and includes a meta-test that guards the checker itself against false negatives.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A["serialize"] --> B{"match self"}
    B --> C["Unit/Fallback variant"]
    B --> D["Named variant"]
    C --> G["let __len = 1"]
    D --> H{"any Option fields?"}
    H -- no --> I["let __len = constant_count"]
    H -- yes --> J["let mut __len = constant_count; increment per Some"]
    G --> K["serialize_struct(name, __len)"]
    I --> K
    J --> K
    K --> L["serialize_field(discriminator, wire_tag())"]
    L --> M["serialize remaining fields, skip None"]
    M --> N["SerializeStruct::end"]
Loading

Reviews (2): Last reviewed commit: "refactor(derive): serialize tagged WireE..." | Re-trigger Greptile

Comment thread wacore/derive/src/lib.rs Outdated
Comment thread wacore/tests/wire_enum_serde_test.rs
Comment thread wacore/derive/src/lib.rs Outdated
@github-actions

github-actions Bot commented Jul 24, 2026

Copy link
Copy Markdown

📦 Binary size report

Metric main PR Δ
bin size (stripped) 9.89 MiB 9.89 MiB 0
bin .text 7.94 MiB 7.94 MiB 0
bin allocated (text+data+bss) 9.88 MiB 9.88 MiB 0
llvm-lines wacore 490,362 490,362 0
llvm-lines wacore copies 16,315 16,315 0
llvm-lines whatsapp-rust lib 688,104 688,104 0
llvm-lines whatsapp-rust lib copies 21,941 21,941 0
deps crates (Cargo.lock) 471 471 0
.text per crate
Crate main PR Δ
.text whatsapp_rust 1.74 MiB 1.74 MiB 0
.text wacore 652.43 KiB 652.43 KiB 0
.text wacore_binary 89.42 KiB 89.42 KiB 0
.text wacore_libsignal 161.89 KiB 161.89 KiB 0
.text wacore_appstate 22.36 KiB 22.36 KiB 0
.text wacore_noise 21.60 KiB 21.60 KiB 0
.text waproto 1.74 MiB 1.74 MiB 0
.text whatsapp_rust_sqlite_storage 510.95 KiB 510.95 KiB 0
.text whatsapp_rust_tokio_transport 39.78 KiB 39.78 KiB 0
.text whatsapp_rust_ureq_http_client 10.36 KiB 10.36 KiB 0
.text std 1.06 MiB 1.06 MiB 0
.text other deps 1.88 MiB 1.88 MiB 0

Baseline: 8cf3c6d87 (latest main run) · Head: 3a041fb59 · Graphs

The tagged branch emitted its payload as a map, so every field name went
through the serializer's value path even though each one is a compile-time
constant. Serializers that intern struct keys could not intern them and had
to materialize a fresh key per field per value; in a host-object backend
that is a new string plus a UTF-8 decode on every event, while the
`#[derive(Serialize)]` structs alongside them cost nothing after the first.

Switch to `serialize_struct` with an exact field count computed per variant
(constant fields plus the discriminator, then one per present `Option`), so
length-prefixed formats stay valid. `#[wire(skip)]` filtering, the omission
of `None` fields and `Deserialize` are unchanged, and self-describing
formats produce byte-identical output.

The tuple-variant diagnostic is scoped to its own variant pattern instead of
a wildcard arm, which would have shadowed every arm declared after it.

The new tests pin the exact JSON for the tagged enums in the repo, covering
all-fields-present, omitted `None`, skipped and unit variants, and the
fallback tag. Since JSON discards the declared field count, a small
serializer checks that count against the fields actually written, and a
deliberately miscounted struct proves the check bites.
@jlucaso1
jlucaso1 force-pushed the claude/wireenum-tagged-struct-serialize-f9i0z4 branch from b8d1437 to 23f1187 Compare July 24, 2026 20:10

Copy link
Copy Markdown
Collaborator Author

Semver Checks (informational) is red here, but it's red on main too — the same job failed on 8cf3c6d (run). Every finding is in waproto (protobuf structs and fields that moved since the published 0.6.0), and this PR only touches wacore/derive and a wacore test. Nothing to fix on this branch.

Worth noting separately: the job is meant to be informational, but continue-on-error is on the step, so the job still concludes as a failure and shows up red on every PR.


Generated by Claude Code

@jlucaso1
jlucaso1 merged commit f58cef4 into main Jul 24, 2026
25 of 27 checks passed
@jlucaso1
jlucaso1 deleted the claude/wireenum-tagged-struct-serialize-f9i0z4 branch July 24, 2026 20:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants