Code review · fdd-database · main @ 30339a5

FDD Database Review

A financial due-diligence tool in Python and Postgres: trial-balance and journal import, account mapping, statement rendering, adjustments, cash flow. Reviewed on two axes — correctness defects that are wrong today, and architectural friction that makes tomorrow's changes expensive.

src
30,272
tests
1,030
bugs
5
arch findings
7
decision records
62

This is a well-built codebase — dated decision records, near-total docstring coverage, CI gating ruff, pytest and mypy, and a schema defended by CHECK constraints and plpgsql triggers. The findings below are not about neglect. They cluster around one shape: the domain's hardest rules live inside SQL string literals and regex character classes, and neither can be imported or type-checked — so each new surface re-types the rule, and a parsing mistake fails silently instead of loudly.

Correctness findings

fix now

Actual defects, listed first because they are wrong in production today. Findings 1–4 were confirmed by executing the code; finding 5 is latent. They compound: the E-notation defect corrupts values silently, the separator defects push German amounts into the parse-failure path, and finding 4 turns that failure into a plausible-looking wrong number instead of a rejected row.

DefectWhat goes wrongFixSeverity
01 Currency regex eats letters parser/numbers.py:24
_CURRENCY_NOISE

It is a character class, not an alternation, so it strips any single C/H/F/E/U/R/S/D letter — either case — anywhere in the cell.

verified by execution
'2E6'   → 26
'1.5E3' → 1.53
'7E2'   → 72

It parses successfully, so the caller's warn-and-skip path never fires. A 2,000,000 balance imports as 26 with no error anywhere downstream.

Make it an alternation over whole currency tokens — CHF|EUR|USD|[€$£¥₣] — anchored to word boundaries, so it can never eat a digit-adjacent letter. High
02 German format never parses parser/numbers.py:20
_DEFAULT_THOUSANDS_SEPARATORS

The default tuple omits ".", so the German format the module docstring advertises fails — even when the caller correctly passes decimal_separator=",". The strip loop skips "," because it is the decimal separator, and never strips ".", leaving 1.234.56, which Decimal rejects.

verified by execution
'1.234,56'     → None
'1.234.567,89' → None
'999,50'       → 999.50  ✓

Only unseparated German values survive.

Add "." to the tuple — the existing "never strip the decimal separator" guard already makes that safe in both locales.

Same incomplete tuple copied in models.py:67, fs_committer.py:52, imports.py:48 — fix all four, or give them one home.
High
03 Journal import drops separators web/routes/import_journal.py:163

It passes decimal_separator but never thousands_separators — unlike the TB importer (imports.py:559) and the FS importer (import_fs.py:545), which both call _thousands(...).

So a German ledger export with the decimal separator set to ',' falls through to the broken default from finding 2, and every 1.234,56 is dropped.

The TB form offers a "Thousands separators" input (import.html:111) as a workaround. The journal form has none — so German journal files cannot be imported at all through the UI.

Thread _thousands(...) into the journal config the way the other two wizards do, and add the matching field to journal_import.html.

Fixing finding 2 repairs the default path; this restores user control.
High
04 Bad debit silently becomes zero parser/journal_parser.py:272
_line_amount

(debit or 0) - (credit or 0) cannot distinguish "blank" from "failed to parse", and the guard above rejects the row only when both sides are None.

A row with debit 1.234,56 (unparseable, per finding 2) and credit 500,00 (valid) is accepted and books 0 − 500 = −500.

The malformed debit vanishes silently — no warning fires, because the function returned a value rather than None. The journal then looks internally consistent while being wrong.

Distinguish the two states: treat an unparseable-but-non-empty cell as a rejection, and reserve the zero default for a genuinely empty one.

Blank-vs-invalid is the caller's decision, not a silent coercion.
Medium
05 to_excel mangles a sheet named TB services/amount_expr.py:208

\bTB\b matches the sheet-name half of a workpaper reference, because ! is a non-word character and satisfies the trailing word boundary.

A sheet named TB — natural in a tool whose own vocabulary is "trial balance" — canonicalises to TB!C5, and to_excel rewrites it to =Database!D10!C5, invalid Excel.

Latent: the function has no callers today, and the docstring's claim that extract_export uses it is stale — that module emits no TB formulas at all.

Either delete the function and correct the docstring, or make the substitution skip tokens containing ! before wiring it up.

Stale docs pointing at broken dead code is the real trap.
Low

Checked and clean

Raw-SQL injection surfaces (all nine f-string text() sites interpolate from closed sets); auth and per-project authorization; schema CHECK constraints and triggers; expression evaluation and ratio cycle detection; upload handling and download headers.

Two things looked like bugs and were verified not to be: the five copies of the BS-movement rule currently do agree with each other, and the fiscal quarter / half-year / year arithmetic is correct across non-January fiscal starts.

Not covered

The running application, PDF snipping geometry, and Excel / chart export output.

These need a live database and rendered artifacts to judge. Static reading was not enough to claim anything about them in either direction — so nothing here is a clean bill of health for those paths.

Architecture findings

pays off over months

Ranked by how much future change each one makes easier, not by severity. Nothing here is broken today. Strength reflects confidence that deepening pays off.

FindingWhy it hurtsHow to improveStrength
01Layer algebra has no home rendering_service.py:177 (private)
extract_plan.py:41
databook.py:45
The reported→mgmt→bdo cumulation rule is written three times. Two copies carry docstrings admitting they mirror a private function. A fourth layer means finding and editing all three.

Promote the private function to a module. A services/layer_algebra.py owning the layer vocabulary, returning a LayerExpansion value object. Re-express kind_buckets and _KIND_TARGET as thin projections, then delete both "mirrors…" comments.

≈ half a day. One table test replaces coverage across three suites.
Strong
02BS-movement rule copied as SQL rendering_service.py:741, :970
queries.py:517, :546
routes/adjustments.py:212
Five hand-written copies of one correctness-critical rule — "current sum − prior sum, prior matched on period.kind". It produces the quality-of-earnings figure a deal team signs off on, and the copies can silently drift apart.

Give the rule one composable home. A services/bs_movement.py exposing prior_period_id(...) and an effective_amount_sql(line_alias, period_alias) fragment. Callers keep their own SELECTs but stop re-typing the arithmetic.

Alternative worth weighing: a Postgres VIEW or generated column, which also covers the CLI and any future reporting path.
Strong
03Domain logic living in a route web/routes/adjustments.py
1,605 lines · 15 endpoints
20 private helpers
Intercompany elimination, provenance drift, split logic and a formula grammar all sit behind HTTP handlers — so the only way to exercise them is to POST a form. Largest file in src/, and still growing.

Extract a read model; leave transport behind. One build_adjustments_view(...) returning the page's whole view state as a typed value. Move _parse_cell_formula into the amount_expr module it duplicates. Handlers shrink to parse → call → commit → redirect.

Sequence after #2 — a third of the helper mass is the duplicated movement rule.
Strong
04queries.py is shallow and untyped web/queries.py · 759 lines
25 pass-throughs · 21 Any
27 template call sites
Rows leave as list[Any], so row.acount_number type-checks, renders empty, and ships. mypy gates CI but is vacuous exactly where the code changes fastest.

Type the rows, then split by concept. (a) A NamedTuple per query — zero runtime cost, and the mypy gate starts biting at all 27 call sites. (b) Split the 759 lines along the concepts its comments already group by.

(a) pays off even if (b) never happens. Don't delete this module — that spreads complexity into handlers.
Worth it
05No schema seam ~350 text() sites
30 modules with 5+
mapping_service 26 · queries 25
Table and column names exist only as substrings of Python strings. One machine-readable schema description exists — the 1,932-line Alembic baseline — and nothing links it to the 350 places depending on it. A rename is grep-and-pray.

Declare the schema once; let CI hold it. A schema.py of Core Table objects plus an Alembic compare_metadata check, so the declaration cannot drift from the migrations. Existing text() queries keep working untouched.

Largest item here, least urgent. Give it its own decision entry.
Worth it
06Presentation assembled four times routes/render.py:372
extract_data.py:80
databook.py:189
cli/commands/statement.py
All four call render_statement, then each independently orders roots, labels them and applies buckets. Section order is user-configurable, so screen, extract and workbook can drift apart.

Move the seam one step outward. A pure statement_layout module taking a RenderResult plus display settings and returning ordered, labelled sections. Each surface keeps its own rendering but shares the ordering.

No session argument, so the WYSIWYG promise becomes assertable without Postgres.
Worth it
07The test surface is Postgres tests/conftest.py
63 of 80 files DB-bound
1,030 tests · 27k lines
A rule expressed in SQL can only be tested by executing SQL. So "does a first-period derived line carry the full balance?" — pure arithmetic — costs a container, a transaction and a seeded project.

Do not act on this directly. Mocking the session would make the tests worse; the transactional-rollback fixture is well built and should stay. It resolves as a side effect of 1, 2 and 6.

Watch "test files that don't take the session fixture" (17/80 today) as the metric that deepening is working.
Speculative

The seven candidates in detail

Each card applies the same test: would deleting the thing concentrate complexity, or just move it? A "concentrates" is the signal worth acting on.

01 · Layer algebra

Strong
Problem

The rule that says which value sources a layer cumulates lives in a private function. Two other surfaces cannot import it, so they re-type it — and say so in their docstrings: "Mirrors rendering_service._expand_layer". A comment promising two surfaces stay in lockstep is the codebase naming the module it wants.

Benefit

Three callers exist today, so the seam is real rather than hypothetical. The §3.7 layers-≤-L rule becomes one file you can read in thirty seconds, and one parametrised table test — needing no database — replaces coverage currently smeared across three suites.

Before · three copies
_expand_layer  ⛔ private
kind_buckets  "mirrors…"
_KIND_TARGET  "matches…"

Copied by hand, not called. A fourth layer costs three edits and three test suites.

→
After · one module
layer_algebra.expand()
rendering_service
extract_plan
databook

Imported, not copied. One edit adds a layer; one test covers all three surfaces.

Deletion testDelete kind_buckets: complexity concentrates into one module. ✔

02 · Balance-sheet movement

Strong
Problem

A derived normalization line has no stored amount: it is the referenced BS adjustment's current-period sum minus its prior-period sum, prior matched on project, period kind and greatest date_end below the current one. That sentence exists only as five independently typed correlated subqueries, each re-deriving the "no prior period → 0" edge case by hand.

Benefit

Five existing callers — the strongest seam evidence in the repo. The four edge cases (first period, no lines, kind mismatch, NULL amount) get tested once instead of never. The copies happen to agree today; nothing makes them keep agreeing.

Before · five copies
rendering · tree values
rendering · breakdown
queries · line detail
queries · account deltas
routes · page grid

No compiler, type or test binds them. Drift is silent: the page shows one number, the statement another.

→
After · one fragment
bs_movement.effective_amount_sql()
rendering × 2
queries × 2
routes × 1

Callers compose it into their own SELECT. One place to test the edge cases.

Deletion testDelete any one copy: the others do not cover it, and the behaviour vanishes from that surface. Complexity concentrates under a shared module. ✔

03 · A domain module wearing a router

Strong
Problem

The module docstring is excellent and forty lines long — eligibility pre-filtering, trigger passthrough, derived-line semantics, inline-edit identity. That is a domain docstring on a transport file, and the consequence is mechanical: intercompany elimination can only be exercised by POSTing a form.

_parse_cell_formula implements an expression grammar beside FormData parsing, while services/amount_expr.py already exists for exactly that and has its own fast unit test. The file is not badly written — it is well-written code in the wrong module.

Logic hiding behind HTTP
_provenance_status
drift vs source
_consolidated_cells
intercompany elimination
_entity_period_sums
aggregation
_stored_effective
amount resolution
_parse_cell_formula
formula grammar
_split_check
month/quarter split
_assemble_groups
view model
_unit_scope_sets
scope algebra
Benefit

Locality: "what does the adjustments page show, and why" becomes one readable module instead of twenty helpers interleaved with routing.

Leverage: the CLI (cli/commands/adjustment.py, 523 lines) is the second caller waiting to happen.

Tests: test_adjustments.py and test_adjustment_values.py — 1,477 lines of HTML-shaped assertions — become value assertions on a dataclass, far less brittle to template edits.

Do this after candidate 2. Half the helper mass here is the duplicated movement rule, so extracting that first makes this a smaller job.
Before · where the mass sits
routes/adjustments  1,605 lines
adjustment_service  695
adjustment_group_service  ~380

The route is heavier than both services it calls.

→
After · transport is thin
routes/adjustments  parse → call → redirect
adjustment_view  typed read model
adjustment_service
adjustment_group_service

The read model is importable and typed, so the CLI can reuse it.

Deletion testDelete the private helpers and inline them into handlers: complexity spreads. Delete them into a view module: it concentrates. ✔

04 · A shallow module that erases types

Worth exploring
Problem

DECISIONS records (2026-06) that "mypy baseline burned down to zero; the CI job now gates" — a real achievement. But the gate is vacuous through the web layer: rows leave as Any, so a typo'd column name type-checks, renders empty, and ships. The type system stops exactly where the fastest-changing code starts.

The recurring shape
def list_entities(session, project_id) -> list[Any]: return session.execute( text("SELECT ... FROM entity WHERE ..."), {"pid": project_id}, ).all()

Interface ≈ implementation. That is the definition of shallow.

Benefit

This is not a deletion candidate — removing it would push twenty-five SQL strings into route handlers, which spreads complexity. It needs deepening, not removal.

Two of its functions — fetch_account_adjustment_deltas and fetch_adjustment_line_detail, about 280 lines combined — are already genuinely deep. They are the outliers that show what the rest could be.

Tests: row-shape regressions get caught by the type checker rather than by a route test asserting on rendered HTML.

Before · 23 slabs and 2 wells

Pass-throughs: SELECT in, list[Any] out. No depth, no leverage, no type safety.

→
After · narrower surface, typed rows

project · mapping · adjustment · period — each returning NamedTuple rows, so mypy bites in the templates' callers.

05 · No schema seam

Worth exploring
⚠ Touches an existing decision DECISIONS 2026-04 fixes the stack as SQLAlchemy Core. This does not contradict it — it observes that Core was adopted as text()-plus-a-Session only. Core's Table/MetaData half was never built, so the repo pays Core's ceremony without Core's schema safety. Worth reopening as a follow-up decision, not a reversal.
Problem

Table and column names exist only as substrings of Python string literals. There is exactly one machine-readable description of the schema — alembic/versions/0001_baseline.py, 1,932 lines of DDL — and nothing links it to the 350 places that depend on it.

DECISIONS 2026-06 already records a table-rename migration, so this cost has been paid by hand at least once. It will be paid again.

Benefit

Locality: "what columns does adjustment_line have" becomes one import instead of one grep.

Leverage: every future migration gets a safety net; renames stop being archaeology.

Tests: the metadata can build a schema in a throwaway database without replaying 1,932 lines of baseline DDL.

Scope honestly: this is the largest item here and the least urgent. It is listed because candidates 1, 2 and 5 are the same disease at three magnifications.
Before · nothing links them
alembic baseline · 1,932 lines DDL
mapping_service · 26 strings
cashflow_service · 25 strings
queries.py · 25 strings
…27 more modules

No edge between the schema and its 350 dependants.

→
After · one reference point
schema.py · Core MetaData
CI: compare_metadata fails on drift
services import the tables
read modules import the tables

One CI check catches every stale column reference.

06 · Presentation assembled four times

Worth exploring
Problem

rendering_service is genuinely deep — it returns a clean RenderResult of RenderedNodes and stops there. That part is right.

But every consumer then repeats the same second half: order the roots, label them, group nodes into sections, apply granularity buckets. Four implementations, four chances to disagree about section order — which is user-configurable per DECISIONS 2026-06.

Benefit

Weaker than 1–3, and worth saying so: the copies are structurally similar rather than literally duplicated, and each surface has real differences — Excel formulas, HTML, terminal output. The shared part is the ordering and labelling spine, not the whole assembly.

Tests: a pure function over a constructed RenderResult needs no Postgres, and the WYSIWYG promise from DECISIONS 2026-06 becomes assertable rather than aspirational.

Before · seam stops one step early
rendering_service → RenderResult
routes/render · order + label + bucket
extract_data · order + label + bucket
databook · order + label + bucket
cli/statement · order + label
→
After · seam moves one step out
rendering_service → RenderResult
statement_layout → ordered sections
routes/render → HTML
extract_data → cells
databook → formulas
cli/statement → text

A fifth export format costs a template, not an assembler.

07 · The interface is the test surface

Speculative
Problem

The transactional-rollback fixture is well built and well documented — this is not a criticism of the test infrastructure. It is an observation about what it implies: a rule expressed in SQL can only be tested by executing SQL.

So a question like "does a derived line in the first period carry the full balance?" — pure arithmetic — costs a container, a transaction and a seeded project.

The exceptions prove the point

test_amount_expr.py, test_ratio_expr.py, parser/ — the modules with a real seam already have fast, focused tests. Nobody had to argue for them; the design made them possible.

Marked speculative deliberately. Do not attack it by mocking the session — that would make the tests worse. It resolves as a side effect of candidates 1, 2 and 6.

Before · an inverted pyramid
pure DB-bound · 63 of 80 files

Route tests assert on HTML; 17 files run without a database.

→
After · rules testable without a container
route service + DB pure rule tests — fast

Integration coverage unchanged — additive, not a swap.

Not a candidateListed as the payoff to expect from 1, 2 and 6, and as the metric to watch afterwards.

Aside — one missing artefact

The repo has 2,643 lines of docs/DECISIONS.md and 4,785 lines of docs/FDD_Database_Design.md — both excellent, both chronological. What it does not have is a one-page domain glossary.

Layer, normalization, BS adjustment, derived line, consolidation unit, reporting group, bucket, extract, databook, bridge are all load-bearing terms defined only in prose, scattered across dated entries.

For a person this is a slow onboarding. For an agent it is worse: it must read 7,400 lines to learn that "layer" and "bucket" are different things.

A CONTEXT.md with one line per term — and a pointer to the DECISIONS entry that fixed each one — is the cheapest navigability win in this review. It also names the seams the candidates above want to create, which is why it belongs before them rather than after.

What to do first

This week

Correctness findings 1–3. The German-format defect blocks a documented core use case for a DACH tool, and the fix is small: add "." to one tuple, make the currency regex an alternation, and thread _thousands(...) into the journal route. All three are confirmed by execution, so each has a test you can write before the fix.

Then

Architecture findings 2 then 1, as one adjustment algebra module. It is the only architectural item with a correctness edge rather than a maintainability one, the seam is proven by five existing callers, and it needs no migration and no reversed decision — the 1,030-test suite holds it in place while you extract.

Why it's tractable

The seam is already proven, not hypothetical — five callers exist today and two of them carry docstrings admitting they are copies. The rule is small and closed. And it needs no schema change, no migration and no reversed decision: it is a pure extraction that the existing 1,030-test suite will hold in place while you do it.

What it unlocks

Architecture finding 1 is the same move at smaller scale and should follow immediately — together they form one adjustment algebra module. Once both land, finding 3 shrinks by roughly a third before anyone touches it, and finding 7's fast-test layer appears without being argued for.

Not yet

The schema seam (finding 5): the largest item, the least urgent, and it brushes against the 2026-04 stack decision — open it as its own decision entry rather than scheduling it as a task. Finding 7 needs no action at all. And the CONTEXT.md glossary is cheap enough to do alongside any of the above.

bugs 1–3→ arch 2 · bs-movement→ arch 1 · layer algebra→ arch 3 · read model→ arch 4 · typed rows→ arch 6 · layout→ arch 5 · schema (decide first)