Skip to content

fix(databases): answer bad query input with 4xx, not 500 or warnings - #14538

Merged
abnegate merged 10 commits into
mainfrom
qfix-errors-blockers
Oct 15, 2026
Merged

abnegate merged 10 commits into
mainfrom
qfix-errors-blockers

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 QA of the query-lib migration (#11649, build c3f599d) found bad input answering 500 or raising PHP warnings, in code paths the migration made live:

  • Aggregate overflow: stddev/sum over a float column holding 1e308 answers 500. MySQL raises 1690 / PostgreSQL 22003, the adapter maps it to Utopia\Database\Exception\Limit, and the documents/rows list never caught it. Aggregations are new with the migration.
  • PHP warnings in packages/query: malformed spatial values hit Undefined array key warnings in Builder/Trait/Spatial.php (and silently fabricated POINT(x 0)), a malformed distance tuple raised a TypeError (500), and limit/offset values beyond the int range warned in Query::groupByType on PHP 8.5. On main (DB 7.4.2) none of this code ran: 7.4.2 never called utopia-php/query.

Fix

  • packages/query: malformed geometry (including a polygon ring with fewer than 4 points or not closed, and a flat point with more than two ordinates) and distance tuples throw ValidationException, which the adapter already turns into a Query exception, so the API answers 400 general_query_invalid. Out-of-range limit/offset values read as absent instead of warning.
  • New database_query_out_of_range (400) for an aggregate the database cannot represent: a Limit exception from the engine, or a non-finite result.
  • A query naming a nested path under a plain attribute (equal("s.x")) is fixed at the root in fix(query): refuse a nested path on an attribute that holds no nested values utopia-php/database#1022 (8.3.0): the validator refuses it before it reaches the engine. The database bump PR adds the end-to-end assertions for it.

Tests

  • Unit (packages/query): HelperTest, Builder/Feature/SpatialTest, Builder/SpatialDistanceFilterTest. Each new case collects PHP warnings and fails on BASE 5204588: 3, 28 and 9 failing cases respectively.
  • E2E (Legacy, TablesDB and DocumentsDB through DatabasesBase): Queries/RejectedValues covers malformed geometry and aggregate overflow.
  • Pint, PHPStan, Rector and bin/monorepo check query pass locally. The local unit-suite failures (yaml, maxminddb, Imagick fonts, JWT key) are environmental and identical on BASE.

E2E not run locally (no Docker); CI is the first run.

🤖 Generated with Claude Code

abnegate and others added 3 commits October 15, 2026 22:11
…p warnings

The query-lib migration routes every user filter through packages/query,
which DB 7.4.2 on main never called. Malformed query values from the public
API then reached code that assumed a well-formed shape:

- geometryToWkt read $p[1] / $point[1] from points with one ordinate and
  fabricated a POINT(x 0) from the result, so a malformed geometry raised
  "Undefined array key" warnings and silently matched the wrong shape, or
  produced WKT the database rejects with a 500.
- SpatialDistanceFilter::fromTuple read missing tuple keys and passed a
  non-boolean meters flag into a bool parameter (TypeError, 500).
- groupByType ran intval() on limit/offset values beyond the int range,
  which PHP 8.5 reports as a warning before the validator rejects them.

Malformed geometry and distance tuples now throw ValidationException, which
the database adapter already turns into a Query exception, so the API answers
400 general_query_invalid. Limit and offset values PHP cannot hold read as
absent instead of warning. A point with extra ordinates keeps its x and y, as
before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Aggregation queries are new with the query-lib migration. Summing or taking
the deviation of large doubles overflows: MySQL raises 1690 and PostgreSQL
22003, which the adapter maps to a Limit exception, and the list action let
it escape as a 500. An engine that returns the overflow as infinity instead
makes the response unencodable.

Both now answer 400 with the new database_query_out_of_range type, since the
query is valid but its result cannot be represented.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
utopia-php/database 8.x maps an unknown column (MySQL 1054, PostgreSQL
42703) to NotFound('Attribute not found'). The documents/rows list and the
files list catch every NotFound as "the backing table is missing", so
equal("s.x") on a plain column answered 404 table_not_found or
collection_not_found, and list endpoints with no NotFound catch, /users
among them, answered 500.

A NotFound whose driver cause is an unknown column is now classified by
Appwrite\Databases\Rejection from its SQLSTATE and driver code, not its
message. The HTTP error hook maps it to 400 general_query_invalid for every
endpoint, and the two lists that catch NotFound check it first. The
documents list also falls back to looking the table up, so only a table
that is really missing still answers 404.

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. 🟡 2 medium

💬 Inline comments (2)

  • 🟡 Flat [x,y,z] point silently truncated, nested one rejected — Spatial.php:19
  • 🟡 Global Rejection mapping turns server-side schema faults into 400s — general.php:1306

This PR hardens how list endpoints handle malformed queries and how driver errors are surfaced to clients. Geometry values passed to spatial filters are now validated (shape, finite numeric coordinates, WKT strings) before compilation, and distance tuples validate type and the meters flag. A new Appwrite\Databases\Rejection mapper converts driver-specific unknown-column errors (MySQL 1054, PostgreSQL 42703) into a 400 general_query_invalid response instead of a 404, with a fallback that still returns 404 when the collection is genuinely missing.

Files Change
packages/query/src/Builder/Trait/Spatial.php, SpatialDistanceFilter.php, Query.php Strict geometry/coordinate validation, distance-tuple validation, and warning-free toInteger() limit/offset parsing
src/Appwrite/Databases/Rejection.php, app/controllers/general.php, app/config/errors.php, src/Appwrite/Extend/Exception.php Driver-error classification into 400 responses, new DATABASE_QUERY_OUT_OF_RANGE error type, and updated Http::error() handling
Documents/XList.php, Storage Files/XList.php notFound() helper using the new rejection mapper plus LimitException → out-of-range mapping and assertRepresentable() guard on aggregate rows
tests/unit/*, tests/e2e/* Unit tests for Rejection, e2e coverage for rejected query values and dotted-path queries

Two medium-severity items remain open: inconsistent rejection of 3-element coordinates in geometryToWkt(), and a global unknown-column → 400 mapping in general.php that can misclassify server-side schema faults as client errors.

Reviewed commit: 855ffdf

@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 15, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

This PR hardens query handling by validating malformed spatial and distance inputs, treating out-of-range pagination values as absent, and mapping aggregate overflow to a structured 400 response. It also updates database and file list error handling and adds unit and E2E coverage for rejected query values.

Latest changes: The latest commit removes the unknown-column classifier and its dotted-path E2E case, while changing the document-list catches to treat every NotFound as a missing collection or table.

Verdict New comments Fixed Still open
✅ Approved 0 0 0

Couldn't attach to a line

These findings could not be placed on a changed line, so they were not posted as inline comments.

📂 Walkthrough · 18
File Change
packages/query/src/Builder/SpatialDistanceFilter.php, packages/query/src/Builder/Trait/Spatial.php, packages/query/src/Query.php Validates malformed spatial and distance query values and safely handles out-of-range limit and offset inputs.
packages/query/tests/API/HelperTest.php, packages/query/tests/Builder/Feature/SpatialTest.php, packages/query/tests/Builder/MySQLTest.php, packages/query/tests/Builder/SpatialDistanceFilterTest.php Adds regression tests for pagination parsing, malformed geometries, and invalid distance tuples.
app/config/errors.php, src/Appwrite/Extend/Exception.php Registers the structured 400 error for aggregate results outside the representable range.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/XList.php Adds aggregate result checks and maps database query failures; the latest change classifies every NotFound as a missing collection or table.
src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/XList.php Updates error handling for file-list database queries.
app/controllers/general.php, src/Appwrite/Databases/Rejection.php, tests/unit/Databases/Fakes/DriverException.php, tests/unit/Databases/RejectionTest.php Introduces and then removes the driver-based unknown-column classifier and its unit-test support.
tests/e2e/Services/Databases/DatabasesBase.php, tests/e2e/Services/Databases/Queries/RejectedValues.php, tests/e2e/Services/Users/UsersBase.php Adds API regression coverage for rejected query values; the latest change removes the dotted-path database case.
app/config/errors.php Registers a structured 400 error for aggregate results outside the representable range.
packages/query/src/Builder/SpatialDistanceFilter.php Validates distance tuples before constructing spatial filters.
packages/query/src/Builder/Trait/Spatial.php Validates spatial coordinates and geometry shapes, including polygon rings.
packages/query/src/Query.php Treats out-of-range limit and offset values as absent during query parsing.
packages/query/tests/API/HelperTest.php Adds regression coverage for safe pagination-value parsing.
packages/query/tests/Builder/Feature/SpatialTest.php Adds malformed spatial geometry regression cases.
packages/query/tests/Builder/MySQLTest.php Expects points with excess ordinates to be rejected.
packages/query/tests/Builder/SpatialDistanceFilterTest.php Covers malformed distance tuples and default distance units.
src/Appwrite/Extend/Exception.php Adds the aggregate-out-of-range exception type.
tests/e2e/Services/Databases/DatabasesBase.php Includes rejected-query scenarios in the shared database E2E suite.
tests/e2e/Services/Databases/Queries/RejectedValues.php Covers malformed geometry, aggregate overflow, and dotted paths on plain attributes.

Reviewed the commits since 9b6d8af · 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 strict validation of user-supplied geometry in spatial queries, a driver-error rejection mapper that turns unknown-column DB errors into 400s, and a new database_query_out_of_range error type covered by unit and e2e tests.

Key findings

  • 🟡 Flat [x,y,z] point silently truncated, nested one rejected — Spatial.php:19
  • 🟡 Global Rejection mapping turns server-side schema faults into 400s — general.php:1306

Comment thread app/controllers/general.php Resolved
@github-actions

github-actions Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → qfix-errors-blockers (after).

Metric Before After Change
🚀 Requests/sec 199.26 193.63 ⚪ -2.8%
⏱️ Latency P50 87.03 ms 90.56 ms ⚪ +4.1%
⏱️ Latency P95 200.82 ms 206.21 ms ⚪ +2.7%
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 90.56 206.21 12,483 193.63 +5.39
Account 165.27 302.19 657 10.88 +30.05
TablesDB 86.97 161.77 6,789 108.25 -3.33
Storage 85.25 191.53 3,285 53.72 +5.48
Functions 126.4 243.25 1,752 29.34 +21.5

Top API waits (after)

API request Max wait (ms)
storage.buckets.create 504.4
functions.variables.update 456.1
storage.files.create 434.88
account.name.update 431.46
account.prefs.update 397.89

abnegate and others added 3 commits October 15, 2026 23:19
A polygon ring with fewer than four points or whose last point differs
from its first passed validation and compiled to WKT the spatial parser
refuses, so the engine raised it as a 500. A flat point with a z ordinate
was cut down to its x and y and silently matched a different shape, while
the same point nested inside a line was already refused.

Both now throw ValidationException, which the API answers with 400
general_query_invalid.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…sent queries

The error hook turned every unknown-column driver error into 400
general_query_invalid on every route. A server fault, such as schema drift
on a platform collection or an internal query naming a column that was
never created, then read as the caller's mistake and skipped the >= 500
reporting path.

The hook now classifies the error only on a route that takes queries and
only when the request sent some. Anything else stays a 500.

MongoDB has no column list, so a nested path on a plain attribute matches
nothing there; the users test now expects an empty 200 on schemaless
engines instead of the 400 the SQL engines answer.

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

@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:36
MongoDB stores documents, not columns, so a nested path on a plain
attribute is a valid path that matches nothing and answers 200, as it did
before the query-lib migration. Only the SQL engines raise an unknown
column, which is the 404 and 500 regression these tests guard. The
attribute-support flag is true on MongoDB, so the tests now key on the
adapter instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/XList.php
#	tests/e2e/Services/Databases/DatabasesBase.php
abnegate and others added 2 commits October 16, 2026 00:35
utopia-php/database 8.3.0 refuses a nested path on an attribute that holds
no nested values before the query reaches the engine, so the unknown-column
driver error this mapped to 400 no longer happens for caller input. The
classifier, its error-hook wiring and the documents and files list
fallbacks go, and the lists treat NotFound as a missing table again.

The dotted-path end-to-end tests move to the database bump, where every
adapter answers them with 400 through QueryException.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@abnegate
abnegate merged commit c21bbe6 into main Oct 15, 2026
229 of 230 checks passed
@abnegate
abnegate deleted the qfix-errors-blockers branch October 15, 2026 11:57
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