Skip to content

fix(escrow): add GET DIAGNOSTICS row_count guards to auto_release_milestones - #23

Merged
shaiksohelll merged 2 commits into
mainfrom
fix/auto-release-row-count-guard
Jun 4, 2026
Merged

shaiksohelll merged 2 commits into
mainfrom
fix/auto-release-row-count-guard

Conversation

@shaiksohelll

@shaiksohelll shaiksohelll commented Jun 4, 2026

Copy link
Copy Markdown
Owner

User description

Problem

Audit finding F1 (MEDIUM): The two wallet UPDATEs in auto_release_milestones (client debit, worker credit) lacked GET DIAGNOSTICS row_count verification.

If either wallet row were missing, the UPDATE would silently affect 0 rows — money would vanish from the client's locked balance without arriving at the worker.

Every other money-path RPC (fund_escrow, approve_milestone, withdraw_wallet, topup_wallet) already has this guard.

Fix

New forward-only migration 20260604060000_auto_release_row_count_guard.sql that CREATE OR REPLACEs auto_release_milestones() with:

-- After client debit:
get diagnostics v_rows = row_count;
if v_rows <> 1 then
  raise exception 'pakka:wallet_not_found: ...' using errcode = 'P0002';
end if;

-- After worker credit:
get diagnostics v_rows = row_count;
if v_rows <> 1 then
  raise exception 'pakka:wallet_not_found: ...' using errcode = 'P0002';
end if;

Everything else (FOR UPDATE, status guard, ledger insert order, REVOKE/GRANT) is identical to the prior version.

Validation

  • tsc --noEmit — clean
  • vitest run — 22/22 pass
  • npx supabase db push — migration applied to dev
  • scratch/test_concurrent.ts — approve + auto-release case: money moves exactly once, 1 ledger row, correct balances

Diff

1 file changed: supabase/migrations/20260604060000_auto_release_row_count_guard.sql (+146)

No existing migrations modified.


CodeAnt-AI Description

Protect automatic milestone release from silently losing money

What Changed

  • Automatic milestone release now checks that both wallet updates affected exactly one wallet before moving funds
  • If a client or worker wallet is missing, the release now stops with a clear wallet-not-found error instead of silently dropping the transfer
  • The rest of the release flow stays the same, including milestone status updates, ledger entries, job completion, and user notifications

Impact

✅ Fewer lost escrow transfers
✅ Clearer auto-release failures
✅ Safer milestone payouts

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

Summary by CodeRabbit

  • Chores

    • Updated project configuration to exclude temporary JSON files from version control while preserving essential configuration files.
  • Improvements

    • Enhanced the automatic milestone release process with validation safeguards to ensure wallet transactions complete successfully and prevent data inconsistencies.

@codeant-ai

codeant-ai Bot commented Jun 4, 2026

Copy link
Copy Markdown

CodeAnt AI is reviewing your PR.


Thanks for using CodeAnt! 🎉

We're free for open-source projects. if you're enjoying it, help us grow by sharing.

Share on X ·
Reddit ·
LinkedIn

@vercel

vercel Bot commented Jun 4, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
pakka Ready Ready Preview, Comment Jun 4, 2026 7:40am

@coderabbitai

coderabbitai Bot commented Jun 4, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@shaiksohelll, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 27 minutes and 10 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 8d3a7ff9-94c4-4302-8585-64760fe5af9d

📥 Commits

Reviewing files that changed from the base of the PR and between d659881 and 655cb56.

📒 Files selected for processing (1)
  • supabase/migrations/20260604060000_auto_release_row_count_guard.sql
📝 Walkthrough

Walkthrough

This PR contains two independent changes: a .gitignore update to exclude temporary JSON files, and a database migration that adds diagnostic guards to wallet transaction operations in the automatic milestone release function to prevent silent transaction failures.

Changes

Temporary JSON files configuration

Layer / File(s) Summary
Temporary JSON files pattern
.gitignore
Root-level /*.json files are now ignored except package*.json, tsconfig*.json, and jsconfig.json.

Wallet update diagnostics guard

Layer / File(s) Summary
Wallet transaction safety diagnostics
supabase/migrations/20260604060000_auto_release_row_count_guard.sql
The auto_release_milestones() function is recreated with GET DIAGNOSTICS row_count checks immediately after both wallet debit and credit UPDATE statements. If either UPDATE affects a row count other than 1, the function raises a pakka:wallet_not_found exception. The rest of the release flow—milestone status update, job completion, ledger entry, notifications, and permission restrictions—remains intact.

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • shaiksohelll/Pakka#20: Directly related prior modifications to auto_release_milestones() release flow and constraint handling.

Suggested labels

size:L

🐰 A wallet now stands firm, with guards checked twice,
No silent failures slip through the ice.
Temporary files hop away with care,
Safe transactions bloom everywhere! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix(escrow): add GET DIAGNOSTICS row_count guards to auto_release_milestones' directly and specifically describes the main change: adding row_count guards to the auto_release_milestones function in the escrow system.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/auto-release-row-count-guard

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 and usage tips.

@codeant-ai codeant-ai Bot added the size:L This PR changes 100-499 lines, ignoring generated files label Jun 4, 2026
@codeant-ai

codeant-ai Bot commented Jun 4, 2026

Copy link
Copy Markdown

CodeAnt AI finished reviewing your PR.

@greptile-apps

greptile-apps Bot commented Jun 4, 2026

Copy link
Copy Markdown

Greptile Summary

This migration adds GET DIAGNOSTICS row_count guards to the two wallet UPDATE statements in auto_release_milestones() and — critically — adds a WHEN SQLSTATE 'P0002' branch to the per-milestone exception handler so that a missing wallet skips only that milestone rather than aborting the entire pg_cron batch.

  • The WHEN SQLSTATE 'P0002' handler directly addresses the previous audit finding: without it, a wallet-not-found error would propagate out of the subtransaction and roll back every milestone already released in the same cron run.
  • A new explicit client-wallet existence check (lines 60-64) cleanly separates the "wallet missing → P0002 skip" path from the "wallet present but underfunded → NOTICE skip" path; the worker wallet relies solely on the GET DIAGNOSTICS guard, which is correct and sufficient.
  • The .gitignore change adds a blanket /*.json rule to prevent scratch JSON files from being committed, with negations for the standard config files.

Confidence Score: 5/5

Safe to merge — the core escrow logic is correct, the wallet-not-found exception is now properly caught per-milestone, and no existing migration is modified.

The SQL function change is a targeted, forward-only CREATE OR REPLACE that adds the missing exception handler and row_count guards without touching any other code path. The wallet debit/credit logic, ledger ordering, and permission lockdown are unchanged. Both findings are non-blocking observations that do not affect correctness or safety.

No files require special attention — the migration is the only substantive change and its logic is sound.

Important Files Changed

Filename Overview
supabase/migrations/20260604060000_auto_release_row_count_guard.sql Adds GET DIAGNOSTICS row_count guards for both wallet UPDATEs and a when sqlstate 'P0002' handler so a missing wallet skips that milestone instead of aborting the whole cron batch; logic is sound but the client-debit row_count check (lines 76-79) is logically unreachable since the row is already locked and verified to exist.
.gitignore Adds /*.json blanket ignore for root-level JSON files, but components.json (shadcn/ui config) is not covered by any negation pattern — currently safe because the file is already tracked, but this creates a footgun for the future.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[pg_cron fires auto_release_milestones] --> B[Cursor: submitted milestones past auto_release_at\nFOR UPDATE OF m SKIP LOCKED]
    B --> C{More rows?}
    C -- No --> Z[Return v_count]
    C -- Yes --> D[BEGIN subtransaction]
    D --> E[PERFORM wallets FOR UPDATE\nlock both in profile_id order]
    E --> F{Client wallet exists?}
    F -- No --> G[RAISE P0002 wallet_not_found]
    F -- Yes --> H{Client locked_balance >= amount?}
    H -- No --> I[RAISE NOTICE: underfunded, continue loop]
    I --> C
    H -- Yes --> J[UPDATE wallets DEBIT client locked_balance]
    J --> K{GET DIAGNOSTICS v_rows = 1?}
    K -- No, dead path --> G
    K -- Yes --> L[UPDATE wallets CREDIT worker available_balance]
    L --> M{GET DIAGNOSTICS v_rows = 1?}
    M -- No, worker wallet missing --> G
    M -- Yes --> N[UPDATE milestones status=released]
    N --> O[INSERT escrow_ledger]
    O --> P{All milestones released or refunded?}
    P -- Yes --> Q[UPDATE jobs status=completed]
    P -- No --> R[INSERT notifications x2]
    Q --> R
    R --> S[v_count + 1, END subtransaction]
    S --> C
    G --> T{EXCEPTION handler}
    T -- unique_violation --> U[RAISE WARNING: duplicate blocked]
    T -- P0002 --> V[RAISE WARNING: wallet not found]
    U --> C
    V --> C
Loading

Reviews (3): Last reviewed commit: "fix(escrow): add GET DIAGNOSTICS row_cou..." | Re-trigger Greptile

Comment thread supabase/migrations/20260604060000_auto_release_row_count_guard.sql

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@supabase/migrations/20260604060000_auto_release_row_count_guard.sql`:
- Around line 49-54: The current IF uses an EXISTS check on public.wallets
(select 1 ... where w.profile_id = v_milestone.client_id and w.locked_balance >=
v_milestone.amount) which conflates "wallet missing" and "insufficient
locked_balance" and thus never triggers the new wallet_not_found / row_count
guard; change the logic to first check for the existence of a wallet row for
v_milestone.client_id (e.g., EXISTS(select 1 from public.wallets w where
w.profile_id = v_milestone.client_id)) and, if missing, raise/route to the
wallet_not_found / P0002 path, otherwise check locked_balance >=
v_milestone.amount and only then treat as underfunded, ensuring the row_count
guard executes when no wallet row exists.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 4a9968fa-ac80-4522-9bea-1a3f02082e2c

📥 Commits

Reviewing files that changed from the base of the PR and between aef1499 and d659881.

📒 Files selected for processing (2)
  • .gitignore
  • supabase/migrations/20260604060000_auto_release_row_count_guard.sql

Comment thread supabase/migrations/20260604060000_auto_release_row_count_guard.sql
…estones

The two wallet UPDATEs in auto_release_milestones (client debit, worker
credit) lacked row_count verification. If either wallet row were missing,
the UPDATE would silently affect 0 rows — money would vanish from the
client's locked balance without arriving at the worker.

Every other money-path RPC (fund_escrow, approve_milestone, withdraw_wallet,
topup_wallet) already has this guard. This forward-only migration brings
auto_release into line.

Additionally:
- The per-milestone EXCEPTION handler now catches SQLSTATE P0002
  (wallet_not_found) so a missing wallet skips that milestone and
  continues the loop, instead of aborting the entire pg_cron batch.
- The client-wallet check is split: first verify the wallet row exists
  (route to P0002 if missing), then check locked_balance >= amount
  (route to the underfunded skip path if insufficient).

Fixes: audit finding F1 (MEDIUM)
Addresses: Greptile (batch-abort blast radius), CodeRabbit (client-wallet conflation)
Tested: scratch/test_f1_isolation.ts (multi-milestone: A released, B skipped, count=1)
         scratch/test_f1_guard.ts (single missing wallet: count=0, balance unchanged)
         scratch/test_concurrent.ts (happy path: money moves exactly once)
@shaiksohelll

Copy link
Copy Markdown
Owner Author

@greptile-apps review

@shaiksohelll

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 4, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

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.

@shaiksohelll
shaiksohelll merged commit 5628728 into main Jun 4, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant