Skip to content

fix(databases): apply transaction bulk updates once, to matching rows only - #14378

Merged
HarshMN2345 merged 11 commits into
mainfrom
fix-transaction-bulk-update
Oct 28, 2026
Merged

HarshMN2345 merged 11 commits into
mainfrom
fix-transaction-bulk-update

Conversation

@HarshMN2345

@HarshMN2345 HarshMN2345 commented Oct 12, 2026 •

Copy link
Copy Markdown
Member

What changed

The transaction commit now trusts the database result for bulk updates and deletes, instead of replaying the operations in memory.

  • bulkUpdate: the commit uses the rows updateDocuments() returns as the transaction state. Before, it replayed the update onto rows already in the state and upserted them back. That applied operators a second time, and it overwrote rows that the in-memory filter matched but the database query did not. applyBulkUpdateToState() is removed.
  • bulkDelete: the commit no longer runs a second, in-memory pass after deleteDocuments(). onNext already unsets every deleted row. The extra pass could also drop a row the database kept, where PHP and the database compare differently (Postgres en_US orders 'B' after 'a', PHP before). A later upsert of that row was then silently lost. applyBulkDeleteToState() is removed.
  • bulkUpsert: parseOperators() now unwraps the Document rows that transaction logs return. A staged bulkUpsert with an operator now commits; before, it failed with a 400 or stored the operator JSON in a string column.
  • Transaction reads: includes fix: handle missing query operators in transaction state filters #14324 by SahilArate. TransactionState::documentMatchesFilters() now handles notStartsWith, notEndsWith, notContains, notBetween, and, or, containsAny and containsAll. It compares equal/notEqual null-safely and rejects queries it cannot evaluate. This matcher now only serves reads with transactionId. extractFilters() now also skips orderRandom and vector queries, which only order rows; without that, the new default would hide staged rows from those reads.
  • Tests: the unit test from fix: handle missing query operators in transaction state filters #14324 is removed. It reached the matcher only through applyBulk*ToState(), which no longer exist.

Tested

Main (shared local stack) compared with this branch (sidecar API container), Postgres:

  • 🐛 Bug Report: Operators in a transaction bulkUpdate are applied twice #14217: increment 2 then multiply 3: main 27, branch 9. increment 1 twice: 4 and 3. create n=1 then increment 1: 3 and 2. stringConcat a, b: xabb and xab. arrayAppend a, b: [a,b,b] and [a,b].
  • 🐛 Bug Report: Transaction bulkUpdate changes rows that do not match the filter #14222: update A, bulkUpdate {ds: BULK} filtered by notStartsWith, notEndsWith, notContains, notBetween, or or equal u="", then upsert A. Main changes A on every filter; the branch leaves it. With the same filters, the transactionId read view shows the staged value on A on main but not on the branch.
  • Update A, bulkDelete with lessThan ix "a" (the database keeps A, where ix = "B"), then upsert A with ds: upserted: main commits but drops the upsert; the branch applies it.
  • Staged bulkUpdate with orderRandom(), read with transactionId: BULK on main and on the branch.
  • bulkUpsert increment 2 on an existing row: main 400, branch n=3. bulkUpsert stringConcat: main stores the operator JSON, branch xa.
  • LegacyTransactionsCustomServerTest (50 tests), DocumentsDBTransactionsCustomServerTest (50) and VectorsDB/Transactions/TransactionsCustomServerTest (22) pass. Pint and PHPStan report no issues on the changed files.

Fixes #14222
Fixes #14217

SahilArate and others added 5 commits October 10, 2026 09:01
documentMatchesFilters() had no case for notStartsWith, notEndsWith,
notContains, notBetween, and, or, containsAny and containsAll, and no
default branch, so these operators matched every row already in the
transaction state. Add the missing operators, make equal/notEqual
null-safe, and make unknown operators never match.

Fixes #14222

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DS3yiV1YkSdmHF1BVYyzeU
…-filter-operators

fix: handle missing query operators in transaction state filters
The commit replayed each bulkUpdate onto rows already in the
transaction state, then upserted those rows from that state after the
database update. The state copy still held the Operator, so the upsert
applied it a second time, and rows the in-memory filter wrongly matched
were overwritten.

Take the rows updateDocuments() returns as the new state instead. The
database already matched them and computed operator values.

Fixes #14217
An unconfigured mock raises a PHPUnit notice on every case.
Transaction logs decode bulk rows as Documents, which parseOperators()
skipped, so a bulkUpsert operator reached the database as its JSON
string: a 400 on numeric columns and the literal JSON stored in string
columns.
@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟡 2 medium

💬 Inline comments (2)


The change consolidates how transaction state is updated and read during bulk operations. Filter evaluation is rewritten inside TransactionState, with explicit null handling added for several NOT operators and a fallback for unevaluable operators. The now-unused bulk-update state mutation path is removed, and the Transactions/Update endpoint plus the shared Databases action base are adjusted accordingly, with a unit test suite covering the new matcher.

Files Change
src/Appwrite/Databases/TransactionState.php Rewrites in-memory documentMatchesFilters evaluation (null handling, NOT operators, unevaluable-operator fallback) and drops applyBulkUpdateToState.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Update.php Updates the transaction commit flow to work with the refactored state, dropping the removed mutation path.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Action.php Adjusts shared bulk-operation handling to match the new state semantics.
tests/unit/Databases/TransactionStateTest.php Adds unit coverage for the rewritten filter matcher.

Reviewed commit: e790cd0

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

@ghost

ghost commented Oct 12, 2026 •

Copy link
Copy Markdown

🔵 Tier A · Mergeable after minor fixes

The previously reported regression-test finding remains open; these commits do not add the requested commit-and-read test.

Transaction commits now trust database-returned bulk update and delete results, preventing duplicate operator application and in-memory filter mismatches. Bulk-upsert transaction logs are normalized before operator parsing, and transaction-aware reads evaluate supported filters safely while ignoring ordering-only clauses. Bulk-operation results are also carried into post-commit event processing.

Latest changes: The new commits pass each bulk operation's affected-document buffer into its handler and capture bulk-update results there for post-commit events.

Verdict New comments Fixed Still open
✅ Approved 0 0 1
Fix with agent prompt
### Issue 1
src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Update.php:993-997
**Add a commit regression test for operator bulk updates**

The added unit test covers filter matching, while existing transaction E2E coverage uses plain-value bulk updates. No automated test commits an operator bulk update after an earlier operation touched the same row, so the double-application regression this change fixes could return without failing CI; please add a commit-and-read assertion for that case.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
📂 Walkthrough · 3
File Change
src/Appwrite/Databases/TransactionState.php Removes redundant bulk-operation state replay and expands safe filter matching for transaction reads.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Action.php Unwraps logged Document rows before parsing bulk-upsert operators.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Update.php Uses database-returned bulk operation results for transaction state and passes affected documents through to post-commit event processing.
⏳ Still open from earlier reviews · 1

Reviewed the commits since da625f3 · 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 · Looks good to merge. Summary

Comment on lines +993 to +997
return $dbForDatabases->updateDocuments(
$collectionId,
clone $updateData,
new Document($data['data']),
$queries,
onNext: function (Document $updated, Document $old) use (&$state, $collectionId, $createdAt, &$dependentDocs) {
onNext: function (Document $updated, Document $old) use (&$state, $collectionId, $createdAt) {

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 a commit regression test for operator bulk updates

The added unit test covers filter matching, while existing transaction E2E coverage uses plain-value bulk updates. No automated test commits an operator bulk update after an earlier operation touched the same row, so the double-application regression this change fixes could return without failing CI; please add a commit-and-read assertion for that case.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Update.php
Line: 993-997

Comment:
**Add a commit regression test for operator bulk updates**

The added unit test covers filter matching, while existing transaction E2E coverage uses plain-value bulk updates. No automated test commits an operator bulk update after an earlier operation touched the same row, so the double-application regression this change fixes could return without failing CI; please add a commit-and-read assertion for that case.

---

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.

@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 reworks transaction state handling for Databases bulk operations, refactoring in-memory filter matching in TransactionState and removing the dead applyBulkUpdateToState path.

Key findings

Comment on lines +770 to +774
default:
// Operators that cannot be evaluated in memory (e.g. search,
// notSearch, regex) must never match, otherwise a bulk operation
// would modify rows that the database query excludes.
return false;

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

Unevaluable filters keep deleted rows in transaction state

The new default: return false in documentMatchesFilters (src/Appwrite/Databases/TransactionState.php:770) also governs state cleanup and read projection during bulk deletes, where applyBulkDeleteToState and the replay cases in getTransactionState now keep state-only entries the in-memory matcher cannot evaluate (search, notSearch, regex). Previously those operators fell through and matched, so the entry was removed. A document created earlier in the same transaction, then bulk-deleted with such a query, stays in $state even though the database row is gone: transaction-aware reads and countDocuments still report it, and a later bulkUpsert in the same transaction merges into that stale entry and re-upserts it, resurrecting the deleted document.

📋 Prompt for AI Agents

In src/Appwrite/Databases/TransactionState.php around lines 770-774, the newly added default: return false in documentMatchesFilters makes applyBulkDeleteToState and the bulkDelete replay in getTransactionState (called from src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Update.php) keep state entries for rows the database bulk delete actually removed when the query uses search/notSearch/regex. Fix by giving the delete path a mode where unevaluable filters match state-only documents (e.g. a boolean parameter or separate cleanup method), so those entries are removed and a later bulkUpsert cannot resurrect a deleted document. Add a unit case in tests/unit/Databases/TransactionStateTest.php covering delete-with-search against a state-only row.

Comment on lines 624 to 628
case Query::TYPE_NOT_EQUAL:
if (\in_array($docValue, $values)) {
if ($this->valueInList($docValue, $values)) {
return false;
}
break;

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

notEqual matches NULL rows, diverging from SQL

The rewritten TYPE_NOT_EQUAL branch matches a document whose attribute is null, because valueInList(null, ['x']) is false (src/Appwrite/Databases/TransactionState.php:624-628). SQL attr != 'x' / attr NOT IN (...) evaluates to NULL for a NULL attribute and excludes the row — compileNotIn in packages/query/src/Builder.php even compiles an all-null value list to attr IS NOT NULL, showing the intended semantics. The sibling NOT_CONTAINS and NOT_BETWEEN branches added in this same patch handle null explicitly, but NOT_EQUAL does not, so countDocuments, applyBulkDeleteToState, and the replayed bulk operations disagree with the database for rows whose filtered attribute is null.

📋 Prompt for AI Agents

In src/Appwrite/Databases/TransactionState.php at lines 624-628, add a null guard before the valueInList check in the Query::TYPE_NOT_EQUAL case: if ($docValue === null) { return false; }. This mirrors SQL three-valued logic where NULL != x is NULL and the row is excluded, consistent with the null handling in the TYPE_NOT_CONTAINS (line 650) and TYPE_NOT_BETWEEN (line 678) branches, and keeps countDocuments / bulk-delete state cleanup consistent with the SQL builders in packages/query/src/Builder.php. Add unit cases to tests/unit/Databases/TransactionStateTest.php: notEqual does not match a null column, and notEqual with null in the value list.

@github-actions

github-actions Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix-transaction-bulk-update (after).

Metric Before After Change
🚀 Requests/sec 216.34 219.41 ⚪ +1.4%
⏱️ Latency P50 81.74 ms 78.71 ms ⚪ -3.7%
⏱️ Latency P95 181.41 ms 185.8 ms ⚪ +2.4%
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 78.71 185.8 13,680 219.41 +4.39
Account 146.7 291.57 720 12.17 +33.65
TablesDB 76.14 142.46 7,440 121.56 +0.87
Storage 72.5 166.86 3,600 60.73 -14.54
Functions 114.08 212.05 1,920 33.01 +5.48

Top API waits (after)

API request Max wait (ms)
account.prefs.update 478.98
account.name.update 472.71
functions.create 418.42
tablesdb.rows.delete 381.88
tablesdb.rows.update 369.36

After deleteDocuments() unset every deleted row from the transaction
state, the commit also dropped every state row the in-memory filter
matched. Where PHP and the database disagree (Postgres en_US orders
'B' after 'a', PHP before), that dropped a row the database kept, and a
later upsert of it in the same transaction was silently lost.

deleteDocuments() already reports exactly the rows it removed, so drop
the second pass. Its unit test goes with it, since the in-memory filter
now only serves transaction reads.
…tion reads

They only order rows, but extractFilters() passed them to the in-memory
filter, which now rejects queries it cannot evaluate. A staged bulk
update with orderRandom() stopped showing in transaction reads.
# Conflicts:
#	src/Appwrite/Databases/TransactionState.php
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Update.php
…update

# Conflicts:
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Update.php
@HarshMN2345
HarshMN2345 merged commit 4af4ddf 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

2 participants