Skip to content

fix(databases): apply filters, order and paging to staged writes in a transaction read - #14590

Merged
abnegate merged 4 commits into
mainfrom
qfix-txn-list-overlay
Oct 16, 2026
Merged

abnegate merged 4 commits into
mainfrom
qfix-txn-list-overlay

Conversation

@abnegate

@abnegate abnegate commented Oct 16, 2026 •

Copy link
Copy Markdown
Member

What

Inside a transaction, GET …/rows?transactionId=T (and the documents equivalent) read the stored page and then patched in the staged writes. Staging QA reported:

  • Staged creates were appended whatever the filter.
  • Staged updates were not re-checked against the filter (a renamed row still matched its old name).
  • orderDesc + limit returned extra rows, unsorted.
  • cursor/offset only counted stored rows, so staged rows showed up on every page.
  • total was off: it was counted from the default first page of stored rows.

Fix (plain reads only)

TransactionState::listDocuments()/countDocuments(): a read with no joins and no distinct now merges stored rows and staged writes before paging.

  • Filters. Staged creates and updated rows are matched with their staged values. For a stored row whose staged change doesn't touch a filtered attribute, the database's own match decides. documentMatchesFilters() takes its filters from Query::groupByType(), returns false for a method it can't evaluate, and learns and/or, notContains, containsAny/containsAll, the not… string and between variants, exists/notExists, substring contains, and null-safe comparisons.
  • Order. Rows follow the read's orders plus the $sequence tie break the database adds. Staged creates sort after every stored row, in staging order, as they will once committed.
  • Cursor, offset, limit apply to the merged set:
    • Stored rows are read past the cursor with a limit of offset + limit + staged count, so dropping the staged IDs still leaves a full page.
    • cursorBefore mirrors the database (nearest rows before the cursor).
    • A cursor may name a row staged in the transaction. Documents/XList.php falls back to TransactionState::getDocument() when the stored lookup is empty. That's a 3-line change in the cursor block, away from chore(deps): bump utopia-php/database to 8.3.4 #14576's hunk.
  • Total = stored count over the filters, minus staged rows that matched as stored, plus staged rows that match now.

Per the decision on this batch, distinct/grouped/join reads inside a transaction keep the existing in-place overlay: no read-time rehearsal and no new refusal. Aggregates stay refused as before.

Known gaps:

  • PHP comparison can differ from an engine's collation for staged string values (case and accent folding).
  • Filters only the engine evaluates (search, regex, spatial, vector, JSON, elemMatch) don't match a staged value. Stored rows still match through the database.

Tests

Unit tests, at the fixing layer (tests/unit/Databases/TransactionStateTest.php, SQLite):

Test origin/main this PR
testStagedCreateThatMissesTheFilterIsLeftOut ❌ appended ✅
testStagedUpdateIsMatchedAgainstTheFilterWithItsNewValues ❌ matched on old value ✅
testOrderAndLimitApplyToTheMergedSet (orderDesc/orderAsc + limit; total 4) ❌ extra rows, unsorted ✅
testDefaultOrderPutsStagedCreatesAfterStoredRows (with a staged delete) ❌ ✅
testOffsetAndCursorPageThroughTheMergedSet (offset, cursorAfter/Before on stored and staged rows) ❌ ✅
testUnjoinedReadInATransactionOrdersStagedWritesWithStoredRows (was …AppendsCreates, which encoded the bug) — ✅
testOrderOnAnAttributeTheReadSelectsAwayStillOrdersStoredRows (review) ❌ ✅
testExistsFilterSeesAStagedUpdateThatSetsTheAttribute (review) ❌ ✅
testStagedWriteIsNotMatchedByAFilterOnlyTheEngineEvaluates (review: staged bulkDelete by regex) ❌ ✅

API E2E (tests/e2e/Services/Databases/Transactions/StagedReads.php, in TransactionsBase): stored rows Ada and Bob; the transaction creates Cy and Abe and renames Ada to Zed.

Test TablesDB main TablesDB PR Legacy PR DocumentsDB main DocumentsDB PR
testListInATransactionFiltersStagedWrites (equal Bob → 1, equal Ada → 0, equal Zed → Ada; totals) ❌ staged creates appended ✅ ✅ ❌ ✅
testListInATransactionOrdersAndPagesStagedWrites (orderDesc+limit 2 → [Zed, Cy], total 4; offset; cursorAfter a stored row; cursorAfter a staged row) ❌ extra unsorted rows ✅ ✅ ❌ ✅

Also passing locally: the full TablesDB (server and client), Legacy and DocumentsDB transaction suites, both transaction-permission suites, both ACID suites, and tests/unit/Databases. The one exception is testCommitEventPayloadCarriesSurfaceIds, which fails the same way on main in my local stack because of webhook delivery.

🤖 Generated with Claude Code

abnegate and others added 2 commits October 16, 2026 21:42
… transaction read

A list inside a transaction read the stored page and then patched the staged
writes in: staged creates were appended whatever the filters, staged updates
were not checked against them, orderDesc and limit returned extra rows out of
order, a cursor or offset counted only stored rows, and the total was
counted from the first stored page.

A read without joins or distinct now merges the stored rows with the staged
writes before paging. Staged creates and updated rows are matched against
the filters with their staged values; the database decides for a stored row
whose staged changes leave the filtered attributes alone. The merged rows
are ordered by the read's orders and the $sequence tie break, with staged
creates after every stored row, then the cursor, offset and limit apply. The
stored rows are read past the cursor in a page large enough that removing
every staged row still fills it. The total is the stored count adjusted by
the staged rows that join or leave the filter. A cursor may name a row
staged in the transaction.

Reads with joins or distinct inside a transaction keep the in-place overlay.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟠 2 high

💬 Inline comments (1)

📍 Findings outside the diff (1) — 🟠 1 high — defects on lines GitHub can't attach comments to

🟠 High — NULL attributes mishandled in Equal/NotEqual/negated filters · TransactionState.php:1126–1130 · unchanged line

// src/Appwrite/Databases/TransactionState.php
1126	                case Method::NotEqual:
1127	                    if (\in_array($docValue, $values)) {
1128	                        return false;
1129	                    }
1130	                    break;

In documentMatchesFilters, Method::NotEqual passes a document whose attribute is null because in_array(null, $values) is false (TransactionState.php:1126-1130). SQL evaluates col != value as UNKNOWN for a NULL column and drops the row, so a staged row appears inside the transaction but disappears after commit. The same gap hits the negated string filters: NotContains (1070-1076), NotStartsWith (1086-1090) and NotEndsWith (1092-1096) all keep null and non-string values that SQL's NOT LIKE would exclude. The mirror-image divergence exists in Method::Equal (1120-1124): loose in_array makes null == 0 true, so a staged document with a null attribute matches Query::equal('attr', [0]), which SQL excludes. The NotBetween case at line 1099 already guards $docValue === null, showing the switch otherwise intends three-valued logic.

🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Assert status codes on every staged-read list call (StagedReads.php:35) — Only the $afterStaged call asserts the HTTP status; the $descending, $offset and $afterStored responses (StagedReads.php:35, 39, 42) are asserted straight from the body.

The change introduces staged-read overlay support for database transactions: pending staged writes are merged into list results alongside committed rows, with PHP-side emulation of query filters, ordering, and cursor/offset pagination for rows not yet in the backing store.

Files Change
src/Appwrite/Databases/StagedDocuments.php, src/Appwrite/Databases/TransactionState.php New staged-write bookkeeping plus overlay logic that merges staged creates/updates/deletes into list, get, and count results with filter/order/pagination emulation.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/XList.php List endpoint now routes through the transaction-aware path and falls back to transaction-scoped getDocument when resolving cursors against staged rows.
tests/e2e/Services/Databases/Transactions/StagedReads.php, tests/e2e/Services/Databases/Transactions/TransactionsBase.php New e2e fixture covering staged creates, updates, deletes, ordering, pagination, and filters across the transaction suites.
tests/unit/Databases/TransactionStateTest.php Unit coverage for the new filter-emulation and merge-sort behavior.

Reviewed commit: 9cc7249

@github-actions

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

19 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (12)
  • php.appwrite.secret-compare-timing (5)
  • 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 16, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

This pull request merges staged transaction writes with stored documents for plain transaction reads, applying filters, ordering, paging, and totals to the combined result. It also supports staged documents as cursors and adds unit and API coverage for staged filtering, ordering, and pagination.

Latest changes: The newest commits preserve stored sort keys before removing internal order-only fields, include exists/notExists attributes when detecting staged filter changes, and use Query grouping plus a non-match fallback for filters the PHP matcher cannot evaluate.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 6
File Change
src/Appwrite/Databases/StagedDocuments.php Adds a value object holding staged documents and their match, ordering, and stored-row metadata.
src/Appwrite/Databases/TransactionState.php Merges staged writes into plain reads and applies filters, ordering, cursor/offset/limit paging, and totals.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/XList.php Falls back to a transaction-staged document when resolving a cursor ID.
tests/e2e/Services/Databases/Transactions/StagedReads.php Adds API coverage for filtering, ordering, totals, and paging staged transaction writes.
tests/e2e/Services/Databases/Transactions/TransactionsBase.php Includes staged-read tests in the transaction API suites.
tests/unit/Databases/TransactionStateTest.php Covers staged read filtering, ordering, selection, cursor, and bulk-operation behavior.

Reviewed the commits since 9cc7249 · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

ghost
ghost previously requested changes Oct 16, 2026

@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 B · 1 blocking finding to address. Summary

@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 adds transaction-scoped staged reads so documents created, updated, or deleted inside a pending transaction are visible to list/get/count within that same transaction, including in-PHP filter, order, and pagination emulation for staged rows.

Key findings

@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → qfix-txn-list-overlay (after).

Metric Before After Change
🚀 Requests/sec 206.57 211.1 ⚪ +2.2%
⏱️ Latency P50 82.81 ms 81.94 ms ⚪ -1.1%
⏱️ Latency P95 193.08 ms 192.89 ms ⚪ -0.1%
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 81.94 192.89 13,509 211.1 -0.2
Account 155.16 288.53 711 11.79 +22.03
TablesDB 79.49 146.2 7,347 118.07 +0.69
Storage 74.66 169.55 3,555 58.4 -27.51
Functions 119.37 230.37 1,896 31.73 +13.44

Top API waits (after)

API request Max wait (ms)
account.name.update 410.2
tablesdb.rows.create 406.94
functions.variables.update 395.5
functions.create 392.31
account.prefs.update 334.54

abnegate and others added 2 commits October 16, 2026 22:00
…match staged writes only on filters PHP can evaluate

The sort key of a stored row was taken after removing order attributes the
read had not selected, so those rows ordered as if the value were null. The
key is now taken first.

exists and notExists name their attributes in their values, so a staged
change to one of them was not seen as touching the filter and the stored
match was reused. Filters only the engine evaluates (search, regex, spatial,
vector, JSON, elemMatch) no longer match a staged value, where they matched
every one; filters now come from Query::groupByType, so joins, orders and
selects never reach the matcher.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ghost
ghost dismissed their stale review October 16, 2026 09:03

The findings that requested changes are resolved. See the summary comment for what is still open.

@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 S · Looks good to merge. Summary

@abnegate
abnegate merged commit 10cb3b7 into main Oct 16, 2026
54 checks passed
@ChiragAgg5k ChiragAgg5k mentioned this pull request Oct 21, 2026
6 tasks
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.

1 participant