Skip to content

fix(databases): type, name and shape aggregate, distinct and join rows - #14537

Merged
abnegate merged 10 commits into
mainfrom
qfix-aggregate-shape
Oct 15, 2026
Merged

abnegate merged 10 commits into
mainfrom
qfix-aggregate-shape

Conversation

@abnegate

@abnegate abnegate commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

Release blocker for #11649, found by staging QA of appwrite-labs/cloud#5410.

Problem

Staging evidence:

  • Aggregate values came back as raw DB strings: counts "7", variance "6.405119350733394e17", grouped booleans "1"/"0", arrays as JSON strings, datetimes "2023-06-01 00:00:00.000".
  • groupBy on system fields returned internal names: _uid, _createdAt, _id, _permissions.
  • Joined group keys were inconsistent: groupBy(['o.grp']) gave grp, while groupBy(['grp','o.grp']) gave o.grp.
  • Aggregate, distinct and unmatched right/full-join rows carried placeholder system fields: $sequence:"", $createdAt:"", $updatedAt:"", $id:null/"", $permissions:[].
  • distinct with values was silently accepted and the values ignored.

Fix

  • Typing, naming and decoding of aggregate rows now lives in utopia-php/database 8.3.0 (bump utopia/analytics to 0.2.0 #1024), bumped in chore(deps): bump utopia-php/database to ^8.3 and delete the stopgaps it replaces #14560. The server-side Aggregation class this PR first carried has been deleted. aggregate() now returns:
    • count, countDistinct and bit* as int; avg, stddev and variance as float; sum as int over an integer column and float otherwise; min and max typed by their column
    • groups typed and decoded like row values
    • system columns under their public names
    • joined columns always alias-qualified
  • The list wraps each aggregate row in Appwrite\Utopia\Database\Documents\Aggregate, on both the read and the cached path, so the response models know it is not a stored record.
  • Contract: a row carries a system field only if it really has one. Aggregate/groupBy rows hold only aggregates and groups. Distinct rows without $id and unmatched join rows drop all system fields. Normal rows keep the existing "" fill, which transactions depend on. Documented in list-rows.md and list-documents.md.
  • distinct with an attribute or values is rejected with a 400. In the library grammar, distinct dedupes the select() columns.

Tests

  • Unit: tests/unit/Utopia/Response/Model/RowTest.php, DocumentTest.php and packages/query/tests/API/ParseTest.php. They fail without the fix. The row-shaping unit tests moved to the library with the code (tests/unit/AggregationTest.php in feat(aggregate): type, name and decode rows as a read returns them utopia-php/database#1024).
  • E2E: tests/e2e/Services/Databases/Queries/AggregateShape.php (TablesDB and Legacy) asserts the response shape end to end. It now passes on the library's shaping alone.

Follow-ups

  • The SDK specs still mark $id, $sequence and timestamps as required on Row/Document, so typed SDKs can't parse aggregate rows until those become optional (they already failed before this PR).
  • A distinct read selecting $id still gets "" timestamps.

🤖 Generated with Claude Code

abnegate and others added 4 commits October 15, 2026 22:10
Query::distinct() takes nothing: it is a flag that deduplicates the
attributes the read's select() names. parseQuery() still accepted
{"method":"distinct","values":["grp"]} and dropped the values, so a
caller that meant "distinct on grp" got a distinct over whatever the
select named instead, with no sign anything was ignored.

Honouring values as a column list would give distinct a second way to
name its columns that disagrees with select() whenever both are given,
so the parser refuses it, and an API built on it answers 400.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Database::aggregate() hands back each row as the driver fetched it: no
casting, decoding or key mapping, unlike find(). The list action wrapped
those rows in a Document as they were, so the API returned counts as
"7", variances as "6.405119350733394e17", grouped booleans as "1"/"0",
arrays as their JSON text and datetimes in storage format. A group on a
system attribute came back under its storage column (_uid, _id,
_createdAt, _permissions), and a joined group came back bare ("grp")
unless another group shared its name, when it was "o.grp".

Aggregation decodes each row against the read's schema and queries:
count, countDistinct and the bitwise aggregates are integers; avg,
stddev and variance floats; sum, min and max take the type of the
attribute they read; each group is typed as a row types the attribute
(bool, int, float, decoded array, ISO 8601 datetime) and named as a read
names it, with a joined one always qualified by its join alias. It runs
after aggregate(), so a join the Joins hook refuses fails as before.

The rows come back as Documents\Aggregate, so the response models can
tell a row of an aggregation from a stored record without guessing from
its keys; the TTL cache rewraps cached aggregate rows the same way.

This belongs in utopia-php/database: aggregate() should return rows as
find() does. Until it does, the API decodes them here.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The Row and Document models filled $sequence, $createdAt and $updatedAt
with "" on every non-empty row. Aggregate rows have no record behind
them, so they came back with three fake system fields; distinct rows
carried $id: null beside $databaseId and $tableId; and a right or full
join row that no row of the main table matched carried $id: "" and
$permissions: [].

The contract is now that a row carries a record attribute only when it
has one:
- aggregate and groupBy rows (typed as Documents\Aggregate) hold only
  their aggregates and groups, and a group on $id or $createdAt keeps
  it;
- a row whose $id is empty or null (a distinct read that does not select
  $id, a join row with no main match) drops every record attribute,
  $databaseId and $tableId/$collectionId included;
- a record keeps the "" fill, because staged transaction writes rely on
  it to hydrate SDK models before they are committed.

An empty string is not a valid id, and a placeholder that typed SDKs can
parse is still wrong data: a client that reads $id from an aggregate row
gets "" and treats it as a row. A separate response model was not used,
because listRows and listDocuments return one model and swapping it for
a union would change every SDK's return type. The Row and Document
specs keep their required system fields, so typed SDKs need to make them
optional (a major SDK change) before they can parse these rows; the
list endpoints' descriptions now state the contract.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… join rows

Asserts, through TablesDB and the legacy documents API, the exact keys
and types staging QA found wrong: aggregate values by method and
attribute, grouped values typed like row values, system groups under
their public names, joined groups qualified by alias, distinct rows
holding only their selected columns, distinct with values refused, and
an unmatched right join row with no record attributes.

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

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

Copy link
Copy Markdown

Review complete. 🟠 1 high

💬 Inline comments (1)

  • 🟠 $parsed->isAggregation() is called but never defined — XList.php:159
🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Avoid preg_replace in aggregate alias sanitizing (Aggregation.php:310) — The new alias() helper strips non-alphanumeric characters from the default aggregate alias with preg_replace (src/Appwrite/Utopia/Database/Aggregation.php:310), which violates the repository convention against regex in new code.

This PR makes aggregation queries on list-documents/list-rows return typed, correctly named aggregate rows instead of raw driver output. It introduces a new Aggregation decoder plus an Aggregate document subclass, updates the Document/Row response-model filters to strip and re-fill system attributes, and rejects malformed distinct queries at parse time, with unit and e2e coverage and doc updates.

Files Change
src/Appwrite/Utopia/Database/Aggregation.php, Documents/Aggregate.php New aggregation row decoder with per-adapter casting and naming, plus its document type.
src/Appwrite/Platform/Modules/Databases/Http/.../Documents/XList.php Wires aggregation decoding and joined-collection lookup into the list endpoint, including the cached-response path.
packages/query/src/Query.php, packages/query/tests/API/ParseTest.php Validates that distinct queries carry no attribute/values, with parse tests.
src/Appwrite/Utopia/Response/Model/Document.php, Row.php Adjust response filtering to shape aggregate rows and strip stored/system attributes on empty $id.
tests/unit/**, tests/e2e/Services/Databases/**, docs/references/** Unit, e2e aggregate-shape coverage and reference doc updates.

Reviewed commit: 76a6dfc

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

@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 typed aggregation result decoding and response shaping for the Databases list endpoints, guarded by a distinct-query parse validation.

Key findings

  • 🟠 $parsed->isAggregation() is called but never defined — XList.php:159

@github-actions

github-actions Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → qfix-aggregate-shape (after).

Metric Before After Change
🚀 Requests/sec 211.89 218.94 ⚪ +3.3%
⏱️ Latency P50 80.52 ms 79.98 ms ⚪ -0.7%
⏱️ Latency P95 186.8 ms 182.09 ms ⚪ -2.5%
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 79.98 182.09 13,680 218.94 -4.71
Account 149.6 277.43 720 12.25 +7.03
TablesDB 79.42 150.9 7,440 121.8 -1.95
Storage 69.35 160.64 3,600 60.56 -14.58
Functions 108.3 202.94 1,920 32.83 +0.69

Top API waits (after)

API request Max wait (ms)
account.name.update 480.61
functions.create 386.9
account.prefs.update 374.43
functions.variables.update 337.3
account.get 313.79

@ghost

ghost commented Oct 15, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

This PR fixes the response shape for aggregate, distinct, and unmatched join results, including typed aggregate values and consistent field names. It also rejects unsupported distinct arguments, adjusts response models to omit synthetic system fields when appropriate, and documents the resulting API contract.

Latest changes: The latest commits remove app-side aggregate decoding and custom list pagination/count handling, instead wrapping the database library’s aggregate rows and passing the original queries through to its native read and count behavior.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 12
File Change
docs/references/databases/list-documents.md Document system-field behavior for aggregate, distinct, and unmatched join documents.
docs/references/tablesdb/list-rows.md Document system-field behavior for aggregate, distinct, and unmatched join rows.
packages/query/src/Query.php Reject distinct queries that specify unsupported attributes or values.
packages/query/tests/API/ParseTest.php Cover valid distinct parsing and rejection of unsupported arguments.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/XList.php Use library-shaped aggregate rows and native library pagination and counting.
src/Appwrite/Utopia/Database/Documents/Aggregate.php Add an aggregate-row document type for response-model filtering.
src/Appwrite/Utopia/Response/Model/Document.php Preserve normal document defaults while omitting synthetic fields from partial rows.
src/Appwrite/Utopia/Response/Model/Row.php Preserve normal row defaults while omitting synthetic fields from partial rows.
tests/e2e/Services/Databases/DatabasesBase.php Add shared setup and helpers for aggregate-shape API coverage.
tests/e2e/Services/Databases/Queries/AggregateShape.php Cover aggregate typing and naming, distinct output, and unmatched joins across APIs.
tests/unit/Utopia/Response/Model/DocumentTest.php Test full and partial document response shapes.
tests/unit/Utopia/Response/Model/RowTest.php Test full and partial row response shapes.

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

ghost
ghost previously requested changes Oct 15, 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

abnegate and others added 2 commits October 15, 2026 22:31
AGENTS.md forbids new regular expressions. The default alias only maps
every byte outside [A-Za-z0-9_] to an underscore, which ctype_alnum
expresses per byte with the same result. Database::aliasAggregates() is
private, so there is no helper to reuse.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A group was only JSON decoded and cast, so an attribute with a filter or
codec, such as an encrypted string, came back from groupBy in its stored
form while a normal read of the same row decrypts it. Groups are now
passed through Database::decode() for the collection, or join, they are
read from, which applies every filter the attribute declares, honours
disabled filters and resolves registered codecs the same way find() does.

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

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 and others added 2 commits October 15, 2026 23:02
# Conflicts:
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/XList.php
abnegate and others added 2 commits October 16, 2026 01:47
# Conflicts:
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/XList.php
#	tests/e2e/Services/Databases/DatabasesBase.php
utopia-php/database#1024 (8.3.0) types, names and decodes aggregate rows
the way find() returns documents, and owns the tests for it, so
Aggregation and its unit tests go. The list wraps each row in an Aggregate,
which the Document and Row response models use to leave out the stored
attributes an aggregate row does not group. The AggregateShape e2e tests
now cover the library's shaping end to end.

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

Copy link
Copy Markdown
Member Author

Reworked onto utopia-php/database 8.3.0, now on main through #14560.

What stays here is what the server owns:

  • the Document/Row response models leaving out synthetic system fields on aggregate, distinct and unmatched-join rows
  • the docs in list-documents.md / list-rows.md
  • the packages/query refusal of distinct with an attribute or values

The AggregateShape e2e tests are unchanged, so they now prove the library's shaping end to end.

@abnegate
abnegate merged commit 82c0216 into main Oct 15, 2026
226 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