Skip to content

fix(databases): read staged increments on top of the stored value - #14751

Merged
abnegate merged 2 commits into
mainfrom
fix/transaction-staged-increments
Oct 22, 2026
Merged

abnegate merged 2 commits into
mainfrom
fix/transaction-staged-increments

Conversation

@abnegate

@abnegate abnegate commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Fixes two bugs in how reads inside a transaction see staged increments and decrements (TransactionState::replay()).

  1. TablesDB increments were invisible. Replay read only data.attribute, but TablesDB stages data.column (the operation validator requires column for tablesdb). Every TablesDB increment/decrement was ignored by getDocument, listDocuments/countDocuments and the stagedView used for authorization, even though commit applied it. Replay now uses the same attribute/column fallback as commit, moved from Transactions/Update.php into TransactionState::attributeOf() so both use one helper.
  2. The delta was read as the value. When the row had no staged value for the attribute, replay staged ±value as the attribute's value, and readers laid it over the stored row: stored total 15 + increment 5 read back as 5. After a staged update of another attribute, it started from 0 instead of the stored value. These increments are now kept as pending deltas (increments per staged document) and added to the stored value wherever staged state is merged with stored rows: getDocument, the join overlay and the staged creates/upserts it appends, the plain list/count path (filter matching and ordering see the new value), and stagedView.

Semantics:

  • A staged create, or an attribute a staged write already sets, stays absolute (increment builds on the staged value).
  • A later staged update/bulk update/bulk upsert that sets the attribute replaces the delta; a delete drops it; consecutive increments and decrements sum.
  • Min/max clamps are still enforced only at commit, as before.
  • perf(databases): read transaction logs and tenant database once per request #14749's per-request caching of logs and tenant database is unchanged.

Test Plan

New cases in tests/unit/Databases/TransactionStateTest.php. Each fails on origin/main and passes with this change:

Test origin/main this PR
Staged increment builds on the stored value (TablesDB column), via getDocument and stagedView 15 ≠ 20 pass
Same, legacy attribute 5 ≠ 20 pass
Consecutive increment +5, decrement −2, increment (default 1) sum 15 ≠ 19 pass
Increment, update total: 30, increment +2 30 ≠ 32 pass
Update of another attribute, then increment (column / attribute) 15 / 5 ≠ 20 pass
Staged create total: 7, then increment +3 7 ≠ 10 pass
list total > 18 ordered desc includes the incremented row, drops an incremented-then-deleted row; count agrees [ada 20] ≠ [bob 25, ada 20] pass
Increment pending in the same request is visible 15 ≠ 20 pass
Distinct read appends a staged upsert of a new row with its staged increment total null ≠ 3 pass

The full file runs 29 tests / 67 assertions green locally. Pint passes.

Related PRs and Issues

🤖 Generated with Claude Code

Reads inside a transaction replay its staged operations, and replay got
increments and decrements wrong in two ways:

- It looked only for `data.attribute`, but TablesDB stages `data.column`,
  so every TablesDB increment or decrement was invisible to getDocument,
  listDocuments, countDocuments and the staged view used to authorize
  writes. Replay now resolves the key with the same attribute/column
  fallback commit uses, now shared as TransactionState::attributeOf().
- With no staged value to build on, it staged the delta as the value, and
  readers laid it over the stored row: a stored total of 15 incremented by
  5 read back as 5. After a staged update of another attribute it started
  from 0 instead of the stored value. Such increments are now kept as
  pending deltas per document and added to the stored value wherever
  staged state is merged with stored rows, including the filter, order and
  count of a list. A staged create, or an attribute a staged write sets,
  stays absolute; a later write of the attribute replaces the delta, a
  delete drops it, and consecutive increments sum. Min and max are still
  enforced only at commit.

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

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

Copy link
Copy Markdown

Review complete. 🟠 1 high · 🟡 4 medium

💬 Inline comments (1)

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

🟠 High — Join/distinct countDocuments ignores staged increments · TransactionState.php:278–292 · unchanged line

// src/Appwrite/Databases/TransactionState.php
278	            } elseif ($docState['action'] === 'update' || $docState['action'] === 'upsert') {
279	                $wasInResults = isset($committedRows[$docId]);
280	                $nowMatches = $this->documentMatchesFilters($docState['document'], $filters);
281	
282	                if (!$wasInResults && $nowMatches && $docState['action'] === 'upsert') {
283	                    $adjustedCount++;
284	                } elseif ($wasInResults && !$nowMatches) {
285	                    $adjustedCount -= $committedRows[$docId];
286	                } elseif (!$wasInResults && $nowMatches) {
287	                    // Update shouldn't add a new doc, but upsert might have
288	                    if ($docState['action'] === 'upsert') {
289	                        $adjustedCount++;

The join/distinct branch of countDocuments evaluates filters against $docState['document'] alone (src/Appwrite/Databases/TransactionState.php:280), but increment-only changes are staged in docState['increments'], leaving the document empty for a pure increment (src/Appwrite/Databases/TransactionState.php:866-884). documentMatchesFilters sees an empty document, returns false, and the branch subtracts the still-matching committed rows from the count at line 285. A join or distinct count after a pure increment undercounts, while listDocuments on the same query keeps the rows via overlay()/merge().


🟡 Medium — Join/distinct listDocuments drops increments from staged upserts · TransactionState.php:161–163 · unchanged line

// src/Appwrite/Databases/TransactionState.php
161	            if ($docState['action'] === 'create' || $docState['action'] === 'upsert') {
162	                $documents[] = $this->applyProjection($docState['document'], $queries);
163	            }

In the join/distinct branch of listDocuments, a staged row the stored read did not return is emitted as $this->applyProjection($docState['document'], $queries) (src/Appwrite/Databases/TransactionState.php:161-163) without applying docState['increments']. For a staged upsert whose data does not include the incremented attribute, replay() records the delta separately (src/Appwrite/Databases/TransactionState.php:879-883), so the joined list shows the pre-increment value while getDocument and the plain-list path via resolveStaged both apply it. The same document reads differently depending on whether the query uses joins or distinct.


🟡 Medium — Staged increment on nonexistent document reads inconsistently · TransactionState.php:96–107 · unchanged line

// src/Appwrite/Databases/TransactionState.php
96	            if ($docState['action'] === 'update' || $docState['action'] === 'upsert') {
97	                // Merge with committed version
98	                $committedDoc = $dbForDatabases->getDocument($collectionId, $documentId, $queries);
99	                if (!$committedDoc->isEmpty()) {
100	                    // Reapply projection in case transaction added new fields
101	                    return $this->applyProjection($this->merge($committedDoc, $docState), $queries);
102	                } elseif ($docState['action'] === 'upsert') {
103	                    return $this->applyProjection($this->increment($docState['document'], $docState), $queries);
104	                }
105	            }
106	        }
107	        return $dbForDatabases->getDocument($collectionId, $documentId, $queries);

An increment staged against a document id with no stored row diverges between the two read paths. In replay() the entry is created with action => 'update' and an empty document (src/Appwrite/Databases/TransactionState.php:866-871), so getDocument() finds the committed doc empty, skips the upsert branch, and returns an empty document — while stagedView() for the same state returns the delta applied over an empty document (e.g. total = 5). A read-your-writes call on a nonexistent id therefore returns nothing inside the same transaction where the permission pre-check sees the incremented value.


🟡 Medium — Staged bulkUpdate/bulkDelete match on pre-increment values · TransactionState.php:915–918 · unchanged line

// src/Appwrite/Databases/TransactionState.php
915	                            $document = $entry['document'];
916	                            $filters = $this->extractFilters($queries);
917	
918	                            if ($this->documentMatchesFilters($document, $filters)) {

In replay(), the bulkUpdate and bulkDelete cases evaluate filters against $entry['document'] alone (src/Appwrite/Databases/TransactionState.php:918), which does not include the deferred increments map. An increment staged earlier in the same transaction is invisible to the match: a document the increment moves into the bulk query's range is skipped for the state-side update or delete, while the commit path — which applies operations in order against the stored rows — matches it on the incremented value. Later in-transaction reads therefore never show the bulk effect on that document, diverging from the committed result.


This change extends TransactionState so increment/decrement operations staged inside a transaction are visible to in-transaction reads: replay() accumulates deltas into a deferred increments map per document, getDocument/listDocuments/resolveStaged apply them over staged or committed values, and the transaction commit endpoint (Transactions/Update.php) keeps its existing clamped apply path. Unit coverage for the new increment behavior is added in TransactionStateTest.php.

Files Change
src/Appwrite/Databases/TransactionState.php Stages increments in a deferred map and applies them across the read/replay paths, with join/distinct and bulk-operation handling
src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Update.php Commit-side endpoint adjusted to align with the new staged-increment state
tests/unit/Databases/TransactionStateTest.php New unit suite covering increment staging and read visibility

Reviewed commit: 027b9e9

@ghost

ghost commented Oct 22, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

No new actionable issue was found in the incremental changes.

Transaction replay now keeps increments and decrements as deltas over stored values, with shared attribute/column handling for legacy Databases and TablesDB operations. Transaction-aware reads and authorization views apply those deltas to merged documents, and the tests cover staged writes, filtering, ordering, and count behavior. The latest change also applies pending deltas when distinct/join reads append a staged upsert that has no row in the query result.

Latest changes: The latest commit applies pending increments to staged create/upsert rows appended by the distinct/join list path and adds a regression test for a new staged upsert.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 3
File Change
src/Appwrite/Databases/TransactionState.php Replays staged increments as deltas and applies them to transaction-visible documents, including newly appended staged rows in distinct/join reads.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Update.php Uses the shared attribute/column lookup for increment and decrement commit operations.
tests/unit/Databases/TransactionStateTest.php Covers stored-value increment behavior, staged operation sequences, filtered and ordered list/count results, and increments on a staged upsert in a distinct read.

Reviewed the commits since 027b9e9 · 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

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

Adds staged-increment support to TransactionState with read-your-writes visibility in transaction reads, but several read paths (join/distinct count, staged bulk operations, min/max clamping) diverge from the commit path.

Key findings

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

@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/transaction-staged-increments (after).

Metric Before After Change
🚀 Requests/sec 201.96 195.99 ⚪ -3%
⏱️ Latency P50 85.07 ms 89.16 ms ⚪ +4.8%
⏱️ Latency P95 201.07 ms 203.71 ms ⚪ +1.3%
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 89.16 203.71 12,483 195.99 +2.64
Account 164.45 304.41 657 11 +18.37
TablesDB 85.66 161.87 6,789 110.06 -4.19
Storage 84.33 184.34 3,285 54.67 -2.25
Functions 123.74 244.56 1,752 29.76 +28.85

Top API waits (after)

API request Max wait (ms)
account.name.update 511.22
storage.buckets.create 401.08
tablesdb.rows.create 370.69
functions.create 351.22
account.prefs.update 349.74

…stinct read appends

The join and distinct list path appends staged creates and upserts the
stored read did not return, and laid out the staged upsert without the
increments staged after it, so the same row read differently there than
through getDocument or a plain list.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@abnegate

Copy link
Copy Markdown
Member Author

Re the review findings outside the diff:

  • Join/distinct listDocuments drops increments from staged upserts. Fixed in 1a14e5e: the appended staged create/upsert now gets its pending increments. Regression test: testDistinctReadAddsAStagedIncrementToAStagedUpsertOfANewRow, which fails on the previous head and on main.
  • Join/distinct countDocuments evaluates filters on the staged document alone. This predates the PR: that branch never merges stored rows, so any partial staged update (for example of name under a filter on another column) is miscounted the same way, and on main legacy increments already hit it with the delta as the value. Fixing it means reading the stored rows in that path, which is a separate change from this fix.
  • Increment of an id with no stored row: getDocument empty vs stagedView value. Also predates the PR, for any staged update of a missing row (stagedView has always returned the staged document when the stored one is empty). Commit rejects the operation with not found either way.
  • Bulk update/delete matching and min/max. Answered in the inline threads.

@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 51dc61d into main Oct 22, 2026
49 checks passed
@abnegate
abnegate deleted the fix/transaction-staged-increments branch October 22, 2026 06:55
Tapraj-Pathak pushed a commit to Tapraj-Pathak/appwrite that referenced this pull request Oct 24, 2026
…d-increments

fix(databases): read staged increments on top of the stored value

(cherry picked from commit 51dc61d)
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