Skip to content

fix(plugin): update a tracked plugin and its mtime atomically - #1976

Merged
robcohen merged 2 commits into
mainfrom
chore/atomic-mutation-sweep
Aug 6, 2026
Merged

robcohen merged 2 commits into
mainfrom
chore/atomic-mutation-sweep

Conversation

@robcohen

@robcohen robcohen commented Aug 6, 2026

Copy link
Copy Markdown
Member

#1902 Phase 2 — the non-atomic multi-step mutation sweep. One small real
defect; everything else was already atomic
, which is most of what this reports.

Method

The shape, from BookingEngine::apply (#1863/#1897), which gets it right:

snapshot the state a failure would strand
for each step: mutate; on failure roll back and return Err

The defect is the same loop without the snapshot — a mid-loop ? leaves
everything before it applied, while the caller sees Err and reasonably assumes
nothing happened.

Detector: &mut + returns Result + mutates + can exit early after the first
mutation + no snapshot/staging vocabulary. Self-checked against a planted
non-atomic function, a snapshot-guarded one, a validate-first one, and an
infallible one.

Recall correction worth flagging: the first version matched only self.X
mutations and found 5 candidates. That pattern is blind to mutation through
&mut parameters — which is exactly how this codebase accumulates
(directives: &mut Vec<_>, errors: &mut Vec<_>). Fixing it took the candidate
set from 5 to 28. A sweep reporting "no defect" from the narrow pattern
would have been worthless.

The defect

WatchingPluginManager::reload_all:

let new_plugin = Plugin::load(&tracked.path, &self.config)?;
let metadata = std::fs::metadata(&tracked.path)?;
tracked.plugin = new_plugin;                 // mutate
tracked.modified = metadata.modified()?;     // ...then a fallible call

A failure on the last line leaves the new plugin recorded against the old
timestamp
— an inconsistent pair, and tracked.modified is the only state
reload_if_changed consults to decide whether a reload is due.

Its sibling reload_if_changed already resolves the timestamp before touching
either field. This matches it.

Atomicity is per plugin, not across the loop, and the doc now says so: a
failure on the third leaves the first two reloaded and returns Err. Each is a
valid instance either way, so the result is incomplete rather than corrupt.

Honest limit: this is structural, not behavioral. metadata.modified()
fails only where the platform has no mtime, which I cannot reproduce in a test.
The guarantee is that no fallible call sits between the paired writes — checkable
by reading, and matching the sibling's shape.

Everything else was already atomic

Four different mechanisms, all correct:

site mechanism
BookingEngine::apply snapshot + rollback, skipped only when overflow is provably impossible
apply_plugin_ops stages into a fresh Vec, swaps at the end
execute_insert validates everything, then commits with no fallible step in the loop
load_recursive include-stack push/pop balanced; the only Err returns before the push
dispatch_sync the mutation and the error are in mutually exclusive match arms
report_* / run_with_writer streaming output — a partial write cannot be rolled back, and callers do not expect it to be

Verification

cargo test --workspace — 132 suites, 0 failures. Clippy and doc clean.

#1902 Phase 2, the non-atomic multi-step mutation sweep.

reload_all assigned tracked.plugin and only THEN called
metadata.modified()?. A failure there left the new plugin recorded
against the old timestamp - an inconsistent pair, and tracked.modified
is the only state reload_if_changed consults to decide whether a reload
is due.

Its sibling reload_if_changed already resolves the timestamp before
touching either field. This matches it: every fallible step for a
plugin now runs before either field is written.

Atomicity is per PLUGIN, not across the loop, and the doc now says so.
A failure on the third plugin leaves the first two reloaded and returns
Err - each is a valid instance either way, so the result is incomplete
rather than corrupt.

Structural rather than behavioral: metadata.modified() fails only where
the platform has no mtime, which I cannot reproduce in a test. The
guarantee is that no fallible call sits between the paired writes,
which is checkable by reading and matches the sibling's shape.

Everything else the sweep turned up was already atomic, by four
different mechanisms - recorded here because the negative result is
most of the value:

  BookingEngine::apply       snapshot + rollback, skipped only when
                             overflow is provably impossible
  apply_plugin_ops           stages into a fresh Vec, swaps at the end
  execute_insert             validates everything, then commits in a
                             loop with no fallible step
  load_recursive             include-stack push/pop balanced; the only
                             Err returns before the push
  dispatch_sync              the mutation and the error are in
                             mutually exclusive match arms
  report_*/run_with_writer   streaming output; a partial write cannot
                             be rolled back and callers do not expect it
@robcohen
robcohen requested a review from a team as a code owner August 6, 2026 14:18
Copilot AI review requested due to automatic review settings August 6, 2026 14:18

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

Updates WatchingPluginManager::reload_all to avoid leaving a tracked plugin in an inconsistent state if retrieving the file mtime fails, aligning the reload-all behavior with the existing per-plugin reload path in rustledger-plugin’s runtime.

Changes:

  • Compute the plugin file’s modified timestamp before mutating tracked.plugin / tracked.modified, so the pair is updated atomically per plugin.
  • Add documentation explaining the atomicity guarantee and its scope (per plugin, not across the whole loop).

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

Comment thread crates/rustledger-plugin/src/runtime.rs Resolved
@github-actions

github-actions Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 31.5ms ± 1.3ms 24.2 MB
beancount 603.5ms ± 12.7ms 50.7 MB
Comparison 19.2x faster 2.1x less

vs main branch (2026-08-06)

Metric main this PR Change
Time 37.8ms 31.5ms -16.7% 🟢
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

@codecov

codecov Bot commented Aug 6, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-plugin/src/runtime.rs 0.00% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

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

@robcohen
robcohen enabled auto-merge (squash) August 6, 2026 14:37
The doc referred to reload_if_changed. No such method exists - the one
that consults tracked.modified is check_and_reload. Caught in review.

Precisely the defect the Inventory sweep found one PR earlier, where
two comments referenced a rebuild_caches that had never existed, and I
wrote the same thing into the fix for the next sweep.
Copilot AI review requested due to automatic review settings August 6, 2026 15:17

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

Copilot reviewed 1 out of 1 changed files in this pull request and generated no new comments.

Suppressed comments (1)

crates/rustledger-plugin/src/runtime.rs:644

  • Use intra-doc links for check_and_reload so rustdoc will validate the reference and prevent future drift (this file already uses link-style references, e.g. [PluginManager::execute_all]).
    /// inconsistent pair, and the only state `check_and_reload` consults to
    /// decide whether a reload is due. `check_and_reload` already gets this right;
    /// this matches it (#1902 Phase 2).

@robcohen
robcohen merged commit 606ee02 into main Aug 6, 2026
50 of 52 checks passed
@robcohen
robcohen deleted the chore/atomic-mutation-sweep branch August 6, 2026 15:40
robcohen added a commit that referenced this pull request Aug 8, 2026
… and lying in release (#1988)

* fix(booking): report a failed reduction instead of panicking in one profile and lying in the other

Closes #1987.

`apply()` ended its posting loop with `debug_assert!(reduced.is_ok())`
followed by `let _ = reduced`, described as "release builds keep the
historical ignore-and-continue behavior". So the two build profiles
disagreed about a user's ledger:

  debug   `report balances` PANICKED, exit 101
  release the reduction was DROPPED — 20 AAPL reported for an account
          holding 15

The release half is the worse one, and it is the one real users got. An
over-stated holding is not a crash you can see; it is a number you act
on. CI never saw it because CI runs debug, where the same input panics.

Reduction failures are now returned. The precondition is unchanged and
still documented — `apply` wants booked input — but violating it is
reported rather than asserted in one profile and ignored in the other.
Every existing caller already handles the `Err`: `book()` records it and
marks the transaction failed, the wasm entry checks `is_ok()`.

ATOMICITY. Returning mid-loop would leave the earlier postings applied,
which is exactly #1976's shape, so the snapshot gate widens from
`overflow_is_possible` to `rollback_needed` = overflow OR the
transaction contains a reduction. Kept as two predicates so #1897's
reasoning stays legible: snapshotting EVERY transaction cost 2.4x heap
churn and 6% CPU, and reductions are a minority of transactions, so this
widens the gate without reopening that regression. `has_reduction` calls
the canonical `Inventory::is_booking_reduction` rather than re-deriving
"is this a reduction" from the sign.

Not relying on the coincidence that `overflow_is_possible` returns true
for an unfilled posting: a filled-but-unbookable transaction (ambiguous
STRICT with explicit amounts) would otherwise mutate half its accounts
and then return Err.

THE CLI. The root cause is upstream of `apply`: `run_booking` partitions
failures out, and `finalize` re-merges them so the user still sees their
own input — documented as being "for output", with nothing stopping the
same directives flowing into computation. `account_balances` even
documents the precondition the pipeline then fails to establish.

`bail_on_booking_errors` now gates `query` and `report`, mirroring
`bail_on_parse_errors` one phase later, and says what to run instead.
That also fixes the query half of #1987, which never touched `apply`:
BALANCES re-aggregates by lot key and printed a dangling `-5 AAPL` for
an account holding 15, exiting 0.

  before: report panics (exit 101), query prints a wrong row (exit 0)
  after:  both refuse with the same message and exit 1; `check` still
          reports it, and a clean ledger is untouched

TWO TESTS CHANGED BECAUSE THE BEHAVIOR DID.

`strict_ambiguity_is_reported_by_both_surfaces` was the characterization
test added with the guard in #1986. It tripped, which is what it was
for, and is now the agreement assertion it was always meant to be.

`ambiguous_strict_reduction_yields_no_rows` asserted that capgains
succeeded with a header-only CSV. Not fabricating a disposal was right;
exiting 0 was not — a header-only capital-gains CSV is indistinguishable
from "you had no disposals this year". It now asserts the refusal AND
that no row is fabricated.

The parity guard's NONE fixture also turned out to be comparing two
WRONG answers: `-5 AAPL {}` cannot book under NONE (cost tracking off,
"2 unknowns"), so both surfaces were realizing an unbooked transaction
and agreeing. Making failures fatal is what exposed it; NONE now reduces
by price, the only shape that means anything without lots.

Sabotage-verified: restoring ignore-and-continue fails two tests,
returning Err without rolling back fails the atomicity test. The new
tests pass identically under --release, which is the point.

* fix(query): --no-errors must not license answering over an unbooked ledger

Copilot, and it was a real hole in the fix. The guard sat INSIDE the
`!args.no_errors` block, so:

  rledger query --no-errors x.beancount BALANCES

walked past the booking failure and printed the dangling `-5 AAPL` row
with exit 0 — the exact bug this PR exists to prevent, reachable through
a flag documented as suppressing the PRINTING of diagnostics. Verbosity
is not permission to compute figures from a ledger that did not book.

Worth recording how the first attempt to reproduce it "passed": with
`query FILE QUERY --no-errors` the flag lands after the positionals,
where it is swallowed into the BQL text and never registers, so
`no_errors` stayed false and the guard fired. The order matters, and
the regression test says so.

Also derives the fixture cash leg from its lot instead of hard-coding
-1500.00 for both buys, the second of which is 10 @ 200.00. `apply`
does not check balance today, so nothing failed — which is why an
internally inconsistent fixture is worth fixing before something starts
depending on it.

Sabotage-verified: nesting the guard back inside `--no-errors` fails
the new test.
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