Skip to content

Conversation

@fogelito
Copy link
Contributor

@fogelito fogelito commented Aug 31, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Improved transaction reliability with retry and backoff, reducing intermittent failures.
    • Immediate fail-fast on non-retriable errors for clearer, earlier feedback.
    • Consistent transaction state reset to prevent stuck or misreported states.
    • More accurate error surfacing during rollbacks for better diagnostics.
  • Refactor

    • Simplified transaction start/rollback logic for clearer behavior and maintenance.
    • Removed an unused dependency from the SQL adapter to reduce overhead.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 31, 2025

Walkthrough

Refactors transaction handling. Adapter::withTransaction adds explicit retry loop with backoff and immediate bail-outs for specific exceptions, resetting inTransaction as needed. SQL adapter simplifies startTransaction and rollbackTransaction to direct PDO calls, adjusts inTransaction, and changes rollback exception wrapping to DatabaseException.

Changes

Cohort / File(s) Summary
Transaction retry and error handling
src/Database/Adapter.php
Adds configurable retry loop (2 retries, 50ms incremental backoff) in withTransaction. Introduces early rethrow for specific exceptions (Duplicate, Restricted, Authorization, Relationship, Conflict, Limit). Ensures inTransaction reset on exit paths. Throws TransactionException on repeated failure.
SQL adapter transaction methods
src/Database/Adapter/SQL.php
Removes Spatial import. Simplifies startTransaction and rollbackTransaction to direct PDO calls with inTransaction adjustments; returns true on success. Changes rollback exception wrapping to DatabaseException. No signature changes; commitTransaction unchanged.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client Code
  participant A as Adapter::withTransaction
  participant DB as SQL Adapter / PDO

  Note over A: New retry flow with backoff
  C->>A: withTransaction(callback)
  loop up to 3 attempts
    A->>DB: startTransaction()
    alt callback succeeds
      A->>DB: commitTransaction()
      A-->>C: return result
    else callback throws
      alt Non-retriable exception (Duplicate/Restricted/Auth/Relation/Conflict/Limit)
        A->>DB: rollbackTransaction()
        A-->>C: rethrow immediately
      else Retriable failure
        A->>DB: rollbackTransaction()
        Note over A: usleep(50ms × (attempt+1))
      end
    end
  end
  A-->>C: throw TransactionException("Failed to execute transaction")
Loading
sequenceDiagram
  autonumber
  participant A as SQL Adapter
  participant PDO as PDO

  Note over A: Simplified start/rollback
  A->>PDO: beginTransaction() or SAVEPOINT
  A->>A: inTransaction++
  A-->>A: return true

  A->>PDO: ROLLBACK TO savepoint or rollBack()
  A->>A: adjust inTransaction (decrement/reset)
  A-->>A: return true
  Note over A: On PDOException during rollback -> wrap as DatabaseException
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

A rabbit taps the transaction drum,
Three hops forward, backoff hum—
If thorns appear (conflicts, limits), flee!
Otherwise, retry hop two and three.
SQL burrows smoothed, quick rollbacks glide—
Carrot-commits when tests abide. 🥕✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch with-transaction

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

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

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/Database/Adapter.php (2)

351-359: Doc contradicts implementation of nested rollbacks

Doc says "roll back all transactions," but SQL adapters roll back only one level via SAVEPOINT. This discrepancy can mislead callers and breaks expectations in withTransaction.

Action: either update the doc to "single-level rollback (savepoint)" semantics or change adapters to roll back all levels. Given existing nested semantics elsewhere, updating the doc is likely correct.


379-421: Drain all nested transactions before retry or bail-out

Resetting $this->inTransaction to 0 without fully rolling back leaves the underlying connection in a transaction when callbacks used nested transactions. Ensure you drain to the top by looping rollbackTransaction until 0.

Apply this diff:

         for ($attempts = 0; $attempts <= $retries; $attempts++) {
             try {
                 $this->startTransaction();
                 $result = $callback();
                 $this->commitTransaction();
                 return $result;
             } catch (\Throwable $action) {
                 try {
-                    $this->rollbackTransaction();
+                    $this->rollbackTransaction();
+                    // Ensure we fully reset DB state (drain nested savepoints)
+                    while ($this->inTransaction > 0) {
+                        $this->rollbackTransaction();
+                    }
 
                     if (
                         $action instanceof DuplicateException ||
                         $action instanceof RestrictedException ||
                         $action instanceof AuthorizationException ||
                         $action instanceof RelationshipException ||
                         $action instanceof ConflictException ||
                         $action instanceof LimitException
                     ) {
                         $this->inTransaction = 0;
                         throw $action;
                     }
 
                 } catch (\Throwable $rollback) {
                     if ($attempts < $retries) {
                         \usleep($sleep * ($attempts + 1));
                         continue;
                     }
 
                     $this->inTransaction = 0;
                     throw $rollback;
                 }
 
                 if ($attempts < $retries) {
                     \usleep($sleep * ($attempts + 1));
                     continue;
                 }
 
                 $this->inTransaction = 0;
                 throw $action;
             }
         }
🧹 Nitpick comments (3)
src/Database/Adapter/SQL.php (2)

59-72: Avoid unconditional ROLLBACK when no transaction is active

Issuing ROLLBACK outside an active transaction can error on some drivers. Since you already guard with inTransaction(), the else-branch is unnecessary and risky.

Apply this diff:

             if ($this->getPDO()->inTransaction()) {
                 $this->getPDO()->rollBack();
-            } else {
-                // If no active transaction, this has no effect.
-                $this->getPDO()->prepare('ROLLBACK')->execute();
             }
 
             $this->getPDO()->beginTransaction();

131-131: Use TransactionException for rollback errors for consistency

startTransaction/commitTransaction throw TransactionException. Align rollback to the same specialized exception.

-            throw new DatabaseException('Failed to rollback transaction: ' . $e->getMessage(), $e->getCode(), $e);
+            throw new TransactionException('Failed to rollback transaction: ' . $e->getMessage(), $e->getCode(), $e);
src/Database/Adapter.php (1)

379-381: Make backoff configurable (optional)

Expose $retries and $sleep as adapter-level configurables (properties or setter) rather than hardcoding, so callers can tune per environment.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 8a536fe and 18a2875.

📒 Files selected for processing (2)
  • src/Database/Adapter.php (3 hunks)
  • src/Database/Adapter/SQL.php (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
src/Database/Adapter.php (4)
src/Database/Exception.php (1)
  • Exception (7-21)
src/Database/Exception/Conflict.php (1)
  • Conflict (7-9)
src/Database/Exception/Relationship.php (1)
  • Relationship (7-9)
src/Database/Exception/Restricted.php (1)
  • Restricted (7-9)
src/Database/Adapter/SQL.php (1)
src/Database/Adapter.php (1)
  • inTransaction (366-369)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Setup & Build Docker Image
🔇 Additional comments (1)
src/Database/Adapter.php (1)

7-12: LGTM: granular bail-out imports

Adding Authorization/Conflict/Relationship/Restricted/Limit exceptions enables clearer early exits. No concerns.

@fogelito fogelito requested a review from abnegate August 31, 2025 13:20
@abnegate abnegate merged commit 87fb55e into main Sep 1, 2025
15 checks passed
@abnegate abnegate deleted the with-transaction branch September 1, 2025 06:01
@coderabbitai coderabbitai bot mentioned this pull request Sep 18, 2025
@coderabbitai coderabbitai bot mentioned this pull request Sep 26, 2025
Merged
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.

3 participants