Skip to content

fix(databases): lock the transaction while staging operations - #14384

Merged
HarshMN2345 merged 8 commits into
mainfrom
fix-transaction-staging-race
Oct 28, 2026
Merged

HarshMN2345 merged 8 commits into
mainfrom
fix-transaction-staging-race

Conversation

@HarshMN2345

Copy link
Copy Markdown
Member

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 201 and were never applied.

  • A new stage() on the Databases base action locks the transaction row and checks status === 'pending' and the limit again. It then inserts the logs and increments operations in 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 with transactionId.
  • After COMMIT the transaction is purged from the cache. Before, a concurrent read could cache the old count, so GET showed 99 operations while 100 were stored.
  • Commit claims the transaction before it reads the logs. A transaction with no logs used to be marked committed without the lock, so operations staged at that moment were lost. The database lookups after the claim moved into the try, so a failure there marks the transaction failed instead of leaving it committing.

Verified

Local stack running this branch (TablesDB on Postgres), limit 100:

Scenario main this branch
8 concurrent createOperations, 60 creates each all 201, 480 operations, 480 rows one 201, seven 400 transaction_limit_exceeded, 60 rows
130 concurrent createRow with transactionId 113 accepted, 113 rows 100 accepted, 100 rows
commit racing 6 createOperations (one op staged first), 20 rounds 137 accepted, 82 lost 74 accepted (30 rounds), 0 lost
commit racing 6 createRow with transactionId, 20 rounds 140 accepted, 99 lost 101 accepted (30 rounds), 0 lost
commit of an empty transaction racing 6 createOperations, 40 rounds 235 accepted, 228 lost 49 accepted (30 rounds), 0 lost
  • e2e: TablesDBTransactionsCustomServerTest, TablesDBTransactionsCustomClientTest, TablesDBTransactionPermissionsCustomClientTest and LegacyTransactionsCustomServerTest pass.

Fixes #14332

…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.
@luxor-code-review

luxor-code-review Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Review complete. 🟡 1 medium

💬 Inline comments (1)

  • 🟡 Failure between claim and try leaves transaction stuck in committing — Update.php:172

The change reworks the Databases transaction lifecycle so a commit or rollback claims the transaction (status committing/rolling) before reading and applying staged operations, and document actions (create, update, delete, upsert, bulk variants, increment/decrement) participate in that flow via a shared withTransaction() helper on Action.php.

Files Change
src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Update.php, .../Transactions/Operations/Create.php Restructure commit/rollback status transitions, operation claiming, and failure-path status resets
src/Appwrite/Platform/Modules/Databases/Http/Databases/Action.php Add shared transaction-scoping helper used by document actions
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/** Thread transaction handling through single and bulk document actions, including increment/decrement attribute operations

Reviewed commit: 1f364da

@ghost

ghost commented Oct 12, 2026 •

Copy link
Copy Markdown

🔵 Tier A · Mergeable after minor fixes

The previously reported missing coverage for concurrent staging and commit remains open.

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.

Verdict New comments Fixed Still open
✅ Approved 0 0 1
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
File Change
src/Appwrite/Platform/Modules/Databases/Http/Databases/Action.php Adds shared, locked staging with status, expiry, and operation-limit checks plus cache invalidation.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Attribute/Decrement.php Routes staged decrement requests through the shared staging helper.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Attribute/Increment.php Routes staged increment requests through the shared staging helper.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Bulk/Delete.php Routes staged bulk-delete requests through the shared staging helper.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Bulk/Update.php Routes staged bulk-update requests through the shared staging helper.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Bulk/Upsert.php Routes staged bulk-upsert requests through the shared staging helper.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Create.php Routes staged create requests through the shared staging helper.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Delete.php Routes staged delete requests through the shared staging helper.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Update.php Routes staged update requests through the shared staging helper.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Upsert.php Routes staged upsert requests through the shared staging helper.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Operations/Create.php Routes batch-operation staging through the shared staging helper.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Update.php Claims transactions before reading staged logs, handles commit failures, and annotates the types of error context populated by the commit closure.
⏳ Still open from earlier reviews · 1

Merged main (fe21322); no changes to this PR's code since 7962c79 · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

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

🔵 Tier A · See the inline comments. Summary

$current = new Document();

$transaction = $dbForProject->withTransaction(function () use ($dbForProject, $transactionId, $logs, $max, &$current) {
$current = $dbForProject->getDocument('transactions', $transactionId, forUpdate: true);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

@github-actions

github-actions Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

6 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (3)
  • php.appwrite.secret-compare-timing (1)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

@luxor-code-review luxor-code-review 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.

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

Comment on lines +172 to 204
$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;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 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.

@github-actions

github-actions Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix-transaction-staging-race (after).

Metric Before After Change
🚀 Requests/sec 208.12 216.46 ⚪ +4%
⏱️ Latency P50 82.86 ms 80.07 ms ⚪ -3.4%
⏱️ Latency P95 193.66 ms 189.37 ms ⚪ -2.2%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 80.07 189.37 13,680 216.46 -4.28
Account 158.4 286.31 720 12.14 +22.36
TablesDB 77.83 146.01 7,440 121.42 -15.61
Storage 73.22 166.78 3,600 59.74 -19.36
Functions 114.78 221.67 1,920 32.66 +15.75

Top API waits (after)

API request Max wait (ms)
account.name.update 549.06
account.prefs.update 413.59
tablesdb.rows.create 404.74
functions.variables.update 378.81
storage.files.create 358.06

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

🔵 Tier A · Looks good to merge. Summary

@HarshMN2345
HarshMN2345 merged commit 6b6cc6d into main Oct 28, 2026
38 checks passed
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.

🐛 Bug Report: Concurrent staging bypasses the transaction operation limit and loses acknowledged operations

1 participant