Skip to content

feat(document-records): make persistence retries idempotent - #312

Draft
seonghobae wants to merge 23 commits into
feat/document-record-persistencefrom
feat/document-record-idempotent-persistence
Draft

feat(document-records): make persistence retries idempotent#312
seonghobae wants to merge 23 commits into
feat/document-record-persistencefrom
feat/document-record-idempotent-persistence

Conversation

@seonghobae

@seonghobae seonghobae commented Sep 12, 2026

Copy link
Copy Markdown
Contributor

Finding

#107 makes immutable document metadata durable, but tenant-scoped UNIQUE constraints alone do not provide an authoritative result for uncertain post-commit retries. A lost response followed by the same logical command can surface a generic uniqueness error; that error cannot prove that the committed row came from the same semantic command.

This stacked PR implements #309 inside the document_records owner. Replay truth stays out of talent_acquisition and other consumers, and no database transaction is held around OCR/model/artifact/network work.

Current exact authority

RED → causal repair lineage

  1. 6260960f2909d34803dad2890f0c0bfd0f7bede7 — real-PostgreSQL RED for same-key replay, changed-semantic conflict, concurrent first attempts, one document + one receipt, cleanup, FORCE RLS, and append-only receipt state; migration 0024 did not yet exist.
  2. b341784aaabca61dff2663986d24fd5e61b5a1c9 — initial 0024_document_record_idempotent_persistence.sql: tenant-scoped append-only replay receipt plus persist_document_record_once(...), server-side semantic digest, transaction-scoped advisory-lock arbitration.
  3. db8360801ac852f343cebae5fdd592866c091ae700ba4ee03df7ca86bfc3ef2383e04de211532296 — timezone-drift RED then owner-local UTC causal fix.
  4. 7a5393c279d9ef65f412a01ab891e71e4585c7fdbfc26948096e72524c434d22a7f6944e8446334b — unsupported-isolation RED then Read Committed fail-closed causal fix.
  5. cb7076c49fef13262fcb5c7f300cf902ce6715c9147973ef2709dcaffefffa9f40c00f1a49d464d1 — cross-tenant coordination RED then pre-lock tenant-context causal fix.
  6. 4ba85c535626f81468c74f4a5584385b1ad1a883 — existing retry/concurrency acceptance repaired to set tenant context explicitly for every supported function call.
  7. 262122bfe0f959d5225e57bf8de9f9e54018af13 — remove fixed scheduling delay from concurrency evidence. The first PostgreSQL session is held idle in transaction; the second must expose an ungranted advisory lock in pg_locks, and pg_blocking_pids(...) must name the first backend before the first transaction may commit. The same contract proves receipt-policy behavior through a temporary NOBYPASSRLS role.
  8. 8d28ab4a8beaf21a6405fce9b23b3642b7008924 — traceability currentized to the observable advisory-wait barrier and behavioral receipt-RLS evidence.
  9. 4757e24ae03db08c10d93ccf07f6ddbf9fe73a85 — make the temporary RLS probe principal execution-local and bind DROP OWNED + DROP ROLE to EXIT cleanup so an early assertion failure cannot leave the fixed historical role behind.
  10. be064e24280375c7eecb4b9e910f65d1145d434b — normal-path cleanup is fail closed while failure-path cleanup remains best-effort so cleanup cannot mask the original assertion failure.
  11. a9dc83aaf139f4f0bf0ee1ddb70cf2ba37000866 — traceability currentized to the failure-safe probe-principal lifecycle; predecessor CodeRabbit review found no new issue on that head.
  12. fb8da85bc62df519828c480a3f07b8a44be344ee — repair the remaining acceptance-isolation defect: ${BASHPID} is only process-local/reusable and can collide with a leaked role from another runner/container or a later PID reuse against the same database. The probe role now uses a fresh UUID-derived 24-hex suffix while preserving strict success cleanup and best-effort failure cleanup. The delta is one ordinary-forward commit, one test file, +7/-2; no production contract or gate was weakened.

Persistence contract

The receipt is value-minimized: tenant identity, opaque purpose-bound idempotency key, semantic-command digest, committed document identity, receipt digest, and database time. It stores no document bytes, credentials, names, compensation, ratings, free-form HR content, or duplicated Person/Employment truth.

persist_document_record_once(...) verifies transaction_isolation = read committed, rejects null authoritative fields, verifies the session tenant equals the requested tenant, computes a versioned semantic digest, then acquires a transaction-scoped advisory lock on tenant + document_records namespace + idempotency key. Same key + same semantic digest returns the first committed document/audit/outbox references and receipt. Same key + changed semantics fails closed before any second document write. A tenant-qualified FK prevents a receipt from binding to another tenant's document.

The tenant check deliberately precedes replay coordination. FORCE RLS protects row access but does not authorize taking a database-global advisory lock for another tenant, and privileged maintenance/test roles can bypass RLS. Digest construction executes with function-local UTC. The function is VOLATILE, and stronger transaction isolation fails closed rather than silently inheriting semantics that depend on post-lock Read Committed visibility. No long-running compute or external I/O belongs inside this transaction.

Executable acceptance

tests/test_document_record_idempotency_postgres.sh uses real PostgreSQL sessions and requires first/retry convergence, UTC↔Asia/Seoul timezone stability, changed-semantic rejection, observable advisory-lock blocking for concurrent first attempts, exactly one durable document + receipt, zero leaked acceptance connections, FORCE RLS plus NOBYPASSRLS behavioral isolation, collision-resistant per-execution probe-principal identity, failure-safe cleanup, and append-only receipt state. Bounded observation loops wait for explicit PostgreSQL state; elapsed time itself is never accepted as serialization evidence.

tests/test_document_record_idempotency_isolation_postgres.sh enters a real REPEATABLE READ transaction and requires the explicit owner isolation error before null/command validation, then verifies the normal Foundation connection is exercising Read Committed.

tests/test_document_record_idempotency_tenant_context_postgres.sh submits a valid tenant-beta command from a tenant-alpha session and requires the explicit tenant-boundary error plus zero durable beta document/receipt rows.

Evidence boundary

Hosted GREEN is not claimed. This PR correctly targets #107, while #310/#311 own PostgreSQL Foundation discovery/execution on a separate prerequisite stack. Exact head fb8da85b... has zero pull-request workflow runs. Combined statuses currently contain Devin Review success and CodeRabbit success only; submitted PR reviews are still zero. Those signals are not PostgreSQL runtime acceptance or a qualifying independent APPROVED review. Predecessor CodeRabbit findings/verdicts do not transfer to this head.

Do not add a feature-local workflow, temporarily retarget to develop, synthesize statuses, transfer predecessor GREEN, self-approve, or weaken a protected gate.

Integration boundary

Keep Draft until #107 and the Foundation prerequisite stack (#258/#259#310/#311 or verified successors) integrate or this branch is ordinary-forward reconciled onto their then-current protected truth. Then admit all three PostgreSQL contracts through owner-neutral Foundation discovery, run exact-head Foundation/SAST/Security/CodeQL/OpenCode/Noema/Strix, resolve findings, obtain the qualifying review evidence required by the then-live policy, and merge normally without bypass/force/destructive rebase.

Refs #309.

@coderabbitai

coderabbitai Bot commented Sep 12, 2026

Copy link
Copy Markdown

Review Change StackReview Change Stack

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
✨ 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/document-record-idempotent-persistence

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 the current exact head, especially the transaction-scoped idempotency serialization, replay digest binding, tenant-qualified receipt FK/RLS, and the real-concurrency PostgreSQL contract. Do not treat predecessor #107 evidence as current-head acceptance.

@coderabbitai

coderabbitai Bot commented Sep 12, 2026

Copy link
Copy Markdown
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '== PR metadata and exact head =='
gh pr view 312 --repo ContextualWisdomLab/Orgmetra \
  --json number,state,isDraft,baseRefName,baseRefOid,headRefName,headRefOid,mergeStateStatus,statusCheckRollup \
  --jq '{number,state,isDraft,baseRefName,baseRefOid,headRefName,headRefOid,mergeStateStatus,statusCheckRollup}'

echo '== Changed files at the PR head =='
gh pr diff 312 --repo ContextualWisdomLab/Orgmetra --name-only

echo '== Repository head =='
git rev-parse HEAD
git status --short

echo '== Locate relevant artifacts =='
fd -a -i '0024.*document.*record.*idempotent.*persistence.*\.sql|0309.*|test_document_record_idempotency_postgres\.sh' . || true

echo '== SQL migration outline and content =='
sql_file="$(fd -a -i '0024.*document.*record.*idempotent.*persistence.*\.sql' . | head -n1)"
if [ -n "$sql_file" ]; then
  ast-grep outline "$sql_file" --items all || true
  nl -ba "$sql_file"
fi

echo '== PostgreSQL contract content =='
test_file="$(fd -a -i 'test_document_record_idempotency_postgres\.sh' . | head -n1)"
if [ -n "$test_file" ]; then
  nl -ba "$test_file"
fi

echo '== ADR content =='
adr_file="$(fd -a -i '0309.*' . | head -n1)"
if [ -n "$adr_file" ]; then
  nl -ba "$adr_file"
fi

echo '== Related table definitions, policies, and persistence callers =='
rg -n -i -C 4 \
  'document_records?|idempotency|replay.*receipt|persist_document_record_once|row level security|create policy|force row level' \
  --glob '*.sql' --glob '*.sh' --glob '*.md' .

Length of output: 202018


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sql=database/migrations/0024_document_record_idempotent_persistence.sql
test=tests/test_document_record_idempotency_postgres.sh

echo '== Exact PR head and changed files =='
gh pr view 312 --repo ContextualWisdomLab/Orgmetra \
  --json headRefOid,baseRefOid,isDraft,state,mergeStateStatus,statusCheckRollup \
  --jq '{headRefOid,baseRefOid,isDraft,state,mergeStateStatus,checks:[.statusCheckRollup[]? | {name,conclusion,status,workflowName}]}'
gh pr diff 312 --repo ContextualWisdomLab/Orgmetra --name-only

echo '== Exact repository head =='
git rev-parse HEAD

echo '== Migration: complete function and privilege metadata =='
nl -ba "$sql" | sed -n '74,325p'
rg -n -C 3 'GRANT|REVOKE|ALTER FUNCTION|SECURITY DEFINER|persist_document_record_once' \
  database/migrations

echo '== Parent document relation and its RLS policy =='
nl -ba database/migrations/0021_document_record_persistence.sql | sed -n '1,130p;315,345p'

echo '== Test: setup, helper functions, and sequential replay/conflict assertions =='
nl -ba "$test" | sed -n '1,172p'

echo '== Test: concurrency, tenant RLS, and append-only assertions =='
nl -ba "$test" | sed -n '173,280p'

echo '== Test registry state on this head =='
rg -n -C 2 'test_document_record_idempotency_postgres|document-record.*idempot' \
  README.md docs .github tests 2>/dev/null || true

echo '== Migration ordering and application mechanism =='
rg -n -C 3 'migrations/|database/migrations|0024_document_record' \
  tests .github README.md docs 2>/dev/null || true

Length of output: 84875


@seonghobae I reviewed exact head 3ef61434b04c6cc01d15788a62e71fc8036ad926.

I found two issues.

  1. Replay digest depends on the PostgreSQL session TimeZone.
    In database/migrations/0024_document_record_idempotent_persistence.sql, Line 163 passes p_received_at directly to jsonb_build_object. PostgreSQL JSON conversion of timestamptz uses the current session time zone. Two retry sessions can provide the same instant with different TimeZone settings. They then compute different semantic digests. The second request fails as a changed command instead of replaying the original result.

    Normalize p_received_at to a fixed UTC representation before digest construction. Add a regression that performs the same-key replay from a session with a different TimeZone.

  2. The concurrency contract uses a fixed scheduling delay.
    In tests/test_document_record_idempotency_postgres.sh, Line 181 uses sleep 0.25 before it starts the second session. A slow first session can cause the second session to start after the first transaction commits. The test then passes without proving that the second session waited on pg_advisory_xact_lock.

    Replace the delay with an observable database barrier. The first session should signal after it has acquired the advisory lock. The test should then start the second session, confirm that it blocks, and release the first session. This proves real concurrent serialization.

The receipt table has the requested tenant-qualified composite foreign key and FORCE ROW LEVEL SECURITY. However, the current contract only verifies the RLS flags. It does not prove read and write denial through a NOBYPASSRLS role.

No hosted PostgreSQL acceptance is available on this exact head. I did not treat predecessor #107 evidence as current-head acceptance.

⚠️ 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.

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

Current exact head is now 00ba4ee03df7ca86bfc3ef2383e04de211532296. Please review the complete current delta from #107, including the timezone-stable semantic/receipt digest repair, VOLATILE + Read Committed replay assumption, advisory-lock scope, tenant-qualified receipt FK/RLS, and real concurrent PostgreSQL acceptance. Prior review state must not be transferred to this head.

@coderabbitai

coderabbitai Bot commented Sep 12, 2026

Copy link
Copy Markdown
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

repo="ContextualWisdomLab/Orgmetra"
expected_head="00ba4ee03df7ca86bfc3ef2383e04de211532296"

echo '== PR metadata =='
gh pr view 312 --repo "$repo" \
  --json number,state,isDraft,baseRefName,baseRefOid,headRefName,headRefOid,mergeStateStatus,statusCheckRollup \
  --jq '{number,state,isDraft,baseRefName,baseRefOid,headRefName,headRefOid,mergeStateStatus,checks:[.statusCheckRollup[]? | {name,status,conclusion,workflowName}]}'

echo '== checked-out commit =='
git rev-parse HEAD
git status --short

echo '== changed files: PR delta =='
gh pr diff 312 --repo "$repo" --name-only

echo '== changed files: exact base-to-head delta =='
base="$(gh pr view 312 --repo "$repo" --json baseRefOid --jq .baseRefOid)"
git diff --name-status "$base" "$expected_head"

echo '== locate primary and related artifacts =='
fd -a -i '002[0-9].*document.*record.*\.sql|0309.*|test_document_record_idempotency_postgres\.sh' . || true

echo '== outlines =='
for f in \
  database/migrations/0021_document_record_persistence.sql \
  database/migrations/0024_document_record_idempotent_persistence.sql \
  tests/test_document_record_idempotency_postgres.sh
do
  if [ -f "$f" ]; then
    echo "-- $f"
    ast-grep outline "$f" --items all || true
  fi
done

echo '== idempotency migration =='
nl -ba database/migrations/0024_document_record_idempotent_persistence.sql

echo '== predecessor document schema and RLS =='
nl -ba database/migrations/0021_document_record_persistence.sql

echo '== PostgreSQL contract =='
nl -ba tests/test_document_record_idempotency_postgres.sh

echo '== ADR 0309 =='
adr="$(fd -a -i '0309.*' . | head -n 1 || true)"
if [ -n "$adr" ]; then nl -ba "$adr"; fi

echo '== all persistence-function references and migration/test execution references =='
rg -n -C 3 \
  'persist_document_record_once\s*\(|document_record_replay_receipts|test_document_record_idempotency_postgres|database/migrations' \
  --glob '*.sql' --glob '*.sh' --glob '*.md' --glob '*.yml' --glob '*.yaml' .

Length of output: 89733


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '== exact patch =='
git diff --find-renames --find-copies 7ce73aa44f47113b2ecd42d51bb5d38a22c0367d 00ba4ee03df7ca86bfc3ef2383e04de211532296 -- \
  database/migrations/0024_document_record_idempotent_persistence.sql \
  docs/adr/0309-document-record-idempotent-persistence.md \
  docs/traceability/document-record-idempotent-persistence.md \
  tests/test_document_record_idempotency_postgres.sh

echo '== tenant-context helper, RLS patterns, and relevant grants =='
rg -n -C 8 \
  'CREATE( OR REPLACE)? FUNCTION public\.current_tenant_record_id|current_tenant_record_id\(\)|GRANT .*document_record|REVOKE .*document_record|GRANT .*persist_document_record_once|REVOKE .*persist_document_record_once|ALTER TABLE .* FORCE ROW LEVEL SECURITY' \
  --glob '*.sql' database/migrations

echo '== document migrations 0022 and 0023 =='
nl -ba database/migrations/0022_document_record_evidence_unique_keys.sql
nl -ba database/migrations/0023_document_record_canonical_encoding.sql

echo '== traceability =='
nl -ba docs/traceability/document-record-idempotent-persistence.md

echo '== all PostgreSQL test concurrency synchronization patterns =='
rg -n -C 10 \
  'pg_advisory|pg_stat_activity|pg_sleep|mktemp|application_name|wait "\$\{|sleep [0-9]' \
  --glob 'test_*postgres*.sh' tests

echo '== function volatility/isolation declarations in migrations =='
rg -n -C 5 \
  'LANGUAGE plpgsql|VOLATILE|STABLE|SET TRANSACTION ISOLATION LEVEL|transaction_isolation|pg_advisory_xact_lock' \
  --glob '*.sql' database/migrations

Length of output: 174249


@seonghobae I reviewed exact head 00ba4ee03df7ca86bfc3ef2383e04de211532296 against base 7ce73aa44f47113b2ecd42d51bb5d38a22c0367d.

I found two issues.

  1. The concurrent acceptance does not prove advisory-lock contention.
    In tests/test_document_record_idempotency_postgres.sh, Line 181 uses sleep 0.25 before it starts the second session. If the first session has not reached pg_advisory_xact_lock, the test does not establish the required ordering. If the first session completes before the second invocation, the test still passes without proving waiting behavior.

    Add an observable first-session barrier after the function obtains the lock. Then start the second session. Confirm that the second session is blocked on the advisory lock before the first session commits. Existing tests use pg_stat_activity polling for this type of synchronization.

  2. The RLS acceptance checks metadata, not RLS enforcement.
    In tests/test_document_record_idempotency_postgres.sh, Lines 214-221 only verify relrowsecurity and relforcerowsecurity. The test never uses a NOBYPASSRLS role. It also never sets tenant context before receipt access.

    Add a role-based test that grants only required access, sets orgmetra.tenant_record_id, and verifies that the role can access its own receipt but cannot read or write another tenant’s receipt. This proves the policy and the FORCE RLS setting work at runtime.

The function-local UTC setting correctly covers timestamptz serialization in the semantic digest and receipt digest. The VOLATILE declaration and the ADR’s Read Committed restriction are consistent with the post-lock replay lookup. The advisory-lock key includes tenant identity, owner namespace, and idempotency key. The receipt foreign key is tenant-qualified.

No hosted PostgreSQL execution or protected-base acceptance exists for this exact head. I did not use predecessor #107 evidence as current-head acceptance.

⚠️ 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.

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

Please review exact current head 45a0296f9ad513b3f73dfce24a09d26d629b447a from base #107 7ce73aa44f47113b2ecd42d51bb5d38a22c0367d. Focus on the transaction-scoped advisory-lock replay semantics, function-local UTC digest identity, explicit Read Committed fail-closed guard, tenant-qualified receipt FK/RLS/immutability, and both real PostgreSQL acceptance contracts. Do not transfer findings/approval from predecessor heads.

@coderabbitai

coderabbitai Bot commented Sep 12, 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

repo="ContextualWisdomLab/Orgmetra"
base="7ce73aa44f47113b2ecd42d51bb5d38a22c0367d"
head="45a0296f9ad513b3f73dfce24a09d26d629b447a"

echo '== Pull request metadata and exact commits =='
gh pr view 312 --repo "$repo" \
  --json number,state,isDraft,baseRefName,baseRefOid,headRefName,headRefOid,mergeStateStatus,statusCheckRollup \
  --jq '{number,state,isDraft,baseRefName,baseRefOid,headRefName,headRefOid,mergeStateStatus,checks:[.statusCheckRollup[]? | {name,status,conclusion,workflowName}]}'
printf 'checked_out='; git rev-parse HEAD
printf 'expected_base=%s\nexpected_head=%s\n' "$base" "$head"

echo '== Complete base-to-head changed-file list =='
git diff --name-status "$base" "$head"

echo '== Locate relevant files =='
fd -a -i \
  '0021_document_record_persistence\.sql|0024_document_record_idempotent_persistence\.sql|0309.*|document-record-idempotent-persistence.*|test_document_record_idempotency(_isolation)?_postgres\.sh' \
  . | sort

echo '== Migration 0024 complete content =='
nl -ba database/migrations/0024_document_record_idempotent_persistence.sql

echo '== Parent document-record schema, RLS, and ownership definitions =='
nl -ba database/migrations/0021_document_record_persistence.sql

echo '== Both real PostgreSQL acceptance contracts =='
for f in \
  tests/test_document_record_idempotency_postgres.sh \
  tests/test_document_record_idempotency_isolation_postgres.sh
do
  if [ -f "$f" ]; then
    echo "-- $f"
    nl -ba "$f"
  fi
done

echo '== ADR and traceability documents =='
for f in \
  docs/adr/0309-document-record-idempotent-persistence.md \
  docs/traceability/document-record-idempotent-persistence.md
do
  if [ -f "$f" ]; then
    echo "-- $f"
    nl -ba "$f"
  fi
done

echo '== Exact implementation patch =='
git diff --find-renames --find-copies "$base" "$head" -- \
  database/migrations \
  tests/test_document_record_idempotency_postgres.sh \
  tests/test_document_record_idempotency_isolation_postgres.sh \
  docs/adr/0309-document-record-idempotent-persistence.md \
  docs/traceability/document-record-idempotent-persistence.md

echo '== Relevant schema helpers, grants, triggers, policies, and test discovery =='
rg -n -C 5 \
  'persist_document_record_once|document_record_replay_receipts|current_tenant_record_id|pg_advisory_xact_lock|transaction_isolation|set_config|TimeZone|timezone|ROW LEVEL SECURITY|FORCE ROW LEVEL SECURITY|CREATE POLICY|GRANT|REVOKE|CREATE TRIGGER|append.only|UPDATE|DELETE|test_document_record_idempotency' \
  --glob '*.sql' --glob '*.sh' --glob '*.md' --glob '*.yml' --glob '*.yaml' \
  database tests docs .github 2>/dev/null || true

Length of output: 203164


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '== Exact head confirmation =='
git rev-parse HEAD
git merge-base --is-ancestor 7ce73aa44f47113b2ecd42d51bb5d38a22c0367d 45a0296f9ad513b3f73dfce24a09d26d629b447a && echo 'base_is_ancestor=yes'

echo '== Migration 0024: table and full function body in focused ranges =='
nl -ba database/migrations/0024_document_record_idempotent_persistence.sql | sed -n '1,340p'

echo '== Idempotency main contract: complete file =='
nl -ba tests/test_document_record_idempotency_postgres.sh

echo '== Isolation contract: complete file =='
nl -ba tests/test_document_record_idempotency_isolation_postgres.sh

echo '== Related 0021 table definition, constraints, triggers, and RLS only =='
rg -n -A10 -B5 \
  'CREATE TABLE.*document_record|ALTER TABLE.*document_record|CREATE (UNIQUE )?INDEX.*document_record|CONSTRAINT.*document_record|FOREIGN KEY|document_record.*tenant|ENABLE ROW LEVEL SECURITY|FORCE ROW LEVEL SECURITY|CREATE POLICY|append.only|TRUNCATE' \
  database/migrations/0021_document_record_persistence.sql

echo '== Main contract concurrency and RLS sections with syntax context =='
rg -n -A55 -B12 \
  'PGAPPNAME|application_name|concurr|pg_stat_activity|pg_locks|advisory|NOBYPASSRLS|SET ROLE|document_record_persist_receipt|append-only|TRUNCATE|OTHER_TENANT|other tenant' \
  tests/test_document_record_idempotency_postgres.sh

echo '== SQL references from test: extracted heredocs around function invocation =='
rg -n -A45 -B8 \
  'persist_document_record_once\(' \
  tests/test_document_record_idempotency_postgres.sh

echo '== Test registration / inventory coverage at exact head =='
rg -n -C3 \
  'test_document_record_idempotency_postgres\.sh|test_document_record_idempotency_isolation_postgres\.sh' \
  .github tests docs README.md package.json 2>/dev/null || true

Length of output: 56917


@seonghobae I reviewed exact head 45a0296f9ad513b3f73dfce24a09d26d629b447a from base 7ce73aa44f47113b2ecd42d51bb5d38a22c0367d.

I found two issues.

  1. The concurrent acceptance does not prove advisory-lock contention.
    In tests/test_document_record_idempotency_postgres.sh, Line 181 uses sleep 0.25 before the test starts the second PostgreSQL session. The first session can still be before pg_advisory_xact_lock, or it can have completed before the second session invokes the function. In either case, the test can pass without proving that the retry waited for the transaction-scoped advisory lock.

    Use an observable database barrier after the first invocation has acquired the lock and persisted its receipt. Then start the second session. Confirm that the second session waits on the advisory lock before the first transaction commits.

  2. The receipt RLS test checks catalog metadata but not runtime enforcement.
    In tests/test_document_record_idempotency_postgres.sh, Lines 214-221 check only relrowsecurity and relforcerowsecurity. The test does not use a NOBYPASSRLS role to read or write document_record_persist_receipt.

    Add a role-based acceptance case. Grant only the required receipt privileges. Set orgmetra.tenant_record_id. Verify that the role can access its tenant receipt, cannot access another tenant receipt, and cannot insert a receipt for another tenant. This verifies the policy and FORCE ROW LEVEL SECURITY at runtime.

The function-local SET TimeZone = 'UTC' protects the timestamptz values used in the semantic and receipt digest construction. The same-key retry test covers UTC to Asia/Seoul replay. The VOLATILE declaration and the Read Committed guard are consistent with the post-lock replay lookup. The receipt foreign key is tenant-qualified. The receipt has update/delete and TRUNCATE guards.

No hosted PostgreSQL execution is available for this exact head. I did not use predecessor evidence as current-head acceptance.

You are interacting with an AI system.

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

Current exact head is 8ba15958762ed49bc33c4f6d78573b0427bec927. Please review the new tenant-context boundary in persist_document_record_once(...) and tests/test_document_record_idempotency_tenant_context_postgres.sh, including whether tenant mismatch is rejected before advisory-lock acquisition or durable state and whether the existing retry/concurrency tests now supply tenant context consistently.

@coderabbitai

coderabbitai Bot commented Sep 12, 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

repo="ContextualWisdomLab/Orgmetra"
base="7ce73aa44f47113b2ecd42d51bb5d38a22c0367d"
head="8ba15958762ed49bc33c4f6d78573b0427bec927"

echo '== Exact PR and checkout identity =='
gh pr view 312 --repo "$repo" \
  --json number,state,isDraft,baseRefOid,headRefOid,mergeStateStatus,statusCheckRollup \
  --jq '{number,state,isDraft,baseRefOid,headRefOid,mergeStateStatus,checks:[.statusCheckRollup[]? | {name,status,conclusion,workflowName}]}'
printf 'checked_out='
git rev-parse HEAD
git merge-base --is-ancestor "$base" "$head" && echo 'base_is_ancestor=yes'

echo '== Complete base-to-head changed files =='
git diff --name-status "$base" "$head"

echo '== Locate review artifacts =='
fd -a -i \
  '002[1-4]_document_record.*\.sql|0309.*|document-record-idempotent-persistence.*|test_document_record_idempotency(_(isolation|tenant_context))?_postgres\.sh' \
  . | sort

echo '== Migration 0024 outline =='
ast-grep outline database/migrations/0024_document_record_idempotent_persistence.sql --items all || true

echo '== Migration 0024 complete content =='
nl -ba database/migrations/0024_document_record_idempotent_persistence.sql

echo '== Tenant helper and document-record RLS/schema definitions =='
rg -n -A18 -B8 \
  'CREATE( OR REPLACE)? FUNCTION public\.current_tenant_record_id|current_tenant_record_id\(\)|CREATE TABLE.*document_record|ALTER TABLE.*document_record|ENABLE ROW LEVEL SECURITY|FORCE ROW LEVEL SECURITY|CREATE POLICY|FOREIGN KEY|GRANT|REVOKE' \
  --glob '*.sql' database/migrations

echo '== All three PostgreSQL contracts =='
for f in \
  tests/test_document_record_idempotency_postgres.sh \
  tests/test_document_record_idempotency_isolation_postgres.sh \
  tests/test_document_record_idempotency_tenant_context_postgres.sh
do
  echo "-- $f"
  nl -ba "$f"
done

echo '== Every persistence-function call, tenant context assignment, and concurrency synchronization path =='
rg -n -A18 -B10 \
  "persist_document_record_once\s*\(|orgmetra\.tenant_record_id|set_config\s*\(\s*'orgmetra\.tenant_record_id'|current_tenant_record_id\s*\(|pg_advisory_xact_lock|pg_stat_activity|wait_event|application_name|PGAPPNAME" \
  --glob '*.sql' --glob '*.sh' database tests

echo '== Exact patch for reviewed scope =='
git diff --find-renames --find-copies "$base" "$head" -- \
  database/migrations/0024_document_record_idempotent_persistence.sql \
  tests/test_document_record_idempotency_postgres.sh \
  tests/test_document_record_idempotency_isolation_postgres.sh \
  tests/test_document_record_idempotency_tenant_context_postgres.sh \
  docs/adr/0309-document-record-idempotent-persistence.md \
  docs/traceability/document-record-idempotent-persistence.md

Length of output: 189664


@seonghobae I reviewed exact head 8ba15958762ed49bc33c4f6d78573b0427bec927 from base 7ce73aa44f47113b2ecd42d51bb5d38a22c0367d.

I found one issue.

  1. The concurrent PostgreSQL acceptance still does not prove advisory-lock contention.
    In tests/test_document_record_idempotency_postgres.sh, Line 189 waits for a fixed sleep 0.25 before it starts the second session. The first session can still be before pg_advisory_xact_lock, or it can complete before the second call. The test can then pass without proving that the second call waited on the transaction-scoped advisory lock.

    Use an observable database barrier. First confirm that the first session has persisted its receipt and remains in its transaction. Then start the second session. Confirm that it waits on the advisory lock before the first session commits.

The tenant-context boundary is correctly ordered in persist_document_record_once(...). The function checks current_tenant_record_id() after the required null-field guard and before semantic-digest construction, replay lookup, pg_advisory_xact_lock, and durable writes. A valid tenant-mismatch command therefore fails before it can coordinate on another tenant’s advisory-lock key.

tests/test_document_record_idempotency_tenant_context_postgres.sh supplies valid tenant-beta fields with tenant-alpha session context. It requires the explicit tenant-boundary error and verifies zero tenant-beta document and receipt rows. The static function order establishes that this rejection also occurs before lock acquisition.

The existing retry calls use with_tenant. Both concurrent psql sessions set orgmetra.tenant_record_id. The isolation test intentionally omits tenant context because it verifies that the Read Committed guard fails before command-field validation.

I did not verify hosted PostgreSQL execution for this exact head.

You are interacting with an AI system.

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

Current exact head is 8ba15958762ed49bc33c4f6d78573b0427bec927. Please review the idempotent document-record persistence boundary, especially replay semantic membership, tenant-before-coordination ordering, Read Committed visibility assumptions, advisory-lock behavior, and real PostgreSQL acceptance. Do not treat predecessor evidence as current-head approval.

@coderabbitai

coderabbitai Bot commented Sep 12, 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

repo="ContextualWisdomLab/Orgmetra"
base="7ce73aa44f47113b2ecd42d51bb5d38a22c0367d"
head="8ba15958762ed49bc33c4f6d78573b0427bec927"

echo '== Exact PR and checkout identity =='
gh pr view 312 --repo "$repo" \
  --json number,state,isDraft,baseRefOid,headRefOid,mergeStateStatus,statusCheckRollup \
  --jq '{number,state,isDraft,baseRefOid,headRefOid,mergeStateStatus,checks:[.statusCheckRollup[]? | {name,status,conclusion,workflowName}]}'
printf 'checked_out='
git rev-parse HEAD
git merge-base --is-ancestor "$base" "$head" && echo 'base_is_ancestor=yes'

echo '== Complete base-to-head changed-file list =='
git diff --name-status "$base" "$head"

echo '== Migration and test outlines =='
for f in \
  database/migrations/0021_document_record_persistence.sql \
  database/migrations/0024_document_record_idempotent_persistence.sql \
  tests/test_document_record_idempotency_postgres.sh \
  tests/test_document_record_idempotency_isolation_postgres.sh \
  tests/test_document_record_idempotency_tenant_context_postgres.sh
do
  if [ -f "$f" ]; then
    echo "-- $f"
    ast-grep outline "$f" --items all || true
  fi
done

echo '== Idempotency migration =='
nl -ba database/migrations/0024_document_record_idempotent_persistence.sql

echo '== Parent schema, tenant helper, RLS, and document constraints =='
rg -n -A24 -B10 \
  'CREATE( OR REPLACE)? FUNCTION public\.current_tenant_record_id|CREATE TABLE.*document_record|document_record.*tenant|ENABLE ROW LEVEL SECURITY|FORCE ROW LEVEL SECURITY|CREATE POLICY|FOREIGN KEY|CREATE TRIGGER|GRANT|REVOKE' \
  --glob '*.sql' database/migrations

echo '== All real PostgreSQL idempotency contracts =='
for f in \
  tests/test_document_record_idempotency_postgres.sh \
  tests/test_document_record_idempotency_isolation_postgres.sh \
  tests/test_document_record_idempotency_tenant_context_postgres.sh
do
  echo "-- $f"
  nl -ba "$f"
done

echo '== All persistence invocations, tenant context, lock coordination, and transaction handling =='
rg -n -A24 -B12 \
  "persist_document_record_once\s*\(|orgmetra\.tenant_record_id|set_config\s*\(\s*'orgmetra\.tenant_record_id'|current_tenant_record_id\s*\(|pg_advisory_xact_lock|pg_stat_activity|wait_event|application_name|PGAPPNAME|BEGIN|COMMIT|transaction_isolation|TimeZone" \
  --glob '*.sql' --glob '*.sh' database tests

echo '== Exact reviewed patch =='
git diff --find-renames --find-copies "$base" "$head" -- \
  database/migrations \
  tests/test_document_record_idempotency_postgres.sh \
  tests/test_document_record_idempotency_isolation_postgres.sh \
  tests/test_document_record_idempotency_tenant_context_postgres.sh \
  docs/adr/0309-document-record-idempotent-persistence.md \
  docs/traceability/document-record-idempotent-persistence.md

echo '== Test discovery and CI registration =='
rg -n -C4 \
  'test_document_record_idempotency(_isolation|_tenant_context)?_postgres\.sh|document-record-idempotent' \
  .github tests docs README.md package.json 2>/dev/null || true

Length of output: 203533


@seonghobae I reviewed exact head 8ba15958762ed49bc33c4f6d78573b0427bec927 from base 7ce73aa44f47113b2ecd42d51bb5d38a22c0367d.

I found two issues.

  1. The concurrent acceptance does not prove advisory-lock contention.
    In tests/test_document_record_idempotency_postgres.sh, Line 189 waits for a fixed sleep 0.25 before it starts the second session. The first session can still be before pg_advisory_xact_lock. The first session can also finish before the second invocation starts. The test can then pass without proving that the second invocation waited on the transaction-scoped advisory lock.

    Use an observable barrier after the first call has persisted its receipt and remains inside its transaction. Then start the second call. Confirm through pg_stat_activity or pg_locks that the second session waits for the advisory lock before the first session commits.

  2. The receipt RLS acceptance does not prove runtime enforcement.
    In tests/test_document_record_idempotency_postgres.sh, Lines 214-221 only check relrowsecurity and relforcerowsecurity. The contract does not use a NOBYPASSRLS role with receipt privileges.

    Add a runtime RLS case. Set tenant context under a NOBYPASSRLS role. Verify that the role can read its tenant receipt. Verify that it cannot read or insert a receipt for another tenant. This verifies the receipt policy and FORCE RLS behavior.

The implementation order is otherwise correct. persist_document_record_once(...) checks Read Committed before command validation. It checks current_tenant_record_id() before digest construction, replay lookup, advisory-lock acquisition, and durable writes. The function-local UTC setting protects timestamptz values in both digest paths. The semantic digest binds the governed command fields. The receipt has a tenant-qualified composite foreign key to document_record. Same-key changed semantics fail before a second document write.

No hosted PostgreSQL execution was available for this exact head. I did not treat predecessor evidence as current-head acceptance.

You are interacting with an AI system.

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

Please review current exact head 8d28ab4a8beaf21a6405fce9b23b3642b7008924. The predecessor review's timezone finding is already repaired; this head specifically repairs the remaining fixed-delay concurrency evidence and metadata-only receipt-RLS evidence. Verify the pg_stat_activity/pg_locks advisory-wait barrier, FIFO-held first transaction cleanup, and the temporary NOBYPASSRLS role assertions. Do not transfer predecessor approval/evidence.

@coderabbitai

coderabbitai Bot commented Sep 12, 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

repo="ContextualWisdomLab/Orgmetra"
base="7ce73aa44f47113b2ecd42d51bb5d38a22c0367d"
head="8d28ab4a8beaf21a6405fce9b23b3642b7008924"

echo '== Exact PR identity =='
gh pr view 312 --repo "$repo" \
  --json number,state,isDraft,baseRefOid,headRefOid,mergeStateStatus,statusCheckRollup \
  --jq '{number,state,isDraft,baseRefOid,headRefOid,mergeStateStatus,checks:[.statusCheckRollup[]? | {name,status,conclusion,workflowName}]}'
printf 'checked_out_head='
git rev-parse HEAD
git merge-base --is-ancestor "$base" "$head" && echo 'base_is_ancestor=yes'

echo '== Complete delta from `#107` base to requested head =='
git diff --name-status "$base" "$head"

echo '== Relevant artifact locations =='
fd -a -i \
  '0021_document_record_persistence\.sql|0024_document_record_idempotent_persistence\.sql|test_document_record_idempotency(_(isolation|tenant_context))?_postgres\.sh|0309.*|document-record-idempotent-persistence.*' \
  . | sort

echo '== Migration 0024: complete content =='
nl -ba database/migrations/0024_document_record_idempotent_persistence.sql

echo '== Parent schema: document records, RLS, and tenant helper =='
rg -n -A30 -B12 \
  'CREATE( OR REPLACE)? FUNCTION public\.current_tenant_record_id|CREATE TABLE.*document_record|document_record.*tenant|ENABLE ROW LEVEL SECURITY|FORCE ROW LEVEL SECURITY|CREATE POLICY|FOREIGN KEY|CREATE TRIGGER|GRANT|REVOKE' \
  --glob '*.sql' database/migrations

echo '== Main real-PostgreSQL contract =='
nl -ba tests/test_document_record_idempotency_postgres.sh

echo '== Related real-PostgreSQL contracts =='
for f in \
  tests/test_document_record_idempotency_isolation_postgres.sh \
  tests/test_document_record_idempotency_tenant_context_postgres.sh
do
  if [ -f "$f" ]; then
    echo "-- $f"
    nl -ba "$f"
  fi
done

echo '== Concurrency barrier and RLS assertion paths with context =='
rg -n -A45 -B15 \
  'mkfifo|FIFO|PGAPPNAME|application_name|pg_stat_activity|pg_locks|pg_blocking_pids|advisory|wait_event|granted|idle in transaction|NOBYPASSRLS|SET ROLE|document_record_replay_receipts|UPDATE|DELETE|TRUNCATE|cleanup|trap' \
  --glob '*.sh' --glob '*.sql' tests database/migrations

echo '== All calls: transaction state and tenant context =='
rg -n -A20 -B10 \
  "persist_document_record_once\s*\(|orgmetra\.tenant_record_id|set_config\s*\(\s*'orgmetra\.tenant_record_id'|BEGIN|COMMIT|ROLLBACK|transaction_isolation|TimeZone" \
  --glob '*.sh' --glob '*.sql' tests database/migrations

echo '== Patch for current-head repairs =='
git diff --find-renames --find-copies 8ba15958762ed49bc33c4f6d78573b0427bec927 "$head" -- \
  database/migrations/0024_document_record_idempotent_persistence.sql \
  tests/test_document_record_idempotency_postgres.sh \
  tests/test_document_record_idempotency_isolation_postgres.sh \
  tests/test_document_record_idempotency_tenant_context_postgres.sh \
  docs/adr/0309-document-record-idempotent-persistence.md \
  docs/traceability/document-record-idempotent-persistence.md

echo '== Test registration/discovery =='
rg -n -C4 \
  'test_document_record_idempotency(_isolation|_tenant_context)?_postgres\.sh|document-record-idempotent' \
  .github tests docs README.md package.json 2>/dev/null || true

Length of output: 203753


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '== Requested main contract, complete focused ranges =='
nl -ba tests/test_document_record_idempotency_postgres.sh | sed -n '1,430p'

echo '== Migration 0024, complete focused ranges =='
nl -ba database/migrations/0024_document_record_idempotent_persistence.sql | sed -n '1,380p'

echo '== Exact current-head status and recent repair patch =='
git rev-parse HEAD
git diff --check 8ba15958762ed49bc33c4f6d78573b0427bec927 8d28ab4a8beaf21a6405fce9b23b3642b7008924
git diff --unified=80 8ba15958762ed49bc33c4f6d78573b0427bec927 8d28ab4a8beaf21a6405fce9b23b3642b7008924 -- tests/test_document_record_idempotency_postgres.sh

echo '== Receipt DDL, RLS policy, immutability, and function order =='
rg -n -A35 -B10 \
  'CREATE TABLE.*document_record_persist_receipt|document_record_persist_receipt.*FOREIGN KEY|document_record_persist_receipt.*UNIQUE|ENABLE ROW LEVEL SECURITY|FORCE ROW LEVEL SECURITY|CREATE POLICY|append.only|reject.*truncate|CREATE FUNCTION public\.persist_document_record_once|transaction_isolation|current_tenant_record_id|pg_advisory_xact_lock|SELECT.*document_record_persist_receipt|INSERT INTO document_record_persist_receipt' \
  database/migrations/0024_document_record_idempotent_persistence.sql

echo '== Current test role setup/teardown patterns =='
rg -n -A20 -B10 \
  'CREATE ROLE orgmetra_document_receipt_probe|DROP OWNED BY orgmetra_document_receipt_probe|DROP ROLE orgmetra_document_receipt_probe|trap cleanup|cleanup\(\)' \
  tests/test_document_record_idempotency_postgres.sh

Length of output: 60515


@seonghobae I reviewed exact head 8d28ab4a8beaf21a6405fce9b23b3642b7008924 from base 7ce73aa44f47113b2ecd42d51bb5d38a22c0367d.

I found one issue.

  1. The temporary RLS probe role leaks when an RLS assertion fails.
    In tests/test_document_record_idempotency_postgres.sh, Lines 303-309 create orgmetra_document_receipt_probe. Lines 347-350 remove it only after all RLS assertions pass. If an assertion at Lines 317, 328, or 342 fails, set -e exits the script. The cleanup() trap at Lines 181-190 removes the FIFO and terminates active psql clients, but it does not drop the role.

    A later test execution against the same PostgreSQL cluster then fails at CREATE ROLE. Add role cleanup to the exit trap. The cleanup should tolerate a role that was never created.

The concurrency repair is correct. The first session stays idle in transaction after persist_document_record_once(...) returns. The FIFO keeps that transaction open. Before the test permits COMMIT, it requires the second session to have an ungranted advisory lock and requires pg_blocking_pids(...) to name the first backend. This proves real transaction-scoped advisory-lock contention without using elapsed time as serialization evidence.

The FIFO cleanup is also correct for the client processes. On an early exit, it closes the descriptor, terminates active first and second psql clients, and removes the temporary directory.

The RLS repair verifies runtime behavior. The temporary role is non-superuser and NOBYPASSRLS. It can read its tenant receipts, sees zero receipts under the other tenant context, and cannot update a hidden cross-tenant receipt. The catalog check also confirms FORCE ROW LEVEL SECURITY.

The function-local UTC digest repair, VOLATILE declaration, Read Committed guard, tenant-before-lock ordering, tenant-qualified receipt foreign key, and append-only receipt controls remain consistent with the stated contract.

I did not treat predecessor evidence as approval. I could not verify hosted PostgreSQL execution for this exact head.

You are interacting with an AI system.

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

Current exact head is 4757e24ae03db08c10d93ccf07f6ddbf9fe73a85. Your current-head finding was valid: the temporary NOBYPASSRLS probe role could survive an early assertion failure. This head gives each run a distinct probe principal and binds best-effort DROP OWNED + DROP ROLE cleanup into the existing EXIT trap, while reusing the same cleanup on the success path. Please verify the failure-path cleanup and the unchanged advisory-lock/RLS acceptance. Do not transfer predecessor approval/evidence.

@coderabbitai

coderabbitai Bot commented Sep 12, 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

repo="ContextualWisdomLab/Orgmetra"
base="7ce73aa44f47113b2ecd42d51bb5d38a22c0367d"
head="4757e24ae03db08c10d93ccf07f6ddbf9fe73a85"

echo '== Exact PR and commit identity =='
gh pr view 312 --repo "$repo" \
  --json number,state,isDraft,baseRefOid,headRefOid,mergeStateStatus,statusCheckRollup \
  --jq '{number,state,isDraft,baseRefOid,headRefOid,mergeStateStatus,checks:[.statusCheckRollup[]? | {name,status,conclusion,workflowName}]}'
printf 'checked_out_head='
git rev-parse HEAD
git merge-base --is-ancestor "$base" "$head" && echo 'base_is_ancestor=yes'

echo '== Changed files from stated base =='
git diff --name-status "$base" "$head"

echo '== Relevant artifact locations =='
fd -a -i \
  '0024_document_record_idempotent_persistence\.sql|test_document_record_idempotency(_(isolation|tenant_context))?_postgres\.sh|0309.*|document-record-idempotent-persistence.*' \
  . | sort

echo '== Main PostgreSQL acceptance contract =='
nl -ba tests/test_document_record_idempotency_postgres.sh

echo '== Related PostgreSQL acceptance contracts =='
for f in \
  tests/test_document_record_idempotency_isolation_postgres.sh \
  tests/test_document_record_idempotency_tenant_context_postgres.sh
do
  if [ -f "$f" ]; then
    echo "-- $f"
    nl -ba "$f"
  fi
done

echo '== Migration 0024 =='
nl -ba database/migrations/0024_document_record_idempotent_persistence.sql

echo '== Repair patch from predecessor head =='
git diff --check 8d28ab4a8beaf21a6405fce9b23b3642b7008924 "$head"
git diff --unified=100 8d28ab4a8beaf21a6405fce9b23b3642b7008924 "$head" -- \
  tests/test_document_record_idempotency_postgres.sh \
  database/migrations/0024_document_record_idempotent_persistence.sql \
  docs/adr/0309-document-record-idempotent-persistence.md \
  docs/traceability/document-record-idempotent-persistence.md

echo '== Cleanup, role lifecycle, advisory barrier, and RLS assertions =='
rg -n -A55 -B18 \
  'cleanup\(|trap|DROP OWNED|DROP ROLE|CREATE ROLE|NOBYPASSRLS|probe|mktemp|mkfifo|PGAPPNAME|pg_stat_activity|pg_locks|pg_blocking_pids|idle in transaction|advisory|SET ROLE|document_record_persist_receipt|UPDATE|DELETE|TRUNCATE' \
  --glob '*.sh' --glob '*.sql' tests database/migrations

echo '== Test discovery references =='
rg -n -C4 \
  'test_document_record_idempotency(_isolation|_tenant_context)?_postgres\.sh' \
  .github tests docs README.md package.json 2>/dev/null || true

Length of output: 202858


🏁 Script executed:

#!/bin/bash
set -euo pipefail

test="tests/test_document_record_idempotency_postgres.sh"
head="4757e24ae03db08c10d93ccf07f6ddbf9fe73a85"

echo '== Current head and focused patch =='
git rev-parse HEAD
git diff --unified=40 8d28ab4a8beaf21a6405fce9b23b3642b7008924 "$head" -- "$test"

echo '== Test setup, probe-role identifier, cleanup trap, and success cleanup =='
nl -ba "$test" | sed -n '1,230p'
nl -ba "$test" | sed -n '280,430p'

echo '== All shell control-flow paths that can run after role creation =='
rg -n -A12 -B12 \
  'PROBE|probe|cleanup|trap|exit [0-9]+|DROP OWNED|DROP ROLE|CREATE ROLE|SET ROLE|RESET ROLE' \
  "$test"

echo '== Advisory-lock proof and RLS assertions =='
rg -n -A55 -B15 \
  'first.*backend|second.*backend|pg_stat_activity|pg_locks|pg_blocking_pids|idle in transaction|advisory|NOBYPASSRLS|relforcerowsecurity|cross-tenant|cross_tenant|UPDATE' \
  "$test"

echo '== Shell syntax parse =='
bash -n "$test"
echo 'bash_syntax=valid'

Length of output: 45631


@seonghobae I reviewed exact head 4757e24ae03db08c10d93ccf07f6ddbf9fe73a85.

I found no new issues.

The failure-path cleanup fixes the prior finding. PROBE_ROLE now includes ${BASHPID}. This prevents normal concurrent runs from using the same probe principal. The EXIT trap calls cleanup(). cleanup() calls cleanup_probe_role() before it removes the temporary directory. cleanup_probe_role() checks for the role, then performs best-effort DROP OWNED BY and DROP ROLE. An assertion failure after role creation therefore enters the same cleanup path as a successful run. The success path also calls cleanup_probe_role() before the append-only assertion.

The advisory-lock acceptance remains correct. The first session must reach idle in transaction. The second session must show an ungranted advisory lock. pg_blocking_pids(...) must name the first backend before the test permits the first transaction to commit.

The receipt RLS acceptance remains correct. The temporary principal is NOBYPASSRLS. It can read tenant-alpha receipts. It sees zero receipts with tenant-beta context. It cannot update a tenant-alpha receipt with tenant-beta context.

Static shell validation passed with bash -n. I did not verify hosted PostgreSQL execution for this exact head. I did not use predecessor evidence as approval.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

You are interacting with an AI system.

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

Current exact head advanced to be064e24280375c7eecb4b9e910f65d1145d434b. The cleanup repair now distinguishes paths deliberately: the EXIT trap is best-effort so it cannot mask the original failing assertion, while the normal success path is strict and fails the contract if role existence cannot be verified or DROP OWNED/DROP ROLE fails. Please review this exact head; predecessor 4757e24... is not acceptance evidence.

@coderabbitai

coderabbitai Bot commented Sep 12, 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

repo="ContextualWisdomLab/Orgmetra"
base="7ce73aa44f47113b2ecd42d51bb5d38a22c0367d"
previous="4757e24ae03db08c10d93ccf07f6ddbf9fe73a85"
expected_head="be064e24280375c7eecb4b9e910f65d1145d434b"

echo '== Pull request identity and requested commit =='
gh pr view 312 --repo "$repo" \
  --json number,state,isDraft,baseRefOid,headRefOid,mergeStateStatus,statusCheckRollup \
  --jq '{number,state,isDraft,baseRefOid,headRefOid,mergeStateStatus,checks:[.statusCheckRollup[]? | {name,status,conclusion,workflowName}]}'
printf 'checked_out_head='
git rev-parse HEAD
git merge-base --is-ancestor "$base" "$expected_head" && echo 'base_is_ancestor=yes'

echo '== Complete changed-file list from stated base =='
git diff --name-status "$base" "$expected_head"

echo '== Repair delta from preceding head =='
git diff --check "$previous" "$expected_head"
git diff --unified=100 "$previous" "$expected_head" -- \
  tests/test_document_record_idempotency_postgres.sh \
  database/migrations/0024_document_record_idempotent_persistence.sql \
  tests/test_document_record_idempotency_isolation_postgres.sh \
  tests/test_document_record_idempotency_tenant_context_postgres.sh \
  docs/adr/0309-document-record-idempotent-persistence.md \
  docs/traceability/document-record-idempotent-persistence.md

echo '== Locate current review artifacts =='
fd -a -i \
  '0021_document_record_persistence\.sql|0024_document_record_idempotent_persistence\.sql|test_document_record_idempotency(_(isolation|tenant_context))?_postgres\.sh|0309.*|document-record-idempotent-persistence.*' \
  . | sort

echo '== Main acceptance test: setup, cleanup paths, role lifecycle, and append-only assertion =='
nl -ba tests/test_document_record_idempotency_postgres.sh | sed -n '1,460p'

echo '== Cleanup and probe-role paths with context =='
rg -n -A60 -B20 \
  'cleanup\(|cleanup_probe_role|trap|EXIT|DROP OWNED|DROP ROLE|CREATE ROLE|PROBE_ROLE|NOBYPASSRLS|exit [0-9]+|return [0-9]+' \
  tests/test_document_record_idempotency_postgres.sh

echo '== Advisory lock evidence and runtime RLS assertions =='
rg -n -A65 -B18 \
  'mkfifo|PGAPPNAME|application_name|idle in transaction|pg_stat_activity|pg_locks|pg_blocking_pids|advisory|NOBYPASSRLS|SET ROLE|RESET ROLE|document_record_persist_receipt|cross-tenant|UPDATE|DELETE|TRUNCATE' \
  tests/test_document_record_idempotency_postgres.sh

echo '== Persistence function, receipt DDL, RLS, and immutability =='
nl -ba database/migrations/0024_document_record_idempotent_persistence.sql

echo '== Related PostgreSQL contracts =='
for f in \
  tests/test_document_record_idempotency_isolation_postgres.sh \
  tests/test_document_record_idempotency_tenant_context_postgres.sh
do
  if [ -f "$f" ]; then
    echo "-- $f"
    nl -ba "$f"
  fi
done

echo '== Shell static validation =='
bash -n tests/test_document_record_idempotency_postgres.sh
echo 'bash_syntax=valid'

echo '== Test discovery references =='
rg -n -C4 \
  'test_document_record_idempotency(_isolation|_tenant_context)?_postgres\.sh' \
  .github tests docs README.md package.json 2>/dev/null || true

Length of output: 100305


@seonghobae I reviewed exact head be064e24280375c7eecb4b9e910f65d1145d434b from base 7ce73aa44f47113b2ecd42d51bb5d38a22c0367d.

I found no new issues.

The cleanup split is correct.

  • cleanup() calls cleanup_probe_role best-effort from the EXIT trap.
  • If the role lookup or role removal fails during failure handling, the trap returns successfully. It does not mask the original assertion failure.
  • The normal path calls cleanup_probe_role strict.
  • In strict mode, a failed role-existence query causes a nonzero return.
  • In strict mode, failure of DROP OWNED BY or DROP ROLE causes a nonzero return.
  • If the role does not exist, cleanup succeeds. This supports failures before role creation.

The prior failure-path protection remains in place. PROBE_ROLE includes ${BASHPID}, and the EXIT trap removes the role on an early RLS assertion failure when PostgreSQL is available.

The advisory-lock acceptance remains valid. The first session remains idle in transaction. The second session must show an ungranted advisory lock. pg_blocking_pids(...) must identify the first backend before the test commits the first transaction.

The RLS acceptance remains valid. The NOBYPASSRLS probe role can read its tenant rows. It cannot read or update rows under the other tenant context.

bash -n tests/test_document_record_idempotency_postgres.sh passed. I did not verify hosted PostgreSQL execution for this exact head. I did not use predecessor 4757e24... evidence as current-head acceptance.

You are interacting with an AI system.

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

Current exact head is now a9dc83aaf139f4f0bf0ee1ddb70cf2ba37000866, a documentation-only descendant of code head be064e24280375c7eecb4b9e910f65d1145d434b that you reviewed with no new issues. The new commit only currentizes traceability for the failure-safe RLS probe-principal cleanup. Please verify the exact current delta and do not treat the predecessor review as formal approval for this head.

@coderabbitai

coderabbitai Bot commented Sep 12, 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

repo="ContextualWisdomLab/Orgmetra"
base="7ce73aa44f47113b2ecd42d51bb5d38a22c0367d"
previous="be064e24280375c7eecb4b9e910f65d1145d434b"
expected_head="a9dc83aaf139f4f0bf0ee1ddb70cf2ba37000866"

echo '== Pull request and exact commit identity =='
gh pr view 312 --repo "$repo" \
  --json number,state,isDraft,baseRefOid,headRefOid,mergeStateStatus,statusCheckRollup \
  --jq '{number,state,isDraft,baseRefOid,headRefOid,mergeStateStatus,checks:[.statusCheckRollup[]? | {name,status,conclusion,workflowName}]}'
printf 'checked_out_head='
git rev-parse HEAD
git merge-base --is-ancestor "$base" "$expected_head" && echo 'base_is_ancestor=yes'
git merge-base --is-ancestor "$previous" "$expected_head" && echo 'previous_is_ancestor=yes'

echo '== Current exact delta from the reviewed code head =='
git diff --check "$previous" "$expected_head"
git diff --name-status "$previous" "$expected_head"
git diff --unified=100 "$previous" "$expected_head"

echo '== Complete base-to-current-head changed-file list =='
git diff --name-status "$base" "$expected_head"

echo '== Traceability artifact and relevant contract context =='
fd -a -i 'document-record-idempotent-persistence.*|test_document_record_idempotency_postgres\.sh|0024_document_record_idempotent_persistence\.sql' . | sort
trace_file="$(fd -a -i 'document-record-idempotent-persistence.*' docs | head -n1 || true)"
if [ -n "$trace_file" ]; then
  echo "-- $trace_file"
  nl -ba "$trace_file"
fi

echo '== Cleanup, advisory-lock, and RLS acceptance context at current head =='
test="tests/test_document_record_idempotency_postgres.sh"
if [ -f "$test" ]; then
  rg -n -A60 -B18 \
    'cleanup\(|cleanup_probe_role|trap|DROP OWNED|DROP ROLE|CREATE ROLE|PROBE_ROLE|NOBYPASSRLS|mkfifo|idle in transaction|pg_stat_activity|pg_locks|pg_blocking_pids|advisory|SET ROLE|RESET ROLE|append-only' \
    "$test"
  bash -n "$test"
  echo 'bash_syntax=valid'
fi

echo '== Test discovery references =='
rg -n -C4 \
  'test_document_record_idempotency(_isolation|_tenant_context)?_postgres\.sh|document-record-idempotent' \
  .github tests docs README.md package.json 2>/dev/null || true

Length of output: 43211


@seonghobae I reviewed exact head a9dc83aaf139f4f0bf0ee1ddb70cf2ba37000866 from base 7ce73aa44f47113b2ecd42d51bb5d38a22c0367d.

I found no new issues.

The exact delta from be064e24280375c7eecb4b9e910f65d1145d434b modifies only docs/traceability/document-record-idempotent-persistence.md.

The traceability update is accurate.

  • It records the run-unique NOBYPASSRLS probe-role cleanup repair at 4757e24....
  • It records the strict success-path cleanup repair at be064e....
  • It distinguishes best-effort cleanup in the EXIT trap from strict cleanup on the normal success path.
  • It states that exact-head re-review and hosted PostgreSQL execution remain pending.
  • It does not represent predecessor review as approval for this head.

The current acceptance script retains the FIFO-held first transaction, the observable advisory-lock wait check through pg_locks and pg_blocking_pids(...), and the runtime RLS assertions under the temporary NOBYPASSRLS role.

bash -n tests/test_document_record_idempotency_postgres.sh passed.

I did not verify hosted PostgreSQL execution for this exact head.

You are interacting with an AI system.

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

Current exact head is fb8da85bc62df519828c480a3f07b8a44be344ee. Please review the ordinary-forward delta from a9dc83aaf139f4f0bf0ee1ddb70cf2ba37000866, especially the temporary NOBYPASSRLS probe-principal identity and cleanup lifecycle. Do not transfer the predecessor verdict.

@coderabbitai

coderabbitai Bot commented Sep 12, 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

repo="ContextualWisdomLab/Orgmetra"
base="a9dc83aaf139f4f0bf0ee1ddb70cf2ba37000866"
head="fb8da85bc62df519828c480a3f07b8a44be344ee"
test="tests/test_document_record_idempotency_postgres.sh"

echo '== PR identity and requested commit =='
gh pr view 312 --repo "$repo" \
  --json number,state,isDraft,baseRefOid,headRefOid,mergeStateStatus,statusCheckRollup \
  --jq '{number,state,isDraft,baseRefOid,headRefOid,mergeStateStatus,checks:[.statusCheckRollup[]? | {name,status,conclusion,workflowName}]}'
printf 'checked_out_head='
git rev-parse HEAD
git merge-base --is-ancestor "$base" "$head" && echo 'base_is_ancestor=yes'

echo '== Exact ordinary-forward delta =='
git diff --check "$base" "$head"
git diff --name-status "$base" "$head"
git diff --unified=100 "$base" "$head"

echo '== Full current test contract =='
nl -ba "$test"

echo '== Probe-principal identity and cleanup lifecycle =='
rg -n -A70 -B25 \
  'PROBE_ROLE|probe.*role|uuid|uuidgen|/proc/sys/kernel/random/uuid|openssl|CREATE ROLE|cleanup_probe_role|DROP OWNED|DROP ROLE|cleanup\(|trap.*EXIT|EXIT|best-effort|strict' \
  "$test"

echo '== Cleanup call sites and shell control flow =='
rg -n -A20 -B12 \
  'cleanup_probe_role\s|cleanup\s|trap\s|exit\s|return\s|CREATE ROLE|DROP OWNED|DROP ROLE' \
  "$test"

echo '== Related lock and RLS acceptance remains present =='
rg -n -A50 -B15 \
  'mkfifo|idle in transaction|pg_stat_activity|pg_locks|pg_blocking_pids|advisory|NOBYPASSRLS|SET ROLE|RESET ROLE|relforcerowsecurity' \
  "$test"

echo '== Static shell syntax =='
bash -n "$test"
echo 'bash_syntax=valid'

echo '== Test references/discovery =='
rg -n -C3 \
  'test_document_record_idempotency_postgres\.sh' \
  .github tests docs README.md package.json 2>/dev/null || true

Length of output: 79309


@seonghobae I reviewed exact head fb8da85bc62df519828c480a3f07b8a44be344ee against a9dc83aaf139f4f0bf0ee1ddb70cf2ba37000866.

I found no new issues.

The delta changes only tests/test_document_record_idempotency_postgres.sh.

PROBE_ROLE_SUFFIX now derives from uuid.uuid4().hex[:24]. The resulting probe-role name is fresh for each test execution. It avoids the collision risk from ${BASHPID}, which is process-local and can be reused by another runner, container, or later process against the same database.

The generated role name remains within PostgreSQL's identifier-length limit.

The cleanup lifecycle remains correct.

  • The EXIT trap calls cleanup_probe_role best-effort.
  • Failure-path cleanup does not mask the original assertion failure.
  • The normal path calls cleanup_probe_role strict.
  • Strict cleanup fails the contract if role lookup, DROP OWNED, or DROP ROLE fails.
  • The role-existence check still permits cleanup before role creation.
  • The trap still removes a role after an early RLS assertion failure.

The advisory-lock and RLS acceptance remains unchanged. The first transaction stays open through the FIFO. The second session must expose an ungranted advisory lock and list the first backend in pg_blocking_pids(...). The temporary principal remains NOBYPASSRLS.

bash -n tests/test_document_record_idempotency_postgres.sh passed.

I did not verify real PostgreSQL execution or hosted acceptance for this exact head. I did not transfer the predecessor verdict.

You are interacting with an AI system.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant