Skip to content

fix(wasm): inventory query cells carry each position's cost - #2491

Merged
robcohen merged 3 commits into
mainfrom
fix/wasm-inventory-cell-cost-2402
Oct 8, 2026
Merged

robcohen merged 3 commits into
mainfrom
fix/wasm-inventory-cell-cost-2402

Conversation

@robcohen

@robcohen robcohen commented Oct 7, 2026 •

Copy link
Copy Markdown
Member

What

The wasm query result's inventory cell dropped each position's cost. PositionValue had only units, so BALANCES and sum(position) over wasm showed lots at different costs as bare 5 X and -2 X side by side. A single position cell already carried its cost, and rledger query, the component's WIT (#1398) and beancount all report 5 X {100 USD} and -2 X {90 USD}.

  • PositionValue gains cost: Option<CostValue>. The field is skip_serializing_if = "Option::is_none" / ts(optional), as on CellValue::Position, so a cost-less position omits the key.
  • In value_to_cell, the Position and Inventory arms now both build their element through one position_value helper, so they cannot drift again.
  • scripts/regen-bindings.sh regenerated bindings/index.d.ts (cost?: CostValue), index.schema.json and types.py. RUSTLEDGER_TS_CHECK=1 passes locally.

The repro ledger from the issue now returns:

["Assets:Stock",{"positions":[{"units":{"number":"5","currency":"X"},"cost":{"number":"100","currency":"USD","date":"2020-01-02"}},{"units":{"number":"-2","currency":"X"},"cost":{"number":"90","currency":"USD","date":"2020-01-03"}}]}]

Wire-format decision: no version bump, no Breaking entry

The change is additive. The new key is optional and absent exactly when there is no cost, so existing readers that ignore unknown keys keep working, and the TS type only gains an optional property. The one visible effect is for a consumer that compares whole result rows byte for byte (as wasm_booking_method.rs did): it now sees the key. The CHANGELOG ### Fixed entry says so. Crate versions are set at release time by set-version, so nothing is bumped here. The in-repo MCP server's formatCell now renders the cost (5 X {100 USD, 2020-01-02}) for inventory and position cells. A position without a cost, or a wasm package without the field, renders as before.

Tested

  • New host unit test inventory_cell_keeps_each_position_cost_2402 (convert.rs). It pins both lots' costs and dates, the omitted key on a cost-less position, and that an inventory element is identical to the same position's Position cell.
  • tests/wasm_booking_method.rs now asserts the 100 USD and 90 USD costs on all four wasm entry points, plus the Ledger.fromCache round-trip. wasm-pack test --node -- --test wasm_booking_method: 4 passed.
  • Fail without the fix: with the Inventory arm forced to cost: None, the unit test panics and every wasm entry point fails with BALANCES must hold the 5 X {100 USD} and -2 X {90 USD} lots apart.
  • cargo test -p rustledger-wasm --all-features: 153 + 2 passed. cargo clippy --workspace --all-features --all-targets -D warnings is clean, and so is cargo doc -D warnings -p rustledger-wasm.

Closes #2402

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

PositionValue, the element of an inventory cell, had only `units`, so
BALANCES or sum(position) over wasm showed lots at different costs as
bare units side by side. A single position cell already carried its
cost; the CLI, the component's WIT and beancount all report it.

PositionValue gains an optional `cost` (skipped when absent, as in the
Position cell), and both the Position and Inventory arms of
value_to_cell now build their element through one `position_value`
helper so they cannot drift again. TS, JSON Schema and Python bindings
regenerated with scripts/regen-bindings.sh.

Tests: a host unit test pins the inventory cell's JSON (costs, dates,
an omitted cost key on a cost-less position, and equality with the
Position cell), and wasm_booking_method.rs now asserts the 100 USD and
90 USD costs on every wasm entry point. Both fail with the cost dropped
from the Inventory arm.

Closes #2402

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen requested a review from a team as a code owner October 7, 2026 20:24
@github-actions

github-actions Bot commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 44.9ms ± 1.2ms 835.5ms ± 22.8ms 18.6x 50.8 MB / 50.2 MB
investment 68.1ms ± 0.6ms 3004.7ms ± 6.3ms 44.1x 55.1 MB / 58.1 MB
fifo 65.2ms ± 0.7ms 15467.9ms ± 138.2ms 237.3x 55.0 MB / 57.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 44.0ms ± 0.3ms 44.9ms ± 1.2ms +2.2% ✅ within noise 50.9 MB → 50.8 MB (-0.1%)
investment 68.6ms ± 4.4ms 68.1ms ± 0.6ms -0.7% ✅ within noise 55.0 MB → 55.1 MB (+0.1%)
fifo 65.4ms ± 1.1ms 65.2ms ± 0.7ms -0.3% ✅ within noise 55.0 MB → 55.0 MB (-0.0%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 0.6ms, investment 2.0ms, fifo 0.6ms), and is at least 5%.
10,000 transactions per shape · 20 runs, 3 warmup · hyperfine

What do these numbers mean?
  • simple — Two-posting transfers, one currency. The historical workload — keep as the floor, not as the benchmark.
  • investment — Cost specs, per-unit prices and lot reductions. Exercises booking and inventory, which simple leaves at 0.3%.
  • fifo — Bare {} reductions against a FIFO account — how FIFO sells are normally written. The other four shapes reach the ordered-selection path twice in 2k transactions between them, so it was effectively unprofiled until it turned out to be quadratic (plan_ordered scans every lot per reduction: FIFO ledgers are quadratic (8.8s at 20k transactions) #2083).
  • vs base: the PR and the base-branch commit it is built on, built and measured in the same job
  • RSS: peak resident set size, a single sample — reported without a verdict because there is no spread to test it against
  • A shape with no beancount column is one bean-check reports errors on; it is timed for rledger only

@github-actions

github-actions Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 179 masked)
Full AST Match 100%
Total Files 819
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
    The headline is the EFFECTIVE rate, after pairs where beanquery
    itself is wrong are masked. raw is the same run with nothing
    masked. A widening gap means the registry grew, not that rledger
    changed.
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

@codecov

codecov Bot commented Oct 7, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Review follow-up for #2402. The MCP server's formatCell read only
`units` from inventory positions, so the new `cost` key never reached
its tables, and it printed a single position cell as raw JSON. Both
now render `5 X {100 USD, 2020-01-02}` (label in quotes when present).
A position without a cost, or an inventory from a wasm package that
predates the field, renders as bare units, as before.

Tested: three new formatCell cases in the MCP test suite (124 pass);
two of them fail against the previous formatCell.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen

robcohen commented Oct 8, 2026 •

Copy link
Copy Markdown
Member Author

Review (adversarial pass)

Consumers of the wasm query wire, checked for the new cost key:

  • packages/mcp-server formatCell read only units from inventory positions, so the new key never reached its tables. It also printed a single position cell as raw JSON (pre-existing). Fixed in 7364db3, since it was trivial and in scope. Positions now render as 5 X {100 USD, 2020-01-02}, with the label quoted when present. A cost-less position, or an inventory from a wasm package without the field, renders as bare units, as before. The MCP suite runs against the published @rustledger/wasm ^0.24.0, which predates the field, so the new cases test formatCell on synthetic cells: 3 new cases, 124 pass, and 2 of them fail against the old formatCell.
  • rustfava consumes the FFI component (WIT), not rustledger-wasm; its WIT position already carries cost (FFI-WASI: emit per-position cost in Inventory query output #1398). Unaffected.
  • TS bindings: PositionValue.cost?: CostValue, matching CellValue.Position. The only in-repo TS consumer is the MCP server.
  • Docs: docs/guides/integration.md and the wasm README only print rows. No inventory-shape example to update.

null vs absent: both the Position arm and the inventory element skip the key when there is no cost (skip_serializing_if = "Option::is_none", ts(optional)). The host unit test pins {"units":{…}} with no cost for a cost-less position, and pins that an inventory element equals the same position's Position cell. The wasm test's Assets:Cash row ({"units":{"number":"-320","currency":"USD"}}) shows the same through serde_wasm_bindgen. The JSON Schema says anyOf [CostValue, null] and Python says CostValue | None; both readers accept absence.

Local verification on a per-worktree target: cargo test -p rustledger-wasm --all-features 155 passed; wasm-pack test --node -- --test wasm_booking_method 4 passed, and 4 fail with the Inventory arm's cost dropped.

Second pass

  • MCP package hygiene. packages/mcp-server has no CHANGELOG of its own. Its version is bumped only at release (RELEASING.md), and its changes are recorded in the root CHANGELOG, where this PR's entry already mentions the MCP rendering. So no version or changelog change is needed here.
  • The new tests run in CI. The MCP Server job (ci.yml: npm ci, npm run build, npm test) ran on this head: ✓ src/__tests__/index.test.ts (124 tests), Tests 124 passed (124). On main the same job reports Tests 121 passed (121), so the 3 new formatCell tests executed.
  • TS consumers type-check. bindings/index.d.ts is embedded into the published package's .d.ts via include_str! + typescript_custom_section (src/lib.rs). A strict tsc --noEmit consumer that builds PositionValue with and without cost, reads cost?.currency, and has a @ts-expect-error on cost: "100 USD" passes against this branch's bindings. Against main's it fails with TS2353: 'cost' does not exist in type 'PositionValue'.
  • Cross-PR. Against fix(lsp): skip WASM and Python plugins in every build, as E8006 says #2496 and fix(booking): infer a currency-less units number from the account balance #2490 this PR conflicts only on the CHANGELOG.md ### Fixed top-insert. Keep both entries.

Third pass

  • Bindings are fresh. Re-running scripts/regen-bindings.sh on the final head leaves git diff --exit-code clean, so index.d.ts, index.schema.json and types.py match byte for byte.
  • One conversion. position_value is the only Position→wire conversion. It feeds both the Position arm and the Inventory arm, and the unit test pins that the two produce equal output.
  • Not changed here. Building AmountValue from an Amount still appears at four existing places in convert.rs (postings, prices, balances); none of them was touched by this PR. A shared From<&Amount> would be a separate cleanup.
  • CHANGELOG. The entry matches the final behavior: optional key, absent rather than null, bindings regenerated, MCP rendering.

@robcohen
robcohen merged commit 8f9075b into main Oct 8, 2026
50 of 51 checks passed
@robcohen
robcohen deleted the fix/wasm-inventory-cell-cost-2402 branch October 8, 2026 05:59
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.

wasm: inventory query cells drop per-position cost (PositionValue has units only)

1 participant