codex/aram-gate3-integration-validation-20261030
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 | """Strict, non-executing XLSX interchange for explicit mapping decisions. |
| 2 | |
| 3 | The workbook carries only mapping identifiers, not balances or inferred targets. |
| 4 | All database changes are staged in a savepoint; the caller owns the outer commit. |
| 5 | """ |
| 6 | from __future__ import annotations |
| 7 | |
| 8 | from dataclasses import dataclass |
| 9 | from io import BytesIO |
| 10 | from zipfile import BadZipFile, ZipFile |
| 11 | from xml.etree import ElementTree |
| 12 | |
| 13 | from openpyxl import Workbook, load_workbook |
| 14 | from sqlalchemy.orm import Session |
| 15 | |
| 16 | from aram_backend.mapping_service import MappingValidationError, save_mapping_rule |
| 17 | |
| 18 | HEADERS = ("rule_key", "account_code", "target_note_id", "mapping_type", "version") |
| 19 | SHEET = "Mapping" |
| 20 | MAX_FILE_BYTES = 10 * 1024 * 1024 |
| 21 | MAX_UNCOMPRESSED_BYTES = 40 * 1024 * 1024 |
| 22 | MAX_ROWS = 10_000 |
| 23 | |
| 24 | |
| 25 | @dataclass(frozen=True) |
| 26 | class MappingEntry: |
| 27 | rule_key: str |
| 28 | account_code: str |
| 29 | target_note_id: int |
| 30 | mapping_type: str |
| 31 | version: int |
| 32 | |
| 33 | |
| 34 | def _safe_archive(content: bytes) -> None: |
| 35 | if not isinstance(content, bytes) or not content or len(content) > MAX_FILE_BYTES: |
| 36 | raise MappingValidationError("XLSX must be nonempty and at most 10 MiB") |
| 37 | try: |
| 38 | with ZipFile(BytesIO(content)) as archive: |
| 39 | infos = archive.infolist() |
| 40 | if len(infos) > 1_000 or sum(i.file_size for i in infos) > MAX_UNCOMPRESSED_BYTES: |
| 41 | raise MappingValidationError("XLSX archive exceeds safety limits") |
| 42 | if any(i.flag_bits & 0x1 for i in infos): |
| 43 | raise MappingValidationError("Encrypted XLSX entries are not supported") |
| 44 | except MappingValidationError: |
| 45 | raise |
| 46 | except (BadZipFile, ValueError) as exc: |
| 47 | raise MappingValidationError("Invalid XLSX archive") from exc |
| 48 | |
| 49 | |
| 50 | def _reject_hidden_dimensions(content: bytes, worksheet_path: str) -> None: |
| 51 | """Stream worksheet XML to detect hidden row/column metadata safely. |
| 52 | |
| 53 | openpyxl's read-only worksheet deliberately lacks row_dimensions and |
| 54 | column_dimensions. Loading arbitrary XLSX in full-memory mode merely to |
| 55 | inspect visibility would defeat the bounded streaming parser. |
| 56 | """ |
| 57 | try: |
| 58 | with ZipFile(BytesIO(content)) as archive: |
| 59 | with archive.open(worksheet_path.lstrip("/")) as worksheet: |
| 60 | for action, element in ElementTree.iterparse( |
| 61 | worksheet, events=("start", "end") |
| 62 | ): |
| 63 | if action == "start": |
| 64 | kind = element.tag.rsplit("}", 1)[-1] |
| 65 | if element.attrib.get("hidden", "").lower() not in ("1", "true"): |
| 66 | continue |
| 67 | if kind == "row": |
| 68 | # Any hidden row can conceal Mapping decisions, including |
| 69 | # a header or a visually empty spacer. |
| 70 | raise MappingValidationError("Hidden Mapping row is prohibited") |
| 71 | if kind == "col": |
| 72 | try: |
| 73 | first = int(element.attrib["min"]) |
| 74 | last = int(element.attrib["max"]) |
| 75 | except (ValueError, KeyError) as exc: |
| 76 | raise MappingValidationError( |
| 77 | "Hidden Mapping column range is invalid" |
| 78 | ) from exc |
| 79 | if first <= len(HEADERS) and last >= 1: |
| 80 | raise MappingValidationError( |
| 81 | "Hidden Mapping column is prohibited" |
| 82 | ) |
| 83 | else: |
| 84 | element.clear() |
| 85 | except MappingValidationError: |
| 86 | raise |
| 87 | except (BadZipFile, KeyError, OSError, ValueError, ElementTree.ParseError) as exc: |
| 88 | raise MappingValidationError("Unreadable XLSX worksheet visibility metadata") from exc |
| 89 | |
| 90 | |
| 91 | def _parse_int(value: object, label: str, row_number: int) -> int: |
| 92 | if type(value) is not int or value <= 0: |
| 93 | raise MappingValidationError(f"Row {row_number}: {label} must be a positive integer") |
| 94 | return value |
| 95 | |
| 96 | |
| 97 | def _parse_text(value: object, label: str, limit: int, row_number: int) -> str: |
| 98 | if not isinstance(value, str) or not value or value.strip() != value or len(value) > limit: |
| 99 | raise MappingValidationError(f"Row {row_number}: invalid {label}") |
| 100 | return value |
| 101 | |
| 102 | |
| 103 | def preview_mapping_workbook(content: bytes) -> tuple[MappingEntry, ...]: |
| 104 | """Read and validate an XLSX mapping sheet without modifying any database.""" |
| 105 | _safe_archive(content) |
| 106 | try: |
| 107 | book = load_workbook(BytesIO(content), read_only=True, data_only=False, keep_links=False) |
| 108 | except (OSError, ValueError, KeyError, BadZipFile) as exc: |
| 109 | raise MappingValidationError("Unreadable XLSX workbook") from exc |
| 110 | try: |
| 111 | if book.sheetnames != [SHEET]: |
| 112 | raise MappingValidationError("Workbook must contain only a Mapping sheet") |
| 113 | sheet = book[SHEET] |
| 114 | if sheet.sheet_state != "visible": |
| 115 | raise MappingValidationError("Hidden Mapping sheet is prohibited") |
| 116 | # Visibility is checked from the same bounded workbook archive, before |
| 117 | # any mapping entry is parsed or a database transaction can be staged. |
| 118 | _reject_hidden_dimensions(content, sheet._worksheet_path) |
| 119 | if sheet.max_row is not None and sheet.max_row > MAX_ROWS + 1: |
| 120 | raise MappingValidationError("Too many mapping rows") |
| 121 | if sheet.max_column is not None and sheet.max_column > len(HEADERS): |
| 122 | raise MappingValidationError("Unexpected columns in Mapping sheet") |
| 123 | rows = sheet.iter_rows(values_only=False) |
| 124 | header = next(rows, ()) |
| 125 | if tuple(cell.value for cell in header) != HEADERS: |
| 126 | raise MappingValidationError("Mapping sheet headers do not match the contract") |
| 127 | entries: list[MappingEntry] = [] |
| 128 | seen: set[tuple[str, int]] = set() |
| 129 | for row_number, cells in enumerate(rows, start=2): |
| 130 | if row_number > MAX_ROWS + 1: |
| 131 | raise MappingValidationError("Too many mapping rows") |
| 132 | if any(cell.data_type == "f" for cell in cells): |
| 133 | raise MappingValidationError(f"Row {row_number}: formulas are prohibited") |
| 134 | values = tuple(cell.value for cell in cells) |
| 135 | if all(value is None for value in values): |
| 136 | continue |
| 137 | if len(values) != len(HEADERS): |
| 138 | raise MappingValidationError(f"Row {row_number}: invalid column count") |
| 139 | entry = MappingEntry( |
| 140 | rule_key=_parse_text(values[0], "rule_key", 128, row_number), |
| 141 | account_code=_parse_text(values[1], "account_code", 64, row_number), |
| 142 | target_note_id=_parse_int(values[2], "target_note_id", row_number), |
| 143 | mapping_type=_parse_text(values[3], "mapping_type", 32, row_number), |
| 144 | version=_parse_int(values[4], "version", row_number), |
| 145 | ) |
| 146 | identity = (entry.rule_key, entry.version) |
| 147 | if identity in seen: |
| 148 | raise MappingValidationError(f"Row {row_number}: duplicate rule key/version") |
| 149 | seen.add(identity) |
| 150 | entries.append(entry) |
| 151 | if not entries: |
| 152 | raise MappingValidationError("Mapping sheet contains no mapping entries") |
| 153 | return tuple(entries) |
| 154 | finally: |
| 155 | book.close() |
| 156 | |
| 157 | |
| 158 | def export_mapping_workbook(entries: tuple[MappingEntry, ...]) -> bytes: |
| 159 | """Create a deterministic-structure XLSX; force text cells to prevent formula execution.""" |
| 160 | if not entries or len(entries) > MAX_ROWS: |
| 161 | raise MappingValidationError("Mapping export must contain 1 to 10000 entries") |
| 162 | book = Workbook() |
| 163 | sheet = book.active |
| 164 | sheet.title = SHEET |
| 165 | sheet.append(HEADERS) |
| 166 | seen: set[tuple[str, int]] = set() |
| 167 | for index, entry in enumerate(entries, start=2): |
| 168 | if not isinstance(entry, MappingEntry): |
| 169 | raise MappingValidationError(f"Row {index}: invalid mapping entry") |
| 170 | key = (_parse_text(entry.rule_key, "rule_key", 128, index), |
| 171 | _parse_int(entry.version, "version", index)) |
| 172 | if key in seen: |
| 173 | raise MappingValidationError(f"Row {index}: duplicate rule key/version") |
| 174 | seen.add(key) |
| 175 | row = ( |
| 176 | key[0], _parse_text(entry.account_code, "account_code", 64, index), |
| 177 | _parse_int(entry.target_note_id, "target_note_id", index), |
| 178 | _parse_text(entry.mapping_type, "mapping_type", 32, index), key[1], |
| 179 | ) |
| 180 | sheet.append(row) |
| 181 | for col in (1, 2, 4): |
| 182 | sheet.cell(index, col).data_type = "s" |
| 183 | stream = BytesIO() |
| 184 | book.save(stream) |
| 185 | return stream.getvalue() |
| 186 | |
| 187 | |
| 188 | def import_mapping_workbook(session: Session, *, year_id: int, content: bytes) -> int: |
| 189 | """Stage all valid mappings atomically, without committing the caller's transaction.""" |
| 190 | entries = preview_mapping_workbook(content) |
| 191 | # SQLite's legacy transaction mode does not issue a real BEGIN for a SAVEPOINT. |
| 192 | # Without an outer BEGIN, releasing the savepoint can persist rows despite |
| 193 | # session.rollback(). Start the physical transaction explicitly when absent. |
| 194 | if session.get_bind().dialect.name == "sqlite": |
| 195 | connection = session.connection() |
| 196 | if not connection.connection.driver_connection.in_transaction: |
| 197 | connection.exec_driver_sql("BEGIN") |
| 198 | with session.begin_nested(): |
| 199 | for entry in entries: |
| 200 | save_mapping_rule( |
| 201 | session, year_id=year_id, rule_key=entry.rule_key, |
| 202 | account_code=entry.account_code, target_note_id=entry.target_note_id, |
| 203 | mapping_type=entry.mapping_type, version=entry.version, |
| 204 | ) |
| 205 | return len(entries) |