diff --git a/crates/ledger-core/tests/oracle_gnucash.rs b/crates/ledger-core/tests/oracle_gnucash.rs index 2b238a46..86294577 100644 --- a/crates/ledger-core/tests/oracle_gnucash.rs +++ b/crates/ledger-core/tests/oracle_gnucash.rs @@ -4,7 +4,8 @@ //! spec (docs/oracle.md, "Who is right"). This test builds random books //! through wanderbooks' engine (entries, foreign-currency lines, reversals, //! period closes), hands their posted entries to GnuCash 5.10 running in a -//! pinned container (oracle/gnucash/), and compares every account's +//! pinned container (bookspec's `gnucash/oracle/`, image +//! `bookspec-gnucash-oracle`), and compares every account's //! balance at month ends and random dates, exactly. A difference is a //! finding to adjudicate from principles (rules.md), never a reason to //! change wanderbooks to match. @@ -188,7 +189,7 @@ fn ours(l: &Ledger, as_of: NaiveDate) -> BTreeMap { fn gnucash(books: &[Value]) -> Vec { let mut child = Command::new("docker") - .args(["run", "--rm", "-i", "wanderbooks-gnucash-oracle"]) + .args(["run", "--rm", "-i", "bookspec-gnucash-oracle"]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::null()) diff --git a/justfile b/justfile index a4866367..e1136470 100644 --- a/justfile +++ b/justfile @@ -179,8 +179,22 @@ _kani set: echo "Kani ({{set}}): $(wc -l <<<"$names") harnesses verified" # Random books through wanderbooks and GnuCash 5.10, compared exactly (Docker) +# The oracle's Dockerfile and runner live in bookspec (`gnucash/oracle`, +# image `bookspec-gnucash-oracle`): one source of truth. This builds that +# image from the pinned bookspec checkout (the rev in ledger-core's +# Cargo.toml), so no copy is kept here. oracle: - docker build -q -t wanderbooks-gnucash-oracle oracle/gnucash + #!/usr/bin/env bash + set -euo pipefail + rev=$(sed -nE 's/.*bookspec-checker.*rev = "([0-9a-f]+)".*/\1/p' crates/ledger-core/Cargo.toml | head -1) + [ -n "$rev" ] || { echo "oracle: no bookspec rev pinned in crates/ledger-core/Cargo.toml" >&2; exit 1; } + cargo fetch --locked >/dev/null 2>&1 || cargo fetch >/dev/null + checkout=$(ls -d "${CARGO_HOME:-$HOME/.cargo}"/git/checkouts/bookspec-*/"$rev" 2>/dev/null | head -1 || true) + if [ -z "$checkout" ] || [ ! -f "$checkout/gnucash/oracle/Dockerfile" ]; then + echo "oracle: bookspec checkout for rev $rev not found under ${CARGO_HOME:-$HOME/.cargo}/git/checkouts (ran cargo fetch; is the pin fetched?)" >&2 + exit 1 + fi + docker build -q -t bookspec-gnucash-oracle "$checkout/gnucash/oracle" cargo test -p ledger-core --test oracle_gnucash -- --ignored --nocapture # Fuzz one target for some seconds (nightly; corpus in fuzz/corpus/) diff --git a/oracle/gnucash/Dockerfile b/oracle/gnucash/Dockerfile deleted file mode 100644 index 85d37a25..00000000 --- a/oracle/gnucash/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -# GnuCash as a cross-check oracle (docs/oracle.md, "Who is right"): one -# independent implementation of double entry we diff against. Its answers -# are evidence, never the spec. Pinned so every run uses the same GnuCash. -FROM debian@sha256:a29215f6a35e51e22adffa17f89e9d2ef06214e64a2bad10d765c46aea49f11f -RUN apt-get update \ - && apt-get install -y --no-install-recommends \ - gnucash=1:5.10-0.1+b1 python3-gnucash=1:5.10-0.1+b1 \ - && rm -rf /var/lib/apt/lists/* -COPY books.py /oracle/books.py -ENTRYPOINT ["python3", "/oracle/books.py"] diff --git a/oracle/gnucash/books.py b/oracle/gnucash/books.py deleted file mode 100644 index 75cff3df..00000000 --- a/oracle/gnucash/books.py +++ /dev/null @@ -1,96 +0,0 @@ -"""Build books in GnuCash and report its balances. - -stdin: a JSON list of books: - {"accounts": [{"id": 1, "code": "1000", "name": "Cash", "type": "Asset"}], - "entries": [{"date": "2026-01-15", "description": "...", - "lines": [{"account": 1, "side": "debit", "amount": "12.34"}]}], - "as_of": ["2026-01-31", ...]} -stdout: a JSON list, one per book: - {"balances": {"2026-01-31": {"1": "12.34", ...}, ...}} -Balances are GnuCash's own: the sum of split values on the account through -the end of that day, debits positive, as an exact decimal string. -""" -import datetime, json, os, sys, tempfile -from decimal import Decimal -import gnucash -from gnucash import Account, GncNumeric, Session, SessionOpenMode, Split, Transaction - -TYPES = { - "Asset": gnucash.ACCT_TYPE_ASSET, - "Liability": gnucash.ACCT_TYPE_LIABILITY, - "Equity": gnucash.ACCT_TYPE_EQUITY, - "Revenue": gnucash.ACCT_TYPE_INCOME, - "Expense": gnucash.ACCT_TYPE_EXPENSE, -} - - -def numeric(amount: str) -> GncNumeric: - d = Decimal(amount) - sign, digits, exp = d.as_tuple() - denom = 10 ** max(0, -exp) - num = int(d * denom) - return GncNumeric(num, denom) - - -def decimal_of(n) -> str: - return str(Decimal(n.num()) / Decimal(n.denom())) - - -def end_of_day(date: str) -> int: - d = datetime.date.fromisoformat(date) - return int(datetime.datetime(d.year, d.month, d.day, 23, 59, 59, - tzinfo=datetime.timezone.utc).timestamp()) - - -def run(book_spec, path): - s = Session(f"xml://{path}", SessionOpenMode.SESSION_NEW_STORE) - try: - book = s.book - root = book.get_root_account() - usd = book.get_table().lookup("CURRENCY", "USD") - accounts = {} - for a in book_spec["accounts"]: - acct = Account(book) - acct.SetName(f'{a["code"]} {a["name"]}') - acct.SetCode(a["code"]) - acct.SetType(TYPES[a["type"]]) - acct.SetCommodity(usd) - root.append_child(acct) - accounts[a["id"]] = acct - for e in book_spec["entries"]: - d = datetime.date.fromisoformat(e["date"]) - tx = Transaction(book) - tx.BeginEdit() - tx.SetCurrency(usd) - tx.SetDate(d.day, d.month, d.year) - tx.SetDescription(e.get("description", "")) - for line in e["lines"]: - value = numeric(line["amount"]) - if line["side"] == "credit": - value = value.neg() - sp = Split(book) - sp.SetParent(tx) - sp.SetAccount(accounts[line["account"]]) - sp.SetValue(value) - sp.SetAmount(value) - tx.CommitEdit() - out = {} - for date in book_spec["as_of"]: - t = end_of_day(date) - out[date] = {str(i): decimal_of(a.GetBalanceAsOfDate(t)) for i, a in accounts.items()} - return {"balances": out} - finally: - s.end() - - -def main(): - books = json.load(sys.stdin) - results = [] - with tempfile.TemporaryDirectory() as tmp: - for i, b in enumerate(books): - results.append(run(b, os.path.join(tmp, f"book{i}.gnucash"))) - json.dump(results, sys.stdout) - - -if __name__ == "__main__": - main()