@davoodmehraban89 / Aram-2 Mirror · read-only / commits / a00b0dc
Fork 0

Mirrored from https://github.com/davoodmehraban89/Aram.git

Synced Dec 4, 13:00 UTC

fix(money): prove P-02 no-silent-rounding with exhaustive evidence (audit #1)

- ADR-012 revised: exhaustive probe of BOTH ledgers (457,074 rows, 6 money columns) confirms zero fractional rial; scale-0 is lossless. Clarifies .to_integral_value() is a DETECTOR (raises on fractional), never a rounder; round_half_up is display-only. - 7 regression tests: fractional text/boundary rejected (not rounded), fractional through ORM and CSV import fail loudly (StatementError wrapping ValueError). No storage behavior change needed — the fail-loud design already satisfies P-02. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>

davoodmehraban89 committed Dec 3, 2026 at 10:15 UTC a00b0dc5e732a534d97f87b0f3ae469b3dbeb62a
2 files changed +111 -9
backend/tests/test_domain_money.py
+84 -6
@@ -5,6 +5,7 @@ from decimal import Decimal
5 import pytest
6 from hypothesis import given, settings
7 from hypothesis import strategies as st
8 +from sqlalchemy.exc import StatementError
9
10 from aram_backend.domain.money import (
11 Rial,
@@ -46,9 +47,10 @@ class TestRialRoundTrip:
47
48 def test_large_rial_no_silent_rounding(self):
49 big = Decimal("10823163409740108")
49 - assert rial.process_result_value(
50 - rial.process_bind_param(big, dialect=None), dialect=None
51 - ) == big
50 + assert (
51 + rial.process_result_value(rial.process_bind_param(big, dialect=None), dialect=None)
52 + == big
53 + )
54
55
56 class TestRoundHalfUp:
@@ -74,9 +76,7 @@ class TestAllocateRemainder:
76
77 @given(
78 st.lists(
77 - st.integers(min_value=-(10**9), max_value=10**9).map(
78 - lambda x: Decimal(x) / 100
79 - ),
79 + st.integers(min_value=-(10**9), max_value=10**9).map(lambda x: Decimal(x) / 100),
80 min_size=1,
81 max_size=25,
82 )
@@ -88,3 +88,81 @@ class TestAllocateRemainder:
88 result = allocate_remainder(values, total, places)
89 assert sum(result) == round_half_up(total, places)
90 assert len(result) == len(values)
91 +
92 +
93 +class TestP02NoSilentRoundingGuard:
94 + """Owner-audit regression: fractional rial must fail loudly, never round."""
95 +
96 + @pytest.mark.parametrize("bad", ["1.5", "100.5", "100.0001", "0.1", "-2.25"])
97 + def test_fractional_text_rejected_not_rounded(self, bad):
98 + with pytest.raises(ValueError):
99 + rial.process_bind_param(bad, dialect=None)
100 +
101 + def test_boundary_half_rial_rejected(self):
102 + # 100.5 must NOT become 100 or 101; it must raise.
103 + with pytest.raises(ValueError):
104 + rial.process_bind_param(Decimal("100.5"), dialect=None)
105 +
106 + def test_fractional_through_orm_rejected(self, session):
107 + from aram_backend.ingestion import register_source_document
108 + from aram_backend.models import Company, FiscalYear, LedgerBalance
109 +
110 + company = Company(code="P02", name="x")
111 + session.add(company)
112 + session.flush()
113 + year = FiscalYear(company_id=company.id, year=1404)
114 + session.add(year)
115 + session.flush()
116 + source = register_source_document(
117 + session,
118 + year_id=year.id,
119 + filename="l.xlsx",
120 + document_type="general_ledger",
121 + content=b"p02",
122 + )
123 + session.flush()
124 + session.add(
125 + LedgerBalance(
126 + year_id=year.id,
127 + source_document_id=source.id,
128 + source_sheet="Source",
129 + source_row=3,
130 + account_full_code="148348",
131 + account_name="x",
132 + closing=Decimal("100.5"),
133 + )
134 + )
135 + with pytest.raises(StatementError, match="fractional rial"):
136 + session.flush()
137 + session.rollback()
138 +
139 + def test_fractional_csv_import_fails_loudly(self, session):
140 + from aram_backend.ingestion import register_source_document
141 + from aram_backend.ledger_parser import parse_general_ledger_csv
142 + from aram_backend.models import Company, FiscalYear
143 + from aram_backend.services.ledger_import import import_ledger_balances
144 +
145 + company = Company(code="P02C", name="x")
146 + session.add(company)
147 + session.flush()
148 + year = FiscalYear(company_id=company.id, year=1404)
149 + session.add(year)
150 + session.flush()
151 + source = register_source_document(
152 + session,
153 + year_id=year.id,
154 + filename="l.csv",
155 + document_type="general_ledger",
156 + content=b"p02c",
157 + )
158 + session.flush()
159 + csv = (
160 + "حساب,kol,ACCOUNT_NAME,year,نوع,T1_CODE,T2_CODE,T3_CODE,T4_CODE,OPENING,Debit,Credit,CLOSING\n"
161 + "8348,14,x,1404,O,,,,,0,100.5,0,100.5\n"
162 + ).encode()
163 + records = list(parse_general_ledger_csv(csv))
164 + with pytest.raises(StatementError, match="fractional rial"):
165 + import_ledger_balances(
166 + session, year_id=year.id, source_document_id=source.id, records=records
167 + )
168 + session.rollback()
docs/adr/ADR-012-money-scale-rounding.md
+27 -3
@@ -11,14 +11,38 @@
11 large rial amounts (debt D-03). Booklet P-02 forbids float anywhere and requires
12 scaled-integer storage with `Decimal` in Python.
13
14 -## Evidence (read-only probe of `data/source_ledgers/source_1404.xlsx`)
14 +## Evidence (exhaustive read-only probe of BOTH canonical ledgers)
15
16 -- 252,898 data rows streamed; **zero fractional-rial cells** across
17 - `OPENING / Debit / Credit / CLOSING`.
16 +- **457,074 data rows** streamed: `source_1403.xlsx` (204,176 rows) and
17 + `source_1404.xlsx` (252,898 rows).
18 +- **Zero fractional-rial cells** across ALL six money columns
19 + (`OPENING / Debit / Credit / PERIODTURNOVER / CLOSING / مانده صورت مالی`) in
20 + **both** years. Every money value is an exact integer rial.
21 - Magnitudes reach ~1.08e16 rial (total debit == total credit ==
22 10,823,163,409,740,108), well within signed 64-bit (`BIGINT` ≈ 9.22e18).
23 - Official statements (`data/official_statements/financial_1404.xlsx`) state
24 **"(مبالغ به میلیون ریال)"** — amounts presented in **million rial**.
25 +- Data quirk (not a precision issue): `source_1403.xlsx` has 20,701 non-numeric
26 + `Debit` cells; these are rejected loudly by the parser, never coerced.
27 +
28 +## P-02 guarantee — no silent rounding (owner audit, 2026-12-03)
29 +
30 +The owner's line-by-line audit flagged `.to_integral_value()` as a possible silent
31 +round. Clarification and proof:
32 +
33 +- In `Rial.process_bind_param`, `.to_integral_value()` is used **only as a
34 + detector**: `if scaled != scaled.to_integral_value(): raise ValueError(...)`.
35 + It never rounds or truncates; a fractional value is **rejected loudly** (P-09).
36 +- The same detector pattern in `normalize_code` and the year check rejects
37 + non-integral codes/years; it does not round them.
38 +- `decimal_from_cell` returns the exact `Decimal` (float via shortest round-trip
39 + `repr`); it performs no rounding.
40 +- `round_half_up` / `allocate_remainder` are invoked **only in the display/output
41 + layer** (e.g. the golden million-rial comparison), never on the storage or
42 + calculation path. A repo-wide grep confirms no storage-path call site.
43 +- Because the canonical data has zero fractional rial, scale 0 is lossless. If
44 + fractional rial ever appears, the import **fails loudly** rather than silently
45 + rounding, forcing an explicit ADR revision before any scale change.
46
47 ## Decision
48