Skip to content

feat(reconciliation): add maker-checker exception resolution command - #47

Open
seonghobae wants to merge 333 commits into
fix/reconciliation-multi-match-conservationfrom
feat/reconciliation-exception-resolution-command
Open

feat(reconciliation): add maker-checker exception resolution command#47
seonghobae wants to merge 333 commits into
fix/reconciliation-multi-match-conservationfrom
feat/reconciliation-exception-resolution-command

Conversation

@seonghobae

@seonghobae seonghobae commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

Buyer outcome

Add immutable maker-checker reconciliation-exception resolution while preserving PostgreSQL-owned reconciliation authority. Resolution binds retained review evidence, strict incoming-command identity, reviewer separation, valid/system-time causality, terminal status and matching transactional-outbox authority. It cannot post/reverse journals, close periods, alter accounting policy, or write Billing-owned truth.

Exact current state — 2026-09-08

Review RED and causal repair

Fresh review on predecessor 6f8749c569a60fbd9777b630f53d63df37a12937 found one P1 in migration 0029: a backend could commit a canonical lease, release the session advisory hold directly while leaving the lease row, establish REPEATABLE READ snapshot S0, let another backend commit a new reconciliation exception, then reacquire both session and transaction advisory locks directly. The old lease could still appear valid and did not prove continuity across the eligibility-changing commit.

This was an accounting-authority defect, not a test-only issue. TDD repair remained ordinary/non-force:

  1. 4e30115391c1fe05b32d5e115302c22976058bb8 — real PostgreSQL RED reproducing canonical lease commit → raw session unlock → S0 pin → late exception commit → raw session+xact reacquire, requiring SQLSTATE 40001 plus reconciliation_lifecycle_fresh_transaction_required.
  2. 24c8ca349df06aad1da10370d4302e18359f168f — migration 0029 transactionally invalidates tenant/run session leases after successful candidate/match/statement-allocation/journal-allocation/approval/exception mutations. The transition guard locks the exact lease row with SELECT ... FOR UPDATE; a post-S0 invalidation therefore becomes PostgreSQL serialization failure and fails closed as the typed freshness error. No caller GUC, timestamp heuristic, RLS weakening, lock-gate weakening or accounting-truth relaxation was added.
  3. 55c0d65f5ba06a152d2957656b5364fb1590f7a1 and current 263e4ff... — ADR 0066 and direct-session-lock doctoring evidence are code-current, including actual 0029/0030 migration numbers and the lease-continuity invariant.

The lease remains ephemeral coordination evidence. It is not journal, posting, exception-decision, financial-control, or Billing truth. FORCE RLS remains in place, PUBLIC helper execution remains revoked, and issue #44 remains the future purpose-limited database-capability owner.

Exact-head GREEN evidence

Accounting Foundation 34237450022 is terminal GREEN on unchanged exact 263e4ffb79607dccee715686d0aa451981c2eeb8.

  • Accounting 102098735789: 1,315 real-PostgreSQL tests / 0 failures / 0 errors; complete owned production coverage 6,211/6,211 statements and 2,330/2,330 branches; strict denominator enforcement, repository contracts, compile/import, reproducible wheel/evidence and package stages all GREEN.
  • Security 102098735619: GREEN.
  • SAST 102098735914: GREEN.
  • Dependency diff 102098735946: GREEN.
  • Integrated-head attestations 102104813344: skipped because this stacked head is not yet protected integration evidence; the skip is not promoted to GREEN.

Retained exact-head artifacts:

  • behavior 10061043416, sha256:efd4e6f904d9c82796e7e361b28be5335dd2c15c5f6d19e949bd4559a1f24e09;
  • coverage 10061189106, sha256:c33ae1a32bf3e2a8c28431fac05c9732c94848853b0f82c714950b02ad32ac81;
  • package/evidence 10061193521, sha256:2bfd05395fccaf1a6404ac247baff1e15f50f05c19067dfcce10224fe4992de7;
  • dependency diff 10060933382, sha256:6ba6073d9480c9983674b6d621ddad59e55761717f15617cac7cdbaadda0751f.

The exact P1 attack regression passed in the hosted PostgreSQL behavior suite, so its review thread is resolved on evidence rather than source inspection alone. Fresh CodeRabbit review comment 5586974629 then inspected exact 263e4ff... and reported no current-head actionable defect in migration-0029 lease invalidation/freshness, lifecycle authority, maker-checker, retained-evidence, strict source identity, FORCE RLS and outbox boundaries. That review explicitly states that it is not an approval.

Review / merge boundary

No qualifying independent APPROVED review is established by the CodeRabbit comment. Parent #29 also retains its separate central CodeQL publication/approval gate. Keep #47 unmerged until applicable review protection is satisfied; only then integrate normally and derive #53's new parent exact head before non-force restack.

No self-approval, bypass, force-push, destructive rebase, coverage exclusion, synthetic status, no-op queue churn, normal merge, tag or release before the applicable gates are satisfied.

@coderabbitai

coderabbitai Bot commented Sep 1, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

조정 예외 해결 명령과 retained evidence 검증을 추가했습니다. PostgreSQL이 명령·상태·outbox의 원자성과 불변성을 보장합니다. 런 최종화는 해결 명령과 일관된 REPEATABLE READ 스냅샷을 사용합니다. 마이그레이션 설치, 공개 API, 운영 문서 및 회귀 테스트를 갱신했습니다.

Changes

조정 예외 해결 권한

Layer / File(s) Summary
데이터베이스 해결 권한
database/migrations/0020_reconciliation_exception_resolution_command.sql
해결 명령 테이블, retained evidence 외래 키, SHA-256 해시, RLS, 불변성 guard, maker-checker 검증 및 command/status 원자성 검증을 추가했습니다. 런 최종화는 모든 terminal exception에 일치하는 durable command를 요구합니다.
해결 명령 API
src/accounting_information_platform/reconciliation_exception_resolution.py, src/accounting_information_platform/__init__.py, tests/test_reconciliation_exception_resolution.py, tests/test_reconciliation_exception_resolution_json_identity.py
resolve_reconciliation_exception을 공개 API로 추가했습니다. JSON payload 검증, 전체 payload hash, 멱등성 충돌, 정확한 replay, reviewer 분리, 시간 인과성, 상태 변경 및 outbox 기록을 구현했습니다.
런 최종화 동시성 및 증거
src/accounting_information_platform/reconciliation_lifecycle.py, tests/test_reconciliation_lifecycle*.py
session-level advisory lock 이후 새 REPEATABLE READ 트랜잭션을 시작하도록 lifecycle 검증을 확장했습니다. Resolution command 상태와 source snapshot 일관성을 검증하는 테스트를 추가했습니다.
마이그레이션 설치 경로
src/accounting_information_platform/migration_install.py, tests/test_migration_install_exception_resolution.py, tests/test_reconciliation_exception_resolution_review_regressions.py
foundation chain 이후 migration 0020을 실행합니다. 파일 누락과 SQL 실패를 AccountingValidationError로 전달합니다. legacy terminal exception preflight와 forced-RLS 설치 동작을 검증합니다.
설계 및 운영 계약
CHANGELOG.md, README.md, docs/ARCHITECTURE.md, docs/OPERABILITY.md, docs/adr/0062-*, docs/adr/0063-*
해결 명령의 권한 경계, 설치 순서, evidence binding, 멱등성, 동시성, outbox 및 직접 상태 변경 제한을 문서화했습니다.
동시성 및 증거 설계 기록
docs/adr/0060-*, docs/doctoring/*, docs/doctoring/REFERENCES.md, docs/doctoring/STANDARD_TRACEABILITY.md
lock-before-snapshot 모델, retained evidence 권한, strict JSON identity 및 검증 추적성을 기록했습니다.

Estimated code review effort: 5 (Critical) | ~120 minutes

Merge Risk: 🟠 High · up to c9740

This PR adds a privileged command that can terminally resolve reconciliation exceptions, enable run finalization, and emit accounting events. At the current head, command identity and reviewer authority are not independently bound by the database, matching outbox emission is not enforced, and strict-JSON collisions plus migration preflight gaps create additional merge-readiness risk. Do not merge until these issues and the required exact-head checks are resolved.

Sequence Diagram(s)

sequenceDiagram
  participant Reviewer
  participant resolve_reconciliation_exception
  participant PostgreSQL
  participant Outbox
  Reviewer->>resolve_reconciliation_exception: resolve_exception payload 제출
  resolve_reconciliation_exception->>PostgreSQL: payload hash와 입력 검증
  resolve_reconciliation_exception->>PostgreSQL: lifecycle lock 및 retained evidence 조회
  PostgreSQL-->>resolve_reconciliation_exception: 명령 권한 승인
  resolve_reconciliation_exception->>PostgreSQL: resolution command와 exception 상태 기록
  resolve_reconciliation_exception->>Outbox: 일치하는 resolution event 기록
  resolve_reconciliation_exception-->>Reviewer: 불변 resolution receipt 반환
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 87.30% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 126 functions across 14 files. (13 skipped:…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 제목은 불변 maker-checker 조정 예외 해결 명령을 추가하는 PR의 핵심 변경을 정확하고 간결하게 설명합니다.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/reconciliation-exception-resolution-command

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

Please review exact current head 5a332e59ea4f6e527880eb7e032ed15a13877b66 against exact stacked base 48a1857449303e754a928b98828d114ce7ca1669, with focus on PostgreSQL command/status atomicity, maker-checker authority, shared idempotency identity, tenant/run/exception scope, lifecycle-lock ordering, terminal evidence immutability, and exact replay.

Copy link
Copy Markdown
Contributor Author

@codex review

Please independently review exact current head 5a332e59ea4f6e527880eb7e032ed15a13877b66 against exact stacked base 48a1857449303e754a928b98828d114ce7ca1669. Treat predecessor findings/evidence as stale. Prioritize accounting authority, PostgreSQL atomicity/concurrency, maker-checker separation, idempotency/replay, tenant isolation, immutable exception evidence, migration safety, and any false-green test or package/doc gap.

@coderabbitai

coderabbitai Bot commented Sep 1, 2026

Copy link
Copy Markdown
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

base='48a1857449303e754a928b98828d114ce7ca1669'
head='5a332e59ea4f6e527880eb7e032ed15a13877b66'

git cat-file -e "${base}^{commit}"
git cat-file -e "${head}^{commit}"
git merge-base --is-ancestor "$base" "$head"
printf '\n== Exact range ==\n'
git diff --stat "$base" "$head"
printf '\n== Changed files ==\n'
git diff --name-status "$base" "$head"

printf '\n== Relevant file candidates ==\n'
fd -t f . | rg '(0020_reconciliation_exception_resolution_command\.sql|reconciliation.*(test|spec)|.*reconciliation.*\.(sql|ts|js|py|go)$|ADR.*0062|0062.*)'

printf '\n== Migration outline/content ==\n'
migration="$(fd -t f '^0020_reconciliation_exception_resolution_command\.sql$' | head -n1 || true)"
if [ -n "$migration" ]; then
  nl -ba "$migration"
fi

printf '\n== Exact diff: SQL and reconciliation files ==\n'
git diff --find-renames --find-copies --unified=80 "$base" "$head" -- \
  ':(glob)**/*reconciliation*' \
  ':(glob)**/0020_reconciliation_exception_resolution_command.sql' \
  ':(glob)**/*0062*'

Length of output: 7734


🏁 Script executed:

#!/bin/bash
set -euo pipefail

base='48a1857449303e754a928b98828d114ce7ca1669'
head='5a332e59ea4f6e527880eb7e032ed15a13877b66'

number() { awk '{printf "%6d  %s\n", NR, $0}'; }

printf '\n== 0020 migration ==\n'
git show "${head}:database/migrations/0020_reconciliation_exception_resolution_command.sql" | number

printf '\n== Parent migration: exception evidence (0013) ==\n'
git show "${head}:database/migrations/0013_reconciliation_run_exception_evidence.sql" | \
  rg -n -C5 'reconciliation_exception|resolution_status|CREATE.*FUNCTION|CREATE.*TRIGGER|POLICY|GRANT|RLS|outbox'

printf '\n== Parent migration: lock order (0017) ==\n'
git show "${head}:database/migrations/0017_reconciliation_approval_lock_order.sql" | \
  rg -n -C5 'FUNCTION|LOCK|reconciliation_run|exception|transition|FOR UPDATE'

printf '\n== Parent migration: command evidence (0019) ==\n'
git show "${head}:database/migrations/0019_reconciliation_run_command_evidence.sql" | \
  rg -n -C6 'command|idempot|FUNCTION|outbox|RLS|GRANT|POLICY|reconciliation_run'

printf '\n== Python module outlines ==\n'
ast-grep outline src/accounting_information_platform/reconciliation_exception_resolution.py --items all
ast-grep outline src/accounting_information_platform/reconciliation_lifecycle.py --items all

printf '\n== Changed Python implementations ==\n'
git diff --unified=100 "$base" "$head" -- \
  src/accounting_information_platform/reconciliation_exception_resolution.py \
  src/accounting_information_platform/reconciliation_lifecycle.py \
  src/accounting_information_platform/migration_install.py \
  src/accounting_information_platform/__init__.py

printf '\n== Focused PostgreSQL tests ==\n'
git show "${head}:tests/test_reconciliation_exception_resolution_postgres.py" | number

printf '\n== Unit resolution and lifecycle test diffs ==\n'
git diff --unified=80 "$base" "$head" -- \
  tests/test_reconciliation_exception_resolution.py \
  tests/test_reconciliation_lifecycle.py \
  tests/test_migration_install_exception_resolution.py

Length of output: 189828


🏁 Script executed:

#!/bin/bash
set -euo pipefail

head='5a332e59ea4f6e527880eb7e032ed15a13877b66'

printf '\n== Persistence session and migration loader ==\n'
ast-grep outline src/accounting_information_platform/persistence.py --items all --match 'PostgresPostingLedger|apply_foundation_migration'
rg -n -C8 'def _session\b|def apply_foundation_migration\b|class PostgresPostingLedger\b|def _acquire_command_lock\b' \
  src/accounting_information_platform/persistence.py

printf '\n== Outbox schema, uniqueness, RLS, and triggers ==\n'
rg -n -C8 'CREATE TABLE accounting_integration\.outbox_event|outbox_event|outbox.*guard|FORCE ROW LEVEL SECURITY|REVOKE ALL' \
  database/migrations

printf '\n== All 0020 references and PostgreSQL lifecycle acceptance ==\n'
rg -n -C6 'exception_resolution|resolution_command|atomic_pair|reconciliation_exception_resolved|resolution_status_code' \
  tests src/accounting_information_platform database/migrations/0020_reconciliation_exception_resolution_command.sql

printf '\n== Reconciliation lifecycle PostgreSQL test outline and relevant blocks ==\n'
ast-grep outline tests/test_reconciliation_lifecycle_postgres.py --items all
rg -n -C12 'exception|reconcile_reconciliation_run|outbox|raw|status|snapshot|command' \
  tests/test_reconciliation_lifecycle_postgres.py

printf '\n== Migration 0020 trigger definitions and trigger ordering ==\n'
git show "${head}:database/migrations/0020_reconciliation_exception_resolution_command.sql" | \
  rg -n -C4 'CREATE (CONSTRAINT )?TRIGGER|CREATE OR REPLACE FUNCTION|outbox_event|snapshot_hash|resolution.*pair'

printf '\n== Git diff check for outbox enforcement added in exact range ==\n'
git diff --unified=25 \
  '48a1857449303e754a928b98828d114ce7ca1669' "$head" -- \
  ':(glob)database/migrations/**/*.sql' \
  ':(glob)tests/**/*postgres*.py'

Length of output: 232789


@seonghobae I reviewed exact head 5a332e59ea4f6e527880eb7e032ed15a13877b66 against exact base 48a1857449303e754a928b98828d114ce7ca1669.

I found two database-authority gaps.

  1. The resolution command/status pair can commit without its required outbox event.
    database/migrations/0020_reconciliation_exception_resolution_command.sql defines a deferred pair guard at Line 305 through Line 332. The guard checks only resolution_status_code. It does not check accounting_integration.outbox_event.
    resolve_reconciliation_exception() writes the event in the same application transaction, but a privileged SQL caller can insert a valid command, update the matching exception status, and commit without an outbox event. This produces terminal authority without the required accounting event.

    Add a deferred commit-time guard that requires exactly one matching event. The guard should validate the event type, exception aggregate reference, resolution-command payload reference, and database-derived command hash. Add a real PostgreSQL regression for the valid command/status transaction with the outbox insert omitted.

  2. The database does not bind resolution-command state into the lifecycle snapshot.
    The revised accounting_core.assign_reconciliation_run_transition_hash() checks that each terminal exception has a matching command at Line 379 through Line 398. However, at Line 449 it accepts NEW.reconciliation_snapshot_hash as opaque input.
    Python includes ordered resolution-command state in _transition_snapshot_hash(), but PostgreSQL does not recompute or validate this value. A privileged caller can therefore insert a lifecycle command with arbitrary reconciliation_snapshot_hash, satisfy the command/status guards, and commit a database-derived transition-command hash that commits to the arbitrary snapshot.

    Derive or validate the transition snapshot in PostgreSQL from the ordered exception and resolution-command state. Add a real PostgreSQL regression that attempts finalization with a stale or fabricated snapshot hash after a valid exception resolution.

The command/status atomicity, maker-checker identity check, tenant/run/exception foreign-key scope, shared idempotency registry, lifecycle locking, and terminal evidence immutability are otherwise implemented consistently in the reviewed range.

⚠️ Action not completed

Head commit changed.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5a332e59ea

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread database/migrations/0020_reconciliation_exception_resolution_command.sql Outdated
Comment thread tests/test_reconciliation_exception_resolution_postgres.py Outdated

Copy link
Copy Markdown
Contributor Author

@codex review

Please review exact head abf9fa801f8fbe152ad07a694af6af95aa270383 against exact parent 48a1857449303e754a928b98828d114ce7ca1669. Focus on PostgreSQL maker-checker authority, complete incoming-command idempotency identity, legacy terminal-row migration safety, exception evidence immutability from creation, REPEATABLE READ/advisory-lock retry semantics, shared migration installation, atomic command/status/outbox behavior, tenant isolation, and whether any reconciliation evidence can accidentally acquire journal-posting/period-close/accounting-policy authority. Treat queued/absent/predecessor checks as non-passing.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

Copy link
Copy Markdown
Contributor Author

Exact-head refresh after current review repairs: 7900d86df013142044f36482c35b2fdac9c20ab4 remains Draft/mergeable on #43. The release/install documentation finding is now source-addressed as well: CHANGELOG.md records migration 0020, while README and standards traceability were already updated. The CHANGELOG patch is a single additive Unreleased entry; prior history is unchanged. All six currently fetched inline review findings are resolved on this source lineage. Resolution is not approval and predecessor evidence is not transferred. Exact-head Accounting Foundation CI run 33571148244 is queued/non-passing, so no ready/merge/release claim is made.

Copy link
Copy Markdown
Contributor Author

Additional exact-head self-review found and repaired a migration authority defect after the prior review set: migration 0013 already FORCEs RLS on reconciliation_exception, so the 0020 all-tenant legacy-terminal preflight could be tenant-filtered for a non-BYPASSRLS migration owner and falsely observe no terminal history. RED 678042b832e94e751fd9740d64f848774a91d182 requires explicit upgrade visibility. GREEN e826e725fbcbeacf0d041f6b3c87092e846329fe creates a FOR SELECT TO current_user USING (true) policy only inside the migration transaction, runs the legacy-history preflight, then drops that policy before changing durable command authority; any preflight exception rolls the temporary policy back with the migration. ADR 0062 was updated at c104d1a35c75309bd4c78ac7d1a32a37c05e46d7 to record the forced-RLS upgrade boundary and required non-BYPASSRLS acceptance evidence. Exact-head Accounting Foundation CI run 33571672616 is queued/non-passing. Please review the new exact head; no predecessor evidence, ready, merge, or release claim is made.

Copy link
Copy Markdown
Contributor Author

@codex review

Please review exact current head c104d1a35c75309bd4c78ac7d1a32a37c05e46d7 only. Re-check the maker-checker exception-resolution authority boundary, migration 0020 forced-RLS upgrade preflight, shared reconciliation idempotency race, transaction-level serialization retry, terminal status/command atomicity, and exact replay/source-payload identity. Do not transfer findings or approvals from predecessor heads.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@seonghobae seonghobae left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Current-head blocker at f75d221e00535ffa82cd67a53f75402f8f79c726: this commit changes the authority-bearing lifecycle transaction from PostgreSQL REPEATABLE READ to READ COMMITTED, but the exact current test still requires SET TRANSACTION ISOLATION LEVEL REPEATABLE READ and ADR 0060 still defines one coherent authority snapshot under that isolation level. The queued exact-head Foundation run must therefore not be treated as expected GREEN.

This is not only documentation drift. Under READ COMMITTED, _load_review_control_state(), exception-command reads, _database_owned_close_projection_evidence(), opening-command reads, transition insert, status update, and outbox publication can observe different statement snapshots. The run lifecycle advisory lock serializes the reconciliation review mutations that actually acquire it, but current evidence does not prove every source-population mutation used by the bridge—bank-statement facts and posted cash-journal facts included—shares that lock. Merely changing the assertion and ADR to say READ COMMITTED would weaken the one-snapshot accounting contract.

Add a real PostgreSQL barrier regression before the next repair. One connection must wait for the lifecycle lock while another commits relevant authority evidence, and a second case must attempt a source-population mutation between the lifecycle reader's sequential authority queries. Prove either that every contributing mutation is serialized on the same lock, or that the lifecycle command acquires a session-level/application lock before opening a fresh REPEATABLE READ transaction (or derives the complete authority snapshot in an equivalent single-snapshot boundary). The accepted GREEN must preserve exact replay, atomic transition/status/outbox, database-owned populations, and one coherent source/review snapshot. Update ADR 0060, doctoring, and unit contracts only after the real PostgreSQL concurrency proof agrees with the implementation.

@seonghobae seonghobae left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Current-head follow-up at 9721f6d66496efbcc34e0d7f9fb33eb20dcb6657: the new real-PostgreSQL test materially addresses the first half of the prior finding. It uses two connections/threads and PostgreSQL blocking evidence to prove that a finalizer waiting on the run lifecycle lock evaluates an exception resolution committed by the preceding lock holder. ADR 0060 and the concurrency doctoring now consistently describe READ COMMITTED post-wait visibility.

One accounting-consistency acceptance criterion remains unproven. The test patches _database_owned_close_projection_evidence() with a fixed in-memory bridge, so it cannot detect a bank-statement or posted cash-journal source mutation between the lifecycle command's sequential PostgreSQL authority reads. READ COMMITTED still permits a new statement snapshot per query. The current contract assumes every authority-bearing source mutation contributing to the bridge uses the same lifecycle lock, but this head has not demonstrated that for statement and journal source populations.

Keep Draft and add one real PostgreSQL barrier regression that does not mock the close-projection helper: hold or attempt a statement-entry or posted-cash-journal mutation after the finalizer owns the lifecycle lock but before its later population query, and prove the finalizer cannot produce a transition from a mixed source/review snapshot. If those source writers do not share the lifecycle lock, preserve the post-wait visibility fix through a two-phase boundary such as acquiring a session/application lock before opening a fresh REPEATABLE READ transaction, or an equivalent single-snapshot derivation. Do not weaken the source-population authority contract to match READ COMMITTED without that proof.

@seonghobae seonghobae left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Current-head documentation/contract blocker at 647ebf6a96749783af2b6fdca6959f7742327d9f: production now acquires a session advisory lock before opening a fresh REPEATABLE READ authority transaction, and the unit double now asserts that protocol. The real PostgreSQL mixed-source regression added at c01fe177... is the correct RED for the former READ COMMITTED split-snapshot defect.

ADR 0060 is still materially stale, however. It repeatedly declares READ COMMITTED to be the final authority-bearing model, states every later query intentionally receives a fresh snapshot, lists READ COMMITTED as the database concurrency invariant, and asks acceptance tests to require READ COMMITTED. Those statements now contradict the code and would teach an operator/reviewer to reintroduce the defect that f666135... fixes.

Update ADR 0060 and all lifecycle concurrency doctoring/traceability to the exact two-phase protocol: acquire tenant/run-scoped session advisory lock outside the authority transaction, commit the lock-acquisition transaction without releasing the session lock, open a fresh REPEATABLE READ transaction, reacquire the transaction-level lock reentrantly for database-trigger parity, derive all run/review/exception/statement/book authority from that one snapshot, commit or roll back, then release the session lock in finally. Preserve the real PostgreSQL RED and add/retain repository contracts that reject stale READ COMMITTED authority wording. Do not weaken the new coherent-snapshot implementation to make the old ADR pass. Revalidate PostgreSQL, exact 100% owned statement/branch coverage, docs/contracts, package/SBOM/provenance and security on the successor exact head before resolving.

@seonghobae seonghobae left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Current-head verification at 2519ee2d3ff98c8158a4c4a2c81e1805979b4412: the mixed-source snapshot P1 is source-addressed. The real PostgreSQL RED inserts statement facts after the lifecycle review read; the production repair acquires the tenant/run session advisory lock before opening a fresh REPEATABLE READ authority transaction; the transaction-level lock is reacquired for trigger parity; unit contracts verify commit/rollback/unlock ordering; ADR 0060 and concurrency doctoring now describe the same two-phase protocol. This preserves both post-wait visibility and one coherent run/review/statement/book snapshot.

Do not resolve or promote this finding from source inspection alone. Exact-head Accounting Foundation CI 33574848277 is queued, so PostgreSQL behavior, exact 100% owned statement/branch coverage, public-docstring/repository contracts, package/SBOM/provenance and security evidence remain non-passing. Resolve only after that unchanged SHA executes all applicable gates successfully and no current-head review finding invalidates the model.

Copy link
Copy Markdown
Contributor Author

@codex review

Please review exact head 2519ee2d3ff98c8158a4c4a2c81e1805979b4412 against live parent #43@48a1857449303e754a928b98828d114ce7ca1669. Focus on the reconciliation lifecycle concurrency repair: session advisory lock acquired and committed before a fresh REPEATABLE READ authority transaction, reentrant transaction lifecycle lock, single-snapshot review/bank/book evidence, exception maker-checker authority, exact replay provenance, transition/status/outbox atomicity, and whether the two real PostgreSQL concurrency regressions are realistic rather than vacuous. Do not transfer findings or approvals from predecessor heads.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

Copy link
Copy Markdown
Contributor Author

Current exact head is d50d9c1c10696db66a1261922dcb804a9f76d2a2 (tree 9e51ca9a3d7bac7479538b02f814a3ac86a74dd6) against parent #43@48a1857449303e754a928b98828d114ce7ca1669.

New RED→repair boundary: migration 0020 now makes resolution-command recorded_at database-owned by overwriting it with clock_timestamp() in the BEFORE INSERT authority trigger, then rejects effective_at > recorded_at. Real-PostgreSQL regressions cover (1) a future-effective public resolution command and (2) a direct-SQL attempt that supplies a forged future recorded_at; both require no terminal exception state, no resolution-command evidence, and no outbox side effect. ADR 0062 now records the valid/system-time contract and the separate scheduling-command requirement for any future activation semantics.

Exact-head Accounting Foundation 33576063371 and the exact SAST/security/dependency checks are still queued/non-passing. No predecessor evidence is transferable and there is no qualifying independent approval.

@codex review this exact head against the live parent. Please verify specifically that the database-owned recording-time guard cannot be bypassed through direct SQL, that the future-effective rejection is compatible with immediate terminal-state semantics, and that no accounting posting/period-close/policy authority was broadened.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

Copy link
Copy Markdown
Contributor Author

@codex review

Review exact head d50d9c1c10696db66a1261922dcb804a9f76d2a2 only. Verify the maker-checker exception-resolution authority, database-owned valid/system time, two-phase session-lock + fresh REPEATABLE READ lifecycle snapshot, idempotency/concurrency, atomic outbox evidence, migration 0020 upgrade/RLS behavior, and no posting/period-close/policy authority. Treat predecessor findings/evidence as stale.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

Please review exact current head 61bb7317f1839b37b25ce83e8bc9c21ae8b90e5f against exact stacked base #43@48a1857449303e754a928b98828d114ce7ca1669. Focus on RFC 8259 strict source-payload identity (NaN/Infinity/-Infinity fail-closed before persistence), unchanged finite canonical hash behavior, maker-checker authority, two-phase lifecycle serialization, database-owned valid/system time, migration 0020 upgrade/RLS behavior, atomic outbox evidence, and absence of posting/period-close/policy authority. Treat predecessor-head review/check evidence as stale.

@coderabbitai

coderabbitai Bot commented Sep 2, 2026

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

base='48a1857449303e754a928b98828d114ce7ca1669'
head='61bb7317f1839b37b25ce83e8bc9c21ae8b90e5f'

git cat-file -e "${base}^{commit}"
git cat-file -e "${head}^{commit}"
git merge-base --is-ancestor "$base" "$head"

printf '\n== Exact changed files ==\n'
git diff --name-status "$base" "$head"

printf '\n== Relevant file inventory ==\n'
fd -t f . | rg -i '(reconciliation|0020.*resolution|0060|0062|migration_install|outbox|lifecycle)'

printf '\n== Source and test outlines ==\n'
for f in \
  src/accounting_information_platform/reconciliation_exception_resolution.py \
  src/accounting_information_platform/reconciliation_lifecycle.py \
  tests/test_reconciliation_exception_resolution.py \
  tests/test_reconciliation_exception_resolution_postgres.py \
  tests/test_reconciliation_lifecycle_postgres.py
do
  if [ -f "$f" ]; then
    echo "--- $f"
    ast-grep outline "$f" --items all
  fi
done

printf '\n== Exact diff: reconciliation implementation, migrations, and tests ==\n'
git diff --find-renames --unified=50 "$base" "$head" -- \
  ':(glob)src/accounting_information_platform/*reconciliation*' \
  ':(glob)database/migrations/*reconciliation*' \
  ':(glob)tests/*reconciliation*' \
  ':(glob)docs/**/*0060*' \
  ':(glob)docs/**/*0062*' \
  CHANGELOG.md README.md ARCHITECTURE.md OPERABILITY.md

printf '\n== Strict JSON identity definitions and uses ==\n'
rg -n -C8 --glob '*.py' \
  'def _source_payload_hash\b|json\.dumps\(|allow_nan|source_payload_hash|NaN|Infinity|-Infinity' \
  src tests

printf '\n== Migration 0020 authority objects ==\n'
migration="$(fd -t f '^0020_reconciliation_exception_resolution_command\.sql$' | head -n1 || true)"
if [ -n "$migration" ]; then
  nl -ba "$migration" | sed -n '1,620p'
fi

Length of output: 202463


🏁 Script executed:

#!/bin/bash
set -euo pipefail

base='48a1857449303e754a928b98828d114ce7ca1669'
head='61bb7317f1839b37b25ce83e8bc9c21ae8b90e5f'

printf '%s\n' '== Exact changed files =='
git diff --name-status "$base" "$head"

printf '%s\n' '== Relevant path names =='
fd -t f . | rg '(^|/)(reconciliation_exception_resolution|reconciliation_lifecycle|0020_reconciliation_exception_resolution_command|0060|0062)'

printf '%s\n' '== Strict JSON change only =='
git diff --unified=35 "$base" "$head" -- \
  src/accounting_information_platform/reconciliation_exception_resolution.py \
  tests/test_reconciliation_exception_resolution.py \
  tests/test_reconciliation_exception_resolution_postgres.py

printf '%s\n' '== Resolution module: hash and transaction code =='
rg -n -C18 --glob 'reconciliation_exception_resolution.py' \
  'def _source_payload_hash\b|allow_nan|def resolve_reconciliation_exception\b|BEGIN|REPEATABLE|pg_advisory|outbox|recorded_at|effective_at|replay|Idempotency' \
  src/accounting_information_platform

printf '%s\n' '== Lifecycle module: locking and snapshot code =='
rg -n -C18 --glob 'reconciliation_lifecycle.py' \
  'def reconcile_reconciliation_run\b|REPEATABLE|pg_advisory|advisory|BEGIN|transaction|snapshot|retry|40001|finally|lock' \
  src/accounting_information_platform

printf '%s\n' '== Migration 0020: authority, guards, RLS, outbox =='
sed -n '1,620p' database/migrations/0020_reconciliation_exception_resolution_command.sql | \
  grep -nE -C 10 \
  'CREATE (OR REPLACE )?FUNCTION|CREATE (CONSTRAINT )?TRIGGER|resolution_command|outbox_event|recorded_at|effective_at|ROW LEVEL|FORCE ROW|POLICY|GRANT|REVOKE|legacy|preflight|snapshot|status'

printf '%s\n' '== Focused strict JSON and PostgreSQL test definitions =='
rg -n -C12 \
  'nan|NaN|Infinity|finite|canonical|source.payload.hash|forged.*recorded|future.*effective|outbox|direct.SQL|REPEATABLE|advisory|later.*statement|maker|replay' \
  tests/test_reconciliation_exception_resolution.py \
  tests/test_reconciliation_exception_resolution_postgres.py \
  tests/test_reconciliation_lifecycle_postgres.py

printf '%s\n' '== New migration installation references =='
rg -n -C6 '0020_reconciliation_exception_resolution_command|apply_foundation_migration|MIGRATION' \
  src/accounting_information_platform tests/test_migration_install_exception_resolution.py

Length of output: 202867


🏁 Script executed:

#!/bin/bash
set -euo pipefail

base='48a1857449303e754a928b98828d114ce7ca1669'
head='61bb7317f1839b37b25ce83e8bc9c21ae8b90e5f'

printf '%s\n' '== Exact range summary =='
git diff --stat "$base" "$head"
git diff --name-status "$base" "$head"

printf '%s\n' '== Migration 0020 remainder =='
sed -n '460,760p' database/migrations/0020_reconciliation_exception_resolution_command.sql

printf '%s\n' '== All outbox constraints or triggers in migration chain =='
rg -n -C8 \
  'outbox.*(guard|pair|atomic|required)|outbox_event.*(guard|trigger)|reconciliation_exception_resolved|reconciliation_exception_superseded' \
  database/migrations

printf '%s\n' '== All transition snapshot validation code =='
rg -n -C10 \
  'reconciliation_snapshot_hash|assign_reconciliation_run_transition_hash|transition_snapshot' \
  database/migrations src/accounting_information_platform/reconciliation_lifecycle.py \
  tests/test_reconciliation_lifecycle_postgres.py

printf '%s\n' '== Strict JSON regression bodies =='
rg -n -A35 -B5 \
  'NaN|Infinity|non.finite|finite.*(hash|canonical)|canonical.*(hash|finite)|JSON.compatible' \
  tests/test_reconciliation_exception_resolution.py \
  tests/test_reconciliation_exception_resolution_postgres.py

printf '%s\n' '== Resolution direct-SQL and time regression bodies =='
rg -n -A45 -B5 \
  'direct.SQL|forged|future.*effective|recorded_at|atomic.*outbox|outbox.*atomic|without.*outbox' \
  tests/test_reconciliation_exception_resolution_postgres.py

printf '%s\n' '== Lifecycle concurrency regression bodies =='
rg -n -A65 -B5 \
  'post.wait|later.*statement|REPEATABLE|advisory|snapshot|concurrent|ThreadPool|Barrier' \
  tests/test_reconciliation_lifecycle_postgres.py

printf '%s\n' '== Exact strict-JSON patch =='
git diff --unified=80 "$base" "$head" -- \
  src/accounting_information_platform/reconciliation_exception_resolution.py \
  tests/test_reconciliation_exception_resolution.py \
  docs/doctoring/2026-09-02-reconciliation-command-strict-json-identity.md

Length of output: 7484


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '== Resolution authority and pair guard, with source line numbers =='
grep -n -E -A42 -B8 \
  'enforce_reconciliation_exception_resolution_authority|enforce_reconciliation_exception_resolution_pair|resolution_status_pair_guard|outbox_event' \
  database/migrations/0020_reconciliation_exception_resolution_command.sql || true

printf '%s\n' '== Lifecycle transition trigger, with source line numbers =='
grep -n -E -A140 -B8 \
  'assign_reconciliation_run_transition_hash|reconciliation_snapshot_hash|reconciliation_run_transition_command_hash' \
  database/migrations/0020_reconciliation_exception_resolution_command.sql || true

printf '%s\n' '== Dedicated strict JSON regressions =='
sed -n '1,240p' tests/test_reconciliation_exception_resolution_json_identity.py

printf '%s\n' '== Dedicated recorded-time regressions =='
sed -n '1,280p' tests/test_reconciliation_exception_resolution_future_effective_postgres.py

printf '%s\n' '== Lifecycle lock-wait regression test names and assertions =='
grep -n -E -A80 -B5 \
  '^    def test_|assert|pg_advisory|REPEATABLE|snapshot|statement|Barrier|Event' \
  tests/test_reconciliation_lifecycle_lock_wait_postgres.py || true

printf '%s\n' '== Lifecycle snapshot freshness regression test names and assertions =='
grep -n -E -A75 -B5 \
  '^    def test_|assert|REPEATABLE|snapshot|statement|Barrier|Event|later' \
  tests/test_reconciliation_lifecycle_snapshot_freshness.py || true

printf '%s\n' '== Searches for direct SQL coverage of omitted outbox and forged snapshot =='
rg -n -C4 \
  'without.*outbox|omit.*outbox|outbox.*omit|fabricat.*snapshot|stale.*snapshot|snapshot.*(forged|fabricat|stale)|INSERT INTO accounting_core\.reconciliation_run_transition_command' \
  tests/test_reconciliation_exception_resolution* tests/test_reconciliation_lifecycle* || true

printf '%s\n' '== Reconciliation modules: prohibited authority call sites =='
rg -n -C2 \
  'general_journal|journal_entry|post\(|reverse\(|fiscal_period|close_fiscal|accounting_policy|policy' \
  src/accounting_information_platform/reconciliation_exception_resolution.py \
  src/accounting_information_platform/reconciliation_lifecycle.py || true

Length of output: 45266


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '== Public resolution command admission order =='
sed -n '1,245p' src/accounting_information_platform/reconciliation_exception_resolution.py

printf '%s\n' '== Exact source-hash change with line numbers =='
git diff --unified=40 48a1857449303e754a928b98828d114ce7ca1669 61bb7317f1839b37b25ce83e8bc9c21ae8b90e5f -- \
  src/accounting_information_platform/reconciliation_exception_resolution.py | \
  grep -n -E -C8 'source_payload_hash|allow_nan|json.dumps' || true

Length of output: 18836


@seonghobae I reviewed exact head 61bb7317f1839b37b25ce83e8bc9c21ae8b90e5f against exact base 48a1857449303e754a928b98828d114ce7ca1669.

I found three authority defects.

  1. RFC 8259 command identity still accepts Python-only payload shapes.
    src/accounting_information_platform/reconciliation_exception_resolution.py uses json.dumps() with allow_nan=False at Line 345 through Line 359. This correctly rejects NaN, Infinity, and -Infinity before PostgresPostingLedger opens a database session. It also preserves finite-number serialization.

    However, Python json.dumps() accepts tuples as JSON arrays and accepts integer mapping keys as JSON object member names. Therefore, distinct public API inputs can collapse to the same source hash. For example, {"request_context": {"items": (1, 2)}} and {"request_context": {"items": [1, 2]}} have the same canonical representation. An integer key and its equivalent string key can also become the same JSON object member name.

    This violates complete incoming-command identity when callers invoke the Python API directly. Add a recursive strict-JSON validator before hashing. It must permit only null, booleans, strings, finite numbers, lists, and mappings with string keys. It must reject tuples and non-string keys. Add regressions that prove these values fail before persistence.

  2. A resolution command and terminal status can commit without the required outbox event.
    database/migrations/0020_reconciliation_exception_resolution_command.sql has the deferred reconciliation_exception_resolution_status_pair_guard at Line 336 through Line 363. The guard verifies only that the terminal status matches the resolution command.

    No trigger or deferred constraint requires an accounting_integration.outbox_event row. A privileged SQL caller can insert a valid resolution command, update the matching exception to resolved or superseded, and commit without the required reconciliation_exception_resolved or reconciliation_exception_superseded event.

    Add a deferred commit-time guard. It must require exactly one matching outbox event for each resolution command. It should bind the tenant, event type, exception aggregate reference, resolution-command payload reference, and database-derived command hash. Add a real PostgreSQL regression that omits the outbox insert from an otherwise valid command/status transaction.

  3. PostgreSQL does not validate lifecycle snapshot authority.
    accounting_core.assign_reconciliation_run_transition_hash() checks exception command/status authority at Line 410 through Line 429. At Line 469 through Line 506, it includes NEW.reconciliation_snapshot_hash in the transition-command hash as caller-provided input. It does not derive or validate that digest from the reviewed matches, exception-resolution commands, opening command, statement population, book population, and bridge state.

    The Python path derives this digest in src/accounting_information_platform/reconciliation_lifecycle.py. A privileged SQL caller can still insert a lifecycle command with a fabricated snapshot hash, satisfy the current command/status guards, and commit immutable transition evidence that binds the fabricated hash.

    Derive the lifecycle snapshot in PostgreSQL, or validate it against database-owned ordered state before assigning the transition hash. Add a real PostgreSQL regression that attempts finalization with a stale or fabricated snapshot after a valid exception resolution.

The following controls are implemented consistently in the reviewed source:

  • Non-finite numeric values fail before persistence.
  • Finite numeric serialization remains unchanged by allow_nan=False.
  • Database-owned recorded_at replaces caller input before the future-effective check.
  • The direct-SQL forged-time regression verifies rejection with no command, status, or outbox side effect.
  • The session advisory-lock protocol opens the REPEATABLE READ authority transaction after lock acquisition.
  • The lifecycle lock-wait regression verifies visibility of the preceding resolution commit.
  • Resolution maker-checker separation, tenant/run/exception scope, immutable exception evidence, and exact replay checks are present.
  • The reviewed reconciliation modules do not post or reverse journals, close periods, or change accounting policy.

The supplied exact-head Foundation CI state remains queued and non-passing.

You are interacting with an AI system.

@seonghobae seonghobae added the enhancement New feature or request label Sep 2, 2026 — with ChatGPT Codex Connector

@seonghobae seonghobae left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Exact-head review on 4527ca02ff385f3c211976fcf356124e9419c2b1: predecessor 886100a... is no longer a behavior RED. Foundation 34202632635 passed the real-PostgreSQL behavior/repository suite and complete coverage execution, then failed the strict denominator gate because retained coverage had exactly one uncovered production statement and one branch: the post-loop AssertionError after the bounded serialization-retry loop in reconciliation_exception_resolution.py. Source inspection confirms that exit is impossible: success returns, a non-40001 error re-raises, and the third 40001 failure re-raises inside the loop. The current commit removes that dead exit by expressing the same at-most-three retry policy with an explicit counter and while True; it does not add a pragma/exclusion, change the 100% denominator, weaken maker-checker/RLS/snapshot/outbox authority, or alter error translation. Current Foundation 34207629271 is still queued before runner assignment, so this COMMENT is source/RCA review only, not approval or GREEN. Keep Draft and require unchanged-head behavior + exact 100% statement/branch denominator + contracts/package/security/current independent approval before stack advancement.

@seonghobae
seonghobae marked this pull request as ready for review September 8, 2026 10:02

Copy link
Copy Markdown
Contributor Author

Exact head 4527ca02ff385f3c211976fcf356124e9419c2b1 is now unchanged-head GREEN in Accounting Foundation 34207629271: real PostgreSQL behavior/repository, strict 100% coverage denominator, repository contracts, compile/import, reproducible package evidence, security, SAST, and dependency diff all passed. All returned inline review threads are resolved. Please perform a fresh independent review of this exact head only; do not transfer predecessor conclusions. Focus on maker-checker separation, retained evidence binding, strict source-payload identity, session-lock → fresh REPEATABLE READ snapshot ordering, forced RLS, exact Decimal/population/bridge authority, and command/status/outbox atomicity/retention. @coderabbitai review
@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 8, 2026

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review Completed 2026-09-08T12:07:51.820136Z 6f8749c Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Sep 8, 2026

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

head='4527ca02ff385f3c211976fcf356124e9419c2b1'
git cat-file -e "${head}^{commit}"
git checkout --quiet "$head"

echo '== Exact commit =='
git show -s --format='commit=%H%nparents=%P%nsubject=%s' "$head"
parent="$(git rev-parse "${head}^")"
printf 'parent=%s\n' "$parent"
git diff --stat "$parent" "$head"
git diff --name-status "$parent" "$head"

echo '== Migration identity and installer =='
find database/migrations -maxdepth 1 -type f -name '*.sql' -printf '%f\n' | sort | tail -35
nl -ba src/accounting_information_platform/migration_install.py | sed -n '1,220p'

echo '== Authority source outlines =='
ast-grep outline src/accounting_information_platform/reconciliation_exception_resolution.py --items all
ast-grep outline src/accounting_information_platform/reconciliation_lifecycle.py --items all

echo '== Exact change =='
git diff --unified=100 "$parent" "$head" -- \
  src/accounting_information_platform/reconciliation_exception_resolution.py \
  tests \
  database/migrations \
  docs CHANGELOG.md README.md

echo '== Relevant migration constructs =='
for f in \
  database/migrations/0021_reconciliation_run_database_snapshot_authority.sql \
  database/migrations/0022_reconciliation_exception_resolution_command.sql \
  database/migrations/0023_reconciliation_exception_resolution_outbox_pair.sql \
  database/migrations/0024_reconciliation_authority_outbox_retention.sql \
  database/migrations/0025_reconciliation_authority_outbox_orphan_guard.sql \
  database/migrations/0026_reconciliation_control_recording_time_authority.sql \
  database/migrations/0027_reconciliation_lifecycle_recording_time_authority.sql \
  database/migrations/0028_reconciliation_lifecycle_source_payload_identity.sql \
  database/migrations/0029_reconciliation_lifecycle_session_lock_authority.sql \
  database/migrations/0030_reconciliation_lifecycle_capability_privileges.sql; do
  echo "## $f"
  rg -n -C4 'CREATE( OR REPLACE)? FUNCTION|CREATE( CONSTRAINT)? TRIGGER|FORCE ROW LEVEL SECURITY|SECURITY DEFINER|REVOKE|GRANT|outbox|source_payload_hash|snapshot|advisory|resolution|recorded_at|effective_at' "$f"
done

echo '== Focused test inventory =='
fd -t f -e py . tests | rg 'reconciliation.*(postgres|resolution|lifecycle)|migration.*(identity|install)'

Length of output: 4422


🏁 Script executed:

#!/bin/bash
set -euo pipefail

head='4527ca02ff385f3c211976fcf356124e9419c2b1'
parent='886100a5315ca41b7a8709dd7594df7b7e5b6dd7'
git checkout --quiet "$head"

echo '== Installer =='
sed -n '1,240p' src/accounting_information_platform/migration_install.py

echo '== Exact retry repair with context =='
git diff --unified=140 "$parent" "$head" -- src/accounting_information_platform/reconciliation_exception_resolution.py

echo '== Resolution implementation: JSON, retained evidence, transaction, replay, outbox =='
rg -n -C12 \
  'def _require_strict_json_value|def _source_payload_hash|def resolve_reconciliation_exception|40001|REPEATABLE READ|reconciliation_evidence|idempot|outbox|recorded_at|effective_at|INSERT INTO|UPDATE accounting_core\.reconciliation_exception' \
  src/accounting_information_platform/reconciliation_exception_resolution.py

echo '== Lifecycle implementation: session lock and snapshot data =='
rg -n -C12 \
  'def _coherent_lifecycle_session|acquire_reconciliation_lifecycle_session|release_reconciliation_lifecycle_session|REPEATABLE READ|_transition_snapshot_hash|source_payload_hash|Decimal|population|outbox|40001' \
  src/accounting_information_platform/reconciliation_lifecycle.py

echo '== Authority migration definitions and triggers =='
for f in database/migrations/0021_reconciliation_run_database_snapshot_authority.sql \
         database/migrations/0022_reconciliation_exception_resolution_command.sql \
         database/migrations/0023_reconciliation_exception_resolution_outbox_pair.sql \
         database/migrations/0024_reconciliation_authority_outbox_retention.sql \
         database/migrations/0025_reconciliation_authority_outbox_orphan_guard.sql \
         database/migrations/0028_reconciliation_lifecycle_source_payload_identity.sql \
         database/migrations/0029_reconciliation_lifecycle_session_lock_authority.sql \
         database/migrations/0030_reconciliation_lifecycle_capability_privileges.sql; do
  echo "## $f"
  grep -n -E -C 5 \
    'CREATE( OR REPLACE)? FUNCTION|CREATE( CONSTRAINT)? TRIGGER|FORCE ROW LEVEL SECURITY|SECURITY DEFINER|REVOKE|GRANT|outbox|source_payload_hash|snapshot|advisory|resolution|recorded_at|effective_at' "$f"
done

echo '== Focused tests: test names and control assertions =='
for f in \
  tests/test_reconciliation_exception_resolution.py \
  tests/test_reconciliation_exception_resolution_json_identity.py \
  tests/test_reconciliation_exception_resolution_postgres.py \
  tests/test_reconciliation_lifecycle.py \
  tests/test_reconciliation_lifecycle_postgres.py \
  tests/test_reconciliation_lifecycle_snapshot_freshness.py \
  tests/test_reconciliation_lifecycle_lock_wait_postgres.py; do
  echo "## $f"
  grep -n -E '^\s*def test_|source_payload_hash|outbox|retained|evidence|advisory|REPEATABLE|RLS|Decimal|population|retry|40001' "$f" | head -220
done

Length of output: 161718


🏁 Script executed:

#!/bin/bash
set -euo pipefail

head='4527ca02ff385f3c211976fcf356124e9419c2b1'
git checkout --quiet "$head"

echo '== Lifecycle session lease prerequisite =='
sed -n '225,340p' database/migrations/0029_reconciliation_lifecycle_session_lock_authority.sql

echo '== Lifecycle database snapshot and outbox guards =='
sed -n '602,775p' database/migrations/0021_reconciliation_run_database_snapshot_authority.sql
sed -n '107,210p' database/migrations/0023_reconciliation_exception_resolution_outbox_pair.sql

echo '== Resolution evidence, status, and RLS guard bodies =='
sed -n '148,430p' database/migrations/0022_reconciliation_exception_resolution_command.sql

echo '== Lifecycle strict JSON and authority-read sequence =='
sed -n '92,325p' src/accounting_information_platform/reconciliation_lifecycle.py
sed -n '332,390p' src/accounting_information_platform/reconciliation_lifecycle.py

echo '== PostgreSQL regression bodies for direct SQL and atomicity =='
grep -n -A75 -B5 \
  -E 'def test_database_rejects_direct_fabricated_resolution_evidence|def test_raw_terminal_status_without_resolution_command_fails|def test_named_command_resolves_exception_and_emits_atomic_outbox|def test_transition_command_cannot_commit_without_reconciled_status|def test_supported_command_persists_transition_outbox_and_freezes_review_state|def test_waiting_finalizer_observes_resolution_committed_before_snapshot' \
  tests/test_reconciliation_exception_resolution_postgres.py \
  tests/test_reconciliation_lifecycle_postgres.py \
  tests/test_reconciliation_lifecycle_lock_wait_postgres.py

echo '== Regression bodies for source identity, retention, and server-owned snapshot =='
rg -n -A55 -B5 \
  'source payload|source_payload_hash|outbox.*(omit|required|retain|orphan)|database.*(snapshot|population)|fabricated.*snapshot|direct.*outbox' \
  tests/test_reconciliation_exception_resolution_postgres.py \
  tests/test_reconciliation_lifecycle_postgres.py \
  tests/test_reconciliation_lifecycle_source_snapshot_postgres.py \
  tests/test_reconciliation_exception_resolution_review_regressions.py \
  tests/test_reconciliation_lifecycle.py

Length of output: 140094


@seonghobae I reviewed exact head 4527ca02ff385f3c211976fcf356124e9419c2b1 independently.

I found no blocking defect in the requested boundaries.

  • resolve_reconciliation_exception() now makes at most three fresh attempts for SQLSTATE 40001. It re-raises all other errors. The exact repair removes only the unreachable retry exit.
  • PostgreSQL enforces maker-checker separation, tenant/run/exception scope, database-owned recording time, retained-evidence binding, and immutable resolution evidence.
  • The resolution command stores the full strict-JSON source_payload_hash. Exact replay returns the immutable receipt. A changed payload under the same idempotency key conflicts.
  • Lifecycle transition guards require a committed session lease before the fresh REPEATABLE READ authority transaction and its transaction advisory lock.
  • PostgreSQL replaces caller-provided lifecycle snapshot and population values with database-derived values before command-hash assignment.
  • Deferred guards require exactly one matching command, terminal status, and outbox event. Retention and orphan guards prevent later deletion, mutation, duplication, or fabrication of authority-shaped outbox evidence.
  • The inspected PostgreSQL tests cover direct-SQL evidence fabrication, raw status updates, command/status/outbox atomicity, database-owned population references, replay identity, and lock-wait snapshot visibility.

I used the existing constraint context for reconciliation_evidence: its unique tenant/run/type/reference identity makes the retained-evidence lookup single-row under the canonical migration chain.

This review is not an approval. Keep the PR Draft while the required independent-review and merge-process gates are completed.


🧠 Learnings used
Learnt from: seonghobae
Repo: ContextualWisdomLab/accounting-information-platform PR: 47
File: database/migrations/0020_reconciliation_exception_resolution_command.sql:239-257
Timestamp: 2026-09-02T09:24:32.348Z
Learning: In `database/migrations/0013_reconciliation_run_exception_evidence.sql`, `accounting_core.reconciliation_evidence` has a UNIQUE constraint on `(tenant_account_id, reconciliation_run_id, evidence_type_code, evidence_reference)`. Code that queries `reconciliation_evidence` with all four columns fixed has at most one matching row under the canonical migration chain.

You are interacting with an AI system.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4527ca02ff

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread database/migrations/0022_reconciliation_exception_resolution_command.sql Outdated
@seonghobae
seonghobae marked this pull request as draft September 8, 2026 11:08

seonghobae commented Sep 8, 2026

Copy link
Copy Markdown
Contributor Author

/opencode

Continue the existing #47 single-source-writer from exact 27309ca78c59608ff2ee6dce4d5f001f10c4f875 using updated lease comment 5577651065. The hosted predecessor RED is now classified: one intended PostgreSQL failure proves the missing composite retained-evidence FK; the second was a stale static text ratchet already repaired tests-only in 27309ca.... Repair only the remaining current-head P1 in migration 0022, make tests/test_reconciliation_exception_resolution_scope_fk_postgres.py GREEN, then run the three focused PostgreSQL regressions and full Accounting Foundation on the exact successor. Preserve both migration-0029 repairs and intervening descendants. No second branch/writer, force-push, destructive rebase, gate weakening, #53 restack, or #37 baseline write.

Copy link
Copy Markdown
Contributor Author

Exact-head RCA and source repair — 2026-09-08

  • 27309ca78c59608ff2ee6dce4d5f001f10c4f875 / Foundation run 34220239265, job 102041386446 ran 1,314 tests and failed exactly one: test_resolution_evidence_foreign_key_carries_complete_scope returned no reconciliation_evidence_scope_identity (None != (4,)). SAST, security and dependency-diff jobs were GREEN.
  • The failure was a real migration contract gap, not a fixture race: migration 0022 still referenced reconciliation_evidence_id alone.
  • Commit 6f8749c569a60fbd9777b630f53d63df37a12937 adds the four-column evidence scope identity and named four-column reconciliation_exception_resolution_evidence_scope_fk; it does not change migration numbering, trigger validation, RLS, authority cardinality or other production surfaces.
  • New exact-head Checks are authoritative and must complete before readiness; no predecessor result is transferred.

@seonghobae
seonghobae marked this pull request as ready for review September 8, 2026 11:47

Copy link
Copy Markdown
Contributor Author

Exact-head successor verification is now terminal for 6f8749c569a60fbd9777b630f53d63df37a12937.

  • Foundation run 34221269652 / Accounting job 102044692804: success.
  • Complete realistic PostgreSQL suite: 1,314 tests run twice, zero failures.
  • Coverage: 6,211 statements and 2,330 branches, both 100%.
  • Compile, reproducible wheel, SBOM, source-provenance, hash-pinned install and py.typed checks: success.
  • Exact-head SAST 102044692768, security 102044692653, dependency diff 102044692542: success.
  • Integrated-head attestations were skipped because base PR fix: allow conserved multi-match reconciliation approvals #29 is still open; this is not treated as passing.

The PR remains Draft and is not merged: current review disposition, central applicable checks, independent approval, and ordinary integration into #29 remain required.

Copy link
Copy Markdown
Contributor Author

@codex review
@coderabbitai review

Please review exact head 6f8749c569a60fbd9777b630f53d63df37a12937 against base 12e1a4bb9d8de5e4b6c72e2893107b07c515416b. Focus on the three repaired P1 authority boundaries (stacked session-lock admission, lifecycle-session-lease FORCE RLS, retained-evidence composite tenant/run/exception scope), and report only current-head actionable defects. Do not treat predecessor findings or resolved/outdated threads as current defects.

@coderabbitai

coderabbitai Bot commented Sep 8, 2026

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

base='12e1a4bb9d8de5e4b6c72e2893107b07c515416b'
head='6f8749c569a60fbd9777b630f53d63df37a12937'

git cat-file -e "${base}^{commit}"
git cat-file -e "${head}^{commit}"
git merge-base --is-ancestor "$base" "$head"
git checkout --quiet "$head"

echo '== Exact range =='
git show -s --format='head=%H%nparents=%P%nsubject=%s' "$head"
git diff --stat "$base" "$head"
git diff --name-status "$base" "$head"
git diff --unified=100 "$base" "$head" -- database/migrations/0022_reconciliation_exception_resolution_command.sql tests

echo '== Migration identities and installer =='
find database/migrations -maxdepth 1 -type f -name '*.sql' -printf '%f\n' | sort | tail -15
sed -n '1,180p' src/accounting_information_platform/migration_install.py

echo '== Exact P1 migration definitions =='
for f in \
  database/migrations/0022_reconciliation_exception_resolution_command.sql \
  database/migrations/0023_reconciliation_exception_resolution_outbox_pair.sql \
  database/migrations/0029_reconciliation_lifecycle_session_lock_authority.sql \
  database/migrations/0030_reconciliation_lifecycle_capability_privileges.sql; do
  echo "## $f"
  nl -ba "$f" | sed -n '1,520p'
done

echo '== P1 SQL reference map =='
rg -n -C6 \
  'reconciliation_evidence_scope_identity|reconciliation_exception_resolution_evidence_scope_fk|reconciliation_lifecycle_session_lease|FORCE ROW LEVEL SECURITY|CREATE POLICY|acquire_reconciliation_lifecycle_session|release_reconciliation_lifecycle_session|SECURITY DEFINER|GRANT|REVOKE' \
  database/migrations \
  src/accounting_information_platform \
  tests

echo '== Lifecycle call sequence =='
ast-grep outline src/accounting_information_platform/reconciliation_lifecycle.py --items all
rg -n -C16 \
  '_coherent_lifecycle_session|acquire_reconciliation_lifecycle_session|release_reconciliation_lifecycle_session|REPEATABLE READ|_acquire_command_lock|commit\(' \
  src/accounting_information_platform/reconciliation_lifecycle.py

echo '== Focused PostgreSQL test implementations =='
for f in \
  tests/test_reconciliation_exception_resolution_scope_fk_postgres.py \
  tests/test_reconciliation_lifecycle_session_lease_postgres.py \
  tests/test_reconciliation_lifecycle_lock_wait_postgres.py \
  tests/test_reconciliation_exception_resolution_postgres.py; do
  if [ -f "$f" ]; then
    echo "## $f"
    ast-grep outline "$f" --items all
    rg -n -C10 \
      'scope|foreign.key|tenant|session.*lease|FORCE ROW LEVEL SECURITY|advisory|REPEATABLE READ|raw|direct|resolution|outbox' \
      "$f"
  fi
done

Length of output: 112234


🏁 Script executed:

#!/bin/bash
set -euo pipefail

base='12e1a4bb9d8de5e4b6c72e2893107b07c515416b'
head='6f8749c569a60fbd9777b630f53d63df37a12937'
git checkout --quiet "$head"

echo '== Exact migration 0022 delta only =='
git diff --unified=45 "$base" "$head" -- database/migrations/0022_reconciliation_exception_resolution_command.sql

echo '== Evidence scope key and foreign-key declarations =='
rg -n -C8 \
  'reconciliation_evidence_scope_identity|reconciliation_exception_resolution_evidence_scope_fk|FOREIGN KEY|UNIQUE' \
  database/migrations/0013_reconciliation_run_exception_evidence.sql \
  database/migrations/0022_reconciliation_exception_resolution_command.sql

echo '== Resolution command authority function and triggers =='
rg -n -A110 -B12 \
  'FUNCTION accounting_core\.(enforce_reconciliation_exception_resolution_authority|assign_reconciliation_exception_resolution_hash|reject_reconciliation_evidence_mutation)|CREATE (CONSTRAINT )?TRIGGER.*reconciliation.*resolution|FORCE ROW LEVEL SECURITY|CREATE POLICY|REVOKE|GRANT' \
  database/migrations/0022_reconciliation_exception_resolution_command.sql

echo '== Session lease implementation and RLS =='
rg -n -A120 -B12 \
  'FUNCTION accounting_core\.(acquire_reconciliation_lifecycle_session|release_reconciliation_lifecycle_session|require_reconciliation_lifecycle_session_lock)|reconciliation_lifecycle_session_lease|FORCE ROW LEVEL SECURITY|CREATE POLICY|REVOKE|GRANT|CREATE.*TRIGGER' \
  database/migrations/0029_reconciliation_lifecycle_session_lock_authority.sql \
  database/migrations/0030_reconciliation_lifecycle_capability_privileges.sql

echo '== Application lease ordering =='
sed -n '35,140p' src/accounting_information_platform/reconciliation_lifecycle.py

echo '== Focused tests =='
for f in \
  tests/test_reconciliation_exception_resolution_scope_fk_postgres.py \
  tests/test_reconciliation_lifecycle_stacked_session_admission_postgres.py \
  tests/test_reconciliation_lifecycle_session_lease_postgres.py; do
  echo "## $f"
  test -f "$f" && sed -n '1,280p' "$f" || true
done

echo '== Lease, scope, and RLS test inventory =='
rg -n \
  'def test_.*(scope|session|rls|tenant|lease|stacked)|reconciliation_evidence_scope_identity|reconciliation_exception_resolution_evidence_scope_fk|reconciliation_lifecycle_session_lock_required|FORCE ROW LEVEL SECURITY' \
  tests

Length of output: 142002


🏁 Script executed:

#!/bin/bash
set -euo pipefail

head='6f8749c569a60fbd9777b630f53d63df37a12937'
git checkout --quiet "$head"

echo '== Session lease guard tail =='
sed -n '235,380p' database/migrations/0029_reconciliation_lifecycle_session_lock_authority.sql

echo '== Capability migration =='
cat database/migrations/0030_reconciliation_lifecycle_capability_privileges.sql

echo '== Dedicated tenant-RLS regression =='
sed -n '1,260p' tests/test_reconciliation_lifecycle_session_lease_rls_postgres.py

echo '== Direct-lock and reentrancy regressions =='
sed -n '1,280p' tests/test_reconciliation_lifecycle_direct_session_lock_postgres.py
sed -n '1,220p' tests/test_reconciliation_lifecycle_session_lock_reentrancy_postgres.py

echo '== Session-lock contract and migration function privileges =='
sed -n '1,180p' tests/test_reconciliation_lifecycle_session_lock_authority_contract.py
rg -n -C5 \
  'acquire_reconciliation_lifecycle_session|release_reconciliation_lifecycle_session|proacl|has_function_privilege|GRANT EXECUTE|accounting_closing_writer|SECURITY DEFINER' \
  tests database/migrations src/accounting_information_platform

echo '== Current exact diff for P1 migrations relative to base =='
git diff --unified=25 12e1a4bb9d8de5e4b6c72e2893107b07c515416b "$head" -- \
  database/migrations/0029_reconciliation_lifecycle_session_lock_authority.sql \
  database/migrations/0030_reconciliation_lifecycle_capability_privileges.sql \
  tests/test_reconciliation_lifecycle_session_lease_rls_postgres.py \
  tests/test_reconciliation_lifecycle_direct_session_lock_postgres.py \
  tests/test_reconciliation_lifecycle_session_lock_reentrancy_postgres.py \
  tests/test_reconciliation_lifecycle_stacked_session_admission_postgres.py

Length of output: 136523


@seonghobae I reviewed exact head 6f8749c569a60fbd9777b630f53d63df37a12937 against base 12e1a4bb9d8de5e4b6c72e2893107b07c515416b.

I found no current-head actionable defect in the requested P1 boundaries.

  • Migration 0022 defines reconciliation_evidence_scope_identity on tenant, run, exception, and evidence identifiers.
  • Migration 0022 defines reconciliation_exception_resolution_evidence_scope_fk over the same four columns.
  • The retained-evidence authority query remains scoped by tenant, run, exception, type, reference, and digest.
  • Migration 0029 enables and forces RLS on accounting_core.reconciliation_lifecycle_session_lease.
  • The session-lease RLS policy has tenant-bound USING and WITH CHECK clauses.
  • Migration 0029 revokes PUBLIC execution of the SECURITY DEFINER session-lock functions. Migration 0030 reasserts these revocations.
  • The transition guard drains all same-backend session advisory-lock holds before it checks pg_locks. Therefore, stacked session locks cannot satisfy the transaction-lock proof.
  • The transition guard requires REPEATABLE READ and a lease from a different committed transaction.
  • reconcile_reconciliation_run() acquires and commits the session lease before it starts the fresh REPEATABLE READ authority transaction.
  • The inspected PostgreSQL regressions cover the composite foreign key, stacked session-lock admission, direct raw-DML rejection, lock reentrancy and release, forced RLS configuration, and denial of the helper capability to a restricted runtime.

I used the retained learning that the canonical evidence identity is unique for tenant, run, evidence type, and evidence reference. This supports the single-row retained-evidence lookup.

This review does not approve the PR.


🧠 Learnings used
Learnt from: seonghobae
Repo: ContextualWisdomLab/accounting-information-platform PR: 47
File: database/migrations/0020_reconciliation_exception_resolution_command.sql:239-257
Timestamp: 2026-09-02T09:24:32.348Z
Learning: In `database/migrations/0013_reconciliation_run_exception_evidence.sql`, `accounting_core.reconciliation_evidence` has a UNIQUE constraint on `(tenant_account_id, reconciliation_run_id, evidence_type_code, evidence_reference)`. Code that queries `reconciliation_evidence` with all four columns fixed has at most one matching row under the canonical migration chain.

You are interacting with an AI system.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6f8749c569

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@seonghobae
seonghobae marked this pull request as draft September 8, 2026 14:18
@seonghobae
seonghobae marked this pull request as ready for review September 8, 2026 14:42

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

Fresh exact-head review requested for 263e4ffb79607dccee715686d0aa451981c2eeb8 after Accounting Foundation 34237450022 terminal GREEN. Please re-check the current maker-checker exception-resolution and lifecycle-session continuity delta, especially migration 0029 lease invalidation / SELECT ... FOR UPDATE freshness behavior and whether any new accounting-authority or security finding remains. Historical predecessor reviews are not current-head evidence.

@coderabbitai

coderabbitai Bot commented Sep 8, 2026

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

head='263e4ffb79607dccee715686d0aa451981c2eeb8'
repo='ContextualWisdomLab/accounting-information-platform'

git cat-file -e "${head}^{commit}"
git checkout --quiet "$head"
parent="$(git rev-parse "${head}^")"

echo '== Exact commit and immediate delta =='
git show -s --format='head=%H%nparents=%P%nsubject=%s' "$head"
printf 'parent=%s\n' "$parent"
git diff --stat "$parent" "$head"
git diff --name-status "$parent" "$head"
git diff --unified=120 "$parent" "$head" -- \
  database/migrations/0029_reconciliation_lifecycle_session_lock_authority.sql \
  database/migrations/0030_reconciliation_lifecycle_capability_privileges.sql \
  src/accounting_information_platform/reconciliation_lifecycle.py \
  src/accounting_information_platform/reconciliation_exception_resolution.py \
  tests docs README.md CHANGELOG.md

echo '== PR state and exact checks (informational; not predecessor evidence) =='
gh pr view 47 --repo "$repo" \
  --json headRefOid,baseRefOid,state,isDraft,mergeable,statusCheckRollup \
  --jq '{headRefOid,baseRefOid,state,isDraft,mergeable,checks:[.statusCheckRollup[]|{name,status,conclusion}]}' || true

echo '== Migration 0029 and capability hardening =='
nl -ba database/migrations/0029_reconciliation_lifecycle_session_lock_authority.sql
nl -ba database/migrations/0030_reconciliation_lifecycle_capability_privileges.sql

echo '== Lifecycle authority implementation =='
ast-grep outline src/accounting_information_platform/reconciliation_lifecycle.py --items all
rg -n -C14 \
  '_coherent_lifecycle_session|acquire_reconciliation_lifecycle_session|release_reconciliation_lifecycle_session|SELECT .*FOR UPDATE|FOR UPDATE|REPEATABLE READ|advisory|lease|commit\(|rollback\(' \
  src/accounting_information_platform/reconciliation_lifecycle.py \
  database/migrations/0021_reconciliation_run_database_snapshot_authority.sql \
  database/migrations/0029_reconciliation_lifecycle_session_lock_authority.sql \
  database/migrations/0030_reconciliation_lifecycle_capability_privileges.sql

echo '== Related transition authority and RLS definitions =='
rg -n -C8 \
  'reconciliation_lifecycle_session_lock_required|require_reconciliation_lifecycle_session_lock|reconciliation_lifecycle_session_lease|FORCE ROW LEVEL SECURITY|CREATE POLICY|SECURITY DEFINER|REVOKE|GRANT|pg_locks|pg_advisory' \
  database/migrations

echo '== Focused PostgreSQL regression inventory and implementations =='
fd -t f -e py . tests | rg 'reconciliation.*(session|lease|lock|lifecycle).*postgres|reconciliation.*resolution.*postgres' | sort
for f in \
  tests/test_reconciliation_lifecycle_session_lease_postgres.py \
  tests/test_reconciliation_lifecycle_session_lease_rls_postgres.py \
  tests/test_reconciliation_lifecycle_direct_session_lock_postgres.py \
  tests/test_reconciliation_lifecycle_session_lock_reentrancy_postgres.py \
  tests/test_reconciliation_lifecycle_stacked_session_admission_postgres.py \
  tests/test_reconciliation_lifecycle_lock_wait_postgres.py \
  tests/test_reconciliation_lifecycle_snapshot_freshness.py \
  tests/test_reconciliation_exception_resolution_postgres.py; do
  if [ -f "$f" ]; then
    echo "## $f"
    ast-grep outline "$f" --items all
    rg -n -C10 \
      'def test_|FOR UPDATE|fresh|invalidate|lease|session|advisory|REPEATABLE READ|RLS|tenant|resolution|outbox|maker|checker' \
      "$f"
  fi
done

echo '== Migration numeric identity =='
find database/migrations -maxdepth 1 -type f -name '*.sql' -printf '%f\n' | sort | tail -20

Length of output: 20088


🏁 Script executed:

#!/bin/bash
set -euo pipefail

head='263e4ffb79607dccee715686d0aa451981c2eeb8'
git checkout --quiet "$head"
number() { awk '{printf "%6d  %s\n", NR, $0}'; }

echo '== Migration 0029 =='
cat database/migrations/0029_reconciliation_lifecycle_session_lock_authority.sql | number

echo '== Migration 0030 =='
cat database/migrations/0030_reconciliation_lifecycle_capability_privileges.sql | number

echo '== Lifecycle session and transition implementation =='
sed -n '1,260p' src/accounting_information_platform/reconciliation_lifecycle.py | number

echo '== Relevant transition and authority trigger definitions =='
for f in \
  database/migrations/0019_reconciliation_run_command_evidence.sql \
  database/migrations/0021_reconciliation_run_database_snapshot_authority.sql \
  database/migrations/0022_reconciliation_exception_resolution_command.sql \
  database/migrations/0023_reconciliation_exception_resolution_outbox_pair.sql \
  database/migrations/0029_reconciliation_lifecycle_session_lock_authority.sql; do
  echo "## $f"
  rg -n -C8 \
    'CREATE( OR REPLACE)? FUNCTION|CREATE( CONSTRAINT)? TRIGGER|AFTER (INSERT|UPDATE|DELETE)|FOR UPDATE|fresh_transaction|required|40001|reconciliation_lifecycle_session_lease|FORCE ROW LEVEL SECURITY|CREATE POLICY|SECURITY DEFINER|REVOKE|GRANT' \
    "$f"
done

echo '== All mutation invalidation trigger attachment points =='
rg -n -C5 \
  'invalidate.*lifecycle.*lease|lifecycle.*lease.*invalid|reconciliation_lifecycle_session_lease' \
  database/migrations/0029_reconciliation_lifecycle_session_lock_authority.sql \
  database/migrations/0030_reconciliation_lifecycle_capability_privileges.sql

echo '== Focused PostgreSQL test bodies =='
for f in \
  tests/test_reconciliation_lifecycle_stacked_session_admission_postgres.py \
  tests/test_reconciliation_lifecycle_session_lease_postgres.py \
  tests/test_reconciliation_lifecycle_session_lease_rls_postgres.py \
  tests/test_reconciliation_lifecycle_direct_session_lock_postgres.py \
  tests/test_reconciliation_lifecycle_session_lock_reentrancy_postgres.py \
  tests/test_reconciliation_lifecycle_lock_wait_postgres.py \
  tests/test_reconciliation_exception_resolution_postgres.py; do
  if [ -f "$f" ]; then
    echo "## $f"
    sed -n '1,380p' "$f" | number
  fi
done

echo '== Test names that cover lease invalidation, freshness, and authority =='
rg -n \
  '^\s*def test_.*(lease|session|fresh|stale|invalidation|resolution|outbox|maker|checker|rls|tenant)' \
  tests

echo '== Migration identity tail =='
find database/migrations -maxdepth 1 -type f -name '*.sql' -printf '%f\n' | sort | tail -20

Length of output: 197811


@seonghobae I reviewed exact head 263e4ffb79607dccee715686d0aa451981c2eeb8.

I found no current-head actionable defect in the requested boundaries.

  • Migration 0029 forces tenant RLS on reconciliation_lifecycle_session_lease.
  • The lease invalidation function derives tenant and run identity from the mutated row. It does not accept caller-supplied invalidation scope.
  • The invalidation triggers cover candidates, matches, statement allocations, journal allocations, approvals, and exceptions. Each trigger runs in the mutation transaction.
  • The transition guard removes all same-backend session lock holds before it proves the transaction-level lock. It then restores one session hold.
  • The guard locks the exact lease row with SELECT ... FOR UPDATE.
  • If a relevant mutation deletes the lease after the authority transaction establishes its REPEATABLE READ snapshot, the row lock raises a serialization failure. The guard returns SQLSTATE 40001 with reconciliation_lifecycle_fresh_transaction_required.
  • If the mutation commits before the snapshot, the lease is absent. The guard rejects the transition at the same freshness boundary.
  • The PostgreSQL regression reproduces the stale-snapshot sequence with a released session hold, a late committed exception, and direct lock-pair reacquisition. It requires the expected 40001 rejection.
  • The application path still uses database lease acquisition, commits it, starts a fresh REPEATABLE READ transaction, takes the transaction lock, and releases the database-owned lease in finally.
  • The inspected current tree retains maker-checker separation, retained-evidence binding, immutable command evidence, strict source-payload identity, forced RLS, and deferred command/status/outbox controls with outbox retention.

The exact commit changes only the continuity-repair record. Its documentation matches the installed migration and regression behavior that I inspected.

This review is not an approval.

You are interacting with an AI system.

Copy link
Copy Markdown
Contributor Author

@codex review

현재 exact head 263e4ffb79607dccee715686d0aa451981c2eeb8만 review해 주세요. 범위는 reconciliation lifecycle/session lease의 fresh-transaction 연속성, FORCE RLS, tenant/run/exception/evidence composite identity, maker-checker separation, command/status/outbox exactly-once·retention, PUBLIC helper revoke, 그리고 predecessor evidence가 current head로 잘못 승계되지 않는지입니다. Review-only입니다. 브랜치 수정·승인 우회·status 합성은 하지 말고, blocking finding이 있으면 exact file/line과 재현 가능한 acceptance로 남겨 주세요.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Backlog

Development

Successfully merging this pull request may close these issues.

1 participant