Repository navigation
test(loader): cache round-trip properties, and pin the two cache versions together - #1960
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
📊 Benchmark Results
vs main branch (2026-08-04)
What do these numbers mean?
|
…ions together stale cache resurrects fixed bugs unless CACHE_VERSION is bumped, which is a property, not a review". This session proved that literally, twice. WHAT THE SESSION SHOWED The loader cache moved 17 -> 23 and the wasm cache 3 -> 9, six bumps each, every one done by hand and every one requiring a fresh judgment about whether the archived LAYOUT moved or only the VALUE. Two things went wrong: - On #1942 the parser was provably fixed - a probe showed the corrected cost - while `rledger check` still reported the old imbalance, because a stale cache was answering. - On the same PR I bumped the loader and MISSED the wasm cache entirely. It archives the same `Vec<Directive>`, so a stale blob would have kept serving a truncated cost basis on a fixed build. Review caught it. No test did. THREE PROPERTIES 1. `cache_roundtrip_preserves_parsed_directives` round-trips REAL PARSED ledgers, one per shape whose parser output changed in this series: cost arithmetic, negative cost, compound cost, metadata arithmetic, balance tolerance, a unicode account, tags and links, and lots with prices. The existing tests hand-build a CacheEntry from a literal directive, which proves the format works on the shape the author thought of - not the shape that keeps breaking. 2. `a_stale_version_is_refused_rather_than_reinterpreted` writes a real cache, rewrites the header version word to the previous version, and asserts the loader refuses it. This is the property that actually protects an upgrade: the layout usually does NOT change when parser output does, so nothing else stops an old blob deserializing cleanly into the new types and serving a pre-fix answer. 3. `loader_cache_version_is_pinned` pins the wasm cache against the loader's, so moving one without the other fails with a message that asks the right question: did PARSER OUTPUT change (bump both), or was it loader-internal (update the pin alone)? This is the guard for the bug that got past me. ALL THREE VERIFIED TO FAIL version check disabled -> "a cache blob one version behind must be refused" loader moved, pin did not -> the tripwire message above a fixture stops parsing -> "expected a multi-directive parse, got 0" The third is the non-vacuity guard on property 1: without it the comparison is satisfied by two empty vectors, and a shape that stopped parsing would pass as a clean round-trip. `CACHE_VERSION` is now `pub` so the wasm crate can pin against it; that pulled in a stricter doc lint on the public item, hence the paragraph break in its history comment. Refs #1902.
There was a problem hiding this comment.
Pull request overview
Adds regression/property-style tests to ensure loader cache entries round-trip real parsed ledgers correctly, rejects stale cache versions, and prevents future “loader cache bumped but wasm cache not bumped” drift by pinning the two cache versions together.
Changes:
- Add loader integration tests that (a) round-trip parsed directives through the cache and (b) ensure a one-version-stale cache blob is refused.
- Expose
rustledger_loader::cache::CACHE_VERSIONpublicly so other crates can assert against it. - Add a WASM-side
#[cfg(test)]version pin + test to keep the loader and WASM cache versions reconciled when parser output changes.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
| crates/rustledger-wasm/src/cache.rs | Add a test-only pin asserting the WASM cache version is kept in sync with the loader cache version. |
| crates/rustledger-loader/tests/cache_roundtrip_properties.rs | New integration tests for cache round-trip identity on real parsed ledgers and for rejecting stale-version cache blobs. |
| crates/rustledger-loader/src/cache.rs | Make CACHE_VERSION public and document the cross-crate pin contract with rustledger-wasm. |
Suppressed comments (1)
crates/rustledger-loader/tests/cache_roundtrip_properties.rs:143
- This test manipulates the cache file bytes directly after calling
save_cache_entry(). IfBEANCOUNT_DISABLE_LOAD_CACHEorBEANCOUNT_LOAD_CACHE_FILENAMEis set in the environment, the cache may not be written where expected (or at all), making the test flaky and potentially modifying a user’s cache outside the temp directory.
fn a_stale_version_is_refused_rather_than_reinterpreted() {
let dir = temp_dir("stale_version");
let file = dir.join("main.beancount");
let mut f = fs::File::create(&file).expect("create");
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
b2e4684 to
9bcdd70
Compare
Rebasing onto main after #1959 landed, the new tripwire fired on an actual version move rather than a sabotage: the rustledger-loader cache version moved and this one did not... Answering its own question: #1959 made tags and links parse errors in custom and pushmeta values, so PARSER OUTPUT changed - and it correctly bumped BOTH caches, loader 23 to 24 and wasm 9 to 10. Only the pin was behind. So this is the update-the-pin-alone branch of the message, and the guard did exactly what it exists for: it made the question get asked at the moment the versions diverged, rather than leaving it to be noticed in review, or not at all.
…erties Two review findings, both real hazards rather than style. CONCURRENT RUNS COLLIDED. `temp_dir()` built a fixed name under the global temp dir, so two `cargo test` processes landed on the same path - and the cleanup at the START of the helper would delete the other run's fixture out from under it. Now a `tempfile::TempDir` with a unique suffix, which also removes itself on drop, so a failing assertion leaves no litter. Verified by running two copies of the suite concurrently: both pass. THE ENV VARS WERE INHERITED. `save_cache_entry` / `load_cache_entry` read process env, so an inherited BEANCOUNT_LOAD_CACHE_FILENAME would redirect these writes out of the fixture - silently making the round-trip assert nothing - and BEANCOUNT_DISABLE_LOAD_CACHE would stop a cache being written at all. Either could also clobber a developer's real cache file. The unit tests in cache.rs already guard themselves this way (`assert_clean_cache_env`). I did not follow the pattern the crate had already established. Verified the guard fires: $ BEANCOUNT_DISABLE_LOAD_CACHE=1 cargo test --test cache_roundtrip_properties unset BEANCOUNT_DISABLE_LOAD_CACHE before running this test ... Noted in place that CLAUDE.md warns against asserting environment as a precondition (#1729). The exception earns itself here: the alternative is not a hermetic test but one that writes somewhere unexpected, and failing loudly beats that.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 3 out of 3 changed files in this pull request and generated no new comments.
Suppressed comments (3)
crates/rustledger-loader/tests/cache_roundtrip_properties.rs:92
- This test implicitly relies on BEANCOUNT_LOAD_CACHE_FILENAME / BEANCOUNT_DISABLE_LOAD_CACHE being unset. If either is set in a developer's environment, the test may write cache files outside the temp dir (or make save/load a no-op), leading to surprising side effects or spurious failures. Consider guarding/restoring env vars (like cache_env_var_test.rs does) or at least asserting they're unset.
fn cache_roundtrip_preserves_parsed_directives() {
for (name, source) in shapes() {
crates/rustledger-loader/tests/cache_roundtrip_properties.rs:142
- Like the roundtrip test above, this test assumes the cache env vars are unset. If BEANCOUNT_DISABLE_LOAD_CACHE is set, save_cache_entry becomes a no-op; if BEANCOUNT_LOAD_CACHE_FILENAME is set, the test may read/write cache files outside the temp directory.
fn a_stale_version_is_refused_rather_than_reinterpreted() {
let dir = temp_dir("stale_version");
let file = dir.join("main.beancount");
crates/rustledger-loader/tests/cache_roundtrip_properties.rs:126
- Comparing directives via format!("{:?}") is brittle (Debug output is not a stable contract and can change for reasons unrelated to cache correctness) and does extra allocations. Since Directive/Vec implements PartialEq/Eq, compare the vectors directly instead.
assert_eq!(
format!("{:?}", back.directives),
format!("{:?}", entry.directives),
"{name}: directives did not survive the cache round-trip",
);
|
| Metric | Result |
|---|---|
| Check Compatibility | 100% |
| BQL Compatibility | 95% (raw 89%, 162 masked) |
| Full AST Match | 100% |
| Total Files | 812 |
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
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 3 out of 3 changed files in this pull request and generated no new comments.
Suppressed comments (2)
crates/rustledger-loader/tests/cache_roundtrip_properties.rs:195
- The test hard-codes the version field offset as
bytes[8..12], which couples it to the current header layout (magic is 8 bytes and version immediately follows). If the header layout changes (even legitimately), this will fail with an opaque slice panic or silently mutate the wrong bytes. Consider adding a small helper inrustledger-loader(potentiallypub(crate)+#[cfg(test)], or a test-only accessor) that returns the byte range/offset for the version field, or at minimum assert the expected magic bytes before patching so failures point to a header-layout mismatch rather than a slicing issue.
// Rewrite the version word in the header to the previous version.
let path = rustledger_loader::cache_path(&file);
let mut bytes = fs::read(&path).expect("read cache");
let stale = rustledger_loader::cache::CACHE_VERSION
.checked_sub(1)
.expect("CACHE_VERSION >= 1");
bytes[8..12].copy_from_slice(&stale.to_le_bytes());
fs::write(&path, &bytes).expect("write cache");
crates/rustledger-loader/tests/cache_roundtrip_properties.rs:157
- Comparing
format!(\"{:?}\", ...)bakes theDebugrepresentation into the contract. This can make the test brittle ifDebugoutput changes (e.g., field ordering changes in derivedDebug, or any nested collection with non-deterministic iteration order), even when the semantic round-trip is correct. If the goal is strict identity without requiringPartialEq, consider comparing a stable representation instead (e.g., serializingback.directivesandentry.directivesto bytes using the same serializer and asserting byte equality), which keeps the test sensitive to data loss while reducing incidental formatting churn.
assert_eq!(
format!("{:?}", back.directives),
format!("{:?}", entry.directives),
"{name}: directives did not survive the cache round-trip",
);
…istory CI's Documentation job failed with "unclosed HTML tag `Decimal`". The v8 entry in the version history contains `Option<Decimal> + Option<Decimal>` unescaped, and rustdoc parses a bare `<Decimal>` as an HTML tag. It has been there since v8 and was harmless because the constant was PRIVATE - rustdoc does not document private items by default. Making `CACHE_VERSION` public so the wasm crate could pin against it is what exposed the comment. Worth noting the shape: `cargo test` and clippy both pass on this. Only `cargo doc` catches it, which is why the repo has a separate Documentation job - and why I should have run it after making an item public rather than after CI told me. Checked the rest of the block for the same problem (none) and ran `RUSTDOCFLAGS=-D warnings cargo doc --workspace`, which is clean.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 3 out of 3 changed files in this pull request and generated no new comments.
Suppressed comments (1)
crates/rustledger-loader/tests/cache_roundtrip_properties.rs:157
- The round-trip identity check compares
format!("{:?}", ...)forVec<Spanned<Directive>>. This is brittle because directive values includeMetadata = FxHashMap<...>(seerustledger-core/src/directive.rs:83), and hash map debug output uses an arbitrary iteration order. A deserialized map can legitimately iterate in a different order, causing a spurious failure even when the directives are semantically identical.
A more robust check is to compare directive values with Eq (order-insensitive for metadata) while still asserting that span + file_id survived exactly.
assert_eq!(
format!("{:?}", back.directives),
format!("{:?}", entry.directives),
"{name}: directives did not survive the cache round-trip",
);
#1902 Phase 1 asks for cache round-trip properties on the grounds that "a stale cache resurrects fixed bugs unless
CACHE_VERSIONis bumped, which is a property, not a review." This session proved that literally, twice.What the session showed
The loader cache moved 17 → 23 and the wasm cache 3 → 9 — six bumps each, every one by hand, every one needing a fresh judgment about whether the archived layout moved or only the value. Two things went wrong:
rledger checkstill reported the old imbalance, because a stale cache was answering.Vec<Directive>, so a stale blob would have kept serving a truncated cost basis on a fixed build. Review caught it; no test did.Three properties
1.
cache_roundtrip_preserves_parsed_directivesround-trips real parsed ledgers, one per shape whose parser output changed in this series: cost arithmetic, negative cost, compound cost, metadata arithmetic, balance tolerance, a Unicode account, tags and links, and lots with prices.The existing tests hand-build a
CacheEntryfrom a literal directive, which proves the format works on the shape the author thought of — not the shape that keeps breaking.2.
a_stale_version_is_refused_rather_than_reinterpretedwrites a real cache, rewrites the header version word to the previous version, and asserts the loader refuses it. This is what actually protects an upgrade: the layout usually does not change when parser output does, so nothing else stops an old blob deserializing cleanly into the new types and serving a pre-fix answer.3.
loader_cache_version_is_pinnedpins the wasm cache against the loader's. Moving one without the other fails with a message that asks the right question — did parser output change (bump both), or was it loader-internal (update the pin alone)? This is the guard for the bug that got past me.All three verified to fail
The third is the non-vacuity guard on property 1: without it the comparison is satisfied by two empty vectors, and a shape that stopped parsing would pass as a clean round-trip.
Notes
CACHE_VERSIONis nowpubso the wasm crate can pin against it. That pulled the public item into a stricter doc lint, hence the paragraph break in its version-history comment. The pin itself is#[cfg(test)]— it exists to be asserted — but its documentation stays next toCACHE_VERSION, which is what a reader came to change.Verification
cargo fmt --checkcleanRefs #1902.