fix: protect original fiscal-year ownership and note references
davoodmehraban89 committed
Oct 23, 2026 at 16:43 UTC
75f82fcbfa2d9745d4c8e358979fe4fe754a82b6
7 files changed
+539
-21
PROJECT_STATUS.md
+20
-8
@@ -35,7 +35,7 @@
35
| Phase 2B ingestion foundation | VERIFIED_AND_MERGED | [PR #12](https://github.com/davoodmehraban89/Aram/pull/12), squash merge 7b5bd79b760d534dad34b3162f770e838616ebe9 |
36
| Phase 2B control reconciliation | VERIFIED_AND_MERGED | [PR #13](https://github.com/davoodmehraban89/Aram/pull/13), squash merge 7c7533ee87146dc8fc78b46ebf423be55532c7eb |
37
| Gate 2A Pilot workbook contract/preflight | VERIFIED_AND_MERGED | [PR #15](https://github.com/davoodmehraban89/Aram/pull/15), reviewed head 74b6a6397a2a2c9199a5c7bcf818bb661b2ebe06, squash merge 4ab54f4a3cf666827fa1ed30c4e43259ea79f2d4, [Backend CI #24](https://github.com/davoodmehraban89/Aram/actions/runs/32712900800) |
38
-| V1-01 safety-gate hardening | IN_PROGRESS | Draft [PR #21](https://github.com/davoodmehraban89/Aram/pull/21) from exact base `b1ddee87d31ee73b3a5aeac8f9953d0a604c206a`; independently reviewed implementation head `700d800dbd9c657f6bd510faafedcbde4847fafd`; CI-verified stabilized candidate `b3dc8b3a18934ffe63f615e4f650248be21a5f9c`; [Backend CI #39](https://github.com/davoodmehraban89/Aram/actions/runs/33015277194) succeeded with 67 tests, migration round-trip, and compile after broadening one reparent-rejection assertion to accept either valid protection message; code, scope, and protected-data boundary remain unchanged; final independent acceptance is pending this durable-document reconciliation |
38
+| V1-01 safety-gate hardening | VERIFIED_AND_MERGED | [PR #21](https://github.com/davoodmehraban89/Aram/pull/21), merged 2026-08-27; squash commit `7dc864fd032f0c4ae4d650d89304a01286a6d914`; [accepted-head CI](https://github.com/davoodmehraban89/Aram/actions/runs/33063001065) succeeded with 67 tests |
39
| Post-Gate-2A control reconciliation | VERIFIED_AND_MERGED | [PR #18](https://github.com/davoodmehraban89/Aram/pull/18), reviewed head `fcbeb7387218e9ab294318ae462ed59de717fc95`, squash merge `f213d321ff4cd7d3d6fa65ba78dc48f090ee846b`; documentation only |
40
| Durable post-merge acceptance record | VERIFIED_AND_MERGED | [PR #19](https://github.com/davoodmehraban89/Aram/pull/19), reviewed head `b9059592409606a0a4f11a71c30778cff158b6b6`, squash merge `77f9f595ccfe67a87b11024ff0f6143629dba438`; documentation only |
41
| Role-based project operating model | VERIFIED_AND_MERGED | Permanent responsibilities and current assignments are defined in `docs/handoff/MASTER_RECOVERY_PROMPT.md` and ADR-011; introduced through [PR #20](https://github.com/davoodmehraban89/Aram/pull/20) |
@@ -64,19 +64,31 @@ The accepted branch does not include PR #7 desktop/release work, PR #16 alternat
64
## Current risks and blockers
65
66
- The accepted branch is not protected by GitHub branch protection.
67
-- The accepted branch still permits direct identity mutation/deletion of approved or locked fiscal years and parent-company deletion; the V1-01 candidate fixes this but is not accepted yet.
68
-- The accepted Pilot preflight can still accept targetless or structurally invalid mappings and can ignore a declared closing-delta mismatch; the V1-01 candidate fixes this but is not accepted yet.
69
-- The accepted root `index.html` is still a disconnected hard-coded prototype; the V1-01 candidate replaces it with an explicit quarantine page.
67
+- PR #21 is accepted and protects fiscal-year/company identity. A follow-up audit reproduced moving year-owned records out of protected years and relationship-based cross-year statement-note links; the focused candidate on `codex/v1-year-isolation-followup-20261023` addresses these gaps but is not accepted yet.
68
+- Accepted PR #21 rejects targetless/hierarchy-invalid mappings and declared closing-delta mismatches; these previously recorded candidate risks are resolved.
69
+- The accepted root `index.html` is an explicit quarantine page. A real Pilot UI remains unimplemented.
70
- PR #17 was closed without merge; its stale-base 12-file diff is reference material only, and its narrative listed only 9 files.
71
- PR #17 CI was green on its own stale head, but compatibility with accepted Gate 2A was never proven.
72
- Binary execution, release provenance, and clean Windows verification do not exist.
73
- Mapping, notes/sub-notes, Pilot UI, and end-to-end user acceptance remain incomplete.
74
75
-## Next approved action
75
+## Current focused follow-up — 2026-10-23
76
77
-1. Publish this two-file durable-document reconciliation on Draft PR #21; [Backend CI #39](https://github.com/davoodmehraban89/Aram/actions/runs/33015277194) succeeded on stabilized candidate `b3dc8b3a18934ffe63f615e4f650248be21a5f9c` with 67 tests, migration round-trip, and compile.
78
-2. The independent reviewer re-fetches the resulting documentation-only head, confirms that its comparison with `b3dc8b3a18934ffe63f615e4f650248be21a5f9c` changes only `PROJECT_STATUS.md` and `docs/handoff/LATEST_HANDOFF.md`, verifies the final workflow result, then marks the PR ready and squash-merges it.
79
-3. Only after V1-01 is accepted, start the first focused Gate 3 Mapping import/persistence task from the new accepted head.
77
+- Base verified against GitHub: `source-data-cleanup@7dc864fd032f0c4ae4d650d89304a01286a6d914`.
78
+- Candidate branch: `codex/v1-year-isolation-followup-20261023`; status `IN_PROGRESS`, not accepted.
79
+- Scope: original/proposed fiscal-year ownership checks, effective relationship/FK validation, and focused regression tests. No schema, dependency, workflow, canonical-data or release changes.
80
+- Local evidence: 110 tests passed, one existing third-party deprecation warning; isolated Alembic upgrade/downgrade, compilation and whitespace checks passed.
81
+- RED evidence: original ownership regressions reproduced 22 missing rejections; reference-resolution regressions reproduced seven missing rejections before their respective fixes.
82
+- Independent local review found one pending-explicit-ID parent gap, addressed with eight additional direct-FK tests; four reproduced the missing behavior before the fix.
83
+- Graph-wide changes involving clean referencing records, expired fiscal-year lifecycle/same-flush behavior, and bulk/raw/concurrent writes are not certified by this focused ORM fix and require separate release gates.
84
+- Remote publication, final-head CI and independent acceptance must be verified from the live candidate; this preparation record is not acceptance evidence.
85
+- Draft PRs #22–31 exist as of this inspection; Gate 3 candidates are active but remain unaccepted. Their older descriptions may predate current CI results.
86
+
87
+## Next action
88
+
89
+1. Independently review the focused isolation follow-up and its final remote CI before accepting it; the implementation author must not self-merge.
90
+2. Reconcile PR #22 documentation and PR #26/27 mapping candidates with the safety fix. Existing drafts do not yet implement the requested persisted old/new preview, user approval, identical-input coalescing or full account/dimension identity.
91
+3. Continue the owner-requested read-only Peyvast SQL Server integration and governed DB/Excel mapping design. The customer installation version, schema, supported interface and access remain unverified; no live connector or financial reconciliation is claimed.
92
93
## Control documents
94
backend/src/aram_backend/models.py
+59
-13
@@ -184,13 +184,30 @@ class StatementLine(TimestampMixin, Base):
184
def _resolve_parent_year_id(
185
obj: Any, session: Session, rel_attr: str, fk_attr: str, parent_cls: type[Any]
186
) -> int | None:
187
- parent = getattr(obj, rel_attr, None)
188
- if parent is not None:
189
- return parent.year_id
187
+ state = inspect(obj)
188
+ relationship_history = state.attrs[rel_attr].history
189
+ foreign_key_history = state.attrs[fk_attr].history
190
fk_val = getattr(obj, fk_attr, None)
191
- if fk_val is not None:
192
- return session.scalar(select(parent_cls.year_id).where(parent_cls.id == fk_val))
193
- return None
191
+ if relationship_history.has_changes():
192
+ parent = getattr(obj, rel_attr, None)
193
+ parent_id = parent.id if parent is not None else None
194
+ if foreign_key_history.has_changes() and fk_val != parent_id:
195
+ raise ValueError(f"Conflicting {rel_attr} relationship and {fk_attr}")
196
+ elif fk_val is not None:
197
+ # A raw FK assignment does not invalidate an already cached relationship.
198
+ parent = session.get(parent_cls, fk_val)
199
+ if parent is None:
200
+ # Pending explicit-ID parents are not in the Session identity map yet.
201
+ parent = next(
202
+ (
203
+ candidate for candidate in session.new
204
+ if isinstance(candidate, parent_cls) and candidate.id == fk_val
205
+ ),
206
+ None,
207
+ )
208
+ else:
209
+ parent = None
210
+ return parent.year_id if parent is not None else None
211
212
213
def _year_id_for(obj: object, session: Session) -> int | None:
@@ -205,6 +222,31 @@ def _year_id_for(obj: object, session: Session) -> int | None:
222
return None
223
224
225
+def _persisted_year_id_for(obj: Any, session: Session) -> int | None:
226
+ """Read original ownership before flush, even when attributes are expired."""
227
+ identity = inspect(obj).identity
228
+ if identity is None:
229
+ return None
230
+ if isinstance(obj, YearOwnedMixin):
231
+ model = type(obj)
232
+ query = select(model.year_id).where(model.id == identity[0])
233
+ elif isinstance(obj, NoteRow):
234
+ query = (
235
+ select(NoteDefinition.year_id)
236
+ .join(NoteRow, NoteRow.note_id == NoteDefinition.id)
237
+ .where(NoteRow.id == identity[0])
238
+ )
239
+ elif isinstance(obj, StatementLine):
240
+ query = (
241
+ select(FinancialStatement.year_id)
242
+ .join(StatementLine, StatementLine.statement_id == FinancialStatement.id)
243
+ .where(StatementLine.id == identity[0])
244
+ )
245
+ else:
246
+ return None
247
+ return session.scalar(query)
248
+
249
+
250
_PROTECTED_YEAR_STATUSES = {FiscalYearStatus.APPROVED, FiscalYearStatus.LOCKED}
251
252
@@ -276,19 +318,23 @@ def enforce_audit_invariants(session: Session, _flush_context, _instances) -> No
318
if isinstance(obj, FiscalYear):
319
continue
320
year_id = _year_id_for(obj, session)
321
+ original_year_id = _persisted_year_id_for(obj, session)
322
+ for affected_year_id in {year_id, original_year_id} - {None}:
323
+ status = session.scalar(
324
+ select(FiscalYear.status).where(FiscalYear.id == affected_year_id)
325
+ )
326
+ if status in _PROTECTED_YEAR_STATUSES:
327
+ raise ValueError(
328
+ f"Fiscal year {affected_year_id} is {status.value.lower()} and cannot be mutated"
329
+ )
330
if year_id is None:
331
continue
281
- status = session.scalar(select(FiscalYear.status).where(FiscalYear.id == year_id))
282
- if status in {FiscalYearStatus.APPROVED, FiscalYearStatus.LOCKED}:
283
- raise ValueError(
284
- f"Fiscal year {year_id} is {status.value.lower()} and cannot be mutated"
285
- )
332
333
if isinstance(obj, MappingRule):
334
target_year_id = _resolve_parent_year_id(obj, session, "target_note", "target_note_id", NoteDefinition)
335
if target_year_id != obj.year_id:
336
raise ValueError("Mapping rule and target note must belong to the same fiscal year")
291
- if isinstance(obj, StatementLine) and obj.target_note_id is not None:
337
+ if isinstance(obj, StatementLine):
338
target_year_id = _resolve_parent_year_id(obj, session, "target_note", "target_note_id", NoteDefinition)
293
- if target_year_id != year_id:
339
+ if target_year_id is not None and target_year_id != year_id:
340
raise ValueError("Statement line and target note must belong to the same fiscal year")
backend/tests/test_models.py
+328
@@ -231,3 +231,331 @@ def test_draft_year_identity_and_deletion_remain_mutable(session):
231
session.delete(year)
232
session.commit()
233
assert session.get(FiscalYear, year.id) is None
234
+
235
+
236
+@pytest.mark.parametrize("status", [FiscalYearStatus.APPROVED, FiscalYearStatus.LOCKED])
237
+@pytest.mark.parametrize("expire_owner", [False, True])
238
+@pytest.mark.parametrize("record_kind", ["account", "source", "note", "statement"])
239
+def test_record_cannot_leave_protected_year(session, status, expire_owner, record_kind):
240
+ original = make_year(session, 1403)
241
+ destination = make_year(session, 1404)
242
+ records = {
243
+ "account": lambda: AccountVersion(
244
+ year_id=original.id, account_code="1000", account_name="Cash"
245
+ ),
246
+ "source": lambda: SourceDocument(
247
+ year_id=original.id, filename="synthetic.csv", file_hash="synthetic",
248
+ document_type="general_ledger",
249
+ ),
250
+ "note": lambda: NoteDefinition(
251
+ year_id=original.id, note_number="10", title="Assets"
252
+ ),
253
+ "statement": lambda: FinancialStatement(
254
+ year_id=original.id, statement_type=StatementType.BALANCE_SHEET
255
+ ),
256
+ }
257
+ record = records[record_kind]()
258
+ session.add(record)
259
+ session.commit()
260
+ original.status = FiscalYearStatus.APPROVED
261
+ session.commit()
262
+ if status is FiscalYearStatus.LOCKED:
263
+ original.status = FiscalYearStatus.LOCKED
264
+ session.commit()
265
+ record_id, original_id = record.id, original.id
266
+ if expire_owner:
267
+ session.expire(record, ["year_id"])
268
+
269
+ record.year_id = destination.id
270
+ with pytest.raises(ValueError, match="cannot be mutated"):
271
+ session.commit()
272
+ session.rollback()
273
+ session.expire_all()
274
+ assert session.get(type(record), record_id).year_id == original_id
275
+
276
+
277
+@pytest.mark.parametrize("status", [FiscalYearStatus.APPROVED, FiscalYearStatus.LOCKED])
278
+def test_mapping_cannot_leave_protected_year_with_new_target(session, status):
279
+ original = make_year(session, 1403)
280
+ destination = make_year(session, 1404)
281
+ original_note = NoteDefinition(year_id=original.id, note_number="10", title="Old")
282
+ new_note = NoteDefinition(year_id=destination.id, note_number="10", title="New")
283
+ session.add_all([original_note, new_note])
284
+ session.commit()
285
+ rule = MappingRule(
286
+ year_id=original.id, rule_key="cash", account_code="1000",
287
+ mapping_type="O", target_note=original_note,
288
+ )
289
+ session.add(rule)
290
+ session.commit()
291
+ original.status = FiscalYearStatus.APPROVED
292
+ session.commit()
293
+ if status is FiscalYearStatus.LOCKED:
294
+ original.status = FiscalYearStatus.LOCKED
295
+ session.commit()
296
+ original_id, rule_id, note_id = original.id, rule.id, original_note.id
297
+
298
+ rule.year_id = destination.id
299
+ rule.target_note = new_note
300
+ with pytest.raises(ValueError, match="cannot be mutated"):
301
+ session.commit()
302
+ session.rollback()
303
+ session.expire_all()
304
+ stored = session.get(MappingRule, rule_id)
305
+ assert (stored.year_id, stored.target_note_id) == (original_id, note_id)
306
+
307
+
308
+@pytest.mark.parametrize("status", [FiscalYearStatus.APPROVED, FiscalYearStatus.LOCKED])
309
+@pytest.mark.parametrize("child_kind", ["note_row", "statement_line"])
310
+@pytest.mark.parametrize("assignment", ["foreign_key", "relationship"])
311
+def test_child_cannot_leave_protected_parent(session, status, child_kind, assignment):
312
+ original = make_year(session, 1403)
313
+ destination = make_year(session, 1404)
314
+ if child_kind == "note_row":
315
+ old_parent = NoteDefinition(year_id=original.id, note_number="10", title="Old")
316
+ new_parent = NoteDefinition(year_id=destination.id, note_number="10", title="New")
317
+ child = NoteRow(note=old_parent, row_order=0, label="Cash")
318
+ foreign_key, relationship = "note_id", "note"
319
+ else:
320
+ old_parent = FinancialStatement(
321
+ year_id=original.id, statement_type=StatementType.BALANCE_SHEET
322
+ )
323
+ new_parent = FinancialStatement(
324
+ year_id=destination.id, statement_type=StatementType.BALANCE_SHEET
325
+ )
326
+ child = StatementLine(statement=old_parent, line_order=0, line_label="Cash")
327
+ foreign_key, relationship = "statement_id", "statement"
328
+ session.add_all([old_parent, new_parent, child])
329
+ session.commit()
330
+ original.status = FiscalYearStatus.APPROVED
331
+ session.commit()
332
+ if status is FiscalYearStatus.LOCKED:
333
+ original.status = FiscalYearStatus.LOCKED
334
+ session.commit()
335
+ child_id, parent_id = child.id, old_parent.id
336
+ if assignment == "foreign_key":
337
+ session.expire(child, [relationship])
338
+ setattr(child, foreign_key, new_parent.id)
339
+ else:
340
+ setattr(child, relationship, new_parent)
341
+
342
+ with pytest.raises(ValueError, match="cannot be mutated"):
343
+ session.commit()
344
+ session.rollback()
345
+ session.expire_all()
346
+ assert getattr(session.get(type(child), child_id), foreign_key) == parent_id
347
+
348
+
349
+def test_draft_account_edits_and_owner_change_remain_allowed(session):
350
+ original = make_year(session, 1403)
351
+ destination = make_year(session, 1404)
352
+ account = AccountVersion(year_id=original.id, account_code="1000", account_name="Cash")
353
+ session.add(account)
354
+ session.commit()
355
+
356
+ account.year_id = destination.id
357
+ account.account_name = "Reviewed cash"
358
+ session.commit()
359
+ session.expire_all()
360
+ stored = session.get(AccountVersion, account.id)
361
+ assert (stored.year_id, stored.account_name) == (destination.id, "Reviewed cash")
362
+
363
+
364
+@pytest.mark.parametrize("same_company", [False, True])
365
+def test_relationship_only_statement_note_cannot_cross_year(session, same_company):
366
+ first = make_year(session, 1403)
367
+ if same_company:
368
+ second = FiscalYear(company=first.company, year=1404)
369
+ session.add(second)
370
+ session.commit()
371
+ else:
372
+ second = make_year(session, 1404)
373
+ note = NoteDefinition(year_id=first.id, note_number="10", title="Assets")
374
+ statement = FinancialStatement(
375
+ year_id=second.id, statement_type=StatementType.BALANCE_SHEET
376
+ )
377
+ session.add_all([note, statement])
378
+ session.commit()
379
+ statement_id = statement.id
380
+ session.add(StatementLine(
381
+ statement=statement, target_note=note, line_order=0, line_label="Assets"
382
+ ))
383
+
384
+ with pytest.raises(ValueError, match="same fiscal year"):
385
+ session.commit()
386
+ session.rollback()
387
+ session.expire_all()
388
+ assert session.get(FinancialStatement, statement_id).lines == []
389
+
390
+
391
+@pytest.mark.parametrize("record_kind", ["mapping", "statement_line"])
392
+def test_cached_note_cannot_hide_cross_year_foreign_key_change(session, record_kind):
393
+ first = make_year(session, 1403)
394
+ second = make_year(session, 1404)
395
+ old_note = NoteDefinition(year_id=first.id, note_number="10", title="Old")
396
+ new_note = NoteDefinition(year_id=second.id, note_number="10", title="New")
397
+ statement = FinancialStatement(
398
+ year_id=first.id, statement_type=StatementType.BALANCE_SHEET
399
+ )
400
+ session.add_all([old_note, new_note, statement])
401
+ session.commit()
402
+ if record_kind == "mapping":
403
+ record = MappingRule(
404
+ year_id=first.id, rule_key="cash", account_code="1000",
405
+ target_note=old_note, mapping_type="O",
406
+ )
407
+ else:
408
+ record = StatementLine(
409
+ statement=statement, target_note=old_note, line_order=0, line_label="Cash"
410
+ )
411
+ session.add(record)
412
+ session.commit()
413
+ assert record.target_note is old_note
414
+ record_id, old_note_id = record.id, old_note.id
415
+
416
+ record.target_note_id = new_note.id
417
+ with pytest.raises(ValueError, match="same fiscal year"):
418
+ session.commit()
419
+ session.rollback()
420
+ session.expire_all()
421
+ assert session.get(type(record), record_id).target_note_id == old_note_id
422
+
423
+
424
+def test_cached_statement_cannot_hide_move_into_locked_year(session):
425
+ first = make_year(session, 1403)
426
+ second = make_year(session, 1404)
427
+ old_statement = FinancialStatement(
428
+ year_id=first.id, statement_type=StatementType.BALANCE_SHEET
429
+ )
430
+ new_statement = FinancialStatement(
431
+ year_id=second.id, statement_type=StatementType.BALANCE_SHEET
432
+ )
433
+ line = StatementLine(statement=old_statement, line_order=0, line_label="Cash")
434
+ session.add_all([old_statement, new_statement, line])
435
+ session.commit()
436
+ second.status = FiscalYearStatus.APPROVED
437
+ session.commit()
438
+ second.status = FiscalYearStatus.LOCKED
439
+ session.commit()
440
+ assert line.statement is old_statement
441
+ line_id, original_id = line.id, old_statement.id
442
+
443
+ line.statement_id = new_statement.id
444
+ with pytest.raises(ValueError, match="cannot be mutated"):
445
+ session.commit()
446
+ session.rollback()
447
+ session.expire_all()
448
+ assert session.get(StatementLine, line_id).statement_id == original_id
449
+
450
+
451
+@pytest.mark.parametrize("record_kind", ["mapping", "statement_line"])
452
+def test_conflicting_target_relationship_and_foreign_key_are_rejected(session, record_kind):
453
+ year = make_year(session)
454
+ first_note = NoteDefinition(year_id=year.id, note_number="10", title="First")
455
+ second_note = NoteDefinition(year_id=year.id, note_number="11", title="Second")
456
+ statement = FinancialStatement(
457
+ year_id=year.id, statement_type=StatementType.BALANCE_SHEET
458
+ )
459
+ session.add_all([first_note, second_note, statement])
460
+ session.commit()
461
+ if record_kind == "mapping":
462
+ record = MappingRule(
463
+ year_id=year.id, rule_key="cash", account_code="1000", mapping_type="O",
464
+ target_note=first_note, target_note_id=second_note.id,
465
+ )
466
+ else:
467
+ record = StatementLine(
468
+ statement=statement, line_order=0, line_label="Cash",
469
+ target_note=first_note, target_note_id=second_note.id,
470
+ )
471
+ session.add(record)
472
+
473
+ with pytest.raises(ValueError, match="Conflicting"):
474
+ session.commit()
475
+ session.rollback()
476
+
477
+
478
+def test_statement_allows_same_year_relationship_and_optional_note(session):
479
+ year = make_year(session)
480
+ note = NoteDefinition(year_id=year.id, note_number="10", title="Assets")
481
+ statement = FinancialStatement(
482
+ year_id=year.id, statement_type=StatementType.BALANCE_SHEET
483
+ )
484
+ linked = StatementLine(
485
+ statement=statement, target_note=note, line_order=0, line_label="Cash"
486
+ )
487
+ unlinked = StatementLine(statement=statement, line_order=1, line_label="Subtotal")
488
+ session.add_all([note, statement, linked, unlinked])
489
+ session.commit()
490
+ note_id, linked_id, unlinked_id = note.id, linked.id, unlinked.id
491
+ session.expire_all()
492
+ assert session.get(StatementLine, linked_id).target_note_id == note_id
493
+ assert session.get(StatementLine, unlinked_id).target_note_id is None
494
+
495
+ session.get(StatementLine, linked_id).target_note = None
496
+ session.commit()
497
+ session.expire_all()
498
+ assert session.get(StatementLine, linked_id).target_note_id is None
499
+
500
+
501
+@pytest.mark.parametrize("pending_parent", ["note", "statement", "both"])
502
+@pytest.mark.parametrize("same_year", [False, True])
503
+def test_direct_fk_resolves_pending_explicit_id_parents(session, pending_parent, same_year):
504
+ first = make_year(session, 1403)
505
+ second = make_year(session, 1404)
506
+ note = NoteDefinition(
507
+ id=900, year_id=first.id if same_year else second.id,
508
+ note_number="10", title="Synthetic note",
509
+ )
510
+ statement = FinancialStatement(
511
+ id=901, year_id=first.id, statement_type=StatementType.BALANCE_SHEET
512
+ )
513
+ if pending_parent == "note":
514
+ session.add(statement)
515
+ session.commit()
516
+ elif pending_parent == "statement":
517
+ session.add(note)
518
+ session.commit()
519
+ line = StatementLine(
520
+ statement_id=901, target_note_id=900, line_order=0, line_label="Synthetic"
521
+ )
522
+ session.add_all([note, statement, line])
523
+ if same_year:
524
+ session.commit()
525
+ line_id = line.id
526
+ session.expire_all()
527
+ stored = session.get(StatementLine, line_id)
528
+ assert stored.statement.year_id == first.id
529
+ assert stored.target_note.year_id == first.id
530
+ else:
531
+ with pytest.raises(ValueError, match="same fiscal year"):
532
+ session.commit()
533
+ session.rollback()
534
+ session.expire_all()
535
+ assert session.query(StatementLine).count() == 0
536
+
537
+
538
+@pytest.mark.parametrize("same_year", [False, True])
539
+def test_mapping_direct_fk_resolves_pending_note(session, same_year):
540
+ first = make_year(session, 1403)
541
+ second = make_year(session, 1404)
542
+ note = NoteDefinition(
543
+ id=900, year_id=first.id if same_year else second.id,
544
+ note_number="10", title="Synthetic note",
545
+ )
546
+ mapping = MappingRule(
547
+ year_id=first.id, rule_key="synthetic", account_code="1000",
548
+ target_note_id=900, mapping_type="O",
549
+ )
550
+ session.add_all([note, mapping])
551
+ if same_year:
552
+ session.commit()
553
+ rule_id = mapping.id
554
+ session.expire_all()
555
+ stored = session.get(MappingRule, rule_id)
556
+ assert stored.target_note.year_id == stored.year_id == first.id
557
+ else:
558
+ with pytest.raises(ValueError, match="same fiscal year"):
559
+ session.commit()
560
+ session.rollback()
561
+ assert session.query(MappingRule).count() == 0
docs/PROJECT_LOG.md
+20
@@ -278,3 +278,23 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
278
- Recovery: close the candidate PR without merge; accepted branch remains at the recorded base
279
- Remaining risks: comprehensive Mapping, note/sub-note workflow, real Pilot UI/output, Windows packaging, and user acceptance remain incomplete
280
- Next action: publish the focused PR and obtain independent remote review after CI
281
+
282
+### 2026-10-23T13:06:25Z — Protected ownership and statement-note follow-up prepared
283
+
284
+- Actor: Codex, implementing the owner's instruction to continue the safety-first Peyvast/mapping work.
285
+- Verified base: `source-data-cleanup@7dc864fd032f0c4ae4d650d89304a01286a6d914`; remote fetched and matched before editing.
286
+- Dedicated branch: `codex/v1-year-isolation-followup-20261023`.
287
+- Outcome: original and proposed fiscal-year ownership are checked for year-owned records and nested rows; pending relationships and direct FK changes are resolved explicitly; conflicting FK/relationship identities and cross-year statement-note references are rejected.
288
+- Exact changed files: `backend/src/aram_backend/models.py`, `backend/tests/test_models.py`, `PROJECT_STATUS.md`, `docs/PROJECT_LOG.md`, `docs/handoff/LATEST_HANDOFF.md`, `docs/superpowers/specs/2026-10-23-year-isolation-design.md`, `docs/superpowers/plans/2026-10-23-year-isolation.md`.
289
+- RED/GREEN: first regression group reproduced 22 missing rejections on the unchanged base; second group reproduced seven missing rejections before effective-parent changes. Final local `PYTHONPATH=src python -m pytest`: 110 passed, one existing third-party deprecation warning.
290
+- Migration/compile: isolated SQLite Alembic upgrade/downgrade and `python -m compileall -q src tests migrations` succeeded; `git diff --check` passed.
291
+- Governance correction: PR #21 was already merged on 2026-08-27 at this base; its old in-progress narrative is corrected, without claiming this new follow-up is accepted.
292
+- Protected boundary: no canonical XLSX/PDF, `data/`, persisted database, financial-source value, schema, migration, dependency, workflow, binary, ZIP, EXE, tag or release change.
293
+- Publication/CI: pending at this preparation entry; final remote branch, PR, head and Actions must be read from GitHub before acceptance.
294
+- Artifacts/releases: NONE.
295
+- Acceptance: IN_PROGRESS; independent whole-branch review and final remote CI required; author must not self-merge.
296
+- Recovery: close the unmerged candidate; accepted branch remains at the verified base. If later accepted, revert through an independently reviewed rollback PR.
297
+- Remaining risks: ORM-hook protections do not authorize bulk/raw SQL writes; live Peyvast schema/access, governed mapping approval, output reconciliation and user acceptance remain outstanding. Dependent draft branches must be reconciled before acceptance.
298
+
299
+- Independent local review: one Important pending-explicit-ID parent-resolution gap was reproduced. Eight direct-FK cases were added, four failed before the fix, then the complete 110-test suite passed. The review report itself requested changes; this correction has TDD evidence, not a claim of final remote acceptance.
300
+- Explicit remaining boundaries: raw/bulk SQL and concurrent provider enforcement are outside this ORM hook. Graph-wide changes involving clean referencing records and expired fiscal-year lifecycle/same-flush behavior need separate focused acceptance work before a financial release.
docs/handoff/LATEST_HANDOFF.md
+17
@@ -3,6 +3,23 @@
3
> Durable accepted-state record with persistent role assignments and recovery workflow.
4
> GitHub remote evidence remains authoritative. Always fetch the live branch head and open PRs before acting; recorded SHAs are verified events, not perpetual current-head claims.
5
6
+## Current correction and focused candidate — 2026-10-23
7
+
8
+This dated correction supersedes the older PR #21 candidate/single-next-action narrative below; earlier details remain historical evidence.
9
+
10
+- Live accepted base verified: `source-data-cleanup@7dc864fd032f0c4ae4d650d89304a01286a6d914`.
11
+- PR #21 is merged (2026-08-27). Accepted-head [Backend CI](https://github.com/davoodmehraban89/Aram/actions/runs/33063001065) succeeded; 67 tests. The legacy UI is quarantined and the PR #21 validation/identity fixes are accepted.
12
+- New branch `codex/v1-year-isolation-followup-20261023` contains a focused, unaccepted follow-up for original-year ownership and relationship/FK reference validation.
13
+- Local follow-up evidence: 110 pytest tests passed, one existing third-party warning; migration round-trip, compile and whitespace checks passed. Original-owner regressions first produced 22 expected failures; effective-reference regressions first produced seven expected failures.
14
+- Exact application scope: `backend/src/aram_backend/models.py`, `backend/tests/test_models.py`. Control scope: `PROJECT_STATUS.md`, `docs/PROJECT_LOG.md`, this handoff, and `docs/superpowers/{specs/2026-10-23-year-isolation-design.md,plans/2026-10-23-year-isolation.md}`.
15
+- Independent local review requested a pending-explicit-ID parent correction; eight regressions were added and all 110 tests passed after the fix. Final remote acceptance remains pending.
16
+- Remaining boundaries: graph-wide moves of clean referencing records, expired fiscal-year lifecycle/same-flush behavior, and bulk/raw/concurrent writes require separate focused acceptance before a financial release.
17
+- Remote publication and final CI are pending at this preparation snapshot; fetch the live branch/PR before acting. Independent acceptance remains required; author must not self-merge.
18
+- Draft PRs #22–31 are active and unaccepted. In particular #26/27 supply mapping foundations, but do not fulfill full account/dimension identity, persisted old/new preview, approval or identical-input duplicate coalescing.
19
+- Owner clarified Peyvast is the first database source, alongside Excel. Vendor FAQ identifies default Microsoft SQL Server, supports 2019/2022 and recommends 2022: https://payvast.com/نرم-افزار-حسابداری/ . The customer installation/schema/access have not been inspected; no live extraction is claimed.
20
+- Preserve canonical data. No migration, dependency, workflow, source XLSX/PDF, `data/`, financial-source value, ZIP/EXE, tag or release changed.
21
+- Next: independent safety review, reconcile dependent drafts, then shared DB/Excel and governed mapping work against documented customer source semantics. A separate design note exists in the task workspace, not as accepted repository functionality.
22
+
23
## Accepted repository state
24
25
- Repository: davoodmehraban89/Aram
docs/superpowers/plans/2026-10-23-year-isolation.md
new
+62
@@ -0,0 +1,62 @@
1
+# Fiscal-year Isolation Implementation Plan
2
+
3
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [x]`) syntax for tracking.
4
+
5
+**Goal:** Close the reproduced protected-ownership and relationship-based cross-year reference gaps.
6
+
7
+**Architecture:** Extend the existing before-flush hook with persisted-origin checks and change-aware relationship resolution. Keep database schema and dependencies unchanged.
8
+
9
+**Tech Stack:** Python 3.12, SQLAlchemy, pytest, SQLite, Alembic.
10
+
11
+**Spec:** `docs/superpowers/specs/2026-10-23-year-isolation-design.md`
12
+
13
+## Global Constraints
14
+
15
+- Exact base: `7dc864fd032f0c4ae4d650d89304a01286a6d914`; branch `source-data-cleanup`.
16
+- No dependency, workflow, migration, canonical XLSX/PDF, `data/`, persisted database, financial-source value, binary or release change.
17
+- No recovery from closed PR #7 and no acceptance or merge of other draft PRs.
18
+- Application scope: `backend/src/aram_backend/models.py` and `backend/tests/test_models.py`.
19
+- Control records: `PROJECT_STATUS.md`, `docs/PROJECT_LOG.md`, `docs/handoff/LATEST_HANDOFF.md`, and this design/plan pair.
20
+
21
+## Review Focus
22
+
23
+- Original owner is unloaded/expired: moving data must still detect its protected source year.
24
+- Parent relationship was cached before a direct FK change: inspect the proposed parent, not the old cache.
25
+- New relationship-only statement-note reference: validate before FK synchronization.
26
+- Both a relationship and FK are supplied inconsistently: reject conflicting identities.
27
+- No target note and valid Draft-only edits: preserve allowed operations.
28
+
29
+### Task 1: Enforce original and proposed ownership
30
+
31
+**Files:** Modify `backend/src/aram_backend/models.py`; test `backend/tests/test_models.py`.
32
+
33
+**Interfaces:** Existing ORM models and `enforce_audit_invariants`; private helpers may resolve persisted ownership and effective parents. No public API changes.
34
+
35
+- [x] Write regressions for moving AccountVersion and year-owned model variants from Approved/Locked to Draft, including expired ownership; assert rejection plus unchanged stored state after rollback.
36
+- [x] Add raw-FK and relationship reparenting regressions for NoteRow and StatementLine leaving protected years; retain valid Draft-only operations.
37
+- [x] Run the new regressions on unchanged production code; expected meaningful failures proving the bypasses.
38
+- [x] Resolve original ownership by persisted identity, then enforce protection on original and proposed years before flush.
39
+- [x] Run the focused regressions and full `PYTHONPATH=src python -m pytest`; expected all pass.
40
+
41
+### Task 2: Enforce effective statement-note reference identity
42
+
43
+**Files:** Modify the same two application files.
44
+
45
+**Interfaces:** Private `_resolve_parent_year_id` and the existing same-year invariant.
46
+
47
+- [x] Add regressions for relationship-only cross-year/cross-company statement-note creation, cached-parent raw-FK updates, conflicting relationship/FK values, and valid same-year/no-target cases.
48
+- [x] Run new regressions before changing resolution; expected invalid references fail their rejection assertions.
49
+- [x] Resolve effective parent using relationship/FK change history, reject conflicting assignments, and remove the FK-population gate from optional note validation.
50
+- [x] Run focused regressions and the full suite; expected all pass.
51
+
52
+### Task 3: Record and publish evidence
53
+
54
+**Files:** The three control records and design/plan pair.
55
+
56
+**Interfaces:** Repository acceptance policy and PR template.
57
+
58
+- [x] Correct the obsolete PR #21 status using verified remote merge evidence; record this new candidate separately as unaccepted.
59
+- [x] Record exact changed paths, tests, risks, rollback and remaining Peyvast/mapping work; append the project log.
60
+- [x] Run isolated migration upgrade/downgrade, compile and `git diff --check`; expected success and no protected-path diff.
61
+- [x] Obtain independent whole-branch review and resolve material findings with regressions.
62
+- [ ] Publish a dedicated remote branch and focused Draft PR; verify final-head GitHub Actions and record its real URL. Do not self-merge.
docs/superpowers/specs/2026-10-23-year-isolation-design.md
new
+33
@@ -0,0 +1,33 @@
1
+# Fiscal-year ownership and note-reference safety
2
+
3
+## Intent
4
+
5
+Prevent persisted accounting records from leaving an Approved or Locked fiscal year, and enforce statement-to-note year isolation for both ORM relationships and direct foreign-key assignments. These are reproducible gaps in accepted `source-data-cleanup@7dc864fd032f0c4ae4d650d89304a01286a6d914`.
6
+
7
+The owner authorized continuing the proposed safety-first work before database-connector and mapping expansion. This focused change implements only that safety prerequisite.
8
+
9
+## Behavior
10
+
11
+- Validate both persisted original ownership and proposed ownership before flushing modifications or deletions of year-owned records, note rows, and statement lines.
12
+- Protect Approved and Locked years; preserve ordinary Draft-year edits and valid same-year references.
13
+- Resolve changed foreign keys without trusting a cached old relationship. Resolve relationship assignments before SQLAlchemy synchronizes their foreign keys.
14
+- Reject a statement line referencing a note from another fiscal year, including cross-company years. Permit a statement line with no target note.
15
+- Reject conflicting simultaneous relationship/foreign-key assignments instead of validating one identity and persisting another.
16
+- A rejected transaction must leave the stored original row and relationships unchanged after rollback and reload.
17
+
18
+## Approach
19
+
20
+Use the existing `Session.before_flush` invariant hook, query original ownership by persisted identity, and resolve proposed relationships from attribute change history. Checking only current `year_id` misses removal from a protected year. Database triggers or composite-key schema changes would require a separate migration and broader provider-specific review; they are not introduced here.
21
+
22
+## Constraints
23
+
24
+- Exact base: `7dc864fd032f0c4ae4d650d89304a01286a6d914`; branch `source-data-cleanup`.
25
+- No dependency, workflow, migration, canonical XLSX/PDF, `data/`, persisted database, financial-source value, binary or release change.
26
+- No recovery from closed PR #7 and no acceptance or merge of other draft PRs.
27
+- Application scope: `backend/src/aram_backend/models.py` and `backend/tests/test_models.py`.
28
+- Control records: `PROJECT_STATUS.md`, `docs/PROJECT_LOG.md`, `docs/handoff/LATEST_HANDOFF.md`, and this design/plan pair.
29
+- No raw SQL/bulk-write authorization API is added. The hook's existing ORM boundary remains explicit.
30
+
31
+## Acceptance
32
+
33
+Regressions fail on the accepted base and pass with the fix; all existing tests pass; isolated SQLite Alembic upgrade/downgrade and compilation succeed. An independent reviewer inspects the complete remote candidate. The implementation is published as a focused Draft PR and is not self-merged.