Something went wrong. Try again.
Convert CSV banking statements to hledger journals
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217//! Times each step of evaluating a generated project, the work behind one//! `PUT /api/rules`.//!//! Built only by `zig build bench`, never installed. The project is generated//! rather than read, so the numbers depend on no one's bank data. Its shape is//! the one the interface's debug log showed to be slow: a thousand rows with//! long booking texts, and some thirty rules of five or'd predicates each,//! mostly regexes. Pass `-Doptimize` to compare builds.
const std = @import("std");const builtin = @import("builtin");const csv2journal = @import("csv2journal");const diag = csv2journal.diag;const engine = csv2journal.engine;const LapTimer = csv2journal.time.LapTimer;const Stopwatch = csv2journal.time.Stopwatch;
/// The engine logs its own timings at debug; here they would only repeat/// what the bench reports.pub const std_options: std.Options = .{ .log_level = .warn };
const Error = error{ EngineFailed, OutOfMemory, WriteFailed };
/// Each step is timed this often, so the spread shows how far to trust it.const runs = 3;
/// A generated project in which every row matches exactly one rule.////// Each rule has five predicates and only the last one matches its rows, so/// every rule evaluates all five for every row -- the most work an `or` can/// cost, and what a rule matching on its last alternative does.const Fixture = struct { csv: []const u8, rules: []const u8,
const manifest = \\schema: \\ version: 1 \\project: \\ inputPath: data \\profile: \\ name: Bench \\ rulesFile: rules.yaml \\ csv: \\ delimiter: comma \\ lineEnding: lf \\ skipRecords: 0 \\ header: true \\ fields: \\ date: \\ header: Date \\ amount: \\ header: Amount \\ posting: \\ header: Posting \\ transaction: \\ date: \\ field: date \\ format: YYYY-MM-DD \\ amount: \\ field: amount \\ decimalSeparator: dot \\ currency: \\ fixed: EUR \\ sourceAccount: "assets:bank" \\ narrationTemplate: "{posting}" \\ ;
const Shape = struct { rows: usize, rules: usize, };
fn init(arena: std.mem.Allocator, shape: Shape) error{OutOfMemory}!Fixture { var rules: std.ArrayList(u8) = .empty; try rules.appendSlice(arena, "schema:\n version: 1\nrules:\n"); for (0..shape.rules) |rule| { try rules.print(arena, \\ rule{0d:0>3}: \\ match: 'posting ~= /^Kartenzahlung Shop{0d:0>3} / or posting ~= /SHOP{0d:0>3}-ONLINE/i or posting ~= /Mandat\s+M{0d:0>3}\d{{6}}/ or amount == -9{0d:0>3}9.99 or posting ~= /Ref\. R{0d:0>3}[A-Z]{{4}}/' \\ set: \\ targetAccount: "expenses:r{0d:0>3}" \\ , .{rule}); }
var csv: std.ArrayList(u8) = .empty; try csv.appendSlice(arena, "Date,Amount,Posting\n"); for (0..shape.rows) |row| { try csv.print( arena, "2026-09-{d:0>2},-{d}.{d:0>2},SEPA-Lastschrift von Haendler GmbH Mandat 1043587263418 " ++ "Ref. R{d:0>3}ABCD Kartenzahlung Debitk.12 VISA Debit {d}\n", .{ row % 28 + 1, row % 500 + 1, row % 100, row % shape.rules, row }, ); }
return .{ .csv = csv.items, .rules = rules.items }; }
/// The candidate a session prepares for each evaluation. fn prepare(self: Fixture, arena: std.mem.Allocator, diags: *diag.List) Error!engine.Candidate { return engine.prepare( arena, .{ .path = "project.yaml", .text = manifest }, .{ .path = "rules.yaml", .text = self.rules }, diags, ); }};
/// What the steps share, made once and outside the timing.const Setup = struct { fixture: Fixture, history: []const csv2journal.Snapshot.HistoryFiles,
fn init(arena: std.mem.Allocator, fixture: Fixture) Error!Setup { const diags = try diag.List.create(arena); // The approved journal is what the current rules produce, so the // history validates and does all its work. const journal = try engine.generate(arena, try fixture.prepare(arena, diags), "bench.csv", fixture.csv, diags); const history = try arena.dupe(csv2journal.Snapshot.HistoryFiles, &.{.{ .csv = fixture.csv, .csv_path = "bench.csv", .journal = try arena.print("{f}", .{journal}), .journal_path = "bench.journal", }}); return .{ .fixture = fixture, .history = history }; }};
/// The steps of one evaluation, in the order the session runs them.const Step = enum { classify, history, profile, read, rules,
const order = [_]Step{ .profile, .rules, .read, .classify, .history };
fn label(self: Step) []const u8 { return switch (self) { .classify => "classify the rows", .history => "validate the history", .profile => "load the profile", .read => "read the CSV", .rules => "prepare the rules", }; }
fn run(self: Step, arena: std.mem.Allocator, setup: Setup, candidate: engine.Candidate) Error!void { const diags = try diag.List.create(arena); const profile = candidate.profile; const csv = setup.fixture.csv; switch (self) { .classify => _ = try engine.classify(arena, candidate, "bench.csv", csv, diags), .history => try engine.validateHistory(arena, candidate, setup.history, diags), .profile => _ = try engine.Profile.load(arena, .{ .path = "project.yaml", .text = Fixture.manifest }, diags), .read => _ = try engine.classifyUnevaluable(arena, profile, "bench.csv", csv, diags), .rules => _ = try engine.Candidate.withRules(arena, profile, .{ .path = "rules.yaml", .text = setup.fixture.rules }, diags), } }};
pub fn main(init: std.process.Init) Error!void { const arena = init.arena.allocator(); const shape: Fixture.Shape = .{ .rows = 1000, .rules = 30 }; const setup = try Setup.init(arena, try Fixture.init(arena, shape));
var buffer: [512]u8 = undefined; var stdout = std.Io.File.stdout().writer(init.io, &buffer); const out = &stdout.interface; try out.print("{d} rows, {d} rules of 5 predicates, {t}, {d} runs per step\n", .{ shape.rows, shape.rules, builtin.mode, runs, });
var scratch = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer scratch.deinit(); for (Step.order) |step| { var peak: usize = 0; var timer: LapTimer = .start(); for (0..runs) |_| { // As in a session, the rules are prepared in the arena the // evaluation uses, and what their regexes allocate counts too. const candidate = try setup.fixture.prepare(scratch.allocator(), try diag.List.create(scratch.allocator())); const watch: Stopwatch = .start(); try step.run(scratch.allocator(), setup, candidate); timer.add(watch.elapsed().duration); peak = @max(peak, scratch.queryCapacity()); _ = scratch.reset(.free_all); } const mebibytes = @as(f64, @floatFromInt(peak)) / (1024 * 1024); try out.print("{s:<22}{f}, arena {d:.1} MiB\n", .{ step.label(), timer.elapsed(), mebibytes }); try out.flush(); }}
// -- tests -------------------------------------------------------------------
test "every generated row matches exactly one rule" { var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator();
const setup = try Setup.init(arena, try Fixture.init(arena, .{ .rows = 40, .rules = 8 })); const diags = try diag.List.create(arena); const candidate = try setup.fixture.prepare(arena, diags); const classified = try engine.classify(arena, candidate, "bench.csv", setup.fixture.csv, diags);
try std.testing.expectEqual(40, classified.rows.len); for (classified.rows) |row| try std.testing.expectEqual(engine.RowStatus.one, row.status); try std.testing.expect(diags.isEmpty()); try engine.validateHistory(arena, candidate, setup.history, diags);}