Repository navigation
fix(databases): apply transaction bulk updates once, to matching rows only - #14378
Conversation
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.
|
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
Reviewed commit: e790cd0 |
Security rulesNo new WARNING or ERROR findings from security rules. 6 existing findings tracked in
|
🔵 Tier A · Mergeable after minor fixes
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.
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
⏳ Still open from earlier reviews · 1
Reviewed the commits since |
| 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) { |
There was a problem hiding this 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.
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.
There was a problem hiding this comment.
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
- 🟡 Unevaluable filters keep deleted rows in transaction state — TransactionState.php:770
- 🟡
notEqualmatches NULL rows, diverging from SQL — TransactionState.php:624
| 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; |
There was a problem hiding this comment.
🟡 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.
| case Query::TYPE_NOT_EQUAL: | ||
| if (\in_array($docValue, $values)) { | ||
| if ($this->valueInList($docValue, $values)) { | ||
| return false; | ||
| } | ||
| break; |
There was a problem hiding this comment.
🟡 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.
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
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
What changed
The transaction commit now trusts the database result for bulk updates and deletes, instead of replaying the operations in memory.
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.deleteDocuments().onNextalready unsets every deleted row. The extra pass could also drop a row the database kept, where PHP and the database compare differently (Postgresen_USorders'B'after'a', PHP before). A later upsert of that row was then silently lost.applyBulkDeleteToState()is removed.parseOperators()now unwraps theDocumentrows 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.TransactionState::documentMatchesFilters()now handlesnotStartsWith,notEndsWith,notContains,notBetween,and,or,containsAnyandcontainsAll. It comparesequal/notEqualnull-safely and rejects queries it cannot evaluate. This matcher now only serves reads withtransactionId.extractFilters()now also skipsorderRandomand vector queries, which only order rows; without that, the new default would hide staged rows from those reads.applyBulk*ToState(), which no longer exist.Tested
Main (shared local stack) compared with this branch (sidecar API container), Postgres:
increment 2thenmultiply 3: main 27, branch 9.increment 1twice: 4 and 3.create n=1thenincrement 1: 3 and 2.stringConcat a,b:xabbandxab.arrayAppend a,b:[a,b,b]and[a,b].{ds: BULK}filtered bynotStartsWith,notEndsWith,notContains,notBetween,ororequal u="", then upsert A. Main changes A on every filter; the branch leaves it. With the same filters, thetransactionIdread view shows the staged value on A on main but not on the branch.lessThan ix "a"(the database keeps A, whereix = "B"), then upsert A withds: upserted: main commits but drops the upsert; the branch applies it.orderRandom(), read withtransactionId:BULKon main and on the branch.increment 2on an existing row: main 400, branchn=3. bulkUpsertstringConcat: main stores the operator JSON, branchxa.LegacyTransactionsCustomServerTest(50 tests),DocumentsDBTransactionsCustomServerTest(50) andVectorsDB/Transactions/TransactionsCustomServerTest(22) pass. Pint and PHPStan report no issues on the changed files.Fixes #14222
Fixes #14217