codex/gate3-signed-year-scope-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 | """Persistent, UNREVIEWED-only Mapping proposals; NOT an approval or apply API. |
| 2 | |
| 3 | The proposal table has independent MetaData: the legacy initial Alembic |
| 4 | migration uses Base.metadata.create_all(), so the *later*, explicit migration |
| 5 | is solely responsible for creating this table. Never import it into Base. |
| 6 | """ |
| 7 | from __future__ import annotations |
| 8 | |
| 9 | from dataclasses import asdict, dataclass |
| 10 | from hashlib import sha256 |
| 11 | import json |
| 12 | from unicodedata import category |
| 13 | |
| 14 | from sqlalchemy import ( |
| 15 | JSON, CheckConstraint, Column, DateTime, ForeignKey, Integer, MetaData, |
| 16 | String, Table, UniqueConstraint, func, insert, select, |
| 17 | ) |
| 18 | from sqlalchemy.orm import Session |
| 19 | |
| 20 | from aram_backend.mapping_batch_review import ( |
| 21 | MappingBatchPreview, ProposedMappingRow, preview_mapping_batch, |
| 22 | verify_mapping_batch_current, |
| 23 | ) |
| 24 | from aram_backend.mapping_service import MappingValidationError |
| 25 | from aram_backend.mapping_change_preview import _require_clean_mapping_state |
| 26 | from aram_backend.models import FiscalYear |
| 27 | |
| 28 | # Deliberately distinct from Base.metadata. Never create this table with the |
| 29 | # original "20260820_01" Base.metadata.create_all migration. |
| 30 | _proposal_metadata = MetaData() |
| 31 | mapping_review_drafts = Table( |
| 32 | "mapping_review_drafts", |
| 33 | _proposal_metadata, |
| 34 | Column("id", Integer, primary_key=True), |
| 35 | Column( |
| 36 | "year_id", Integer, |
| 37 | ForeignKey(FiscalYear.__table__.c.id, ondelete="RESTRICT"), |
| 38 | nullable=False, |
| 39 | ), |
| 40 | Column("request_key", String(64), nullable=False), |
| 41 | Column("payload_json", JSON, nullable=False), |
| 42 | Column("payload_hash", String(64), nullable=False), |
| 43 | Column("state", String(16), nullable=False, server_default="Unreviewed"), |
| 44 | Column("created_at", DateTime(timezone=True), nullable=False, |
| 45 | server_default=func.current_timestamp()), |
| 46 | UniqueConstraint("year_id", "request_key", name="uq_mapping_review_drafts_year_request"), |
| 47 | CheckConstraint("state = 'Unreviewed'", name="ck_mapping_review_drafts_unreviewed_only"), |
| 48 | ) |
| 49 | |
| 50 | |
| 51 | @dataclass(frozen=True) |
| 52 | class StoredMappingDraft: |
| 53 | """Passive persisted evidence. There are deliberately NO approval fields.""" |
| 54 | |
| 55 | id: int |
| 56 | year_id: int |
| 57 | request_key: str |
| 58 | checksum: str |
| 59 | state: str |
| 60 | created_at: object |
| 61 | |
| 62 | |
| 63 | def _canonical(value: object) -> str: |
| 64 | return json.dumps(value, sort_keys=True, ensure_ascii=True, separators=(",", ":")) |
| 65 | |
| 66 | |
| 67 | def _payload(snapshot: MappingBatchPreview) -> dict: |
| 68 | return {"batch": json.loads(_canonical(asdict(snapshot)))} |
| 69 | |
| 70 | |
| 71 | def _digest(payload: dict) -> str: |
| 72 | return sha256(_canonical(payload).encode("utf-8")).hexdigest() |
| 73 | |
| 74 | |
| 75 | def _valid_request_key(value: object) -> bool: |
| 76 | return ( |
| 77 | isinstance(value, str) and bool(value) |
| 78 | and value == value.strip() and len(value) <= 64 |
| 79 | and not any(category(ch) in ("Cc", "Cf", "Cs") for ch in value) |
| 80 | ) |
| 81 | |
| 82 | |
| 83 | def _from_row(row) -> StoredMappingDraft: |
| 84 | return StoredMappingDraft( |
| 85 | id=row["id"], year_id=row["year_id"], request_key=row["request_key"], |
| 86 | checksum=row["payload_hash"], state=row["state"], created_at=row["created_at"], |
| 87 | ) |
| 88 | |
| 89 | |
| 90 | def _read_row(session: Session, *, draft_id: int, year_id: int): |
| 91 | if type(draft_id) is not int or draft_id <= 0 or type(year_id) is not int or year_id <= 0: |
| 92 | raise MappingValidationError("invalid draft or fiscal year identifier") |
| 93 | row = session.execute( |
| 94 | select(mapping_review_drafts).where( |
| 95 | mapping_review_drafts.c.id == draft_id, |
| 96 | mapping_review_drafts.c.year_id == year_id, |
| 97 | ) |
| 98 | ).mappings().first() |
| 99 | if row is None: |
| 100 | raise MappingValidationError("unreviewed Mapping draft not found for fiscal year") |
| 101 | if (row["state"] != "Unreviewed" or |
| 102 | not isinstance(row["payload_json"], dict) or |
| 103 | _digest(row["payload_json"]) != row["payload_hash"]): |
| 104 | raise MappingValidationError("stored unreviewed Mapping draft corrupted") |
| 105 | # Import locally: the audit schema refers to this module's own Core Table. |
| 106 | from aram_backend.mapping_draft_audit import verify_draft_staging_event |
| 107 | verify_draft_staging_event(session, draft_id=draft_id, year_id=year_id) |
| 108 | return row |
| 109 | |
| 110 | |
| 111 | def save_unreviewed_batch( |
| 112 | session: Session, snapshot: MappingBatchPreview, *, request_key: str, |
| 113 | ) -> StoredMappingDraft: |
| 114 | """Stage an unapproved snapshot under caller-controlled transaction. |
| 115 | |
| 116 | Does not call save_mapping_rule, change any MappingRule, commit, create an |
| 117 | approval identity, or authorize reuse of a preview for an APPLY action. |
| 118 | """ |
| 119 | if not _valid_request_key(request_key): |
| 120 | raise MappingValidationError("invalid proposal request key") |
| 121 | if not isinstance(snapshot, MappingBatchPreview) or not snapshot.ready_for_review: |
| 122 | raise MappingValidationError("mapping batch is not ready for unreviewed staging") |
| 123 | with session.no_autoflush: |
| 124 | _require_clean_mapping_state(session) |
| 125 | verify_mapping_batch_current(session, snapshot) |
| 126 | payload = _payload(snapshot) |
| 127 | checksum = _digest(payload) |
| 128 | existing = session.execute( |
| 129 | select(mapping_review_drafts).where( |
| 130 | mapping_review_drafts.c.year_id == snapshot.year_id, |
| 131 | mapping_review_drafts.c.request_key == request_key, |
| 132 | ) |
| 133 | ).mappings().first() |
| 134 | if existing is not None: |
| 135 | if (existing["state"] != "Unreviewed" or |
| 136 | _digest(existing["payload_json"]) != existing["payload_hash"]): |
| 137 | raise MappingValidationError("stored idempotency request key is corrupted") |
| 138 | if checksum != existing["payload_hash"] or payload != existing["payload_json"]: |
| 139 | raise MappingValidationError("idempotency request key already used for another proposal") |
| 140 | # Existing request must have its original system event; never |
| 141 | # append a second event on an idempotent replay. |
| 142 | from aram_backend.mapping_draft_audit import verify_draft_staging_event |
| 143 | verify_draft_staging_event( |
| 144 | session, draft_id=existing["id"], year_id=snapshot.year_id, |
| 145 | ) |
| 146 | return _from_row(existing) |
| 147 | result = session.execute( |
| 148 | insert(mapping_review_drafts).values( |
| 149 | year_id=snapshot.year_id, request_key=request_key, |
| 150 | payload_json=payload, payload_hash=checksum, state="Unreviewed", |
| 151 | ) |
| 152 | ) |
| 153 | # Caller owns transaction; uniqueness constraint rejects simultaneous |
| 154 | # identical keys on independent DB connections. On IntegrityError the |
| 155 | # caller must rollback; do not recover by unguarded replay. |
| 156 | draft_id = result.inserted_primary_key[0] |
| 157 | from aram_backend.mapping_draft_audit import record_draft_staging_event |
| 158 | record_draft_staging_event( |
| 159 | session, draft_id=draft_id, year_id=snapshot.year_id, |
| 160 | request_key=request_key, payload_hash=checksum, |
| 161 | ) |
| 162 | row = _read_row(session, draft_id=draft_id, year_id=snapshot.year_id) |
| 163 | return _from_row(row) |
| 164 | |
| 165 | |
| 166 | def get_unreviewed_batch( |
| 167 | session: Session, *, draft_id: int, year_id: int, |
| 168 | ) -> StoredMappingDraft: |
| 169 | """Read passive draft metadata scoped to a fiscal year; not authenticated.""" |
| 170 | with session.no_autoflush: |
| 171 | return _from_row(_read_row(session, draft_id=draft_id, year_id=year_id)) |
| 172 | |
| 173 | |
| 174 | def validate_unreviewed_batch_current( |
| 175 | session: Session, *, draft_id: int, year_id: int, |
| 176 | ) -> None: |
| 177 | """Reevaluate stored source rows against current DB state, read-only. |
| 178 | |
| 179 | Even if this succeeds, another transaction can change facts afterwards: |
| 180 | this is NOT a transaction lock, reviewer attestation, or write permission. |
| 181 | """ |
| 182 | with session.no_autoflush: |
| 183 | row = _read_row(session, draft_id=draft_id, year_id=year_id) |
| 184 | try: |
| 185 | batch = row["payload_json"]["batch"] |
| 186 | source = tuple(ProposedMappingRow(**item) for item in batch["source_rows"]) |
| 187 | current = preview_mapping_batch(session, year_id=year_id, rows=source) |
| 188 | if not current.ready_for_review: |
| 189 | raise MappingValidationError("stored Mapping draft is stale") |
| 190 | if _canonical(asdict(current)) != _canonical(batch): |
| 191 | raise MappingValidationError("stored Mapping draft is stale") |
| 192 | except (KeyError, ValueError, TypeError) as exc: |
| 193 | raise MappingValidationError("stored Mapping draft is stale or malformed") from exc |