Skip to content

feat(test): cross-binding wire-format equivalence harness (#1200 item 1) - #1204

Merged
robcohen merged 10 commits into
mainfrom
feat/wire-format-tests-1200
May 27, 2026
Merged

robcohen merged 10 commits into
mainfrom
feat/wire-format-tests-1200

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

Lands the cross-binding wire-format equivalence harness from issue #1200 item 1. New rustledger-wire-format-tests workspace crate depends on both rustledger-ffi-wasi and rustledger-wasm and asserts they emit structurally-equivalent JSON for the same Directive fixture.

This catches the #1168 failure mode (one binding silently drops a field the other emits) at CI time. Each audit finding from issue #1200 item 3 lands as an additional fixture row going forward.

Priority order

Following the revised priority — item 1 (harness) lands first, item 3 (audit findings) lands as fixture rows in this same crate, item 2 (TS generation) is its own design issue.

What changed

  • rustledger-ffi-wasi gains a lib target. The binary in src/main.rs was previously the only consumer of convert/types/etc. — they were private modules. Split out into:

    • src/lib.rs exposing pub mod convert + pub mod jsonrpc + DTOs re-exported at the crate root
    • src/main.rs slimmed to a 4-line shim calling rustledger_ffi_wasi::jsonrpc::process_stdin()
    • commands, helpers, and types are pub(crate) — internal to the JSON-RPC implementation
    • #![allow(missing_docs)] on the lib with a clear rationale comment (the DTOs' meaning is the JSON-RPC API doc; per-field rustdoc would duplicate it and drift; until item 2 of Prevent wire-format drift across bindings (cross-binding tests, TS generation, audit) #1200 lands ts-rs generation, the rust-side type docs are shape-only)
  • rustledger-wasm::convert module promoted from mod to pub mod so the test crate can call directive_to_json. JS consumers still use the api/parsed_ledger bindings.

  • New crates/rustledger-wire-format-tests/ with the equivalence harness:

    • assert_wire_equivalent(label, directive) helper calls both bindings, normalizes known divergences, and asserts JSON equality
    • metadata_equivalence_across_all_meta_value_variants — the direct [Feature]: WASM: add meta to directives #1168 regression test, exercises every MetaValue flavor (10 variants)
    • open_directive_minimal_equivalence — smoke test

Known divergences caught immediately

The harness caught three real divergences on first run (documented in the test rustdoc, normalized for now, each deserves its own follow-up PR to converge):

  1. meta shape: FFI-WASI bundles filename/lineno/hash with user metadata; WASM emits user metadata only.
  2. Empty meta serialization: FFI-WASI emits "meta": {}; WASM uses skip_serializing_if = "HashMap::is_empty".
  3. Optional fields: WASM emits "payee": null; FFI-WASI uses skip_serializing_if = "Option::is_none".

Test plan

  • cargo check --all-features --all-targets
  • cargo clippy --all-features --all-targets -- -D warnings
  • cargo test -p rustledger-wire-format-tests — 2/2 passing
  • cargo test -p rustledger-ffi-wasi -p rustledger-wasm --all-features — pre-existing tests unaffected by the lib-target split
  • RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps --all-features
  • cargo fmt --all -- --check

Tracks #1200.

🤖 Generated with Claude Code

Establishes the test scaffold issue #1200 asks for: a new
rustledger-wire-format-tests workspace crate that depends on both
rustledger-ffi-wasi and rustledger-wasm and asserts they emit
structurally-equivalent JSON for the same Directive fixture.

This catches the #1168 failure mode (one binding silently drops a
field the other emits) at CI time instead of waiting for a user-
filed issue. Each audit finding from issue #1200 item 3 lands as
an additional fixture row going forward.

What's in this PR:

- rustledger-ffi-wasi gains a lib target. Modules `convert` and
  `jsonrpc` are pub for the test + binary; `commands`, `helpers`,
  and `types` are pub(crate). DTOs that participate in the
  conversion surface (DirectiveJson, Posting, Amount, etc.) are
  re-exported at the crate root.

- rustledger-wasm: `convert` module promoted from private `mod` to
  `pub mod` for the test crate. JS consumers still use the
  `api`/`parsed_ledger` bindings.

- crates/rustledger-wire-format-tests/: new test crate with two
  initial tests:
    1. metadata_equivalence_across_all_meta_value_variants —
       exercises every MetaValue flavor (String, Account, Currency,
       Tag, Link, Date, Number, Bool, Amount, None). This is the
       direct #1168 regression: WASM dropped the whole meta field
       for the crate's lifetime before #1199. The exhaustive
       fixture means any future drop of a single variant fails CI.
    2. open_directive_minimal_equivalence — smoke test on a
       minimal Open directive (no metadata, no optional fields).

Three real divergences the harness caught on first run (documented
in the test module's rustdoc, normalized in the assert helper —
each deserves a follow-up convergence PR):

1. FFI-WASI's Meta bundles filename/lineno/hash with user metadata;
   WASM emits user metadata only.
2. FFI-WASI emits `"meta": {}` for empty metadata; WASM uses
   skip_serializing_if = "HashMap::is_empty".
3. WASM emits `"payee": null`; FFI-WASI uses
   skip_serializing_if = "Option::is_none".

Following the priority adjustment in
#1200 (comment) :
item 1 (harness) lands first, item 3 (audit findings) lands as
fixture rows in this same crate, item 2 (TS generation) gets its
own design issue.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Copilot AI review requested due to automatic review settings May 27, 2026 18:20
@robcohen
robcohen requested a review from a team as a code owner May 27, 2026 18:20
@codecov

codecov Bot commented May 27, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Adds a cross-binding wire-format test crate to compare FFI-WASI and WASM JSON output for shared Directive fixtures, while exposing the necessary conversion APIs for testing.

Changes:

  • Adds rustledger-wire-format-tests workspace crate with equivalence tests and normalization helpers.
  • Splits rustledger-ffi-wasi into a library plus binary shim and exposes conversion/jsonrpc surfaces.
  • Makes rustledger-wasm::convert public and updates workspace/supply-chain metadata.

Reviewed changes

Copilot reviewed 8 out of 10 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
Cargo.toml Adds the wire-format test crate to workspace/default members and workspace deps.
Cargo.lock Locks the new test crate package.
crates/rustledger-ffi-wasi/src/lib.rs Introduces the FFI-WASI library surface and DTO re-exports.
crates/rustledger-ffi-wasi/src/main.rs Converts the binary to call the library JSON-RPC entrypoint.
crates/rustledger-wasm/src/lib.rs Exposes the convert module for cross-binding tests.
crates/rustledger-wire-format-tests/Cargo.toml Defines the new unpublished test harness crate.
crates/rustledger-wire-format-tests/src/lib.rs Documents the purpose of the test-only crate.
crates/rustledger-wire-format-tests/tests/equivalence.rs Adds shared fixture builders, normalization, and equivalence tests.
supply-chain/config.toml Removes hashbrown exemptions now covered by audits.
supply-chain/imports.lock Adds imported Mozilla hashbrown audit entries.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@github-actions

github-actions Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 37.2ms ± 7.2ms 25.1 MB
beancount 894.8ms ± 7.1ms 50.5 MB
Comparison 24.1x faster 2.0x less

vs main branch (2026-05-27)

Metric main this PR Change
Time 36.1ms 37.2ms +3.0% ✅
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

…g audits (#1200 item 3)

Builds on the cross-binding equivalence harness landed earlier in
this PR by adding coverage for every directive variant and
posting-level audit candidates from issue #1200 item 3.

New fixtures (13 passing, 3 #[ignore]-pinned audit findings):

- close_directive_equivalence
- balance_directive_with_tolerance_equivalence  [ignored]
- pad_directive_equivalence
- commodity_directive_equivalence
- price_directive_equivalence
- event_directive_equivalence
- note_directive_equivalence
- document_directive_with_tags_and_links_equivalence
- query_directive_equivalence
- custom_directive_with_all_value_variants_equivalence  [ignored]
- open_with_booking_method_equivalence
- posting_with_cost_spec_equivalence
- posting_with_price_annotation_equivalence
- posting_with_flag_equivalence  [ignored]

Three real WASM-side wire-format bugs surfaced by the audit (each
documented inline; each deserves its own focused convergence PR):

1. WASM drops Posting.flag entirely from its DirectiveJson::Transaction
   posting shape. FFI-WASI emits it. Same failure mode as the
   pre-#1199 meta drop — silently absent from one binding.

2. WASM drops Balance.tolerance from its DirectiveJson::Balance
   variant. FFI-WASI emits it.

3. WASM emits Custom.values raw (bare string/number/object) — lossy:
   JS consumers can't distinguish a Date value from a String value.
   FFI-WASI uses a tagged-union shape {type, value} that preserves
   the type info.

Each failing test is marked #[ignore] with a reason pointing at
#1200. When the WASM-side fix lands, the #[ignore] comes off
mechanically and the test starts pinning the convergence going
forward.

The other 13 fixtures pass — meaning every other directive shape
agrees between bindings after the normalization step.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@github-actions

github-actions Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 791
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

…view)

Copilot caught a real bug: the previous `strip_empty_meta_and_nulls`
recursed into every nested object and dropped null values everywhere
— including inside the `meta` object on directives. That hid the
`MetaValue::None` variant from the metadata-equivalence fixture:
the test's intentional `none-key: null` entry was being stripped
from both sides before comparison, so a future binding-side drop
of the `None` variant would have looked like agreement.

Fix: rename to `strip_top_level_empty_meta_and_nulls` and limit it
to the directive's own keys (plus per-posting keys, since postings
also carry optional fields like `flag` per audit finding #1205).
Never recurse into `meta` — null inside `meta` is a legitimate
value that pins `MetaValue::None`'s wire shape.

Test result unchanged (13 passing, 3 #[ignore]) — both bindings
happen to agree on the `MetaValue::None` → `null` representation,
so the fix doesn't surface a new divergence, but it removes a
mask that would have hidden one in the future.

Addresses #1204 (comment)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 <[email protected]>
robcohen and others added 5 commits May 27, 2026 21:35
…cope cleanup

Addresses the v2 self-review findings on PR #1204:

1. **`assert_field_present` helper added**. Walks JSON via
   dot-separated path (e.g. "postings.0.cost"), panics if the field
   is missing from either binding. Used by audit fixtures that care
   about the field being present, not just the two bindings agreeing
   — equivalence alone would pass a lockstep-wrong drop. The module
   docstring now explicitly distinguishes drift detection
   (equivalence) from correctness (presence).

2. **`#[ignore]` reasons reference the specific follow-up issues**
   (#1205, #1206, #1207 — and #1208 just filed for a 4th find).

3. **Cargo.toml cleanup**: drop redundant `path = "src/lib.rs"`;
   correct the misleading "bare lib required for integration tests"
   comment to describe the actual rationale (empty lib, tests live
   under `tests/`).

4. **dev-dependency cleanup**: drop unused `jiff`. Keep `rust_decimal`
   even though only `rust_decimal_macros::dec!` is used directly —
   the macro expands to `rust_decimal::Decimal::from_parts(...)` and
   needs the crate in scope as a direct dep, not transitive.

5. **Metadata fixture applied to non-Transaction directives**:
   added `metadata_equivalence_on_open_directive` and
   `metadata_equivalence_on_document_directive` so the exhaustive
   `MetaValue`-variant check runs against multiple directive
   variants — a binding that handles meta correctly on Transaction
   but drops it on Open/Document would now fail.

6. **Module docstring** acknowledges that equivalence catches drift
   but not lockstep-wrong shapes, and points readers at
   `assert_field_present` for fixtures that need to verify presence.

7. **Builder consistency**: `Posting::with_flag` already exists in
   core (my v2 review was wrong on this); the `posting_with_flag`
   fixture now uses it instead of `let mut`.

New audit finding surfaced by the field-presence helper:

- **Both bindings drop `Document.tags` and `Document.links`** from
  their JSON wire shape — lockstep-wrong, so the original
  equivalence check passed silently. Filed as #1208 with a fix plan
  for both bindings. Test is now `#[ignore]`d pending convergence.

Test result: 14 passing, 4 `#[ignore]`-pinned audit findings (was
13/3 before).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Drive-by: rustc 1.95.0 surfaced a new clippy lint
(`clippy::unnecessary_trailing_comma`) that flagged a trailing comma
inside a `format!` macro call. Since workspace path-deps don't get
`--cap-lints`, this blocks `cargo clippy -- -D warnings` on every
crate in the workspace.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Addresses v3 self-review findings on PR #1204:

1. **Single `assert_wire_format(label, directive, &[required_fields])`
   helper** replaces the previous split between `assert_field_present`
   and `assert_wire_equivalent`. The two checks always ran together
   in practice (every audit fixture wanted both presence and
   equivalence), so the unified call site reads more clearly and is
   harder to misuse.

2. **Catches always-empty regressions, not just missing keys.**
   `is_trivially_default` rejects `null`, `[]`, and `{}` — so a
   future bug that emits `"tags": []` regardless of input still
   fails the audit, even though `tags` is technically "present".
   Previously this would have slipped past `assert_field_present`.

3. **`json_get_path` rustdoc documents the dot-separator constraint:**
   paths containing literal `.` characters (e.g. an account name in
   a JSON key) aren't expressible. None of the current fixtures hit
   this, but the docstring flags it so a future contributor doesn't
   waste time debugging a silent miss.

4. **Cargo.toml polish:**
   - `version = "0.0.0"` with a comment marking the unpublished intent
     explicitly (the previous `0.15.0` was just inherited from the
     workspace scaffold and would be confusing to a future reader).
   - Replace the em-dash in the description with `--` (avoids
     non-ASCII in package metadata).

5. **Minor:** `fixture_posting`'s `.unwrap()` → `.expect(...)` with a
   reason — consistent with the rest of the harness.

Test result unchanged: 14 passing, 4 `#[ignore]`-pinned audit
findings (#1205, #1206, #1207, #1208).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
`strip_top_level_empty_meta_and_nulls` does recurse — into `postings`
— so the "top level" framing in the name reads as inaccurate even
though the docstring captures it. Rename to
`strip_empty_meta_and_directive_nulls` and reflow the docstring to
make the "descends into postings, never into meta" rule the leading
sentence.

No behavior change.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
The `Update Exemptions` workflow checks out the base branch, then
fetches only Cargo.toml files from the PR (`pull_request_target` security
posture: trusted base + Cargo files only — `src/` is not pulled in).
With `[lib]` declared, `cargo metadata` requires `src/lib.rs` to exist
even when the table is empty, and errors with:

  can't find library `rustledger_wire_format_tests`, rename file
  to `src/lib.rs` or specify lib.path

Without the empty `[lib]` table, cargo auto-detects: `src/lib.rs`
present → lib target; absent → no lib target, metadata succeeds. The
on-branch build behavior is unchanged because `src/lib.rs` is still
present in the repo.

Reproduced locally: removing `src/lib.rs` and running `cargo metadata`
errors with the v2 Cargo.toml (which declared `[lib]`) and succeeds
with this fix.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@robcohen
robcohen enabled auto-merge (squash) May 27, 2026 19:56
@robcohen
robcohen disabled auto-merge May 27, 2026 19:58
The Update Exemptions workflow checks out the base branch, then
fetches only Cargo.toml files from the PR. When a PR adds a new
workspace member, `cargo metadata` then fails -- the new Cargo.toml
is present but there is no default target file (src/lib.rs or
src/main.rs), and cargo refuses to load such a manifest.

Extend the file-filter to also fetch */src/lib.rs and */src/main.rs
when present in the PR. Just enough to give cargo a default target
so `cargo metadata` can enumerate the dep graph.

Security model unchanged: `cargo vet regenerate exemptions` invokes
`cargo metadata`, which parses Cargo.toml and resolves the dep graph
but does NOT compile or execute the fetched source -- so pulling a
source file from an untrusted PR can't run code on the runner.
Build scripts (build.rs) are not fetched (cargo metadata doesn't
execute them either, but keeping the surface minimal).

This PR introduces crates/rustledger-wire-format-tests/ and tripped
this bug on its own Update Exemptions run. Note that the fix can't
heal this PR's check -- pull_request_target loads the workflow file
from the base branch -- but lands on merge so subsequent PRs adding
workspace members are clean.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
robcohen added a commit that referenced this pull request May 28, 2026
…) (#1212)

Both bindings' DirectiveJson::Document variants dropped tags and
links entirely from the wire output. The fields were added to
rustledger_core::Document in #1144 but never plumbed through to
either binding's DTO. Lockstep-wrong drop -- equivalence alone
would have missed it, but the new field-presence helper from #1204
caught it on first run.

Mirror the established Vec<Tag> -> Vec<String> pattern:
- Add `tags: Vec<String>`, `links: Vec<String>` with
  `skip_serializing_if = "Vec::is_empty"` to both bindings'
  Document variants.
- Populate via `d.tags.iter().map(ToString::to_string).collect()`
  in each binding's converter -- same pattern Transaction already
  uses for its tags/links.

`skip_serializing_if` (rather than always-emit, which is what
Transaction does for these vec fields) chosen here because:
- The fields are absent in today's wire output, so existing JS
  consumers parsing Document directives don't see them at all.
- skip-if-empty is backward-compatible: documents without tags
  continue to emit no tags field.
- always-emit would add `"tags": []` to every Document, which is a
  larger contract change for an audit fix.

TS declarations updated on all three surfaces (`beancount_wasm.d.ts`,
`beancount.d.ts`, the `typescript_custom_section` inline shape) with
`tags?: string[]` / `links?: string[]` matching the skip-if-empty
serialization.

The cross-binding equivalence test
(`document_directive_with_tags_and_links_equivalence`) had been
`#[ignore]`-pinned with this issue as the rationale; remove the
ignore so the test now guards convergence in CI.

Co-authored-by: Claude Opus 4.7 <[email protected]>
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