Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 3, 22:00 UTC
fix/password-unicode-validation-20261111
add-index-html-10623938925177053894
arena/094f314c-aram
chatgpt-phase1b2-autopilot
codex/adr-future-connectors-pi-v1
codex/aram-account-note-source-trace-20261031
codex/aram-actions-node24-maintenance-20261031
codex/aram-analyst-review-workbook-20261031
codex/aram-bs-candidate-statement-20261031
codex/aram-cash-flow-direct-candidate-20261031
codex/aram-clean-reference-year-integrity-20261030
codex/aram-cross-statement-controls-20261031
codex/aram-equity-changes-candidate-20261031
codex/aram-five-statement-cli-20261031
codex/aram-five-statement-integration-20261031
codex/aram-five-statement-orchestrator-20261031
codex/aram-gate3-coverage-target-guard-20261030
codex/aram-gate3-hidden-xlsx-guard-20261030
codex/aram-gate3-integration-validation-20261030
codex/aram-gate3-mapping-change-preview-20261030
codex/aram-gate3-stale-note-guard-20261030
codex/aram-income-statement-candidate-20261031
codex/aram-manifest-referential-integrity-20261031
codex/aram-mapping-source-parser-20261101
codex/aram-multidimensional-mapping-20261101
codex/aram-multistatement-mapping-20261031
codex/aram-pipeline-manifest-schema-20261031
codex/aram-readonly-mapping-coverage-20261031
codex/aram-reconciliation-review-gate-20261031
codex/aram-same-flush-fiscal-lock-20261030
codex/aram-synthetic-windows-demo-20261031
codex/aram-trial-balance-diagnostic-20261031
codex/aram-windows-background-detail-search-20261031
codex/aram-windows-detail-review-20261031
codex/aram-windows-five-statement-pilot-20261031
codex/aram-windows-statement-figures-20261031
codex/gate-2a-pilot-workbook
codex/gate-2a-pilot-workbook-6864754244772568979
codex/gate3-authenticated-principal-boundary-20261030
codex/gate3-authored-draft-staging-20261030
codex/gate3-carry-forward-preview-20261023
codex/gate3-draft-staging-audit-20261030
codex/gate3-mapping-batch-freshness-20261030
codex/gate3-mapping-batch-review-20261030
codex/gate3-mapping-core
codex/gate3-mapping-coverage-20261023
codex/gate3-mapping-excel-20261023
codex/gate3-note-mapping-review-20261023
codex/gate3-signed-year-scope-20261030
codex/gate3-unapproved-proposal-storage-20261030
codex/payvast-mapping-discovery-20261023
codex/phase-2a-backend-foundation
codex/phase-2b-post-merge-record
codex/phase-2b-source-registration
codex/phase-2b-source-registration-12955190277775369594
codex/post-gate2a-control-reconciliation
codex/post-pr18-acceptance-record
codex/project-control-foundation
codex/t1-repo-hygiene-20261023
codex/t2-ci-hardening-20261023
codex/t3-explicit-migrations-20261023
codex/t6a-readonly-diagnostics-20261023
codex/v1-01-safety-gate-hardening
codex/v1-year-isolation-followup-20261023
codex/windows-native-pilot-shell-20261030
docs/aram-master-control-plan-20261111
docs/aram-roadmap-dashboard-20261030
docs/financial-statement-reconciliation-1402-1404-20261110
feat/gate3-governed-mapping-20261101
feat/gate3-package9-1-security-20261103
feat/gate3-package9-isolated-20261103
fix/password-unicode-validation-20261111
governance/aram-5-1-3-controls-20261030
governance/role-based-operating-model
jules-1168663913887856558-73b8a885
jules-gate-2b-mapping-workflow-foundation-4137724387867065330
phase-1b1-audit-report-7365389436990903239
phase-2a-backend-foundation-10237597358138521261
phase1b2-postmerge-metadata-fix
refactor/drg-parent-year-id-15088443704684163304
source-data-cleanup
| 1 | """Durable SQLite mapping store with serialized writes and optimistic concurrency.""" |
| 2 | from __future__ import annotations |
| 3 | |
| 4 | import json |
| 5 | import sqlite3 |
| 6 | from contextlib import closing |
| 7 | from dataclasses import asdict |
| 8 | from pathlib import Path |
| 9 | |
| 10 | from aram_backend.mapping_integrity import GENESIS, audit_chain, verify_audit_chain |
| 11 | from aram_backend.mapping_workflow import ( |
| 12 | MappingAuditEvent, |
| 13 | MappingDecision, |
| 14 | MappingWorkflowError, |
| 15 | MappingWorkspace, |
| 16 | ) |
| 17 | |
| 18 | |
| 19 | class MappingStore: |
| 20 | def __init__(self, path: str | Path): |
| 21 | self.path = str(path) |
| 22 | if self.path == ":memory:": |
| 23 | raise MappingWorkflowError("durable store requires a filesystem path") |
| 24 | with closing(self._connect()) as db: |
| 25 | db.execute("PRAGMA journal_mode=WAL") |
| 26 | db.executescript(""" |
| 27 | CREATE TABLE IF NOT EXISTS mapping_state ( |
| 28 | company TEXT NOT NULL, year INTEGER NOT NULL, |
| 29 | revision INTEGER NOT NULL, payload TEXT NOT NULL, |
| 30 | PRIMARY KEY(company, year) |
| 31 | ); |
| 32 | CREATE TABLE IF NOT EXISTS mapping_audit ( |
| 33 | sequence INTEGER PRIMARY KEY AUTOINCREMENT, |
| 34 | company TEXT NOT NULL, year INTEGER NOT NULL, |
| 35 | revision INTEGER NOT NULL, payload TEXT NOT NULL, |
| 36 | UNIQUE(company, year, revision) |
| 37 | ); |
| 38 | CREATE TABLE IF NOT EXISTS mapping_audit_hash ( |
| 39 | sequence INTEGER PRIMARY KEY, |
| 40 | digest TEXT NOT NULL, |
| 41 | FOREIGN KEY(sequence) REFERENCES mapping_audit(sequence) |
| 42 | ); |
| 43 | """) |
| 44 | |
| 45 | def _connect(self): |
| 46 | db = sqlite3.connect(self.path, timeout=15, isolation_level=None) |
| 47 | db.execute("PRAGMA busy_timeout=15000") |
| 48 | db.execute("PRAGMA synchronous=FULL") |
| 49 | return db |
| 50 | |
| 51 | def load(self, company: str, year: int) -> tuple[MappingWorkspace, int]: |
| 52 | workspace = MappingWorkspace(company, year) |
| 53 | with closing(self._connect()) as db: |
| 54 | row = db.execute( |
| 55 | "SELECT revision, payload FROM mapping_state WHERE company=? AND year=?", |
| 56 | (workspace.company_code, year), |
| 57 | ).fetchone() |
| 58 | if row is None: |
| 59 | return workspace, 0 |
| 60 | revision, payload = row |
| 61 | state = json.loads(payload) |
| 62 | for item in state["decisions"]: |
| 63 | decision = MappingDecision(**item) |
| 64 | workspace._check_scope(decision) |
| 65 | if decision.mapping_id in workspace._decisions: |
| 66 | raise MappingWorkflowError("duplicate persisted mapping") |
| 67 | workspace._decisions[decision.mapping_id] = decision |
| 68 | for item in state["audit"]: |
| 69 | event = MappingAuditEvent(**item) |
| 70 | if (event.company_code, event.fiscal_year) != (workspace.company_code, year): |
| 71 | raise MappingWorkflowError("foreign audit entry") |
| 72 | workspace._audit.append(event) |
| 73 | return workspace, revision |
| 74 | |
| 75 | def save(self, workspace: MappingWorkspace, expected_revision: int) -> int: |
| 76 | if isinstance(expected_revision, bool) or not isinstance(expected_revision, int) or expected_revision < 0: |
| 77 | raise MappingWorkflowError("invalid expected revision") |
| 78 | for decision in workspace.decisions: |
| 79 | workspace._check_scope(decision) |
| 80 | for event in workspace.audit: |
| 81 | if (event.company_code, event.fiscal_year) != (workspace.company_code, workspace.fiscal_year): |
| 82 | raise MappingWorkflowError("foreign audit event") |
| 83 | # Reject forged state and invalid audit sequences before starting a write. |
| 84 | latest = {} |
| 85 | for event in workspace.audit: |
| 86 | prior = latest.get(event.mapping_id) |
| 87 | if prior is None: |
| 88 | valid = (event.previous_status is None and |
| 89 | event.previous_version is None and |
| 90 | event.new_status == "Draft" and event.new_version == 1) |
| 91 | else: |
| 92 | previous_status, previous_version = prior |
| 93 | valid = (event.previous_status == previous_status and |
| 94 | event.previous_version == previous_version and |
| 95 | event.new_version == previous_version + 1 and |
| 96 | ((previous_status == "Draft" and event.new_status in ("Reviewed", "OwnerAcceptedWithException")) or |
| 97 | (previous_status == "Reviewed" and event.new_status == "Approved") or |
| 98 | event.new_status == "Draft")) |
| 99 | if not valid or not event.actor.strip(): |
| 100 | raise MappingWorkflowError("invalid audit transition or version chain") |
| 101 | latest[event.mapping_id] = (event.new_status, event.new_version) |
| 102 | if {d.mapping_id: (d.status, d.version) for d in workspace.decisions} != latest: |
| 103 | raise MappingWorkflowError("mapping state and audit history diverged") |
| 104 | payload = json.dumps({ |
| 105 | "decisions": [asdict(item) for item in workspace.decisions], |
| 106 | "audit": [asdict(item) for item in workspace.audit], |
| 107 | }, ensure_ascii=False, sort_keys=True) |
| 108 | db = self._connect() |
| 109 | try: |
| 110 | db.execute("BEGIN IMMEDIATE") |
| 111 | row = db.execute( |
| 112 | "SELECT revision, payload FROM mapping_state WHERE company=? AND year=?", |
| 113 | (workspace.company_code, workspace.fiscal_year), |
| 114 | ).fetchone() |
| 115 | current = row[0] if row else 0 |
| 116 | if current != expected_revision: |
| 117 | raise MappingWorkflowError("concurrent update: stale revision") |
| 118 | if row: |
| 119 | previous = json.loads(row[1]) |
| 120 | old_events = previous["audit"] |
| 121 | new_events = [asdict(e) for e in workspace.audit] |
| 122 | if new_events[:len(old_events)] != old_events: |
| 123 | raise MappingWorkflowError("audit history must be append-only") |
| 124 | if len(new_events) == len(old_events) and payload != row[1]: |
| 125 | raise MappingWorkflowError("state changed without audit event") |
| 126 | appended = new_events[len(old_events):] |
| 127 | if appended and not all( |
| 128 | event["mapping_id"] in {d.mapping_id for d in workspace.decisions} |
| 129 | for event in appended |
| 130 | ): |
| 131 | raise MappingWorkflowError("audit event references unknown mapping") |
| 132 | else: |
| 133 | appended = [asdict(e) for e in workspace.audit] |
| 134 | if workspace.decisions and not appended: |
| 135 | raise MappingWorkflowError("decisions require audit events") |
| 136 | new_revision = current + 1 |
| 137 | db.execute( |
| 138 | "INSERT INTO mapping_state(company,year,revision,payload) VALUES(?,?,?,?) " |
| 139 | "ON CONFLICT(company,year) DO UPDATE SET revision=excluded.revision,payload=excluded.payload", |
| 140 | (workspace.company_code, workspace.fiscal_year, new_revision, payload), |
| 141 | ) |
| 142 | digests = audit_chain(workspace.audit) |
| 143 | old_count = len(workspace.audit) - len(appended) |
| 144 | for index, event in enumerate(appended): |
| 145 | cursor = db.execute( |
| 146 | "INSERT INTO mapping_audit(company,year,revision,payload) VALUES(?,?,?,?)", |
| 147 | (workspace.company_code, workspace.fiscal_year, |
| 148 | new_revision * 1000000 + index, json.dumps(event, ensure_ascii=False)), |
| 149 | ) |
| 150 | db.execute( |
| 151 | "INSERT INTO mapping_audit_hash(sequence,digest) VALUES(?,?)", |
| 152 | (cursor.lastrowid, digests[old_count + index]), |
| 153 | ) |
| 154 | db.commit() |
| 155 | return new_revision |
| 156 | except Exception: |
| 157 | db.rollback() |
| 158 | raise |
| 159 | finally: |
| 160 | db.close() |
| 161 | |
| 162 | def audit_log(self, company: str, year: int) -> tuple[MappingAuditEvent, ...]: |
| 163 | with closing(self._connect()) as db: |
| 164 | rows = db.execute( |
| 165 | "SELECT payload FROM mapping_audit WHERE company=? AND year=? ORDER BY sequence", |
| 166 | (company, year), |
| 167 | ).fetchall() |
| 168 | return tuple(MappingAuditEvent(**json.loads(row[0])) for row in rows) |
| 169 | |
| 170 | |
| 171 | def verify_integrity(self) -> None: |
| 172 | """Detect corruption and state/audit disagreement; not privileged tamper-proof.""" |
| 173 | with closing(self._connect()) as db: |
| 174 | if db.execute("PRAGMA quick_check").fetchone()[0] != "ok": |
| 175 | raise MappingWorkflowError("SQLite integrity check failed") |
| 176 | rows = db.execute( |
| 177 | "SELECT company, year, payload FROM mapping_state ORDER BY company, year" |
| 178 | ).fetchall() |
| 179 | for company, year, payload in rows: |
| 180 | state = json.loads(payload) |
| 181 | audit = [json.loads(r[0]) for r in db.execute( |
| 182 | "SELECT payload FROM mapping_audit WHERE company=? AND year=? ORDER BY sequence", |
| 183 | (company, year), |
| 184 | )] |
| 185 | if state["audit"] != audit: |
| 186 | raise MappingWorkflowError("persisted audit/state mismatch") |
| 187 | chain_rows = db.execute( |
| 188 | "SELECT h.digest FROM mapping_audit a " |
| 189 | "LEFT JOIN mapping_audit_hash h ON h.sequence=a.sequence " |
| 190 | "WHERE a.company=? AND a.year=? ORDER BY a.sequence", |
| 191 | (company, year), |
| 192 | ).fetchall() |
| 193 | if any(row[0] is None for row in chain_rows): |
| 194 | raise MappingWorkflowError("audit hash chain missing event digest") |
| 195 | verify_audit_chain( |
| 196 | tuple(MappingAuditEvent(**item) for item in audit), |
| 197 | tuple(row[0] for row in chain_rows), |
| 198 | ) |
| 199 | workspace, _ = self.load(company, year) |
| 200 | latest = {} |
| 201 | for event in workspace.audit: |
| 202 | prior = latest.get(event.mapping_id) |
| 203 | if prior is None: |
| 204 | valid = (event.previous_status is None |
| 205 | and event.previous_version is None |
| 206 | and event.new_status == "Draft" |
| 207 | and event.new_version == 1) |
| 208 | else: |
| 209 | valid = (event.previous_status == prior[0] |
| 210 | and event.previous_version == prior[1] |
| 211 | and event.new_version == prior[1] + 1 |
| 212 | and ((prior[0] == "Draft" and event.new_status in ("Reviewed", "OwnerAcceptedWithException")) |
| 213 | or (prior[0] == "Reviewed" and event.new_status == "Approved") |
| 214 | or event.new_status == "Draft")) |
| 215 | if not valid: |
| 216 | raise MappingWorkflowError("invalid persisted audit chain") |
| 217 | latest[event.mapping_id] = (event.new_status, event.new_version) |
| 218 | if latest != {d.mapping_id: (d.status, d.version) |
| 219 | for d in workspace.decisions}: |
| 220 | raise MappingWorkflowError("persisted mapping state diverged") |
| 221 | orphan = db.execute( |
| 222 | "SELECT 1 FROM mapping_audit a WHERE NOT EXISTS " |
| 223 | "(SELECT 1 FROM mapping_state s WHERE s.company=a.company AND s.year=a.year) " |
| 224 | "LIMIT 1" |
| 225 | ).fetchone() |
| 226 | if orphan: |
| 227 | raise MappingWorkflowError("orphan audit events") |
| 228 | |
| 229 | def backup_to(self, destination: str | Path) -> None: |
| 230 | """Create consistent SQLite snapshot; never overwrite an existing backup.""" |
| 231 | target = Path(destination) |
| 232 | if target.exists() or target.resolve() == Path(self.path).resolve(): |
| 233 | raise MappingWorkflowError("backup destination must be new and distinct") |
| 234 | self.verify_integrity() |
| 235 | try: |
| 236 | with closing(self._connect()) as source, closing(sqlite3.connect(target)) as backup: |
| 237 | source.backup(backup) |
| 238 | MappingStore(target).verify_integrity() |
| 239 | except Exception: |
| 240 | target.unlink(missing_ok=True) |
| 241 | raise |
| 242 | |
| 243 | |
| 244 | def audit_receipt(self, company: str, year: int) -> dict: |
| 245 | """Operator must export the receipt to an independently protected store.""" |
| 246 | from aram_backend.mapping_integrity import integrity_receipt |
| 247 | |
| 248 | workspace, revision = self.load(company, year) |
| 249 | self.verify_integrity() |
| 250 | hashes = audit_chain(workspace.audit) |
| 251 | return integrity_receipt( |
| 252 | company_code=company, fiscal_year=year, revision=revision, |
| 253 | terminal_digest=hashes[-1] if hashes else GENESIS, |
| 254 | ) |
| 255 | |
| 256 | def verify_external_receipt(self, receipt: dict) -> None: |
| 257 | """Check a trusted externally retained receipt against current state.""" |
| 258 | company = receipt["company_code"] |
| 259 | year = receipt["fiscal_year"] |
| 260 | workspace, revision = self.load(company, year) |
| 261 | self.verify_integrity() |
| 262 | if revision != receipt["revision"]: |
| 263 | raise MappingWorkflowError("audit external anchor revision mismatch") |
| 264 | hashes = audit_chain(workspace.audit) |
| 265 | verify_audit_chain( |
| 266 | workspace.audit, hashes, trusted_terminal_digest=receipt["sha256"], |
| 267 | ) |