Repository navigation
feat: external preprocess hook for PDF and other unsupported formats - #1786
Conversation
There was a problem hiding this comment.
Pull request overview
Adds a new preprocess hook to importer TOML entries so users can run an external command (e.g., pdftotext) to convert PDFs or other unsupported formats into CSV/text that flows through the existing rledger extract pipeline; the WASI component explicitly rejects this config surface with guidance.
Changes:
- Introduces
preprocess: Option<Vec<String>>onrustledger_importer::toml_entry::ImporterEntryand documents its trust model. - Implements CLI-side preprocessing in
rledger extractby executing the configured command and feeding stdout to the rest of the pipeline via a temp.csv. - Updates docs and adds tests, plus a component-boundary rejection test for
preprocess.
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 5 comments.
Show a summary per file
| File | Description |
|---|---|
| docs/roadmap/importing.md | Updates roadmap entry to describe phased PDF support starting with preprocess. |
| docs/commands/extract.md | Documents preprocess usage, trust model, and component limitation. |
| crates/rustledger/src/cmd/extract_cmd/mod.rs | Adds maybe_preprocess + wiring in run_with_writer, and CLI tests for preprocess behavior. |
| crates/rustledger/Cargo.toml | Adds tempfile dependency for preprocess temp output. |
| crates/rustledger-importer/src/toml_entry.rs | Extends importer entry schema with preprocess and a parsing test. |
| crates/rustledger-ffi-component/src/convert.rs | Rejects preprocess in component config with actionable guidance + test. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
953e59c to
7c3a721
Compare
📊 Benchmark Results
vs main branch (2026-08-08)
What do these numbers mean?
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
|
| 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
|
This hook is exactly what makes rustledger viable as a drop-in for bespoke PDF importer stacks — declaring One thing that would close the gap for fully retiring custom bank importers: a way to emit per-statement balance assertions. In beancount/hledger workflows the statement closing balance → Is there a planned mechanism for a preprocess/CSV importer to surface a statement's closing balance (e.g. a reserved balance row, a dedicated column, or a sidecar the extractor emits) so rustledger can generate the assertion? Combined with the confidence-scored review flow already on the roadmap, that would let a config-only setup replace a few thousand lines of custom importer code. |
|
Reviewed the full diff plus the resolution code it interacts with. Copilot's five threads are all legitimate — three of them are one bug — and there is a sixth it did not reach that I think gates the PR. 1.
|
…name Addresses the review on #1786. 1. SECURITY: `preprocess` no longer runs from a cwd-discovered config. find_importers_config falls back to ./importers.toml, so `rledger extract statement.csv` executed an arbitrary command from whatever directory the terminal was in - an unzipped bundle, a cloned repo, a shared downloads folder. No flag, no prompt: an entry with filename_pattern = "*" and a preprocess command fires on any extract there. The docs framed this as "exactly like a shell alias". A shell alias lives in your dotfiles; this does not. It is the boundary direnv makes you `allow` per directory rather than document. Config discovery now reports provenance, and preprocess is honored only for --config and the user config dir. A cwd-discovered entry still declares columns; only the exec is withheld, with a warning. 2. Auto-identification matched the TEMP filename. run_with_writer rebound `file` to the preprocessed rledger-preprocess-XXXX.csv, and the --config branch then matched filename_pattern against that. So `*.pdf` never matched: a config with more than one importer failed with "No importer matches file 'rledger-preprocess-...csv'" - naming a file the user never saw, AFTER the command had run. A single-importer config passed anyway via the no-match fallback, which is why the original test missed it. `source_file` keeps the name the user typed for identification; `file` carries the preprocessed content for dispatch. 3. Entry resolution existed twice and disagreed. maybe_preprocess re-implemented it with no single-importer fallback, and took the first of several matches rather than reporting the ambiguity - running a command before the other branch errored. Both now call one resolve_config_entry, so the entry that preprocesses is by construction the entry that extracts. That also removes the second config load. 4. Streams the child's stdout straight into the temp file instead of buffering all of it with Command::output(), and pins stdin to null. 5. Docs: the schema example claimed an argv array could be "piped through a table-to-CSV script". It cannot - the PR body's own `["sh", "-c", ...]` form is the one that pipes. Both spellings are now shown, and extract.md documents the provenance rule. Two tests, each sabotage-verified: identifying from the temp path again fails the auto-identify test, and removing the provenance gate fails the cwd test (which asserts the command did not RUN, via a marker file, rather than that output looked unchanged). NOT fixed, worth a follow-up: there is no timeout on the child, so a hung preprocess command hangs rledger with no output.
|
Pushed 1043429 addressing all five threads, plus the cwd-discovery issue from my review. The one that changes behaviour: Both new tests are sabotage-verified, and the cwd one asserts the command did not run — via a marker file the command would Two things left, deliberately:
|
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 7 changed files in this pull request and generated no new comments.
Suppressed comments (1)
crates/rustledger/src/cmd/extract_cmd/mod.rs:1234
- This test changes the process-wide current working directory via
std::env::set_current_dir, but Rust tests run in parallel by default. That can cause flaky failures if any other test depends on the current directory (or also mutates it) at the same time. Consider serializing the cwd mutation with a global lock and restoring the cwd via a Drop guard so it is reset even if the test panics.
// No --config: discovery has to find it in the current directory.
let prev = std::env::current_dir().unwrap();
std::env::set_current_dir(dir.path()).unwrap();
let args = Args::parse_from(["extract", csv.to_str().unwrap()]);
let mut out = Vec::new();
…name Addresses the review on #1786. 1. SECURITY: `preprocess` no longer runs from a cwd-discovered config. find_importers_config falls back to ./importers.toml, so `rledger extract statement.csv` executed an arbitrary command from whatever directory the terminal was in - an unzipped bundle, a cloned repo, a shared downloads folder. No flag, no prompt: an entry with filename_pattern = "*" and a preprocess command fires on any extract there. The docs framed this as "exactly like a shell alias". A shell alias lives in your dotfiles; this does not. It is the boundary direnv makes you `allow` per directory rather than document. Config discovery now reports provenance, and preprocess is honored only for --config and the user config dir. A cwd-discovered entry still declares columns; only the exec is withheld, with a warning. 2. Auto-identification matched the TEMP filename. run_with_writer rebound `file` to the preprocessed rledger-preprocess-XXXX.csv, and the --config branch then matched filename_pattern against that. So `*.pdf` never matched: a config with more than one importer failed with "No importer matches file 'rledger-preprocess-...csv'" - naming a file the user never saw, AFTER the command had run. A single-importer config passed anyway via the no-match fallback, which is why the original test missed it. `source_file` keeps the name the user typed for identification; `file` carries the preprocessed content for dispatch. 3. Entry resolution existed twice and disagreed. maybe_preprocess re-implemented it with no single-importer fallback, and took the first of several matches rather than reporting the ambiguity - running a command before the other branch errored. Both now call one resolve_config_entry, so the entry that preprocesses is by construction the entry that extracts. That also removes the second config load. 4. Streams the child's stdout straight into the temp file instead of buffering all of it with Command::output(), and pins stdin to null. 5. Docs: the schema example claimed an argv array could be "piped through a table-to-CSV script". It cannot - the PR body's own `["sh", "-c", ...]` form is the one that pipes. Both spellings are now shown, and extract.md documents the provenance rule. Two tests, each sabotage-verified: identifying from the temp path again fails the auto-identify test, and removing the provenance gate fails the cwd test (which asserts the command did not RUN, via a marker file, rather than that output looked unchanged). NOT fixed, worth a follow-up: there is no timeout on the child, so a hung preprocess command hangs rledger with no output.
1043429 to
bc6eb54
Compare
|
Rebased onto main ( One real conflict, and it is the drift I ran into writing the fix: Verified after rebasing rather than assuming the resolution was faithful — a bad merge here could have silently dropped the fix while still compiling:
Both guards still fire, which is the part that matters — the rebase touched the exact file the provenance gate reads. Note on CI right now: the runner fleet is degraded. Main itself has 16 jobs red, every one failing at GitHub's Still open from my review and not addressed here: no timeout on the preprocess child, so a hung command hangs |
Deep review — two findings, both verified by running them1. Command injection through
|
|
Both findings fixed in 7ef2b4f, plus two things the sabotage pass turned up that the tests alone wouldn't have. 1. The shell splice is now refused, not documented around
Refusing rather than warning, because this is stderr in the middle of a batch import — silent when it works, catastrophic when it doesn't — and the feature has never shipped, so nothing is being broken.
Both doc copies ( 2.
|
An importer entry can now declare `preprocess = ["cmd", "args"...]` —
an argv array run before format detection: `{input}` arguments are
replaced with the statement path, and stdout becomes the content the
whole existing pipeline consumes (temp .csv, so --auto inference,
dispatch, and column mapping work unchanged). This makes PDF
statements importable TODAY via the user's tool of choice
(pdftotext + a table script), with a native text-layer parser as the
planned phase 1 (roadmap row updated to the phased plan).
Design points:
- argv array, not a shell string — no shell interpolation of config
values; `{input}` is the only substitution.
- The schema field lives in the canonical toml_entry module; the
WASI component rejects entries that set it with guidance (a
component cannot exec — the host preprocesses and passes bytes).
- Trust model documented in the schema, the command docs, and a note
that a community profile registry must never carry preprocess
entries: this executes user-authored config, the same boundary as
a shell alias or a beangulp Python importer.
- Failing commands surface their exit status and stderr, not a
confusing CSV parse error.
Tests: end-to-end .pdf-named import via a stand-in preprocessor,
command-failure error surfacing, schema parse, component rejection.
Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
…name Addresses the review on #1786. 1. SECURITY: `preprocess` no longer runs from a cwd-discovered config. find_importers_config falls back to ./importers.toml, so `rledger extract statement.csv` executed an arbitrary command from whatever directory the terminal was in - an unzipped bundle, a cloned repo, a shared downloads folder. No flag, no prompt: an entry with filename_pattern = "*" and a preprocess command fires on any extract there. The docs framed this as "exactly like a shell alias". A shell alias lives in your dotfiles; this does not. It is the boundary direnv makes you `allow` per directory rather than document. Config discovery now reports provenance, and preprocess is honored only for --config and the user config dir. A cwd-discovered entry still declares columns; only the exec is withheld, with a warning. 2. Auto-identification matched the TEMP filename. run_with_writer rebound `file` to the preprocessed rledger-preprocess-XXXX.csv, and the --config branch then matched filename_pattern against that. So `*.pdf` never matched: a config with more than one importer failed with "No importer matches file 'rledger-preprocess-...csv'" - naming a file the user never saw, AFTER the command had run. A single-importer config passed anyway via the no-match fallback, which is why the original test missed it. `source_file` keeps the name the user typed for identification; `file` carries the preprocessed content for dispatch. 3. Entry resolution existed twice and disagreed. maybe_preprocess re-implemented it with no single-importer fallback, and took the first of several matches rather than reporting the ambiguity - running a command before the other branch errored. Both now call one resolve_config_entry, so the entry that preprocesses is by construction the entry that extracts. That also removes the second config load. 4. Streams the child's stdout straight into the temp file instead of buffering all of it with Command::output(), and pins stdin to null. 5. Docs: the schema example claimed an argv array could be "piped through a table-to-CSV script". It cannot - the PR body's own `["sh", "-c", ...]` form is the one that pipes. Both spellings are now shown, and extract.md documents the provenance rule. Two tests, each sabotage-verified: identifying from the temp path again fails the auto-identify test, and removing the provenance gate fails the cwd test (which asserts the command did not RUN, via a marker file, rather than that output looked unchanged). NOT fixed, worth a follow-up: there is no timeout on the child, so a hung preprocess command hangs rledger with no output.
…ing failing --auto
Two findings from review, both reproduced against the built binary
before and after.
1. COMMAND INJECTION, in the pattern the docs recommended
docs/commands/extract.md said:
preprocess = ["sh", "-c", "pdftotext -layout {input} - | to-csv"]
`{input}` is plain text replacement into an argument that `sh -c` then
parses as SOURCE. A file named `a;touch PWNED;b.pdf` created PWNED,
with a config that was entirely the user's own - so every provenance
gate this PR added passed, and the injected command ran anyway.
That is the hole in the trust model as written: it reasons carefully
about where the CONFIG came from, and the FILENAME is an equally
untrusted input in the exact shape it recommended. Importing files you
downloaded is the whole point of the feature.
`rledger extract ~/Downloads/*.pdf` was arbitrary code execution.
Now refused, not warned. This is stderr in the middle of a batch
import, it is silent when it works and catastrophic when it does not,
and the remedy is one line. The feature has never shipped, so nothing
is broken. The error carries the rewrite:
preprocess = ["sh", "-c", "… \"$1\" …", "_", "{input}"]
`{input}` as its own argv element stays allowed - that is what makes
the positional form work, and it is why the plain argv form
(["pdftotext", "-layout", "{input}", "-"]) was never affected: no
shell, so nothing re-parses the path.
2. --auto FAILED ON A CONFIG IT NEVER READS
`maybe_preprocess` ran unconditionally and resolved a config entry up
front. `--auto` and the raw-argument path build their config without
reading importers.toml at all, so:
$ ls
importers.toml statement.csv # two matching importers, no preprocess
$ rledger extract --auto statement.csv
error: Multiple importers match file 'statement.csv': a, b.
Built main to confirm this was a regression and not pre-existing; main
imports the file. Same for a config that merely fails to parse.
Split config discovery (fallible) from running the command, and
discovery no longer reports its own errors. Not swallowing them: every
path that USES a config loads and resolves it again below and reports
the identical error from there. Reporting it from preprocessing only
adds the case where a path that does not use a config gets failed by a
file it would never have read.
3. TESTS THAT CANNOT FAIL, AND A CONDITION THAT DID NOTHING
Sabotaging each mechanism separately turned up two things the tests
alone would not have:
- The first --auto regression test passes with EITHER fix removed,
because two mechanisms independently keep it green. That is depth,
not vacuity - it fails with both gone - but a single-point regression
would have slipped. Added an unparsable-config sibling that isolates
the silencing, which is the load-bearing one, and said so in both.
- The silencing started as `if !(args.config.is_some() ||
args.importer.is_some())`, on the theory that a user who named a
config should hear about it. Making it unconditional failed NO test -
because `--config broken.toml` still errors, from the branch below.
A condition whose removal nothing can detect is complexity pretending
to be caution. Removed.
- The declares-`preprocess` early-out is likewise undetectable by test.
Kept, because it skips resolving a config on every extract run that
cannot need one, but relabelled as an early-out rather than a guard
so nobody later leans on it for correctness.
4. A PRE-EXISTING TEST FLAKE, MADE VISIBLE
`std::env::set_current_dir` is process-global and cargo runs tests on
threads. One cwd-mutating test was already latent here; adding a second
made it fail about half the time. All three now go through a
`with_cwd` helper behind a mutex, restoring the directory even on
panic. Verified stable over five consecutive runs.
Sabotage-verified: removing the splice guard, exempting whole-element
{input}, and removing the silencing each fail exactly one test;
restored is green. cargo test --workspace: 132 suites, 0 failures.
7ef2b4f to
2136204
Compare
Phase 0 of PDF import per the roadmap discussion: rather than shipping a parser, let the user declare how a PDF (or xlsx, or anything) becomes importable — an external command whose output feeds the existing pipeline. A native text-layer parser is the planned phase 1 behind the same config surface.
Usage
The command runs BEFORE format detection:
{input}is replaced with the statement path and stdout lands in a temp.csv, so--autoinference, dispatch, and column mapping all operate on the preprocessed content unchanged.Design
{input}is the only substitution (users opt into a shell explicitly via["sh", "-c", ...]).rustledger_importer::toml_entry, shared with the component — which rejects entries that set it with actionable guidance (a WASI component cannot exec; GUI hosts preprocess themselves and pass bytes).docs/commands/extract.md, and the roadmap: this executes user-authored config, the same boundary as a shell alias or a beangulp Python importer — and a community profile registry must never carrypreprocessentries.Testing
End-to-end
.pdf-named import through a stand-in preprocessor (cat), command-failure error surfacing, schema parse test, component-rejection test (all cfg(unix) where they exec). Clippy-D warnings, fmt, full crate suites clean.🤖 Generated with Claude Code