Skip to content

fix(price): apply the timeout to every price source request - #2876

Merged
robcohen merged 2 commits into
mainfrom
fix/price-timeout
Nov 6, 2026
Merged

robcohen merged 2 commits into
mainfrom
fix/price-timeout

Conversation

@robcohen

@robcohen robcohen commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

What changed

  • New shared request helper in crates/rustledger/src/cmd/price/sources/mod.rs:
    • http_get(url, timeout, headers) applies the source's timeout to the whole request (RequestBuilder::config().timeout_global), sets the shared user_agent(), and uses http_status_as_error(false) so a 4xx/5xx body is read rather than discarded (as fix(price): point ratesapi at Frankfurter, as beanprice does #2864 did for ratesapi). It returns the status and body.
    • HttpReply::into_success_body / into_success_json turn a non-2xx status into an error that names the fetch, the status, and a one-line excerpt (max 300 chars) of the provider's body.
    • http_get_json / http_get_text wrap the common 2xx-only case.
  • All 11 source modules (14 call sites) now store their timeout and request only through the helper. ratesapi keeps its own handle_response on the raw reply; ecb keeps "404 means no observations" by checking the reply status.
  • Removed the wrong note claiming ureq 3 has no per-request timeout, and the per-constructor "timeout is accepted but not applied" docs.

Why

Every source discarded its timeout (_timeout) and called ureq::get directly, so a stalled provider blocked rledger price with no limit.

How to test

cargo test -p rustledger --all-features --lib http_tests:

  • test_http_get_applies_the_timeout: a local listener that never answers must fail a 200ms request with a timeout error. The request runs on a thread with a 10s receive deadline, so a missing timeout fails instead of hanging. I checked this by sabotage: with the timeout removed, the test fails with "the 200ms timeout did not apply".
  • test_http_get_is_the_only_request_path: a drift guard that no source file uses ureq:: directly.
  • Error-body formatting tests: excerpt, empty body, 2xx pass-through, and UTF-8-safe truncation.

No test makes a real network call.

Verified locally:

  • cargo fmt --check, cargo clippy --all-features --all-targets -- -D warnings, and RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps pass.
  • cargo test -p rustledger --all-features --no-fail-fast passes except plugin_conformance::python_plugins_back_to_back_after_a_timeout. That test is unrelated to this change (Python plugin time budget) and is load-sensitive: it passes when run alone.
  • The pre-push hook's bean-price compat tests pass.

Closes #2870

Review round 1

  • Regression fixed: [price] timeout = 0 broke every source, because ureq fails at once on a zero Duration. Zero now means no limit, which is main's behavior and the same convention as cache_ttl = 0. No CLI flag sets the timeout. test_http_get_zero_timeout_means_no_limit uses a local server that answers after 100ms. With zero passed through to ureq, the test fails.
  • Timeouts are visible: http_get wraps ureq's timeout error as no complete response within the 30s timeout (set by [price] timeout). fetch_failed now prints the whole cause chain ({e:#}) in the comment line, the --verbose line, and the coded diagnostic. The ag-rledger envelope test, which checks that the message starts with Failed to fetch AAPL: , still passes.
  • API keys redacted: the error-body excerpt replaces the source's API key with [REDACTED]. That covers Alpha Vantage and Quandl (key in the query string) and OANDA and CoinMarketCap (key in a header). The new test is test_into_success_body_redacts_the_api_key.
  • Drift guard: it reads the sources/ directory, so a new source file is checked too. It also asserts that it found at least 11 files.
  • Docs: the PriceConfig::timeout doc no longer claims a ureq limitation. It says 0 means no limit, and that command sources are not limited. docs/commands/price.md notes 0 = no limit, and there is a CHANGELOG entry under Fixed.
  • Re-verified: fmt, clippy -D warnings, cargo doc -Dwarnings, and cargo test -p rustledger --all-features --no-fail-fast all pass. The one exception is the flaky python_plugins_back_to_back_after_a_timeout, which also fails on main.

🤖 Generated with Claude Code

Every price source constructor discarded its timeout and called
`ureq::get` directly, so a stalled provider hung `rledger price` with no
limit. All requests now go through one helper, `http_get` in
`sources/mod.rs`, which applies the timeout to the whole request
(`timeout_global`), sets the shared User-Agent, and reads 4xx/5xx bodies
instead of turning them into a bare status error, so a non-2xx error
quotes the provider's message. `http_get_json` / `http_get_text` wrap it
for the common 2xx-only case; ratesapi and ecb keep their own status
handling on the raw reply.

Tests: a local listener that never answers must make a 200ms request
fail with a timeout (run on a thread, so a missing timeout fails instead
of hanging), a guard that no source file uses ureq directly, and the
error-body formatting. The wrong note that ureq 3 has no per-request
timeout is gone.

Closes #2870

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner November 6, 2026 16:50
@github-actions

github-actions Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 50.8ms ± 1.3ms 764.5ms ± 22.5ms 15.1x 42.9 MB / 51.1 MB
investment 81.3ms ± 1.0ms 2803.9ms ± 20.0ms 34.5x 59.0 MB / 59.2 MB
fifo 75.6ms ± 1.0ms 16655.0ms ± 1074.3ms 220.3x 54.9 MB / 58.8 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 50.6ms ± 0.4ms 50.8ms ± 1.3ms +0.4% ✅ within noise 42.5 MB → 42.9 MB (+1.0%)
investment 81.7ms ± 1.9ms 81.3ms ± 1.0ms -0.5% ✅ within noise 58.8 MB → 59.0 MB (+0.4%)
fifo 78.4ms ± 3.1ms 75.6ms ± 1.0ms -3.6% ✅ within noise 54.6 MB → 54.9 MB (+0.5%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 0.6ms, investment 1.0ms, fifo 1.4ms), 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 Nov 6, 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 826
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

…edact API keys

Review round 1 of #2876:

- `[price] timeout = 0` is no limit again. ureq fails at once on a zero
  `Duration`, so the helper passes no timeout for zero (the same
  convention as `cache_ttl = 0`). No CLI flag sets the timeout.
- A timeout names itself: `http_get` wraps ureq's timeout error with the
  limit and the setting, and a fetch failure prints the whole cause
  chain (`{e:#}`) in the comment line, the verbose line and the coded
  diagnostic.
- The error-body excerpt replaces the source's API key with
  `[REDACTED]` (Alpha Vantage and Quandl put it in the query string;
  OANDA and CoinMarketCap send it in a header).
- The ureq drift guard reads the sources directory instead of a fixed
  file list.
- The `PriceConfig::timeout` doc no longer claims ureq 3 cannot enforce
  it; docs/commands/price.md and the CHANGELOG describe the fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen merged commit fe781a9 into main Nov 6, 2026
49 of 50 checks passed
@robcohen
robcohen deleted the fix/price-timeout branch November 6, 2026 18:39
robcohen added a commit that referenced this pull request Nov 6, 2026
… source's ticker form (#2883)

* fix(price): treat a timeout past 100 years as no limit

`[price] timeout = 9223372036854775807` (the largest TOML integer), or
anything near `u64::MAX` seconds, panicked inside ureq with "overflow
when adding duration to instant": ureq adds the timeout to an
`Instant`. #2876 introduced this, since the timeout used to be ignored.
`http_get` now gives ureq no limit for a timeout over
`MAX_REQUEST_TIMEOUT` (100 years), as it does for zero.

The timeout error is now one message: ureq's trailing
`: timeout: global` only repeated it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(price): read bean-price's source specs, with `^` inversion and each source's ticker form

A `price:` spec written for bean-price failed in `rledger price`:
`EUR:ratesapi/USD-EUR` asked Frankfurter for `USD-EUR` in EUR (HTTP
404), and a `^` was sent to the provider as part of the ticker.

Matching bean-price 2.1.0's `price.py` and source modules:

- `^TICKER` inverts on every source. The registry strips the `^`,
  fetches, and writes `1 / price` labeled with the declared quote
  currency, as bean-price does. The digits follow bean-price's
  `ONE / price` (28 significant digits, half-even; an exact quotient in
  its shortest form), within `rust_decimal`'s 28 decimal places.
- A ticker that names its own quote currency is read into the fetched
  pair by a new `PriceSource::bean_price_pair` hook, before the
  dispatch: `ratesapi` and `ecb` read `BASE-SYMBOL`, `coinmarketcap`
  reads `SYMBOL-BASE`, and `alphavantage` reads `price:SYMBOL:BASE` and
  `fx:CCY:BASE`.
- `quandl` reads `DB:DS[:COLUMN]` with beanprice's column choice
  (`Adj. Close`, else `Close`, or the named column with `_` as a space).
- `coincap` looks up an upper-case symbol its table lacks in the asset
  list, taking the first match by market cap, as beanprice does.
- `tsp` accepts beanprice's `LInco`.
- `ecbrates`, beanprice's name for the ECB source, resolves to `ecb`.

rledger's own ticker forms keep working. The bean-price compat harness
gains a fixture covering every source's spec form and `^`, and maps
bean-price's `1/TICKER` dry-run display to `^TICKER`.

Closes #2866

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(price): keep `^` to price: specs, judge and round inverses exactly

Review round 1 of #2883:

- `^` inverts only in `price:` metadata, the one place bean-price's
  grammar applies. `PriceSourceRegistry::fetch_price` keeps every
  ticker verbatim again, so a `[price.mapping]` ticker, `--mapping` and
  `--source` send Yahoo's `^GSPC` as written, as on main; the new
  `fetch_price_for_spec` reads the spec grammar and is used for
  mappings read from `price:` metadata.
- An inverse must be a price of the pair it is labeled with: the quote
  must be in the commodity and, for a ticker the source reads as a
  pair, the pair must be based in the declared currency. Otherwise it is
  refused, as the #2731 label check refuses the same mismatch without
  `^`.
- The inverse is computed in exact integer arithmetic and rounded once,
  half to even, to 28 significant digits: it matched Python's
  `ONE / D(x)` on 20,000 random samples at or above 0.1. Below 0.1 the
  documented `rust_decimal` limit stands (k - 1 fewer digits near
  10^-k).
- Stricter than Python: bean-price's `ecbrates` leaks its leg
  precision into `ONE / price` (about six digits); rledger keeps 28.
- `^^X` and a bare `^` are refused; an inverse that rounds to zero is
  refused like a zero price; a zero quote falls through the chain,
  where bean-price aborts.
- `coincap`: the lookup comment no longer claims beanprice's exact
  scan, and a provider-returned asset ID is validated before it goes
  into the URL path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(price): check the base of every pair ticker an inversion reads

Review round 2 of #2883:

- The base check of a `^` inversion ran only when `bean_price_pair`
  rewrote the pair, so oanda (`EUR_CHF`), coinbase (`BTC-USD`) and
  yahoo (`EURCHF=X`, `BTC-USD`), which read their own pair, were never
  checked: `USD:oanda/^EUR_CHF` on CHF wrote EUR per CHF labeled USD.
  A new `PriceSource::pair_base` hook names the base of a ticker that
  names its own pair; ratesapi, ecb, coinmarketcap, alphavantage,
  coinbase, oanda and yahoo implement it, and `fetch_inverse` checks it
  before any fetch. Yahoo share classes (`BRK-B`) name no pair.
- A failed inversion now says the `^` was read as bean-price's
  inversion, and that a literal `^` ticker belongs in
  `[price.mapping]` or `--mapping`. The CHANGELOG and docs carry the
  migration line for `price: "USD:yahoo/^GSPC"`.
- Docs: the inverse rule stated exactly, refusals apply without `-b`
  too, `^^X` is no longer listed as stricter than Python, and "at or
  above 2 * 10^28".

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(price): read every inversion base with the source's own request code

Review round 3 of #2883:

- `pair_base` is now derived from the code each source builds its
  request with, not a separate pattern: ratesapi, ecb and coinmarketcap
  from `bean_price_pair`; coinbase from the new `spot_pair` its URL is
  built from; oanda from `format_instrument` and the new
  `instrument_sides` that also labels the response, so CFDs such as
  `NAS100_USD` are checked; alphavantage from the new `route` its fetch
  dispatches on. Bare tickers quoted in the requested currency report
  their base too, so a nonsense inversion of one is refused.
- yahoo, which sends its ticker as it is, keeps its pair conventions,
  now case-insensitive, and reads `XXX=X` (`JPY=X`) as USD-based.
- The inversion note is attached once per failed fetch, after the
  attempts, as ` (note: ...)`, and the `^^X` refusal carries it too.
  Mismatch messages print the base and quote upper-case.
- Tests: oanda CFDs, Yahoo `JPY=X` both ways, lower-case tickers,
  alphavantage `price:IBM:USD` both ways, and the note once per fetch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(price): check the base of a coincap inversion

Review round 4 of #2883: coincap quotes every asset in USD, but had no
`pair_base`, so `USD price: "EUR:coincap/^BTC"` wrote BTC per USD
labeled EUR. Its `pair_base` is now the ticker, upper-case, and the
inversion is refused unless declared in that asset.

The `pair_base` trait doc now says what the default `None` means (the
source cannot read a base), the coinmarketcap doc example uses
`BTC-CHF`, and docs/commands/price.md lists coincap and says an
inverted equity ticker is refused when its exchange-qualified base
(`VOD.LON`) differs from the declared currency.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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.

fix(price): price sources other than ratesapi ignore the configured timeout

1 participant