feat(desktop): validate candidate provenance and exact reconciliation before rendering
davoodmehraban89 committed
Oct 31, 2026 at 21:36 UTC
0b61d0956441a2d87b9609fa7a2584b1eee07c44
1 file changed
+131
backend/src/aram_backend/desktop_five_statement_integrity.py
new
+131
@@ -0,0 +1,131 @@
1
+"""Fail-closed provenance and tie-out checks for desktop-only previews."""
2
+from __future__ import annotations
3
+
4
+import re
5
+
6
+from aram_backend.coverage_preview import CoverageError
7
+from aram_backend.balance_sheet_candidate import BalanceSheetCandidate
8
+from aram_backend.cash_flow_direct_candidate import DirectCashFlowCandidate
9
+from aram_backend.cross_statement_reconciliation import CrossStatementReconciliation
10
+from aram_backend.equity_changes_candidate import EquityChangesCandidate
11
+from aram_backend.five_statement_pipeline import FiveStatementPipelineResult
12
+from aram_backend.income_statement_candidate import IncomeStatementCandidate
13
+from aram_backend.trial_balance_diagnostic import TrialBalanceDiagnostic
14
+
15
+
16
+def _require_false(obj: object, fields: tuple[str, ...]) -> None:
17
+ for field in fields:
18
+ value = getattr(obj, field)
19
+ if type(value) is not bool or value:
20
+ raise CoverageError("DESKTOP_PREVIEW_PROVENANCE_INVALID")
21
+
22
+
23
+def _require_bool(obj: object, field: str) -> bool:
24
+ value = getattr(obj, field)
25
+ if type(value) is not bool:
26
+ raise CoverageError("DESKTOP_PREVIEW_BOOLEAN_INVALID")
27
+ return value
28
+
29
+
30
+def validate_desktop_pipeline_result(result: FiveStatementPipelineResult) -> None:
31
+ """Verify the exact typed orchestration result before rendering any data."""
32
+ if type(result) is not FiveStatementPipelineResult:
33
+ raise CoverageError("DESKTOP_PREVIEW_PIPELINE_TYPE_INVALID")
34
+ candidates = (
35
+ (result.balance_sheet, BalanceSheetCandidate, "UNAPPROVED_BALANCE_SHEET_PRESENTATION_CANDIDATE"),
36
+ (result.income_statement, IncomeStatementCandidate, "UNAPPROVED_INCOME_STATEMENT_PRESENTATION_CANDIDATE"),
37
+ (result.equity_changes, EquityChangesCandidate, "UNAPPROVED_EQUITY_CHANGES_PRESENTATION_CANDIDATE"),
38
+ (result.cash_flow, DirectCashFlowCandidate, "UNAPPROVED_DIRECT_CASH_FLOW_CANDIDATE"),
39
+ (result.trial_balance, TrialBalanceDiagnostic, "UNAPPROVED_TRIAL_BALANCE_DIAGNOSTIC"),
40
+ )
41
+ if result.kind != "UNAPPROVED_FIVE_STATEMENT_PIPELINE_CANDIDATE":
42
+ raise CoverageError("DESKTOP_PREVIEW_PIPELINE_KIND_INVALID")
43
+ _require_false(result, (
44
+ "source_ledger_completeness_verified", "accounting_policy_authorized",
45
+ "independently_reviewed", "trusted_approvals",
46
+ "official_financial_statement", "export_authorized", "releasable",
47
+ ))
48
+ _require_false(result.reconciliation, (
49
+ "source_ledger_completeness_verified", "accounting_policy_authorized",
50
+ "independently_reviewed", "trusted_approvals",
51
+ "official_financial_statement", "export_authorized", "releasable",
52
+ ))
53
+ source_hashes: set[str] = set()
54
+ companies: set[str] = set()
55
+ years: set[int] = set()
56
+ eligibility: list[bool] = []
57
+ for candidate, expected_type, expected_kind in candidates:
58
+ if type(candidate) is not expected_type or candidate.kind != expected_kind:
59
+ raise CoverageError("DESKTOP_PREVIEW_CANDIDATE_TYPE_INVALID")
60
+ if (not isinstance(candidate.source_sha256, str)
61
+ or not re.fullmatch(r"[0-9a-f]{64}", candidate.source_sha256)):
62
+ raise CoverageError("DESKTOP_PREVIEW_SOURCE_HASH_INVALID")
63
+ source_hashes.add(candidate.source_sha256)
64
+ companies.add(candidate.company_code)
65
+ years.add(candidate.fiscal_year)
66
+ eligible_field = (
67
+ "balanced_for_analyst_review" if isinstance(candidate, TrialBalanceDiagnostic)
68
+ else "eligible_for_analyst_review"
69
+ )
70
+ eligibility.append(_require_bool(candidate, eligible_field))
71
+ findings = candidate.findings
72
+ if not isinstance(findings, tuple) or any(
73
+ not isinstance(item, str) or not item for item in findings
74
+ ):
75
+ raise CoverageError("DESKTOP_PREVIEW_FINDINGS_INVALID")
76
+ if isinstance(candidate, BalanceSheetCandidate):
77
+ flags = ("official_financial_statement", "accounting_policy_authorized",
78
+ "independently_reviewed", "export_authorized", "releasable")
79
+ elif isinstance(candidate, IncomeStatementCandidate):
80
+ flags = ("official_financial_statement", "accounting_policy_authorized",
81
+ "independently_reviewed", "export_authorized", "releasable")
82
+ elif isinstance(candidate, EquityChangesCandidate):
83
+ flags = ("official_financial_statement", "accounting_policy_authorized",
84
+ "source_ledger_completeness_verified", "independently_reviewed",
85
+ "export_authorized", "releasable")
86
+ elif isinstance(candidate, DirectCashFlowCandidate):
87
+ flags = ("cash_account_scope_owner_approved",
88
+ "transaction_ledger_completeness_verified",
89
+ "accounting_policy_authorized", "official_financial_statement",
90
+ "independently_reviewed", "export_authorized", "releasable")
91
+ else:
92
+ flags = ("source_ledger_completeness_verified",
93
+ "accounting_policies_verified", "official_financial_statement",
94
+ "independently_reviewed", "releasable")
95
+ _require_false(candidate, flags)
96
+ reconciliation = result.reconciliation
97
+ if type(reconciliation) is not CrossStatementReconciliation:
98
+ raise CoverageError("DESKTOP_PREVIEW_RECONCILIATION_TYPE_INVALID")
99
+ if (len(source_hashes) != 1
100
+ or reconciliation.source_sha256 not in source_hashes
101
+ or reconciliation.same_source_snapshot is not True):
102
+ raise CoverageError("DESKTOP_PREVIEW_SOURCE_SNAPSHOT_MISMATCH")
103
+ if companies != {reconciliation.company_code} or years != {reconciliation.fiscal_year}:
104
+ raise CoverageError("DESKTOP_PREVIEW_SCOPE_MISMATCH")
105
+ if (result.balance_sheet.note_references_sha256
106
+ != result.income_statement.note_references_sha256
107
+ or result.balance_sheet.note_references_sha256
108
+ != result.equity_changes.note_references_sha256):
109
+ raise CoverageError("DESKTOP_PREVIEW_REFERENCE_SNAPSHOT_MISMATCH")
110
+ ties = (
111
+ (result.balance_sheet.equity_total, reconciliation.balance_sheet_equity_total),
112
+ (result.balance_sheet.balance_difference, reconciliation.balance_sheet_difference),
113
+ (result.income_statement.net_result, reconciliation.income_statement_net_result),
114
+ (result.equity_changes.closing_equity_total, reconciliation.equity_statement_closing_total),
115
+ (result.equity_changes.net_profit_loss_movements, reconciliation.equity_net_profit_loss_movements),
116
+ (result.cash_flow.closing_cash_and_equivalents, reconciliation.cash_flow_closing_cash),
117
+ (result.trial_balance.opening_debit_net_total, reconciliation.trial_balance_opening_debit_net_total),
118
+ (result.trial_balance.movement_difference, reconciliation.trial_balance_movement_difference),
119
+ (result.trial_balance.closing_debit_net_total, reconciliation.trial_balance_closing_debit_net_total),
120
+ (result.cash_flow.transaction_ledger_sha256, reconciliation.cash_flow_transaction_ledger_sha256),
121
+ )
122
+ if any(left != right for left, right in ties):
123
+ raise CoverageError("DESKTOP_PREVIEW_RECONCILIATION_MISMATCH")
124
+ overall = _require_bool(result, "eligible_for_analyst_review")
125
+ if overall:
126
+ if (not _require_bool(reconciliation, "eligible_for_analyst_review")
127
+ or not all(eligibility) or result.findings
128
+ or any(candidate.findings for candidate, _, _ in candidates)):
129
+ raise CoverageError("DESKTOP_PREVIEW_FALSE_ELIGIBILITY")
130
+ elif _require_bool(reconciliation, "eligible_for_analyst_review"):
131
+ raise CoverageError("DESKTOP_PREVIEW_ELIGIBILITY_MISMATCH")