Skip to content

feat(extension): utopia-php/query in Rust: classifiers, tokenizers, Query, AST, schemas and builders - #15734

Merged
loks0n merged 76 commits into
mainfrom
feat/query-extension
Nov 24, 2026
Merged

loks0n merged 76 commits into
mainfrom
feat/query-extension

Conversation

@loks0n

@loks0n loks0n commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

Moves five parts of packages/query onto the utopia extension: the classifiers, the tokenizers, Query, the AST's parser and serializers, and the schemas. Off by default: nothing changes unless _APP_EXTENSION_LIBRARIES names query.

This was a stack of five PRs (this one, #15735, #15739, #15748 and #15753). They are now one, and each part keeps its own section below. The builders are here too, under the same query switch. Method and the small enums are still PHP.

crates/extension/tests/query.php runs every part on PHP and on the extension and compares the output: 55,481 lines, identical on macOS and on the Alpine image.

Without #15328

This branch was built on #15328 (string literals quoted per dialect, LIKE with a declared escape, a stricter parser). That is taken back out: 59d225636e reverts its merge and 458b4a59be reverts the Rust port of it, so the PHP package here is main's plus the changes listed under each part.

It came out because it broke SQLite with the extension off. utopia-php/database 10.2.3's SQLite builder appends its own ESCAPE, the package's began to as well, and SQLite refused the statement. The database library's unit suite went from 9 failures to 63, and Cloud's unit tests failed.

Re-landing #15328 is a revert of those two commits, together with a utopia-php/database release that drops its own clause.

The classifiers

What

The interface and the enum are registered as well, not left in PHP: a class registered at module start cannot implement a userland interface. PHP code that implements Classifier, extends Classifier\SQL with its own classify(), or extends a concrete classifier and calls parent::classify() works as before; the corpus covers each.

One thing found on the way

A #[php_class] that derives Default breaks PHP subclasses on ext-php-rs 0.16.5: new Sub() returns an object of the Rust class, so the subclass's overrides are never called and $object instanceof Sub is false. The classes here do not derive it, and a comment says why. Domain and Email do not derive it either, so they are unaffected. Not yet reported upstream.

Checked (locally, macOS, PHP 8.5.12)

  • cargo fmt --all --check and cargo clippy -p utopia-extension -p utopia-query --all-targets -- -D warnings: clean. cargo test -p utopia-query: 54 passed.
  • packages/query/tests without E2E, on the extension: 5,622 tests pass. The same suite passes on PHP.
  • crates/extension/tests/query.php: 24,773 corpus lines, identical on PHP, on the extension, and with emails,query both on.
  • One asserted difference: ReflectionClass::isFinal() is false for Type; a PHP enum reports true. Extending it is refused either way.
  • Seen red: with the MongoDB class wired to the PostgreSQL classifier, 3,011 corpus lines differed and 29 package tests failed.

Benchmark (crates/extension/bench/query.php, release build, OPcache on, median of 5, ns per call):

operation PHP Rust Rust/PHP
mysql COM_QUERY select 458 65 0.14
mysql COM_STMT_EXECUTE 38 44 1.16
postgres Q select 487 113 0.23
postgres Q commented update 864 107 0.12
classifySQL CTE insert 8458 242 0.03
classifySQL begin 359 52 0.14
extractKeyword 740 79 0.11
mongodb find 674 54 0.08
mongodb insert in a txn 1063 65 0.06

COM_STMT_EXECUTE reads one byte and returns, so the call into the extension is all there is to measure.

Not checked:

  • run.sh itself and the Alpine build: both run only in the Extension job.
  • packages/query/tests/E2E on the extension. It does not touch the classifiers.

The tokenizers

What

  • crates/extension/src/query/tokenizer.rs: with query on, the extension registers Utopia\Query\Tokenizer\Tokenizer and its dialects MySQL, MariaDB, PostgreSQL, SQLite and ClickHouse.
  • Token and TokenType stay PHP. A token is a value object, so tokenize() returns the package's own Tokens, made by its constructor with the cases of its enum; filter() returns the objects it was given.
  • An unterminated string or identifier throws the package's ValidationException, with the same message.
  • crates/extension/src/query.rs becomes query/classifier.rs, with the shared exception helper in query/mod.rs.

Tests changed

Five tests in packages/query/tests/Tokenizer/MySQLTest.php called the private replaceHashComments() by reflection, which the native class does not have. They now go through tokenize():

  • Four read the rewritten SQL back by joining the token values, which cover every byte.
  • One input cannot be tokenized at all, so that test now asserts the exception. The exception is the proof the # was left alone: had it been rewritten to a comment, the stray quote would be inside the comment and tokenizing would succeed.

Seen red: with the PHP method changed to rewrite every #, three of the five fail (the other two assert a rewrite that does happen).

Checked (locally, macOS, PHP 8.5.12)

  • cargo fmt --all --check and cargo clippy --locked -p utopia-extension --all-targets -- -D warnings: clean.
  • packages/query/tests without E2E: 5,622 tests pass on PHP and on the extension.
  • crates/extension/tests/query.php: 44,813 corpus lines (20,040 of them new), identical on PHP, on the extension, and with emails,query both on.
  • Two asserted differences, both in the README:
    • A tokenizer holds nothing. PHP keeps the last SQL, its length and position in private properties, so a PHP tokenizer that has tokenized is not == a new one.
    • getIdentifierQuoteChar() exists and returns the dialect's quote, but tokenize() does not ask it, so a subclass that overrides it does not change the quote. Nothing in Appwrite or Cloud does.
  • Seen red: with MariaDB wired to the standard dialect, 703 corpus lines differed. The package's own tests stayed green under that change; they do not cover # comments on MariaDB.

Benchmark (release build, OPcache on, median of 5, ns per call):

operation PHP Rust Rust/PHP
tokenize select (22 tokens) 14914 4667 0.31
tokenize + filter 15246 6253 0.41
tokenize mysql # comment 10920 3391 0.31
tokenize postgres operators 16722 3841 0.23
tokenize CTE (60 tokens) 24394 7035 0.29

Most of the Rust time is building the PHP Token objects through their constructor.

Not checked: run.sh and the Alpine build, which run only in the Extension job.

Query

Two things that would have broken production

The package's own 5,622 tests passed on the first complete version of this binding. Both problems were outside them, in utopia-php/database 10.1.4, which composer.lock pins and whose Query extends this class:

  1. The library failed to load at all. Utopia\Database\Query::cursorAfter(array|object $value) is not compatible with an extension method that declares its parameter mixed, so PHP raised a fatal error when the class was declared. It also reads self::LOGICAL_TYPES, a constant of arrays, which a class registered at module start cannot have.
  2. Its overrides were skipped. Query.php calls static::parseQuery(), static::isMethod() and others mid-parse, and $this->toArray() from toString(). The database library overrides those to decode children given as JSON strings and to write a cursor document as its id. The first version called its own Rust code instead.

Both are fixed, and both are now in the corpus. Its own tests/unit/QueryTest.php (18 tests, 325 assertions) passes on PHP and on the extension.

What

  • crates/extension/src/query/value.rs: with query on, the extension registers Utopia\Query\NativeQuery, the methods and state of Query.
  • packages/query/src/extension.php (a Composer files entry) loads packages/query/extension/Query.php when NativeQuery exists. That declares Query extends NativeQuery with the two array constants, before the autoloader looks for src/Query.php. The declaration is outside src/ so static analysis reads src/Query.php as the one declaration.
  • A query's values stay PHP values. A nested query is the same object, getValues() returns the array that was stored, and clone copies nested queries.
  • Method, NullsPosition, CursorDirection, ParsedQuery and the exceptions stay PHP.
  • json_decode() is PHP's own, called from the binding, so parse() accepts, refuses and reports exactly what it did. toString() writes the JSON itself for a query of nulls, booleans, integers, UTF-8 strings and queries like it, and hands anything else to PHP's json_encode(). The corpus runs both paths over escapes, invalid UTF-8, floats, arrays, objects and 300 levels of nesting.

For subclasses:

  • new static makes the class a method was called on, directly when it keeps the extension's constructor and through its own otherwise, including through parent::.
  • Every method Query.php reaches through static runs a subclass's own, in the same order. The same holds for toArray() and shape() called on a query object.
  • Array parameters are declared array. The cursor factories take array|object and are declared array, the nearest type an array|object override is compatible with.

Tests changed

HelperTest::testContainsHasDeprecatedAttribute read the #[\Deprecated] attribute of contains() by reflection. It is now testContainsRaisesADeprecation, which asserts the deprecation the call raises. The binding raises the same one.

Checked (locally, macOS, PHP 8.5.12)

  • cargo fmt --all --check and cargo clippy --locked -p utopia-extension --all-targets -- -D warnings: clean.
  • bin/monorepo check query (rector, pint, PHPStan at the package's level): passes.
  • packages/query/tests without E2E: 5,622 tests pass on PHP and on the extension.
  • utopia-php/database 10.1.4 tests/unit/QueryTest.php: 18 tests pass on both.
  • crates/extension/tests/query.php: 52,138 corpus lines, identical on PHP, on the extension, and with emails,query both on.
  • Seen red:
    • With the alias rule for joins changed, 260 corpus lines differed and 1 package test failed.
    • With the static dispatch disabled, 13 corpus lines differed. The package's tests stayed green: none of them has a subclass that overrides those methods.

Known differences, each asserted by the corpus:

  • Query has a parent class, NativeQuery.
  • More arguments than a method declares are an ArgumentCountError; PHP ignores the extras.
  • A call that both omits an argument and passes a wrong one raises ArgumentCountError, a subclass of the TypeError PHP raises.
  • isset() on a protected property from outside the class is true.
  • serialize() refuses the object. Nothing in Appwrite serializes a query.

One difference not asserted: groupByType(), getByType(), getCursorQueries(), merge() and validate() read a listed query's state directly, where PHP calls its getters. A subclass that overrides getMethod(), getAttribute() or getValues() is not consulted there. None of the three subclasses in this repository or the database library does.

Benchmark

Release build, OPcache on, median of 5, ns per call:

operation PHP Rust Rust/PHP
Query::equal 140 77 0.55
new Query 123 174 1.42
getters (4) 74 103 1.40
parse filter 814 608 0.75
parse nested (and of 3) 4270 2480 0.58
parseQueries (5) 7610 4838 0.64
toString 220 102 0.47
toString nested 953 354 0.37
clone nested 496 544 1.10
groupByType (8) 1811 1467 0.81
getByType 402 448 1.11
fingerprint (8) 4270 1580 0.37
validate (8) 1510 521 0.34

This is not a performance change. Query is a value object over PHP values, so the binding is mostly glue: factories, parsing, toString() and analysis are faster, and new Query(...), the getters and clone are slower by the cost of crossing into the extension. That cost is ext-php-rs's: it rebuilds each method's argument descriptions, default values included, on every call. The five rows above for new Query, the getters, toString and clone were measured again after mimalloc and the toString() change. A subclass with its own constructor, as Utopia\Database\Query has, pays the new Query cost on every factory call. The reason to have it is that the builders can then be moved without converting queries at their boundary.

Not checked

  • run.sh and the Alpine build, which run only in the Extension job.
  • bin/monorepo validate. Locally it reports duplicates from a linked vendor directory that is not this branch's.
  • Appwrite's E2E suites with query on. Nothing here turns it on.
  • Other libraries that extend Query outside this repository and the database library.

The AST's parser and serializers

What moves

AST\Grammar, AST\Parser, and AST\Serializer with MySQL, MariaDB, PostgreSQL, SQLite and ClickHouse, over crates/utopia/query. The builders are their only callers. utopia-php/database does not use the AST.

The 25 node classes stay PHP. They are readonly data, and Query showed that a native class makes new about twice as slow. AST\Walker and the visitors stay PHP too, because a walk is only calls into a PHP visitor.

One change to PHP, for everyone

The first commit changes packages/query/src/AST/Serializer.php whether or not the extension is on. main drops the parentheses of an equal-precedence right operand for every operator except -, / and %, so it writes a = (b = c) as a = b = c, which reads back as (a = b) = c. The crate was ported from the fixed serializer on feat/rust-utopia-conversion, and the corpus found the 260 cases where the two disagreed. I took @eldadfux's fix as it is and added two tests that fail on the old file.

Two things worth reviewing closely

Nodes are read and written by property slot. The parser does not call the node constructors. They only assign, and the two that validate check what the parser already checked. The first use in a request verifies every node class's property names and offsets, and throws an Error naming the class if the package and the extension disagree.

Deep trees run on an allocated stack. My first version overflowed the native stack on a chain of 1,000 NOTs, which PHP handles because it recurses on its heap. Reading one level of a tree costs 3.1 KB of stack in a release build (measured), and a Swoole coroutine has 2 MB. The binding now measures a tree and works on anything deeper than 32 levels on a stack sized for it, using stacker, which is a new dependency. Nothing on that stack calls PHP code. Under 512 KB and 128 KB fiber stacks, PHP and the extension now stop at the same inputs, where PHP's own engine overflows freeing the objects.

Checks

  • Parity corpus: 54,242 cases, identical on PHP, query and emails,query. The AST adds about 2,100 of them, including 209 statements each cut, dropped and swapped at every token, every pair of 31 operators nested both ways, trees 20,000 levels deep and chains of 8,000 terms.
  • packages/query/tests: 5,624 pass on PHP and on the extension.
  • bin/monorepo check query, cargo fmt, cargo clippy -D warnings: clean.

Known differences, asserted in the corpus

  • serialize() does not call a subclass's serializeExpression() or quoteIdentifier(). PHP does. No subclass in Appwrite or Cloud overrides them.
  • More than 1,024 chained NOT or sign operators are refused with ValidationException. PHP parses until memory runs out. Trees past 100,000 levels are refused the same way.

Benchmark

Release build, medians of 3 runs, macOS arm64.

Operation PHP ns Rust ns Rust/PHP
parse select (23 tokens) 16,847 2,040 0.12
parse report (181 tokens) 84,759 11,154 0.13
parse 150 ORs (609 tokens) 413,727 61,237 0.15
serialize select 2,398 1,187 0.49
serialize report 14,118 6,506 0.46
serialize 150 ORs 89,009 85,441 0.96
SQL to SQL (report) 224,042 60,260 0.27
Grammar::isType 321 41 0.13

Serializing the 150-term chain is no faster. It is 150 levels deep, so it pays for the measuring pass and the allocated stack.

Not checked

  • The small-stack comparison ran in PHP fibers on macOS, not in a Swoole coroutine on Linux.
  • bin/monorepo validate locally, and Appwrite's E2E suites with query on.

The schemas

What moves

Schema and Schema\SQL (abstract), the dialects Schema\MySQL, PostgreSQL, SQLite, ClickHouse and MongoDB, and the 16 Schema\Feature\* interfaces they implement.

The blueprints stay PHP: Table, Column, ForeignKey, Index, CheckConstraint, RenameColumn, their dialect classes, traits and forwarders, and the enums. PHP code fills them with fluent calls and they validate as they are filled. A schema reads a finished blueprint, compiles it with crates/utopia/query and returns the package's Builder\Statement.

Speed

A statement takes 7% to 22% less time than PHP's on the Alpine image. The first commit took 13% to 35% longer, and the second fixes that.

Operation PHP ns First commit ns Now ns Now/PHP
create table (18 columns) 6504 8302 6023 0.93
build and create table 13034 14742 11614 0.89
alter table 6805 9177 5801 0.85
createIndex 899 1073 702 0.78
drop table 311 355 255 0.82

Release builds made by the Dockerfile's extension-build stage, run in appwrite/base:2.3.1 on arm64, OPcache on, median of 5 alternating rounds. On macOS the same cases run at 0.72 to 0.84 of PHP's time.

A profile showed more than half of a compileCreate() in malloc and free. Three changes followed:

  • mimalloc is the extension's allocator. This alone brought Alpine level with PHP. It applies to every library in the extension, and PHP's own allocations stay with PHP's allocator. local_dynamic_tls is what a library loaded with dlopen needs on musl.
  • The crate writes a column definition into one string. It joined a list of parts before. Four dialect functions change, and the crate's tests and the corpus pass unchanged.
  • A Statement is made by setting its property slots. Its constructor only assigns promoted properties, and calling a PHP constructor from Rust costs more than new does in PHP. If the constructor ever does more, this has to follow it.

The margin is small because PHP compiles DDL with string concatenation, which it does well, and the extension has to read the blueprint out of PHP objects first. Only DDL calls a schema, so the main gain is still that the crate's DDL is checked against PHP's, statement for statement.

To review

  • Slot reads. The schema reads blueprint properties by slot. It finds each slot by name once a request for each class (Table\MySQL, Column\ClickHouse, a test's subclass), so a subclass or a class with extra properties still reads right. Reading by name through the property table was twice as slow as PHP.
  • One macro for the methods. A parent's native method reads its own Rust type, so every dialect class declares all its methods. schema_methods! takes the feature list ([views, databases, ...], the same list as PHP's implements) and writes them.
  • Parameter names are PHP's. The database library calls createIndex(unique: ..., rawColumns: ...), and ext-php-rs names a parameter after the Rust one, so schema.rs allows non_snake_case. The corpus compares every signature.
  • The crate change. definition_mut() on Table and Column, to set a blueprint read from elsewhere.
  • The executor. The closure given to setExecutor() is held in Rust, where PHP's cycle collector does not look. A closure that reaches its own schema is freed at the end of the request. The database library's executor is bound to the database, which does not keep the schema.

Checks

  • crates/extension/tests/query.php is identical on PHP, on query and on emails,query: 55,460 lines, 1,231 of them new. The README lists what they cover.
  • packages/query/tests on the extension: 5,624 tests pass.
  • The 80 database library unit test files that create collections, attributes or indexes give the same results on both.
  • The corpus is also identical on the Alpine build, on PHP, on query and on emails,query.
  • 240,000 rounds of table, index, view and error calls on four dialects: the PHP heap grows 32 bytes.
  • cargo fmt --check, cargo clippy -D warnings, Pint.

Known differences

Each is asserted in the corpus and described in the README.

  • The classes have the public methods only. PHP's protected steps (quote(), compileColumnType(), ...) are not there to override or call, and the abstract Schema has no methods of its own. Nothing in Appwrite, Cloud or the database library subclasses a schema.
  • The Feature interfaces declare no methods. instanceof answers as before.
  • A schema reads the whole blueprint before it compiles. PHP reads only what the statement uses. They differ only on a blueprint made past its own validation, with a subclass or reflection.
  • An index length must be a number. PHP writes whatever it is given.
  • A procedure parameter's direction must be a ParameterDirection.
  • MongoDB refuses a string that is not UTF-8 when it reads it. PHP refuses it only if the statement uses it.

Not checked

  • E2E with query switched on.
  • A Swoole coroutine on Linux. Nothing here recurses, so the stack is not a concern as it was for the AST.
  • bin/monorepo validate: no file under packages/ changes.

The builders

Off unless _APP_EXTENSION_LIBRARIES names query, like the rest.

What

  • Builder\MySQL, MariaDB, PostgreSQL, SQLite, ClickHouse and MongoDB, the abstract Builder and Builder\SQL, the Compiler interface and the 51 Feature\* interfaces.
  • Every public and protected method PHP's builders have is native, with PHP's signature. The corpus compares each public one, and the interfaces each builder implements.

What a subclass can rely on

  • A protected method it overrides is the one the build calls, in the order PHP calls them: build(), the compile*() methods, the clause hooks, the validators and every other helper, 73 in all. parent:: runs the native one. An override is handed the package's own objects, and nothing is converted for a method no subclass overrides.
  • fromAst() writes what stays raw SQL with the serializer a subclass's createAstSerializer() returns.
  • bindings, pendingQueries and resolvedAttributeCache are protected properties it reads, assigns and appends to.
  • Its constructor need not call the parent's.
  • It can override a public method with PHP's own types: fluent methods return static, build() returns Statement, select() takes array|string.

These need PHP's post-startup hook, because #[php_class] cannot express them: static and union types, attaching the interfaces, and creating an object with its state already in it.

A fix for Query that came out of this

serialize() of a Query threw. utopia-php/database hashes serialize($queries) for its cache keys. It now writes byte for byte what PHP's class writes, and unserialize() reads it, so either reads what the other wrote.

Tests changed

Two tests in packages/query/tests/Regression/CorrectnessRegressionTest.php read the PHP builder's source file and a private property by reflection. They are skipped when the class is the extension's.

Checked (locally, macOS, PHP 8.5.12)

  • crates/extension/tests/query-builders.php: 15,797 cases, identical on PHP and the extension. They include a subclass that overrides every dispatched helper and records the order they ran in.
  • The package's 5,628 tests pass on PHP, with query on, and with the builders on (two skipped, above).
  • utopia-php/database 10.2.3, which subclasses four builders and overrides 23 of their methods: its 13,217 unit tests fail the same nine on main's PHP package, on this branch's and on the native builders. The nine need a database server.
  • opcache.php with a PHP subclass of each of the 60 builder classes and interfaces.
  • A typical read (five queries, three columns) builds in 3.7 µs against PHP's 11 µs. No JIT, and measured before the last hundred methods moved.

Not done

  • PHP's builders have about fifty more protected properties. They do not exist here, so a subclass that composes one of the package's Builder\Trait\* traits works only when the trait touches pendingQueries and bindings alone.
  • run.sh now runs the builders with the query package's tests. I changed it without being able to run it: it runs only in the Extension job.
  • Not run on Alpine, and there is no E2E for the builders on the extension.

🤖 Generated with Claude Code

abnegate and others added 13 commits November 5, 2026 16:47
toRawSql(), the schema builder and the AST serializer each hand-rolled their
own escaping. The schema builder and AST serializer doubled backslashes for
every dialect, which PostgreSQL (standard_conforming_strings) and SQLite read
literally, so the stored or compared value gained a backslash; the AST path
is executed SQL through fromAst().

StringLiteral gives one case per dialect: Backslash (MySQL/MariaDB) escapes
backslashes, Extended (PostgreSQL) switches to E'' when a backslash is
present, Standard (SQLite) only doubles quotes, Unicode (ClickHouse) escapes
both. A backslash right after a byte >= 0x80 is refused on MySQL, MariaDB and
PostgreSQL, since a GBK/BIG5/SJIS/GB18030 lead byte swallows the escaping
backslash and lets the value close its literal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MySQL and MariaDB escaped LIKE wildcards with a backslash without an ESCAPE
clause, so under NO_BACKSLASH_ESCAPES the backslash was no escape and an
escaped % or _ matched as a wildcard. They now escape with ! and declare
ESCAPE '!', which holds in every sql_mode and leaves backslashes literal.
SQLite has no default LIKE escape, so it now declares ESCAPE '\' for the
backslash escaping it already used. setJsonRemove's JSON_SEARCH matches a
LIKE pattern too, so its value is escaped and the escape character passed.

Every LIKE emit goes through compileLikePredicate so a dialect declares its
escape in one place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
JSON_SEARCH returns NULL for a value that is not in the array (and on MySQL
for any non-string value), and JSON_REMOVE with a NULL path returns NULL, so
removing a missing tag wiped the column or failed on a NOT NULL column in
strict mode. COALESCE falls back to the original column.

The LIKE escape character is now quoted through the dialect's StringLiteral
in both the ESCAPE clause and JSON_SEARCH, and the identical MySQL/SQLite
likeEscape() overrides collapse into one base implementation gated by
DECLARES_LIKE_ESCAPE. PostgreSQL and ClickHouse still emit no ESCAPE clause,
and the ClickHouse LIKE fallback reuses compileLikePredicate(). SQLite's LIKE
index optimization stays available because the backslash escape is ASCII.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Unicode suggested PostgreSQL's U&'' literals, but the case is backslash
escaping without the multibyte lead-byte refusal, so it is now
BackslashUtf8. Per-case behaviour moves into exhaustive match methods
(escapesBackslash, refusesBackslashAfterHighByte, refusesNul,
escapePrefix) so adding a case fails to compile until each is decided,
replacing the default arm and the scattered identity checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The MySQL, MariaDB and ClickHouse builders built the base AST serializer,
leaving their dialect serializer classes unused and free to drift; each
now builds its own, as PostgreSQL and SQLite already did. Those classes
add no behaviour beyond the literal, so output is unchanged.
PostgreSQL::quoteJsonKey hard-coded StringLiteral::Extended instead of
the builder's literal, and was a private one-line wrapper, so it is
inlined. Enum quoting in the MySQL and PostgreSQL schema builders passes
quote(...) as a first-class callable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The serializer quotes per dialect but the tokenizer treated a backslash
as an escape everywhere and the parser undid only '' and \', so the two
disagreed: SQLite's 'C:\' was reported unterminated, PostgreSQL's plain
'a\' swallowed the closing quote and E'..' was not one token, and a
MySQL 'a\\b' parsed to a\\b and re-serialized doubled. toAst() also
parsed CTE bodies with a bare MySQL-flavoured tokenizer.

StringLiteral gains unquote(), the inverse of quote(), which decodes
the dialect's escapes (MySQL keeps \% and \_ as MySQL does; PostgreSQL's
E'' octal, hex and Unicode escapes; ClickHouse's \xHH) and refuses a
malformed literal. Tokenizer and Parser take a StringLiteral, each
dialect tokenizer defaulting to its own, and builders tokenize and parse
CTEs with their dialect's tokenizer and literal.

The SQLite tokenizer no longer narrows identifier quoting to double
quotes: its builder emits backticks, which SQLite accepts, so CTE bodies
from it failed to parse once toAst() used the SQLite tokenizer. No
existing tokenizer or parser test encoded the old backslash behaviour,
so none needed changing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Under NO_BACKSLASH_ESCAPES MySQL and MariaDB read a backslash literally,
so a schema comment or default with one is stored with it doubled. The
'' doubling holds in both modes, so this is wrong data rather than an
injection, but callers running that mode need to know.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Creates a table whose string default, table comment and column comment
hold a backslash and a quote through the schema builder, then reads them
back with obj_description, col_description and an inserted row, so the
E'' quoting is checked against the server rather than against a string.
LikeEscapeTest is made final like the other test classes added here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
toAst() re-parses CTE bodies, and the parser stopped at ESCAPE without
complaint, so MySQL, MariaDB and SQLite CTEs lost their ESCAPE clause while
the bindings stayed escaped. The parser now reads ESCAPE after LIKE, ILIKE
and their negations into Binary::$escape, and parse() rejects any token left
after the statement (one trailing semicolon aside) so an unknown clause can
no longer vanish. toAst() escapes the LIKE values it builds and declares the
dialect's escape character, and fromAst() decodes patterns with the declared
or implicit escape, keeping anything it cannot map raw with its clause.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…mast

fromAst() dropped an OR operand it could not turn into a Query, which now
happens for a LIKE with an unusable ESCAPE value, so the remaining operand
widened the filter. Such operands are kept as raw conditions. A LIKE whose
escape character is itself a wildcard was decoded with the leading % read
as a wildcard before the escape check; it now stays raw.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…gexes

The repository avoids regular expressions; an explicit scan reads each
dialect's escapes with the same rules and is easier to review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Unchanged from feat/rust-utopia-conversion at a962288. Nothing uses it yet.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…_LIBRARIES=query

The first part of packages/query on the utopia extension: the Classifier
interface, Classifier\SQL, MySQL, PostgreSQL and MongoDB, and the Type enum
they return. Every other class of the package stays PHP.

The parity corpus is identical on both implementations but for one asserted
difference (the enum does not report itself final), and packages/query/tests
pass on the extension. run.sh leaves out the package's E2E tests, which need
database servers.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@loks0n loks0n self-assigned this Nov 17, 2026
# Conflicts:
#	crates/extension/src/lib.rs
@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Security rules

WARNING (1 new) — review signal only; does not fail the job.

php.appwrite.weak-secret-env-default (1)

Secret-like env var (SECRET, KEY, PASS, PASSWORD, TOKEN) read with a non-empty literal default. If the variable is unset the process silently runs with a shared, guessable value. Default to '' and fail or disable the feature when it is empty.

  • app/init/resources.php:354 — resource logs
    • What's wrong: _APP_USAGE_PASS falls back to 'appwrite' when unset, so every install that does not set it shares that value.
    • How to fix: Read System::getEnv('_APP_USAGE_PASS', '') and fail or disable the dependent connection when it is empty; keep the example value in .env / app/config/variables.php.
6 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (3)
  • php.appwrite.secret-compare-timing (1)
  • 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.

Tokenizer\Tokenizer and its MySQL, MariaDB, PostgreSQL, SQLite and ClickHouse
dialects, behind _APP_EXTENSION_LIBRARIES=query. Token and TokenType stay PHP:
tokenize() returns the package's own objects.

Five MySQL tokenizer tests reached a private method by reflection; they now go
through tokenize(), so they run on both implementations.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → feat/query-extension (after).

Metric Before After Change
🚀 Requests/sec 214.02 217.49 ⚪ +1.6%
⏱️ Latency P50 78.55 ms 79.33 ms ⚪ +1%
⏱️ Latency P95 196.9 ms 188.1 ms ⚪ -4.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.33 188.1 13,680 217.49 -8.8
Account 159.05 311.61 720 12.08 +1.75
TablesDB 77.21 147.99 7,440 120.82 +0.34
Storage 70.42 164.57 3,600 60.19 -13.86
Functions 110.93 223.32 1,920 32.87 -9.5

Top API waits (after)

API request Max wait (ms)
account.prefs.update 543.17
functions.create 527.95
account.name.update 465.18
tablesdb.rows.increment 426.52
account.get 409.5

loks0n and others added 6 commits November 17, 2026 17:02
The rewritten MySQL tokenizer tests read a string back from tokenize(), so
assertIsString() on it is always true at the package's PHPStan level.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Utopia\Query\Query over the extension's NativeQuery, behind
_APP_EXTENSION_LIBRARIES=query. The package declares Query over it to keep
the two constants that are arrays. A query's values stay PHP values, so
nested queries keep their identity.

Subclasses keep working: new static makes the called class, the methods
Query.php reaches through static run a subclass's own, and so do toArray()
and shape(). Utopia\Database\Query depends on all three.

One test read contains()'s #[\Deprecated] attribute by reflection; it now
asserts the deprecation the call raises.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The AST serializer dropped the parentheses of a right operand of equal
precedence for every operator but -, / and %, so `a = (b = c)` was written
as `a = b = c`, which reads back as `(a = b) = c`. Only the same associative
operator (+, *, ||, AND, OR) may drop them.

The change is the one on feat/rust-utopia-conversion, which crates/utopia/query
was ported from.

Co-Authored-By: Eldad Fux <eldad.fux@gmail.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
AST\Grammar, AST\Parser and AST\Serializer with its five dialects, over
crates/utopia/query, behind _APP_EXTENSION_LIBRARIES=query. The node classes,
the walker and the visitors stay PHP.

The parser returns the package's node objects and the serializers read them,
both through property slots whose layout is checked once a request. A tree
deeper than 32 levels is worked on a stack allocated for its depth, so the
extension takes every tree PHP takes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Schema, Schema\SQL and the dialects MySQL, PostgreSQL, SQLite, ClickHouse
and MongoDB compile with crates/utopia/query when
_APP_EXTENSION_LIBRARIES names query, with the 16 Schema\Feature
interfaces they implement. The blueprints (Table, Column, ForeignKey,
Index and the rest) and the enums stay PHP: a schema reads a blueprint
through its property slots and returns the package's Builder\Statement.

The crate gets definition_mut() on Table and Column, so a blueprint read
from elsewhere can be set without the fluent methods.

The parity corpus adds 1,231 lines for the schemas and is identical on
PHP and the extension. Six known differences are asserted in it and
listed in the README. This part is not faster: a statement takes 6% to
45% longer than PHP's, 1 to 4 microseconds.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A native schema statement took 13% to 35% longer than PHP's on the Alpine
image. It now takes 7% to 22% less.

- mimalloc is the extension's allocator. More than half of a
  compileCreate() was malloc and free, and musl's are slow. The
  local_dynamic_tls feature is what a library loaded with dlopen needs on
  musl.
- The crate writes a column definition into one string, where it joined a
  list of parts.
- A Statement is made by setting its property slots, which is all its
  constructor does. Columns are read straight into the table's list.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@loks0n loks0n changed the title feat(extension): the query classifiers in Rust, behind _APP_EXTENSION_LIBRARIES=query feat(extension): the query classifiers, tokenizers, Query, AST and schemas in Rust Nov 18, 2026
toString() built a PHP array and called json_encode() on it, which took
60% longer than PHP's own. It now writes the JSON itself when the query
holds only nulls, booleans, integers, UTF-8 strings and queries like it,
and leaves anything else to json_encode() as before. The corpus runs both
paths over escapes, invalid UTF-8, floats, arrays, objects and deep
nesting.

A string default is also cheaper to describe: ext-php-rs formats every
default on every call of a method that has one.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@loks0n

loks0n commented Nov 23, 2026

Copy link
Copy Markdown
Member Author

Checks run against the builders on 2026-11-23, and what they found.

Fixed

  • Interleaved builds lost their overrides. The object whose method was running lived in a thread-local, so a coroutine that yields inside an override or a build callback let another builder read the wrong object, or none. 476 of 720 interleaved builds came out wrong. The builder now carries its owner (71f342e). crates/extension/tests/query-coroutines.php covers it and run.sh diffs it against the PHP classes.
  • The detector did not compile on arm64 Linux, where a C char is unsigned (41b4b76). This is on main too. CI builds x86-64 only, so nothing caught it.

Found, not fixed

  • A build does not call a PHP override of quote(), quoteLiteral(), getLikeKeyword(), getBindingValues() or geometryToWkt(). PHP calls each. No subclass in Appwrite, Cloud or utopia-php/database 10.2.3 overrides one. The README lists it as a known difference.
  • CI's E2E lanes never set _APP_EXTENSION_LIBRARIES, so they run the PHP classes. A green E2E run says nothing about the extension.

Passed, on the Alpine image built for arm64

  • run.sh: both corpora, the package tests on the native builders, the coroutine test and the opcache check. The locale corpus differs on one warning text about reading a directory through the bind mount, which CI does not see.
  • E2E Databases and TablesDB on the compose stack with the switch on in every service, on PostgreSQL and on MariaDB: 3,949 tests each, 865 skipped, three failed. The three need the embedding service and fail the same way with the switch off. No native crash in any service log.
  • utopia-php/database 10.2.3, the version composer.lock pins: its 13,217 unit tests give the same result as on PHP.
  • valgrind over both corpora and the coroutine test: no invalid read, write or free in the builders, and the same warnings as the PHP classes give. The query corpus reports 19 invalid accesses, all on the stack stacker grows for a deep AST.
  • Soak: 400,000 rounds of 25 builds, clones, callbacks, failures and serialization in one process, alone and across eight coroutines. Resident memory is flat.

Still open before production: a staging canary (query first, then query-builders), and review.

…lues() and geometryToWkt()

A build called the native ones whatever a subclass declared. They are
steps now, 77 in all. quote() takes the builder mutably like every other
step, so an override that calls back into the builder cannot alias a
field the build is reading; the sites that quoted a field of the
builder copy it first. PHP asks getLikeKeyword() before likeEscape(),
and so does the crate now.

A new object knows its owner before any method runs, so getBindings()
called first reaches the override, and the savepoint methods and
executeMerge() record it for a clone.

The corpus overrides the four in every helper build and adds 40 cases
of its own: 181 cases differ on the commit before this one.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@loks0n

loks0n commented Nov 23, 2026

Copy link
Copy Markdown
Member Author

The override gap from the comment above is closed in fed6849. A build now calls a subclass's quote(), getLikeKeyword(), getBindingValues() and geometryToWkt(), 77 overridable steps in all. quoteLiteral() needed nothing: no builder calls it in PHP either.

The corpus overrides the four in every helper build and adds 40 cases: 15,827 cases match PHP, and 181 differ on the commit before. The package tests, utopia-php/database 10.2.3's suite and the coroutine test give the same results as before, and the benchmark is unchanged. Not rerun for this commit: valgrind, the soak and the local E2E.

main added the `utopia.libraries` setting and the compression library.
`query` and `query-builders` join its names, and naming the builders
brings `query`, whose classes they take and return.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@loks0n

loks0n commented Nov 23, 2026

Copy link
Copy Markdown
Member Author

Merged main in 1f9d4e9. main added the utopia.libraries setting, so query and query-builders are names it takes now, and naming the builders brings query. run.sh checks both.

Rerun on the merged build, on the Alpine image for arm64:

  • run.sh: every step passes up to the locale corpus, which differs on one warning text about reading a directory through the bind mount.
  • valgrind over the builder corpus and the coroutine test: no invalid read, write or free, and the same 19 warning contexts as the PHP classes give.
  • Soak, 400,000 rounds alone and across eight coroutines: resident memory flat at about 80 MB.
  • Package tests, utopia-php/database 10.2.3's suite and both corpora: same results as before.

Not rerun: the local E2E with the switch on.

@loks0n

loks0n commented Nov 23, 2026

Copy link
Copy Markdown
Member Author

Staging canary started.

  • appwrite-labs/cloud#7797 pins server-ce to this branch at 1f9d4e99ae. Its staging deployment is building.
  • appwrite-labs/application-configuration#1353 adds query to _APP_EXTENSION_LIBRARIES on staging. It merges once the image has rolled out.

Baseline before the switch, staging cloud namespace: 2 container restarts in fra1 and 0 in syd1, no Rust panic, PHP fatal or segfault lines in the last hour, every Argo CD app Synced and Healthy.

@loks0n

loks0n commented Nov 23, 2026

Copy link
Copy Markdown
Member Author

query is on in staging since 20:59 UTC, in both regions (fra1 and syd1), on the image from appwrite-labs/cloud#7797 (e42baf74b2, server-ce at 1f9d4e99ae). The flag came from appwrite-labs/application-configuration#1353.

After the switch:

  • Every Cloud pod restarted and reports flag=detector,query, Utopia\Query\NativeQuery internal and the builders still PHP: API, realtime and the workers probed in each region.
  • Container restarts in the cloud namespace: 2 in fra1 and 0 in syd1, the same as before.
  • No Rust panic, PHP fatal, segfault or Utopia\Query line in the logs. Error-level log lines per 10 minutes went from about 45 to about 18 in fra1.
  • In an API pod in each region, Utopia\Database\Query extends the native class, and it parses, groups, serializes and round-trips six queries, throws the library's own exception on bad JSON, and the PHP MySQL builder builds from a native Query.

Staging traffic is thin, so this shows it loads and runs, not that every path was hit. Roll back by removing query from the flag. query-builders is not on yet.

The builders had a switch of their own, query-builders, while they were
being moved. They pass the same checks as the rest now, so query names
all of Utopia\Query and the second name is gone: one switch to roll out,
and no combination that does nothing.

run.sh runs the builder and coroutine corpora under query.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@loks0n

loks0n commented Nov 23, 2026

Copy link
Copy Markdown
Member Author

query-builders is folded into query (2fd867d), and staging has run all of Utopia\Query from the extension since about 21:26 UTC, in fra1 and syd1, on appwrite-labs/cloud#7797 at a3ff143c3c. No config change was needed: staging already had query set.

After the rollout:

  • API, realtime and four workers in each region report the builders and Query as native.
  • Container restarts in the cloud namespace: 2 in fra1 and 0 in syd1, the same as the baseline.
  • No Rust panic, PHP fatal, segfault, SQLSTATE or syntax-error line in the logs.
  • The error-level lines come from the same four sources as 50 minutes before the first switch (API request spans, worker-billing-team-aggregation, worker-stats-resources, worker-edge), each at or below its earlier level.
  • In an API pod per region, utopia-php/database's Builder\MySQL, MariaDB, Postgres and SQLite extend the native classes and build a filtered, sorted, limited select.
  • A login with made-up credentials through the API service returns user_invalid_credentials 401 in both regions, so a users lookup ran through the native builders against the staging database.

Seen in passing, not ours: utopia-php/database 10.2.3's SQLite builder writes LIKE ? ESCAPE '\\' ESCAPE '\\', on the PHP classes as well as the extension. Its override adds the clause and the package's likeEscape() adds it again.

@loks0n
loks0n marked this pull request as ready for review November 23, 2026 21:32
@appwrite

appwrite Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Code review

Commit Status Tier Verdict Details
b10f8bf Reviewed Reviewed 🟡 B · Needs changes before merging 💬 Commented View review

Two earlier open findings remain for Query subclass getter dispatch and schema collation validation order.

This pull request adds an opt-in Rust-backed implementation of the query package’s classifiers, tokenizers, Query, AST, schemas, and builders, while retaining PHP value objects and the PHP fallback. It adds PHP bindings and bootstrap integration, parity and regression coverage, and crate documentation and benchmarks. The Composer build stage now uses a pinned Composer image digest.

Latest changes: The newest commit pins the Composer stage to the Composer 2.11.2 image digest; its embedded Alpine CA bundle includes the 20261020-r0 update.

Note

Not approving while a bug finding is open: Query getter overrides are bypassed during grouping

Fix with agent prompt
### Issue 1
crates/extension/src/query/value.rs:1571
**Query getter overrides are bypassed during grouping**

PHP's `Query::groupByType()` calls `getMethod()`, `getValues()`, and `getAttribute()`, but this path reads the native fields directly; the same bypass occurs in `getByType()`, `getCursorQueries()`, `merge()`, and `validate()`. A `Query` subclass that overrides one of these getters therefore gets different filtering or grouping results with the extension enabled.

### Issue 2
crates/extension/src/query/schema.rs:1405-1408
**Validate collation keys before converting values**

This converts each option value before validating its key, unlike PHP, which rejects an invalid key first. For an input such as `['bad key' => new stdClass()]`, PHP raises the key `ValidationException`, while this binding raises a `TypeError` for the value instead.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
Walkthrough (11)
File Change
Cargo.toml, Cargo.lock, crates/extension/Cargo.toml, crates/utopia/query/Cargo.toml Add the query crate and extension dependencies to the Rust workspace.
Dockerfile Pin the Composer stage to a specific digest and use the updated appwrite/base images across the remaining stages.
crates/utopia/query/src/** Implement classifiers, tokenizers, AST parsing and serialization, builders, schemas, and shared query types.
crates/utopia/query/README.md, crates/utopia/query/guide.md, crates/utopia/query/.github/workflows/mirror.yml, crates/utopia/query/.gitignore, crates/utopia/query/LICENSE Add crate documentation, repository metadata, licensing, and mirror workflow.
crates/extension/src/query/** Bind the query implementations to PHP, including classifiers, tokenizers, Query, AST, schemas, and builders.
crates/extension/src/lib.rs, crates/extension/src/libraries.rs, crates/extension/src/emails.rs, crates/extension/src/string.rs, crates/support/php-std/src/json.rs Register the optional query extension and add shared conversion and JSON support.
packages/query/composer.json, packages/query/extension/Query.php, packages/query/src/extension.php Load the native Query wrapper when the extension is enabled while preserving the PHP fallback.
packages/query/src/AST/Serializer.php, packages/query/tests/AST/SerializerTest.php, packages/query/tests/API/HelperTest.php, packages/query/tests/Regression/CorrectnessRegressionTest.php, packages/query/tests/Tokenizer/MySQLTest.php Fix equal-precedence serialization and adapt regression tests to assert observable behavior.
crates/extension/tests/query.php, crates/extension/tests/query-builders.php, crates/extension/tests/query-coroutines.php, crates/extension/tests/opcache.php, crates/extension/tests/run.sh Add query parity, builder dispatch, coroutine, and OPcache coverage, and update the extension test runner.
crates/extension/bench/query.php, crates/extension/README.md Add extension benchmarks and document the extension and its supported query behavior.
crates/extension/bench/query.php Benchmark query package operations on PHP and the extension.
Still open from earlier reviews (2)
Fixed since the last review (1)
  • Keep compromised eMudhra chains out of Composer's trust store · Dockerfile:2

Reviewed the commits since 748435d

Tip

Comment @appwrite review to re-run, or mention @appwrite with a question.

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

🔵 Tier A · See the inline comments. Summary

for zval in queries.values() {
let Some(query) = query_of(zval) else { continue };
let first = || query.values.array().and_then(|values| values.get_index(0)).filter(|value| !value.is_null());
match query.method {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Query getter overrides are bypassed during grouping

PHP's Query::groupByType() calls getMethod(), getValues(), and getAttribute(), but this path reads the native fields directly; the same bypass occurs in getByType(), getCursorQueries(), merge(), and validate(). A Query subclass that overrides one of these getters therefore gets different filtering or grouping results with the extension enabled.

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/extension/src/query/value.rs
Line: 1571

Comment:
**Query getter overrides are bypassed during grouping**

PHP's `Query::groupByType()` calls `getMethod()`, `getValues()`, and `getAttribute()`, but this path reads the native fields directly; the same bypass occurs in `getByType()`, `getCursorQueries()`, `merge()`, and `validate()`. A `Query` subclass that overrides one of these getters therefore gets different filtering or grouping results with the extension enabled.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

🟡 Minor · bug · Reply if this doesn't apply.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Known and documented (crates/extension/README.md, "Utopia\Query\Query"): no Query subclass in Appwrite, Cloud, Edge or utopia-php/database 10.2.3 overrides getMethod(), getAttribute() or getValues().

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That confirms no current in-repository subclass is affected, but the behavior remains reachable for downstream subclasses. For example, CustomQuery::limit(7) can override getMethod() to return Method::Equal: PHP’s groupByType() dispatches that override, while the extension reads the stored Limit method directly and groups it as a limit. PHP’s factory returns static (Query.php); the PHP grouping path calls the getters (Query.php), whereas the extension reads the native fields (value.rs).

Documenting the limitation and noting no current internal subclass uses it doesn’t make the two implementations behave alike for subclasses. I’m keeping the finding open.

Comment thread crates/extension/src/query/ast.rs Resolved
loks0n and others added 2 commits November 23, 2026 22:24
…ery-extension"

This reverts commit 77db5fc, reversing
changes made to ebe893b.
The commit before this takes #15328 (per-dialect string literals and a
declared LIKE escape) back out of the PHP package, so this pull request
changes no PHP behaviour. With utopia-php/database 10.2.3 the package's
SQLite builder and the library's own each appended ESCAPE, and SQLite
refused the statement; that happened with the extension off.

The Rust port had been written to match #15328, so it follows:

- Reverts 589edce: the tokenizers, parser, serializers and schemas
  read and write string literals as main's PHP does. StringLiteral is
  gone, and the shared filter module stays as it was.
- The builders escape LIKE with a backslash and declare no escape,
  setJsonRemove is main's JSON_REMOVE, toRawSql quotes through each
  dialect's quoteString, and toAst/fromAst carry no escape clause.
- compileLikePredicate(), likeEscape() and createTokenizer() are not
  methods of main's builders, so they and their steps go: 74 remain.
- MySQL, MariaDB and ClickHouse use the base AST serializer, as main's
  createAstSerializer() does.

Both corpora match main's package: 15,797 builder cases and 55,481
query lines. utopia-php/database's suite fails the same nine tests on
main's package, on this branch's PHP and on the extension.

Reverting this commit and the one before re-lands #15328 with its port.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@loks0n

loks0n commented Nov 23, 2026

Copy link
Copy Markdown
Member Author

#15328 is out of this pull request (59d2256 for the PHP package, 458b4a5 for the Rust port of it).

It broke SQLite with the extension off: utopia-php/database 10.2.3's SQLite builder appends ESCAPE '\\' itself, the package's started to as well, and SQLite refuses LIKE ? ESCAPE '\\' ESCAPE '\\'. Cloud's unit tests caught it. The database library's unit suite goes from 9 failures on main's package to 63 with #15328 in.

My earlier "same 63 failures on PHP and on the extension" compared this branch with itself, never with main. With main as the baseline the suite now fails the same nine on main's package, on this branch's PHP and on the extension, and both corpora match main's package: 15,797 builder cases and 55,481 query lines.

#15328 has the same problem on its own. Re-landing it here is a revert of those two commits plus a database library release that drops its own clause.

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

🔵 Tier A · See the inline comments. Summary

Comment on lines +1405 to +1408
let option = match option {
option if option.is_null() => String::new(),
option if option.is_array() => "Array".to_owned(),
option => scalar(false, option, "options")?,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Validate collation keys before converting values

This converts each option value before validating its key, unlike PHP, which rejects an invalid key first. For an input such as ['bad key' => new stdClass()], PHP raises the key ValidationException, while this binding raises a TypeError for the value instead.

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/extension/src/query/schema.rs
Line: 1405-1408

Comment:
**Validate collation keys before converting values**

This converts each option value before validating its key, unlike PHP, which rejects an invalid key first. For an input such as `['bad key' => new stdClass()]`, PHP raises the key `ValidationException`, while this binding raises a `TypeError` for the value instead.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

🟡 Minor · bug · Reply if this doesn't apply.

loks0n and others added 6 commits November 23, 2026 23:04
…mage

appwrite/base 2.5.1 ships python3 3.14.10-r1. Alpine edge has split
python3-ndbm out at r2 and installs it beside python3 on any apk add,
where it overwrites a file r1 still owns. Every apk add on the base
image fails, so CI's image build breaks on its next cache miss: the
Extension job's did.

The ffmpeg and base stages and crates/extension/build.sh upgrade
python3 first, which takes both to r2. It can go once the base image
carries r2.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2.5.1 carries python3 3.14.10-r1. Alpine 3.24 then published r2, which
splits python3-ndbm out and installs it wherever python3 3.14.10 is
present. apk add does not upgrade what is installed, so any apk add on
2.5.1 pulls python3-ndbm r2 beside python3 r1 and fails on a file both
own. The image builds only while its layers are cached.

2.5.2 is the same commit of appwrite/docker-base rebuilt, with python3
r2 and python3-ndbm already in place.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The composer image ships python3 3.14.10-r1, for mercurial. Alpine 3.24
has since split python3-ndbm out at r2 and installs it wherever python3
3.14.10 is present, so the stage's apk add for the CA bundle pulls it
beside r1 and fails on a file both own. apk add does not upgrade what is
installed; apk upgrade first does.

The same conflict on appwrite/base is fixed by 2.5.2.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The stage installed ca-certificates 20261020-r0 or newer to distrust the
eMudhra chains. The composer image has shipped that version since its
Alpine 3.24 build, with none of those roots in its bundle, so the line
installs nothing.

It was also the stage's only apk add, and the one failing: composer's
image carries python3 3.14.10-r1, and any apk add on it now pulls
python3-ndbm r2 beside it. With no install there is nothing to conflict,
so this replaces the apk upgrade added before it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
appwrite[bot]
appwrite Bot previously requested changes Nov 24, 2026

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

🔴 Tier D · 1 blocking finding to address. Summary

Comment thread Dockerfile Resolved
The stage no longer installs the CA bundle, on the strength of what the
image ships: ca-certificates 20261020-r0, with no eMudhra root. A
floating composer:2 could change under that. This pins 2.11.2 at the
digest it was checked on, as the base image is pinned.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@appwrite
appwrite Bot dismissed their stale review November 24, 2026 00:21

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

@loks0n
loks0n merged commit 1426a10 into main Nov 24, 2026
757 of 762 checks passed
@loks0n

loks0n commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

query is on in Toronto production since 02:29 UTC on 2026-11-24, on Cloud 1.53.142. The other five regions run the same release with the PHP classes.

How it got there

First ten minutes in tor1

  • Every Cloud pod restarted with detector,query; API, realtime and six workers report the classes native.
  • About 8,400 requests in 8 minutes, no 5xx. p95 latency 214 ms, against 216 ms over the half hour before.
  • Restarts: 0. No Rust panic, PHP fatal, segfault, SQLSTATE or syntax error line.

What to watch during the soak

  • tor1 5xx ratio and p95 latency against sfo3 and syd1, which have similar traffic: traefik_service_requests_total and traefik_service_request_duration_seconds_bucket, k8s_cluster_name="cloud-tor1-prod".
  • Loki, {k8s_cluster_name="cloud-tor1-prod", namespace="cloud"} for Rust panic, Fatal error, SQLSTATE, syntax error.
  • Restarts and OOM kills in the cloud namespace, and API pod memory (about 420 Mi each at the start).

Roll back

Revert appwrite-labs/application-configuration#1359 (cf11648989). The pods restart on the PHP classes; no deploy is needed, and serialize() output is the same on both, so the database cache stays valid.

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.

3 participants