Repository navigation
feat: add opt-in lint for linked transit transfers - #2819
Conversation
Inspect explicitly linked transit legs without rewriting source or changing default validation. Co-authored-by: Copilot <[email protected]>
9fdf76f to
83bd2a6
Compare
|
Thanks for this, @MoTechnicalities, and for the very clear write-up in #2818. The scope is well chosen: read-only, opt-in, narrow, and conservative about what it calls a match. A few things I especially liked:
There are a few things I'd like changed before merging. Requested changes1. Read the booked ledger, not the raw source. Right now the lint reads
2. Repeated Since #2859 (agcli 0.19), You can't just add 3. A typo in the configuration passes silently.
4. CHANGELOG entry. Every PR here adds a Non-blocking suggestions
RebaseThe branch is about 20 commits behind main. There's one conflict, in the Thanks again. The design is solid and this is mostly about getting it to work on real ledgers. Happy to answer questions on any of these. Would you mind if I made these corrections myself, on top of your branch? Your commits would stay as they are. If you'd rather do them yourself, that's completely fine too; just let me know. |
|
Thank you, @robcohen, for the thoughtful review, the detailed testing, and the practical suggestions. Yes, please feel free to make those corrections on top of the branch. I appreciate you offering to take that on, and keeping the existing commit intact is perfectly fine. The move to the booked ledger and plugin-aware processing makes sense, as do the scoped repeated-account handling, configuration diagnostics, changelog, and rebase. Please keep the conservative behavior for cases the checker cannot safely resolve and surface processing errors rather than reporting a misleading match. The optional nonzero exit mode and more specific mismatch diagnostics would be especially useful for future CI or automated workflows, but I am happy to leave those as follow-ups if they would make this PR too large. Longer term, I am interested in gradually improving opt-in account-boundary and transit checks, while keeping them generally useful and clearly distinguishing ledger consistency from proof of external settlement. No need to broaden this PR for that. Thanks again for helping make this practical for real ledgers! |
Resolves the lint usage string in ag-rledger: keeps main's [-f <format>] and adds linked-transit. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The lint read Loader::load output, so an elided transit amount always came out ambiguous and any plugin line refused the whole ledger. It now follows lint closed-nonempty: refuse on load errors, then run rustledger_loader::process with plugins and the plugin budget, and read the booked directives with ledger.source_map for locations. The inferred-amount branch and the plugin refusal are gone. A processing error refuses the input rather than being reported as a finding: a transaction booking rejects is left out of the booked stream, so its link would otherwise read as missing. Fees, prices, costs and several scoped links stay ambiguous. Transit amounts are rustledger_core::Amount. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Since agcli 0.19 (rustledger#2859) a flag given twice is refused unless it is in MULTI_VALUE_FLAGS, so lint linked-transit --account A --account B failed with PARSE_ERROR. --account takes one value on report and extract, so it cannot join the global list. MULTI_VALUE_COMMAND_FLAGS scopes a long list flag to the commands that own it, as MULTI_VALUE_SHORTS does for short flags, and lists account for lint only. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A typo in --account or --link-prefix printed "No linked transit transfers found." and exited 0. Now: - each --account must pass rustledger_parser::is_valid_account_name, or the lint refuses with the name; - a leading ^ on --link-prefix is dropped with a LINK_PREFIX_CARET note, since links are matched without it; - a configured account the ledger never opens or posts to (ACCOUNT_NOT_IN_LEDGER) and a prefix no link starts with (NO_LINK_MATCHES_PREFIX) are warnings, as are processing warnings. Warnings go through Messages: warning: lines on stderr in rledger, and records in the ag-rledger envelope's warnings (lint now runs under run_buffered_with_warnings). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lead With validation off, a leg rledger check rejects could still be matched (an unbalanced leg, an unopened account, a closed transit account), while a plugin finding such as check_commodity or leafonly refused the whole file. The lint now runs validation, as check does, and sorts what processing reports by what it can do to the answer: - a booking failure or a plugin failure refuses the input: either drops or alters transactions; - any other error located on a linked transaction makes that link ambiguous, with the error as the reason; - everything else (errors elsewhere, errors with no transaction location such as check_commodity, warnings) is passed through as a warning. Advisory-only codes stay silent, as in check. A plugin finding and a plugin that failed to run are both PLUGIN errors, so rustledger-loader marks the latter: LedgerError::is_plugin_failure is set for a plugin that could not be resolved, failed while running, or whose output was discarded. The test ledgers now open their accounts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A transaction a plugin inserted with no source location failed the whole
run ("linked transaction has no source location"). One inserted at a
location another transaction already has was merged into it by the
dedup key, which is meant for a file read twice: two forecast copies of
one leg merged into one and matched the receiving leg.
An unlocated transaction now gets its own key and makes its link
ambiguous. A location shared by several transactions in one ledger
(forecast copies, effective_date splits) makes the link ambiguous too,
so a dedup merge can never produce a match.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
linked-transit passes a ledger error that is not on a linked leg through as a warning. The terminal line said where it was; the envelope's warnings entry kept only the code and message. Diagnostic gains file and line fields, which the lint fills from the error's location and the envelope carries as "file" and "line". The struct literals that named every field now fill the rest from Diagnostic::message. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The four statuses were string literals compared in several places. A Status enum, serialized lowercase, replaces them; the JSON and text output are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
"transit account, currency, amount, or direction differs" left the user to work out which. A mismatch now names it: "account: A vs B", "currency: 100 USD vs -100 EUR", "zero transit amount: 0 USD vs 0 USD", "direction: 100 USD vs 100 USD (same sign)" or "amount: 100.00 USD vs -90.00 USD". Each location in the JSON carries its transit postings, with the booked number as a string and the currency. Co-Authored-By: Claude Opus 5.5 <[email protected]>
On a ledger with hundreds of transfers, listing every matched pair hid
the few problems. The text output now lists the links that did not
match, then a count line ("312 matched, 2 mismatch, 1 missing,
0 ambiguous"). The JSON keeps every finding and gains the same counts.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
linked-transit canonicalized each source path itself, for both the printed location and the dedup key, while the other lints print the source map's path (the file's identity, symlinks already resolved). It now uses that path for both, which drops a second resolution that could fail on its own, and a test pins its locations to closed-nonempty's on a ledger reached through a symlink. Co-Authored-By: Claude Opus 5.5 <[email protected]>
rustledger#2818 asks for an explicit way to make findings fail a CI job or a pre-commit hook. --fail-on mismatch,missing,ambiguous (comma-separated or repeated, any of the four statuses) exits 1 when a link ends in a listed status, as check exits 1 on an error; without it findings still exit 0, like the other lints. ag-rledger reads it with the same names, refuses an unknown status as INVALID_VALUE, and merges a repeated --fail-on in lint (MULTI_VALUE_COMMAND_FLAGS). Its envelope is the one check gives: ok true, exit_code and result.exit_status 1. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The tests follow test_<function>_<scenario>. The table-driven pair test and the grab-bag dedup test are split by what they check, every assertion names its link, and the 79228162514264337593543950335 case, which mostly tested rust_decimal, is gone. The mismatch kinds it covered are in test_run_with_writer_mismatch_names_what_differs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The section was in check.md, but linked-transit is a lint subcommand. docs/commands/lint.md lists the four lints and documents linked-transit in full: options, statuses and reasons, the JSON shape, how processing errors are handled, configuration warnings and --fail-on. The commands index links it, and check.md keeps a pointer. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ated Since agcli 0.19 (rustledger#2859) a flag given twice is refused unless merge_repeated_value_flags merges it, and nothing checked that the tables kept up with rledger. The new guard walks every rledger command definition ag-rledger runs (and fails if one is missing from the list) and asserts that each clap Vec flag taking one value per occurrence is in MULTI_VALUE_FLAGS or, for its command, MULTI_VALUE_COMMAND_FLAGS, with its short form in MULTI_VALUE_SHORTS; that no single-value flag is merged where it applies (report and extract --account); and that no entry is stale. It found one gap, fixed here: check --lint is repeatable in rledger but ag-rledger read one value, so a repeat was a PARSE_ERROR. It is now scoped in MULTI_VALUE_COMMAND_FLAGS and read as a list. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Covers validation and how processing errors are handled, plugin-inserted legs, mismatch reasons, the quieter text output, --fail-on, the docs page, LedgerError::is_plugin_failure, and ag-rledger check accepting a repeated --lint. Co-Authored-By: Claude Opus 5.5 <[email protected]>
An if-let for the source lookup (single_match_else) and backticks on the plugin names in the module docs (doc_markdown). Co-Authored-By: Claude Opus 5.5 <[email protected]>
A native plugin that cannot use its config (rename_accounts with a bad pattern, zerosum with none, effective_date, the check_* "skipping" configs, ...) returns every directive unchanged and one unlocated PLUGIN error. The loader read that as a finding, so linked-transit reported two legs as matched where the rename the config meant makes them ambiguous, and exited 0 even under --fail-on. PluginError gains failed, set with mark_failed() at every site where a native plugin gives up without doing its work: an unusable config in capital_gains (long_short, gain_loss, through unchanged()), check_average_cost, check_commodity, check_option_expiry, commodity_attr, document_discovery, effective_date, onecommodity, rename_accounts and zerosum; a pattern it cannot evaluate (capital_gains, check_commodity, onecommodity); and a documents directory it could not scan. Errors a plugin reports on one directive it leaves as written (valuation, effective_date) stay findings: they are located, so the lint attributes them to the leg. The loader maps failed to LedgerError::with_plugin_failure. failed is serde(skip): the MessagePack array a WASM guest sends is unchanged, so the ABI stays 3, and a WASM or Python plugin's errors remain findings. Tests: the rename_accounts repro (refused, and ambiguous once the pattern is fixed), every marked config site, a finding left unmarked, the wire shape, and one each for the loader's run-error, op-coverage and invalid-entry sites. Co-Authored-By: Claude Opus 5.5 <[email protected]>
"Not readable from the code" read as a remark about the source; it meant the error code. Reworded. Co-Authored-By: Claude Opus 5.5 <[email protected]>
With --fail-on, a finding exits 1, and so did a run that could not
answer (a missing file, load errors, a processing failure, a refused
configuration), so a CI job could not tell "found something" from
"never looked". rledger lint linked-transit now exits 2 for the latter,
as rledger check exits 2 on a file it cannot read. The other lints keep
exiting 1.
ag-rledger is unchanged: a run that could not answer is already an error
envelope ("ok": false, FILE_NOT_FOUND exit 3 or COMMAND_FAILED exit 1),
and 2 means a usage error there. Both are documented in lint.md.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A plugin error is matched to a linked transaction by file and line, and only the header line counted, so an error a plugin located at one of the leg's postings was passed through as a warning and the link could still match. Any line from the header to the last posting now counts. No native plugin locates an error at a posting today (a Python plugin can), so the lookup is a function with its own test. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The plugin-test-quality policy refuses a bare non-empty check: each unusable config gives exactly one error, marked failed, and the finding test exactly one, unmarked. Co-Authored-By: Claude Opus 5.5 <[email protected]>
zerosum found its settings by matching regexes against the config text,
so parse_config never failed: a malformed config such as
{'zerosum_accounts': {'Assets:Transit' ('Assets:Transit-Matched', 30)}}
matched nothing and the plugin did nothing without a word. check exited
0, and lint linked-transit reported legs the plugin should have moved as
matched. Beancount's literal_eval raises on it.
The config is now read with the shared py_literal parser, as
effective_date and check_commodity read theirs. Anything other than a
dict, a zerosum_accounts that is not a dict of (target, days), an
account_name_replace that is not (from, to), or a tolerance that is not
a number is an error, marked failed. Every key stays optional and the
last of a repeated key wins, as in Python.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
PluginError is not non_exhaustive, so code building one with a struct literal must add failed. Said under Breaking, as for NoteData. The wire test also pins the encoded shape: a four-element fixarray. Co-Authored-By: Claude Opus 5.5 <[email protected]>
errors_within's doc and test spoke of a transaction's header and postings, but a directive's span runs up to the next directive, blank and comment lines included. The range now comes from span_lines, whose doc says so, and a test builds it from a parsed ledger: header to the comment line before the next transaction, with an error at a posting attributed to its own transaction only. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… findings The marked-site tests covered the config errors only. They now cover the other sites too: rename_accounts and check_commodity, onecommodity, long_short and gain_loss on a pattern they cannot match (a word boundary on a character Python and rledger disagree on), gain_loss's second rule after a rewrite, check_commodity's pattern it cannot compile (whose finding stays unmarked), the documents directory document_discovery cannot scan, and zerosum's non-dict config. A drift guard the other way pins that per-directive findings stay unmarked: leafonly, no_unused, unique_prices, and valuation's zero-unit total price. Co-Authored-By: Claude Opus 5.5 <[email protected]>
rledger lint | head reported "error: Broken pipe" and exited non-zero (2 for linked-transit since the last change). The Lint arm now treats a closed pipe as the Check arm does: exit 0. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The format! call was too long for rustfmt to fit in the match arm, so it left the block indented by hand, and wrongly. The message is now built first. Co-Authored-By: Claude Opus 5.5 <[email protected]>
zerosum comes from beancount_reds_plugins (0.4.0), whose config is literal_eval'd, each key popped with a default, and each entry unpacked, with no type checks. The previous change refused more than it does. Now, as there: - days may be a float (rounded down, as timedelta(days=x) added to a date is), an int in any literal form (3_0, 0x1e), or a bool (True is 1); - a None target is an empty one, derived with account_name_replace; - a two-character string unpacks into account_name_replace's pair; - flag_unmatched, match_metadata, match_metadata_name, link_transactions and link_prefix are accepted and, like any other key, ignored. It still refuses what the Python plugin refuses: a config that is not a literal or not a dict, a zerosum_accounts that is not a dict, and an entry or account_name_replace that does not unpack into two. A days value or tolerance that is not a number is refused up front, a deliberate strictness (the Python plugin fails, or matches nothing, only once a zerosum posting is reached), commented and tested. Checked against the Python plugin with bean-check and bean-query: the accepted forms move the same postings, and every refused config fails there too. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The reference showed plugin "beancount.plugins.zerosum" "Assets:Reimbursable 30", which never worked: before, the plugin silently did nothing (so the comment that the postings match was false), and now the config is a plugin error. The example is now the dict form the Python zerosum plugin (beancount_reds_plugins) reads, with the accounts opened, and its options are listed. Checked with rledger check and query, and with bean-check and bean-query with beancount_reds_plugins 0.4.0: the same two postings move to Assets:Reimbursable-Matched. Co-Authored-By: Claude Opus 5.5 <[email protected]>
zerosum is beancount_reds_plugins', not beancount's, and literal_eval is only the first of its failures: pop and the unpacking after it fail on the others. Also notes the forms now read as it reads them, the deliberate strictness on a non-number days or tolerance, and the fixed reference example. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings in rustledger#2885-rustledger#2889. The only conflict was CHANGELOG.md, in Breaking and in Fixed, where both sides added entries; both are kept. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- py_days: a negative range matches nothing across two transactions, as in Python, but rledger's same-transaction branch skips the date check, so two postings in one transaction still match. Noted as a known difference; behavior unchanged. - A None tolerance raises TypeError in the Python plugin; it does not match nothing. - CHANGELOG: only a config the Python plugin cannot read is now a plugin error. Days too large for timedelta (an overflow there) and an empty target with no account_name_replace (a hang there) still run here. - plugins.md: with no account_name_replace, an empty target is <account>-Matched. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks again @MoTechnicalities. I've pushed the corrections on top of your branch. Your commit is untouched; the rest is a merge of main plus small commits you can read one at a time. From the review
How errors are handled now It runs validation, the same as
The suggestions, also done
While I was at it I added a test that every repeatable Let me know if any of this doesn't fit what you had in mind. |
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
Summary
Add a read-only, opt-in lint that checks explicitly linked transfer legs through configured transit accounts. It complements
lint transfers, which finds likely unlinked pairs.Type of Change
Changes
rledger lint linked-transit FILE --link-prefix xfer- --account Assets:Transit, with text and JSON output; repeat--accountto configure multiple accounts.ag-rledgerand document the scope and limitations.The lint inspects raw source, not a booked or validated ledger. Run
rledger checkseparately. Findings are advisory and do not establish external settlement, domain isolation, lifecycle persistence, or hash-chain integrity. This contribution was developed with AI assistance.Testing
cargo testpasses (not run)cargo clippypasses (not run)Ran with Rust 1.96 and
--no-default-features --features ag-rledger:cargo test -p rustledger --lib --bin ag-rledger --test ag_rledger_test(606 library, 15 agent binary, 42 agent integration tests passed; synthetic CLI fixture covers a mismatch and repeated accounts).cargo clippy -p rustledger --lib --bins -- -D warnings(passed).cargo fmt --allandgit diff --check.The local build noted that the optional wasm32 sample fixture was unavailable; WASM tests and default-feature/full-workspace checks were not run.
Checklist
Review Focus
Related Issues
Closes #2818