Repository navigation
fix(databases): lock the transaction while staging operations - #14384
Conversation
…staging Staging read the transaction, checked its status and operation limit, and wrote the logs later without a lock. Concurrent requests all passed the limit check, and logs written after a commit had read them were acknowledged but never applied. Every staging path now writes through stage(), which locks the transaction row, checks status and limit again, then inserts the logs and increments the counter in the same database transaction. The transaction is purged from the cache after COMMIT, so a concurrent read cannot leave a stale operation count behind.
A commit that found no logs marked the transaction committed without taking the lock, so operations staged at the same moment were lost. Claim the transaction first, then read its logs; staging takes the same lock and is refused once the transaction is no longer pending.
|
Review complete. 🟡 1 medium 💬 Inline comments (1)
The change reworks the Databases transaction lifecycle so a commit or rollback claims the transaction (status
Reviewed commit: 1f364da |
🔵 Tier A · Mergeable after minor fixes
Transaction staging now locks the transaction row while checking status and operation limits, then stores logs and updates the count atomically; commit claims the transaction before reading its logs. The staging endpoints share this path, and cache invalidation prevents stale operation counts after writes. The latest commit adds type annotations for values set inside the commit closure and read by its error handlers. Latest changes: The newest commit documents the types of the commit error-context variables that are populated by reference inside the closure.
Fix with agent prompt### Issue 1
src/Appwrite/Platform/Modules/Databases/Http/Databases/Action.php:225
**Add coverage for concurrent staging and commit**
The existing transaction e2e suite covers concurrent commits, but does not exercise concurrent staging at the operation limit or staging racing with a commit. Those are the behaviors changed here and the regressions this fix addresses, so they could break again while the current suites still pass.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.📂 Walkthrough · 12
⏳ Still open from earlier reviews · 1
Merged |
| $current = new Document(); | ||
|
|
||
| $transaction = $dbForProject->withTransaction(function () use ($dbForProject, $transactionId, $logs, $max, &$current) { | ||
| $current = $dbForProject->getDocument('transactions', $transactionId, forUpdate: true); |
There was a problem hiding this comment.
Add coverage for concurrent staging and commit
The existing transaction e2e suite covers concurrent commits, but does not exercise concurrent staging at the operation limit or staging racing with a commit. Those are the behaviors changed here and the regressions this fix addresses, so they could break again while the current suites still pass.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Platform/Modules/Databases/Http/Databases/Action.php
Line: 225
Comment:
**Add coverage for concurrent staging and commit**
The existing transaction e2e suite covers concurrent commits, but does not exercise concurrent staging at the operation limit or staging racing with a commit. Those are the behaviors changed here and the regressions this fix addresses, so they could break again while the current suites still pass.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.🟡 Minor · testing · Reply if this doesn't apply.
Security rulesNo new WARNING or ERROR findings from security rules. 6 existing findings tracked in
|
There was a problem hiding this comment.
This PR refines commit/rollback handling for database transactions in the Databases module, claiming transactions before applying staged operations and purging caches across document actions.
Key findings
- 🟡 Failure between claim and try leaves transaction stuck in
committing— Update.php:172
| $transaction = ($isAPIKey || $isPrivilegedUser) | ||
| ? $authorization->skip(fn () => $dbForProject->withTransaction($claim)) | ||
| : $dbForProject->withTransaction($claim); | ||
|
|
||
| if ($transaction->isEmpty()) { | ||
| throw new Exception(Exception::TRANSACTION_NOT_READY); | ||
| } | ||
|
|
||
| $firstOperation = $authorization->skip(fn () => $dbForProject->findOne('transactionLogs', [ | ||
| Query::equal('transactionInternalId', [$transaction->getSequence()]), | ||
| Query::orderAsc(), | ||
| ])); | ||
|
|
||
| if ($firstOperation->isEmpty()) { | ||
| $transaction = $authorization->skip(fn () => $dbForProject->updateDocument( | ||
| 'transactions', | ||
| $transactionId, | ||
| new Document(['status' => 'committed']) | ||
| )); | ||
|
|
||
| $publisherForDeletes->enqueue(new DeleteMessage( | ||
| project: $project, | ||
| type: DELETE_TYPE_DOCUMENT, | ||
| document: $transaction, | ||
| )); | ||
|
|
||
| $response | ||
| ->setStatusCode(SwooleResponse::STATUS_CODE_OK) | ||
| ->dynamic($transaction, $this->getResponseModel()); | ||
|
|
||
| return; | ||
| } | ||
|
|
There was a problem hiding this comment.
🟡 bug · medium
Failure between claim and try leaves transaction stuck in committing
The commit claim flips the transaction to committing before the findOne('transactionLogs') lookup, which now runs outside the try block whose catch handlers reset the status to failed (src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Update.php:180). Any transient error in that lookup, or in the status update on the empty-operations path, leaves the transaction in committing with no handler to recover it. Both commit and rollback are then rejected by the status !== 'pending' guard at line 144, so the transaction and its staged logs survive only until the expiry cleanup removes them.
📋 Prompt for AI Agents
In src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Update.php, the commit branch claims the transaction (status 'committing') at lines 172-178, but the $firstOperation = $dbForProject->findOne('transactionLogs', ...) at line 180 and the empty-firstOperation early-return branch (lines 185-203) run before the try block starting at line 205. If findOne throws there, the transaction is left permanently in 'committing' and can no longer be committed or rolled back (both reject non-pending status at line 144). Restructure so everything after the claim — the firstOperation lookup and the empty-logs branch — is inside the try block, keeping the existing catch handlers unchanged.
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
# Conflicts: # src/Appwrite/Platform/Modules/Databases/Http/Databases/Action.php
…ng-race # Conflicts: # src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Update.php
What changed
Staging checked the transaction status and operation limit on a plain read, then wrote the logs later without a lock. Concurrent requests all passed the limit check. Logs written after a commit had read them got
201and were never applied.stage()on the Databases base action locks the transaction row and checksstatus === 'pending'and the limit again. It then inserts the logs and incrementsoperationsin the same database transaction. All ten staging paths use it:createOperations, plus the row/document create, update, upsert, delete, increment, decrement and bulk update/upsert/delete endpoints withtransactionId.GETshowed 99 operations while 100 were stored.try, so a failure there marks the transactionfailedinstead of leaving itcommitting.Verified
Local stack running this branch (TablesDB on Postgres), limit 100:
createOperations, 60 creates each201, 480 operations, 480 rows201, seven400 transaction_limit_exceeded, 60 rowscreateRowwithtransactionIdcreateOperations(one op staged first), 20 roundscreateRowwithtransactionId, 20 roundscreateOperations, 40 roundsTablesDBTransactionsCustomServerTest,TablesDBTransactionsCustomClientTest,TablesDBTransactionPermissionsCustomClientTestandLegacyTransactionsCustomServerTestpass.Fixes #14332