Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 3, 22:00 UTC
feat(review): add strict read-only note exposure reconciliation gate
davoodmehraban89 committed
Oct 31, 2026 at 00:24 UTC
c7561ad60dc1e4e000dbfd365f094b1e8d2ed20f
1 file changed
+267
backend/src/aram_backend/reconciliation_review.py
new
+267
@@ -0,0 +1,267 @@
1
+"""Strict, read-only note reconciliation for a synthetic or authorized Pilot workbook.
2
+
3
+The module compares candidate mapped closing exposures to explicit, separately
4
+provided reference totals. It neither infers debit/credit sign semantics nor
5
+creates statutory financial statements, approvals, postings, or files.
6
+"""
7
+from __future__ import annotations
8
+
9
+from dataclasses import asdict, dataclass
10
+from decimal import Decimal, InvalidOperation, localcontext
11
+from hashlib import sha256
12
+import json
13
+from typing import Any, Sequence
14
+
15
+from aram_backend.coverage_preview import (
16
+ CoverageError,
17
+ CoveragePreview,
18
+ preview_mapping_coverage,
19
+)
20
+
21
+MAX_REFERENCES = 10_000
22
+MAX_TEXT = 256
23
+ALLOWED_STATEMENTS = frozenset({"BS", "IS", "CF", "EQ"})
24
+
25
+
26
+@dataclass(frozen=True)
27
+class NoteReference:
28
+ statement: str
29
+ section: str
30
+ note_number: str
31
+ subnote_code: str
32
+ expected_closing_exposure: str
33
+ evidence_ref: str
34
+
35
+
36
+@dataclass(frozen=True)
37
+class ReconciledNote:
38
+ statement: str
39
+ section: str
40
+ note_number: str
41
+ subnote_code: str
42
+ candidate_closing_exposure: str | None
43
+ reference_closing_exposure: str | None
44
+ difference: str | None
45
+ evidence_ref: str | None
46
+ matched: bool
47
+
48
+
49
+@dataclass(frozen=True)
50
+class ReviewFinding:
51
+ code: str
52
+ account_code: str
53
+ statement: str
54
+ section: str
55
+ note_number: str
56
+ subnote_code: str
57
+
58
+
59
+@dataclass(frozen=True)
60
+class ReconciliationReview:
61
+ source_sha256: str
62
+ reference_sha256: str
63
+ company_code: str
64
+ fiscal_year: int
65
+ account_count: int
66
+ candidate_mapped_accounts: int
67
+ blocked_accounts: int
68
+ source_closing_exposure: str
69
+ candidate_closing_exposure: str
70
+ blocked_closing_exposure: str
71
+ notes: tuple[ReconciledNote, ...]
72
+ findings: tuple[ReviewFinding, ...]
73
+ matched_for_analyst_review: bool
74
+ kind: str = "UNAPPROVED_NOTE_RECONCILIATION_REVIEW"
75
+ financial_statement: bool = False
76
+ trusted_approvals: bool = False
77
+ approved: bool = False
78
+ releasable: bool = False
79
+
80
+ def to_dict(self) -> dict[str, Any]:
81
+ return asdict(self)
82
+
83
+
84
+def _text(value: object, *, allow_blank: bool = False) -> str:
85
+ if not isinstance(value, str):
86
+ raise CoverageError("INVALID_REFERENCE_TEXT")
87
+ if len(value) > MAX_TEXT or value != value.strip():
88
+ raise CoverageError("INVALID_REFERENCE_TEXT")
89
+ if any(ord(char) < 32 or ord(char) == 127 for char in value):
90
+ raise CoverageError("INVALID_REFERENCE_TEXT")
91
+ if not allow_blank and not value:
92
+ raise CoverageError("INVALID_REFERENCE_TEXT")
93
+ return value
94
+
95
+
96
+def _money(value: object) -> Decimal:
97
+ if not isinstance(value, str) or len(value) > 180 or not value.strip():
98
+ raise CoverageError("INVALID_REFERENCE_AMOUNT")
99
+ try:
100
+ number = Decimal(value)
101
+ except (InvalidOperation, ValueError) as exc:
102
+ raise CoverageError("INVALID_REFERENCE_AMOUNT") from exc
103
+ if not number.is_finite() or (number != 0 and abs(number.adjusted()) > 70):
104
+ raise CoverageError("INVALID_REFERENCE_AMOUNT")
105
+ if len(number.as_tuple().digits) > 150:
106
+ raise CoverageError("INVALID_REFERENCE_AMOUNT")
107
+ return number
108
+
109
+
110
+def _key(
111
+ statement: str, section: str, note: str, subnote: str
112
+) -> tuple[str, str, str, str]:
113
+ return statement, section, note, subnote
114
+
115
+
116
+def _sum_exact(amounts: Sequence[Decimal]) -> Decimal:
117
+ if not amounts:
118
+ return Decimal(0)
119
+ integer_digits = max(1, *(amount.adjusted() + 1 for amount in amounts if amount))
120
+ decimal_places = max(0, *(-amount.as_tuple().exponent for amount in amounts))
121
+ with localcontext() as context:
122
+ context.prec = max(100, integer_digits + decimal_places + len(str(len(amounts))) + 8)
123
+ return sum(amounts, Decimal(0))
124
+
125
+
126
+def _validated_preview(content: bytes, preview: CoveragePreview) -> None:
127
+ if (preview.financial_statement or preview.trusted_approvals
128
+ or preview.releasable or preview.kind != "UNAPPROVED_MAPPING_COVERAGE_PREVIEW"):
129
+ raise CoverageError("COVERAGE_PROVENANCE_INVALID")
130
+ if sha256(content).hexdigest() != preview.source_sha256:
131
+ raise CoverageError("SOURCE_HASH_MISMATCH")
132
+ if (preview.account_count < 1
133
+ or preview.account_count != len(preview.accounts)
134
+ or preview.account_count != preview.candidate_mapped_accounts + preview.blocked_accounts
135
+ or preview.candidate_mapped_accounts != sum(a.included for a in preview.accounts)):
136
+ raise CoverageError("COVERAGE_COUNT_MISMATCH")
137
+ if len({account.account_code for account in preview.accounts}) != preview.account_count:
138
+ raise CoverageError("DUPLICATE_SOURCE_ACCOUNT")
139
+ source_values = [_money(a.closing_exposure) for a in preview.accounts]
140
+ candidate_values = [
141
+ _money(a.closing_exposure) for a in preview.accounts if a.included
142
+ ]
143
+ blocked_values = [
144
+ _money(a.closing_exposure) for a in preview.accounts if not a.included
145
+ ]
146
+ note_values = [_money(n.closing_exposure) for n in preview.notes]
147
+ if (len(preview.notes) != len({
148
+ _key(n.statement, n.section, n.note_number, n.subnote_code)
149
+ for n in preview.notes
150
+ })):
151
+ raise CoverageError("DUPLICATE_CANDIDATE_NOTE")
152
+ if (_sum_exact(source_values) != _money(preview.source_closing_exposure)
153
+ or _sum_exact(candidate_values) != _money(preview.candidate_closing_exposure)
154
+ or _sum_exact(blocked_values) != _money(preview.blocked_closing_exposure)
155
+ or _sum_exact(note_values) != _sum_exact(candidate_values)):
156
+ raise CoverageError("COVERAGE_RECONCILIATION_FAILED")
157
+
158
+
159
+def reconcile_workbook_for_review(
160
+ content: bytes, *, company_code: str, fiscal_year: int,
161
+ references: Sequence[NoteReference],
162
+) -> ReconciliationReview:
163
+ """Compare workbook-marked candidate closings with explicit *untrusted* references.
164
+
165
+ The result is at most an analyst review packet, not approval. Strict,
166
+ zero-tolerance Decimal matching does not certify any statement semantics.
167
+ """
168
+ if not isinstance(references, (tuple, list)) or len(references) > MAX_REFERENCES:
169
+ raise CoverageError("INVALID_REFERENCE_COLLECTION")
170
+
171
+ normalized: dict[tuple[str, str, str, str], tuple[Decimal, str]] = {}
172
+ for ref in references:
173
+ if not isinstance(ref, NoteReference):
174
+ raise CoverageError("INVALID_REFERENCE_OBJECT")
175
+ statement = _text(ref.statement)
176
+ if statement not in ALLOWED_STATEMENTS:
177
+ raise CoverageError("INVALID_REFERENCE_STATEMENT")
178
+ target = _key(
179
+ statement, _text(ref.section), _text(ref.note_number),
180
+ _text(ref.subnote_code, allow_blank=True),
181
+ )
182
+ if target in normalized:
183
+ raise CoverageError("DUPLICATE_NOTE_REFERENCE")
184
+ normalized[target] = (_money(ref.expected_closing_exposure), _text(ref.evidence_ref))
185
+
186
+ canonical = [
187
+ {
188
+ "target": list(target),
189
+ "expected_closing_exposure": str(amount),
190
+ "evidence_ref": reference,
191
+ }
192
+ for target, (amount, reference) in sorted(normalized.items())
193
+ ]
194
+ reference_hash = sha256(
195
+ json.dumps(canonical, ensure_ascii=True, sort_keys=True, separators=(",", ":")).encode("utf-8")
196
+ ).hexdigest()
197
+
198
+ preview = preview_mapping_coverage(
199
+ content, company_code=company_code, fiscal_year=fiscal_year,
200
+ )
201
+ _validated_preview(content, preview)
202
+
203
+ candidates = {
204
+ _key(n.statement, n.section, n.note_number, n.subnote_code): n
205
+ for n in preview.notes
206
+ }
207
+ findings: list[ReviewFinding] = [
208
+ ReviewFinding(
209
+ code="BLOCKED_ACCOUNT_" + exception.code,
210
+ account_code=exception.account_code,
211
+ statement="", section="", note_number="", subnote_code="",
212
+ ) for exception in preview.exceptions
213
+ ]
214
+
215
+ lines: list[ReconciledNote] = []
216
+ for target in sorted(set(candidates) | set(normalized)):
217
+ candidate = candidates.get(target)
218
+ baseline = normalized.get(target)
219
+ actual = _money(candidate.closing_exposure) if candidate is not None else None
220
+ expected = baseline[0] if baseline is not None else None
221
+ if actual is None:
222
+ code = "UNKNOWN_REFERENCE_TARGET"
223
+ elif expected is None:
224
+ code = "MISSING_NOTE_REFERENCE"
225
+ elif actual != expected:
226
+ code = "NOTE_EXPOSURE_MISMATCH"
227
+ else:
228
+ code = None
229
+ if code is not None:
230
+ findings.append(ReviewFinding(
231
+ code=code, account_code="",
232
+ statement=target[0], section=target[1],
233
+ note_number=target[2], subnote_code=target[3],
234
+ ))
235
+ difference = None
236
+ if actual is not None and expected is not None:
237
+ difference = str(_sum_exact([actual, -expected]))
238
+ lines.append(ReconciledNote(
239
+ statement=target[0], section=target[1],
240
+ note_number=target[2], subnote_code=target[3],
241
+ candidate_closing_exposure=str(actual) if actual is not None else None,
242
+ reference_closing_exposure=str(expected) if expected is not None else None,
243
+ difference=difference, evidence_ref=baseline[1] if baseline else None,
244
+ matched=code is None,
245
+ ))
246
+
247
+ if preview.blocked_accounts > 0 and not preview.exceptions:
248
+ raise CoverageError("BLOCKED_ACCOUNTS_UNEXPLAINED")
249
+ return ReconciliationReview(
250
+ source_sha256=preview.source_sha256, reference_sha256=reference_hash,
251
+ company_code=preview.company_code, fiscal_year=preview.fiscal_year,
252
+ account_count=preview.account_count,
253
+ candidate_mapped_accounts=preview.candidate_mapped_accounts,
254
+ blocked_accounts=preview.blocked_accounts,
255
+ source_closing_exposure=preview.source_closing_exposure,
256
+ candidate_closing_exposure=preview.candidate_closing_exposure,
257
+ blocked_closing_exposure=preview.blocked_closing_exposure,
258
+ notes=tuple(lines),
259
+ findings=tuple(sorted(
260
+ findings, key=lambda f: (
261
+ f.account_code, f.statement, f.section,
262
+ f.note_number, f.subnote_code, f.code,
263
+ )
264
+ )),
265
+ matched_for_analyst_review=not findings and preview.blocked_accounts == 0
266
+ and bool(lines),
267
+ )