Skip to content

relayburn: enum wire_str()/Display; drop serde_json::Value round-trips#350

Merged
willwashburn merged 1 commit intomainfrom
rust-enum-wire-str
May 7, 2026
Merged

relayburn: enum wire_str()/Display; drop serde_json::Value round-trips#350
willwashburn merged 1 commit intomainfrom
rust-enum-wire-str

Conversation

@willwashburn
Copy link
Copy Markdown
Member

Summary

Add wire_str() -> &'static str and impl Display to SourceKind, FidelityClass, UsageGranularity, RelationshipSourceKind, RelationshipType in crates/relayburn-sdk/src/reader/types.rs. Replace serde_json::Value round-trip sites in the SDK and the parallel hand-written converters in the CLI with direct enum-method calls.

SDK (per-record alloc removed):

  • ledger/fingerprint.rs — drop the serde_plain helper; five fingerprint fns now call wire_str().
  • ledger/reader.rs::relationship_passes — compare via wire_str() instead of two per-row to_value allocs.
  • ledger/writer.rs — drop source_str; ten callsites pass wire_str() to params!.
  • analyze/findings.rs — replace match serde_json::to_value(...) block.
  • analyze/overhead.rs::describe_applies_to — replace 3 to_value round-trips per call.

CLI (5 hand-written converters deleted):

  • compare.rs::fidelity_class_str, summary.rs::{fidelity_class_key,granularity_key}, hotspots.rs::{source_label,granularity_label}.

Sets up the foundation for #324 (the ledger Query.source comparison no longer needs a per-row Value alloc).

Closes #327.

Test plan

  • cargo build --workspace --all-targets clean
  • cargo test --workspace — 729 passed (golden snapshots verify byte-identical output)
  • cargo clippy --workspace --all-targets — no new warnings

🤖 Generated with Claude Code

Add `wire_str() -> &'static str` and `impl Display` to `SourceKind`,
`FidelityClass`, `UsageGranularity`, `RelationshipSourceKind`, and
`RelationshipType` in `crates/relayburn-sdk/src/reader/types.rs`.

Replace round-trip sites with direct enum-method calls:

SDK (per-record alloc):
- `ledger/fingerprint.rs` — drop the `serde_plain` helper; the five
  fingerprint fns now call `wire_str()` directly. Avoids per-record
  `serde_json::Value` materialization on every ingest.
- `ledger/reader.rs::relationship_passes` — compare via `wire_str()`
  instead of two per-row `to_value` allocations.
- `ledger/writer.rs` — drop the `source_str` helper; ten call sites
  now pass `wire_str()` directly to `params!`.
- `analyze/findings.rs` — replace the `match serde_json::to_value(...)`
  block in the edit-heavy detail string.
- `analyze/overhead.rs::describe_applies_to` — replace three `to_value`
  round-trips per call with a one-line `iter().map(SourceKind::wire_str)`.

CLI (parallel hand-written converters now redundant):
- `commands/compare.rs::fidelity_class_str` — deleted.
- `commands/summary.rs::{fidelity_class_key,granularity_key}` — deleted.
- `commands/hotspots.rs::{source_label,granularity_label}` — deleted.

Scope expansion noted: the directive named three enums but the
fingerprint helper handles five (including the relationship enums).
Adding `wire_str` to `RelationshipSourceKind` and `RelationshipType`
was required to fully delete `serde_plain` and is the same shape of
change. No variants or names touched.

Tests: 729 passed, 0 failed (golden snapshots verify byte-identical
output). Clippy warning count unchanged at 17.

Closes #327.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 7, 2026

Review Change Stack

📝 Walkthrough

Walkthrough

This PR unifies enum-to-string representation across the Relayburn SDK and CLI by introducing wire_str() methods and Display trait implementations for five kebab-case enums, then replacing serde_json round-trips and hand-written helper functions with direct wire string calls throughout ledger, analysis, and CLI modules.

Changes

Wire String Representation Refactoring

Layer / File(s) Summary
Type Definitions: wire_str() and Display
crates/relayburn-sdk/src/reader/types.rs
Add wire_str() -> &'static str methods and fmt::Display implementations for SourceKind, RelationshipSourceKind, UsageGranularity, FidelityClass, and RelationshipType.
SDK Ledger: Fingerprinting via wire_str()
crates/relayburn-sdk/src/ledger/fingerprint.rs
Five fingerprint functions (turn_id_fingerprint, compaction_id_fingerprint, relationship_id_fingerprint, tool_result_event_id_fingerprint, user_turn_id_fingerprint) now use source.wire_str() instead of serde_json round-trips; serde_plain helper removed; tests unchanged.
SDK Ledger: Writer Database Inserts via wire_str()
crates/relayburn-sdk/src/ledger/writer.rs
Remove source_str helper; update append_turns, append_compactions, append_relationships, append_tool_result_events, append_user_turns, append_stamp, and append_content to bind source and relationship_type wire strings directly in INSERT OR IGNORE parameters.
SDK Ledger: Reader Filtering via wire_str()
crates/relayburn-sdk/src/ledger/reader.rs
relationship_passes now compares Query.source and SessionRelationshipRecord.source using wire_str() representations instead of serde_json Value serialization.
SDK Analysis: Finding Source Strings via wire_str()
crates/relayburn-sdk/src/analyze/findings.rs
edit_heavy_to_finding derives source_str directly from session.source.wire_str() instead of serde_json::to_value matching; severity adjustment logic unchanged.
SDK Analysis: Overhead Description via wire_str()
crates/relayburn-sdk/src/analyze/overhead.rs
describe_applies_to generates comma-separated source strings by collecting wire_str() representations and sorting, replacing serde_json serialization/deserialization.
CLI Compare: Fidelity String Handling via wire_str()
crates/relayburn-cli/src/commands/compare.rs
Remove fidelity_class_str helper; update compute_excluded and format_excluded_note to use FidelityClass.wire_str() for cutoff lookup and message rendering.
CLI Hotspots: Breakdown Keying via wire_str()
crates/relayburn-cli/src/commands/hotspots.rs
Remove source_label and granularity_label helpers; update excluded-turn breakdown to key sources by source.wire_str() and granularities by granularity.wire_str().
CLI Summary: JSON Key Generation via wire_str()
crates/relayburn-cli/src/commands/summary.rs
Remove fidelity_class_key and granularity_key helpers; update fidelity_summary_to_json to generate byClass and byGranularity JSON keys using class.wire_str().to_string() and g.wire_str().to_string().

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • AgentWorkforce/burn#315: Directly modifies the same presenters and helper functions that this PR refactors into wire_str() methods.
  • AgentWorkforce/burn#314: Touches the same compare CLI implementation and string-generation sites that are refactored to use wire_str() in this PR.

Poem

🐰 Enums once wasteful, through JSON did roam,
Now wire_str() calls bring them swiftly back home,
No more round-trips through Value and String,
Just kebab-case lookups—a lighter, cleaner thing!
Display trait smiles, helpers wave goodbye, 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 26.32% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: adding wire_str()/Display methods to enums and removing serde_json::Value round-trips throughout the codebase.
Description check ✅ Passed The description comprehensively outlines the changes across SDK and CLI, lists specific files modified, explains the performance benefit (per-record alloc removal), and references related issues and test results.
Linked Issues check ✅ Passed The PR fully addresses issue #327 by adding wire_str() and Display implementations to five enums (SourceKind, FidelityClass, UsageGranularity, RelationshipSourceKind, RelationshipType), replacing all serde_json::Value round-trips in SDK modules with wire_str() calls, and eliminating five hand-written CLI converters.
Out of Scope Changes check ✅ Passed All code changes directly address the objectives in issue #327: adding enum methods, replacing Value round-trips, and removing duplicate converters. No unrelated changes are present.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch rust-enum-wire-str

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

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
crates/relayburn-sdk/src/reader/types.rs (1)

27-45: ⚡ Quick win

Add serde↔wire parity tests for all enum variants.

These wire_str()/Display mappings are now canonical in hashing/output paths, so a typo in any literal can silently drift behavior. Please add table-driven tests asserting wire_str(), Display, and serde serialization stay identical per variant.

Proposed test pattern
+#[test]
+fn source_kind_wire_and_serde_match() {
+    let cases = [
+        (SourceKind::ClaudeCode, "claude-code"),
+        (SourceKind::Codex, "codex"),
+        (SourceKind::Opencode, "opencode"),
+        (SourceKind::AnthropicApi, "anthropic-api"),
+        (SourceKind::OpenaiApi, "openai-api"),
+        (SourceKind::GeminiApi, "gemini-api"),
+    ];
+    for (v, label) in cases {
+        assert_eq!(v.wire_str(), label);
+        assert_eq!(v.to_string(), label);
+        assert_eq!(serde_json::to_string(&v).unwrap(), format!("\"{label}\""));
+    }
+}

Also applies to: 61-82, 153-169, 234-251, 361-377

🤖 Prompt for 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.

In `@crates/relayburn-sdk/src/reader/types.rs` around lines 27 - 45, Add a
table-driven unit test that iterates every SourceKind variant and for each
asserts three things are identical: the wire_str() return, the Display output
via fmt::Display (format!("{}", variant)), and the serde serialization string
(serialize the enum and compare to the expected kebab-case token). Target the
SourceKind enum and its wire_str()/fmt::Display implementations so the test
fails if any literal drifts; mirror this pattern for the other enums in the same
file by creating analogous table-driven tests covering all their variants and
serde output.
🤖 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.

Nitpick comments:
In `@crates/relayburn-sdk/src/reader/types.rs`:
- Around line 27-45: Add a table-driven unit test that iterates every SourceKind
variant and for each asserts three things are identical: the wire_str() return,
the Display output via fmt::Display (format!("{}", variant)), and the serde
serialization string (serialize the enum and compare to the expected kebab-case
token). Target the SourceKind enum and its wire_str()/fmt::Display
implementations so the test fails if any literal drifts; mirror this pattern for
the other enums in the same file by creating analogous table-driven tests
covering all their variants and serde output.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: df3c8ff9-725b-4637-87f1-f263db0d9e82

📥 Commits

Reviewing files that changed from the base of the PR and between c871a04 and 911edbe.

📒 Files selected for processing (9)
  • crates/relayburn-cli/src/commands/compare.rs
  • crates/relayburn-cli/src/commands/hotspots.rs
  • crates/relayburn-cli/src/commands/summary.rs
  • crates/relayburn-sdk/src/analyze/findings.rs
  • crates/relayburn-sdk/src/analyze/overhead.rs
  • crates/relayburn-sdk/src/ledger/fingerprint.rs
  • crates/relayburn-sdk/src/ledger/reader.rs
  • crates/relayburn-sdk/src/ledger/writer.rs
  • crates/relayburn-sdk/src/reader/types.rs

@willwashburn willwashburn merged commit e5e5b99 into main May 7, 2026
8 checks passed
@willwashburn willwashburn deleted the rust-enum-wire-str branch May 7, 2026 03:51
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.

Rust idiom: add wire_str()/Display to SourceKind, FidelityClass, UsageGranularity

1 participant