Skip to content

feat: migrate to utopia-php/database query-lib - #11649

Merged
abnegate merged 767 commits into
mainfrom
feat-query-lib
Oct 15, 2026
Merged

abnegate merged 767 commits into
mainfrom
feat-query-lib

Conversation

@abnegate

@abnegate abnegate commented Mar 26, 2026 •

Copy link
Copy Markdown
Member

Migrates Appwrite onto utopia-php/database query-lib so collection schemas, workers, validators and tests speak Attribute / Index / Relationship and ColumnType / IndexType / PermissionType / Method.

Why this approach

createAttribute() / createIndex() / createRelationship() now take value objects, and Database::createCollection() takes a Collection only — no string-id overload. The string constants and getSupportFor*() were removed in database#823, so a compatibility shim would not compile against that branch.

Follow-ups on this branch after the initial migration:

  • Typed factories (Attribute::string(), Index::key(), Relationship::oneToOne(), …) at schema call sites
  • Caret ranges for Utopia Composer constraints, and a lockfile refresh so composer validate matches
  • Usage / user-events / function-cache moved from Database::on() to Lifecycle hooks (Usage, UserEvents, FunctionCache)
  • Collection configs converted from raw arrays to Attribute/Index value objects
  • All Database::createCollection() call sites wrap new Collection(...)

A real bug this surfaced

Databases worker index creation was broken on every engine. The endpoint validates and stores orders as the strings 'ASC' / 'DESC', while the query-lib Index model takes Order cases and rejects anything else. The resulting InvalidArgumentException is not a DatabaseException, so the handler's error path recorded the failure with no message at all — an index that silently never appeared. The worker now maps through Order::tryFrom() before constructing the index.

Chain

Landing order, bottom up:

  1. utopia-php/database#823 — the query-lib migration itself
  2. utopia-php/abuse#124, utopia-php/audit#133, utopia-php/migration#222 — the schema call sites in the libraries
  3. appwrite/appwrite#11649
  4. appwrite-labs/cloud#5410

Stacked on #823 but not part of it, and not required by anything above: #947 (ORM), #948 (repositories and seeding), #949 (migration runner and schema differ).

Every dev-feat-query-lib pin in this train is re-pinned to its branch head whenever one of them moves, so each PR's CI runs against what the others actually contain.

Verified

  • Pint and php -l across the conversion
  • Merges cleanly with every other open PR on this repo, checked pairwise with git merge-tree against today's main
  • Both library issues this branch was blocked on are fixed upstream and pinned here at utopia-php/database 4ae752e / utopia-php/abuse 21cc37c:
    • c1c9cc0 — the document cache no longer writes an empty marker when the collection cache epoch rotated under the read. Presences went from failing on two engine lanes to one; MariaDB (dedicated) is green and the residual window on MongoDB (dedicated) is down from 20-25s to 2-5s.
    • ceae07c — stddev() and variance() are the population statistic on every adapter. Bare SQL STDDEV is population on MySQL/MariaDB and sample on PostgreSQL, so the same query answered 67.0238 or 77.3985 over the same four rows. stddevSamp()/varSamp() remain the way to ask for the sample statistic. tests/e2e/Services/Databases/Queries/StatisticalAggregates.php now asserts one value per aggregate, and getDatabaseAdapter() / isPostgreSQL() / isMariaDB() are deleted from DatabasesBase.php — nothing in the suite reads _APP_DB_ADAPTER any more.

The Presences failure

Projects/Create.php built its own pooled adapter instead of going through Factory, and the two disagreed on one segment of the collection metadata cache key. Factory::adapter() calls setHostname($poolName), so every reader resolves database_db_main; the inline adapter left the hostname unset and delegated to the pooled connection, which answers with the host it dialled, mariadb. Measured in CI with a temporary probe (f8b5ec4, reverted in d93cf15), for all 19 project namespaces in the run:

write-provisioning     default-cache-mariadb:appwrite:_1::collection:_metadata
read-worker-targets    default-cache-database_db_main:appwrite:_1::collection:_metadata
read-subquery-targets  default-cache-database_db_main:appwrite:_1::collection:_metadata

Provisioning therefore created targets and rotated the metadata epoch under a key no reader holds, so the empty-document marker the maintenance sweep planted mid-provisioning survived its own invalidation. Every later request that decoded a user in that project then failed the subQueryTargets filter with Collection not found until the marker expired — the dedicated-lane Presences failures. utopia-php/database needs no change for it; b5f0cf4 had already fixed the shared-tables analogue, which is why only the (dedicated) lanes were left.

Provisioning now goes through Factory::provisioning(), so one place builds a project database adapter and the two paths cannot drift again. tests/unit/Database/FactoryTest.php pins it: provisioning() and project() must resolve the same _metadata cache base key, and the key must carry the pool hostname rather than the connection's. Both assertions fail against the old construction.

Note on main: it does not have this divergence. Factory::adapter() there is a plain new DatabasePool($this->pools->get($name)) with no setHostname(), and Appwrite\Utopia\Database\Adapter\Pool does not exist — both sites build the adapter identically, so the two keys agree. The hostname segment, and the negative-marker cache that makes a mismatch visible, are both new on this branch.

CI

214 of 214 green at 86721fc, including all six Presences lanes. RealtimeCustomClientTest::testConcurrentRealtimeTrafficCoroutines remains flaky repo-wide — it also fails the same lane on main-based PRs such as #12675 at the same $client->receive() line — and cleared on a single re-run here.


Fixes from the 2026-09-23 review

Upgrade notes (self-hosted)

  • _APP_MIGRATIONS_CLAIM_ENABLED is removed. Nothing reads it, so you can delete it from .env.
    • Migrations, CSV/JSON imports and exports work after the upgrade without it.
    • Run migrate as usual. Until it has reached a project, that project's migration endpoints answer 503 migration_schema_not_ready.
    • A migration can be queued just before the upgrade and picked up by a new worker before migrate reaches its project. It stays pending, and its job is parked on the failed list.
    • Once migrate has finished, re-drive those jobs with docker compose exec appwrite queue-retry --name=v1-migrations.
  • Multi-node installs: delete the database cache after the upgrade.
    • This release changes the names of the database cache keys. They now include the database name, and the servers' databases key their cache by connection pool.

    • During a rolling upgrade, a write handled by a node still on the previous release purges only the old keys. So a node already on this release can keep serving a cached document for up to the 24-hour cache TTL, for example a revoked API key or a blocked user.

    • Once the last node on the previous release has stopped, delete the cache keys on every cache Redis:

      docker compose exec redis sh -c "redis-cli --scan --pattern 'default-cache*' | xargs -r redis-cli unlink"
    • Do not use FLUSHALL on the default setup: the same Redis also holds the queues, locks and abuse counters.

    • A single-node install that stops the old containers before it starts the new ones is not affected.

  • A failing document-event listener fails the request again, as before this PR.
    • These events propagate a listener's exception to the request: document reads, creates, updates, upserts, increments, decrements, deletes, finds, counts and sums, a document write's cache purge, and index creation. That covers appwrite's event, webhook, function and realtime enqueue (UserEvents), the usage hook, and the function-events cache purge.
    • Listener failures on database, collection and attribute events stay isolated, as they were. An isolated failure no longer skips the remaining listeners.
    • An \Error always fails the request.
  • opis/closure stays in composer.lock.
    • It arrives through utopia-php/database → utopia-php/async. appwrite requires neither opis/closure nor utopia-php/async directly, so it cannot drop it.
    • utopia-php/database 8 deletes the only database code path that reached it (Traits\Async).
  • No data migration is needed for these fixes:
    • sessions.latitude/longitude: installs upgrading from a release already store double, which the configuration declares again. Only databases created by an unreleased feat-query-lib build store float in _metadata. The column is the same, so such test environments can keep it or be recreated.
    • Permission rows: installs upgrading from a release already have them, because the previous database library wrote them in the adapter. Only databases run on an unreleased feat-query-lib build lack rows, for these:
      • presences set over realtime (they are deleted when their connection closes and purged when they expire);
      • _metadata rows of collections created at boot, which nothing reads through the permission table.
  • Migration resourceData shape.
    • resourceData is the documented array of {resource, id, status, message} objects (1.9.x always returned []). It keeps the full per-resource report while it fits: 131,070 characters.
    • Once the complete report would pass 128,000 characters, it holds only the resources that did not succeed: errors first, then warnings, then anything still pending, processing or skipped.
      • Each message is cut to 256 characters.
      • Entries are added until the report reaches 128,000 characters.
      • So a large migration where everything succeeded reports [].
    • Rows and documents appear as per-status totals in the complete report and are left out of the reduced one. Per-type totals are always in statusCounters.
  • Migration lifecycle values.
    • status: pending → processing → completed | failed.
    • stage:
      • init: created and queued.
      • processing: claimed by a worker.
      • migrating: transferring resources.
      • finalizing: marking imported databases ready, removing overwrite orphans, registering an export file.
      • finished.
    • Right after a retry (PATCH /v1/migrations/{migrationId}), the migration reads status: pending, stage: finished until a worker picks the new attempt up.
    • A worker's first realtime update for a run is migrating, or the terminal state if the source fails before transferring. The processing transition is written when the job is claimed and emits no event.

Documents endpoints

  • Relationship values are validated again before a write (main parity).
    • Create, update and upsert answer 400 relationship_value_invalid for a relationship value that is not a document, a document ID or a list of them.
    • They answer the same for a nested or linked ID that is not a valid custom ID.
    • Before this fix, a nested {"$id": "bad id!!"} stored a related document with that ID, and a "bad id!!" link stored a dangling reference.
  • Nested related documents get generated IDs from Appwrite again.
    • A nested document whose $id is the unique() placeholder the SDKs send for ID.unique(), or that has no $id, gets a generated ID. This works at any depth, in create, update and upsert, including operations staged in a transaction.
    • utopia-php/database 8 no longer turns unique() into a generated ID. Without this fix, every such request would link to, and overwrite, one related document stored as unique().
    • A nested related document sent without an $id has $sequence, $databaseId and $collectionId/$tableId removed again, as on main. For non-privileged callers, $createdAt/$updatedAt are removed too.
  • List cursors resolve the same way with or without joins.
    • The cursor document is read with authorization skipped and without the request's selects, as on main.
    • A caller who can list a collection but not read the cursor document no longer gets a cursor error in the middle of a joined pagination.
    • A select that leaves out the order attribute no longer fails the next page.
  • Query execution faults are 5xx again.
    • find(), count() and getDocument() map only the database library's Query exception and the query library's ValidationException to 400 general_query_invalid. Every new library rejection throws the former.
    • Internal query-library faults (the base exception, UnsupportedException) reach the error handler as 500 and error reporting.
    • Parsing still answers 400 for any query-library exception.

Joins

  • A join reads a collection exactly as listing it directly does.
    • A collection with document security and no collection-level read (the usual per-user shape) can now be joined. The join returns the rows the caller holds document-level read on, as GET …/documents on that collection does. Before, Appwrite refused the join with 401 before the database library could apply its own rule.
    • A collection the caller cannot list at all (no collection-level read and no document security) is still refused with 401 user_unauthorized.
    • Disabled collections stay 404, and API keys stay privileged across their project.
  • Joined list pagination never takes its page boundary from a row the caller cannot read.
    • The cursor document is still read with authorization skipped, so a caller can page past a document it cannot read.
    • An order on a joined attribute takes its value only from joined rows the caller can read. Those rows are read the way listing that collection directly reads them, narrowed by the list's own filters on that alias.
    • The joined order values are handed to the library as stored and encoded there, once, so datetimes compare correctly.
  • Known limitation: one-to-many joins ordered by a joined attribute.
    • A cursor names only the main document. So when a joined attribute orders a one-to-many join, the cursor cannot say which of the document's joined rows ended the previous page.
    • When a cursor document pairs with several readable joined rows, the next page starts behind the last of them in the list's order, and the previous page ends ahead of the first. Paging always moves forward but can skip rows.
    • To page such a list completely, order by a main-collection attribute or use offset pagination.
  • Tests pin joins and aggregates to what direct reads return. This is contract C6, tested over REST and GraphQL.
    • Joins return exactly what a direct list returns.
    • Adding a join never hides a main row.
    • The one refused shape answers 401 user_unauthorized next to a succeeding positive control.
    • A scoped API key joins any table of its project, and the scope guard stops a key without the read scope.
    • Joined $permissions/$sequence equal what a direct read returns.
    • A one-to-many join ordered by a joined attribute pages every readable row exactly once in both directions.
    • Aggregates are compared with the same joins computed over the rows a direct list returns. That covers inner, left, right, cross and full outer joins; total, count, sum, min, max, avg; groupBy on a joined attribute; and having over a joined sum. Hidden rows never reach a client's aggregate. API keys and the console see all of them.
    • total equals the returned rows for every join type, including cross-join fan-out, whenever the result fits one page.
    • A join without a select returns the main document's attributes plus alias.$id and the joined attributes, decoded like a direct read. It returns no joined internals and no joined value under a bare name.
    • These are clean 400 general_query_invalid rejections:
      • a ninth join;
      • a bare aggregate or groupBy attribute that two joined collections declare, or none;
      • numeric aggregates over string or array attributes;
      • a join on a bulk update or delete;
      • joins or aggregates where the adapter has none (DocumentsDB, and Legacy/TablesDB on MongoDB).
    • Over no rows, count and countDistinct return 0 and every other aggregate returns null.

Usage metering

  • Document operations are metered as on main again, nested relationships included.
    • databases.operations.reads counts every document a Get/List returns, plus every related document nested in it, plus main's one extra read for an empty relationship list.
    • databases.operations.writes counts every document in a Create/Update/Upsert payload plus every related document nested in it, at any depth.
    • Before this fix, Get, Update and Upsert metered 1, and List and Create metered count($documents), whatever they read or wrote through relationships. An update that writes four related documents metered 1 write instead of 5.
    • Writes are counted from the request payload, not from the returned document, which has every related document populated.
    • A List cursor document, update pre-reads and the internal finds of transaction reads are not billed.
  • A list served from the list cache meters the same reads as the list read from the database.
    • The miss stores each document's operation count next to the cached documents, in a new operations field of the list's cache hash, written in the same HMSET.
    • A hit replays the counts without walking the documents again.
    • Before this fix, a list of three albums with their tracks metered 7 reads on the miss and 3 on every hit.
    • The cache key, the documents and total fields and the TTL are unchanged.
    • An entry cached before the upgrade meters one read per document until it expires.
    • A cache adapter that cannot batch writes (Memory, None, Filesystem) no longer caches lists. Those adapters also ignore hash fields, so the list cache was not correct on them anyway.
  • Document requests no longer query the database catalog to name collections.
    • getDatabasesDB($database, $collection) seeds the requested collection's public ID. Related collections resolve theirs through the catalog's document cache, as main did.
    • Before, every document request ran an uncached SELECT … WHERE _sequence = ? for the requested collection, plus three queries per related collection.
  • Deployment usage is attributed to its function or site again.
    • {resourceType}.deployments and {resourceType}.deployments.storage carry resource type function/site and the owner's internal id, as on main.
    • The hook tags its rows through a new, additive Usage\Context::addResourceMetric(). Metrics added later in the same request keep the request's own attribution.
  • The database usage hook emits only what main emitted: sessions and the per-resource-type deployment rows.
    • It no longer re-emits counts the StatsResources gauges own (teams, users, databases, collections, documents, buckets, files, functions, sites, deployments).
    • It no longer emits the per-collection and DocumentsDB/VectorsDB document counts that StatsUsage ingested on every document create.
    • It is no longer registered on tenant databases, matching main.
  • Usage\Context::addReduce() is gone again (main removed it as dead code). No worker read the payload it queued for every deleted user, database, collection, bucket, function and site.

Migrations

  • Migration attempts are gated per project by the V26 ownership schema alone.
    • The _APP_MIGRATIONS_CLAIM_ENABLED flag defaulted to disabled on fresh installs and upgrades. So every migration, CSV/JSON import and export, and every retry answered 503 migration_claim_disabled.
    • The flag and that error are gone.
  • A migration that dies while finalizing no longer stays processing forever.
    • Every processing stage has a lease: an hour without a progress write while processing/migrating, and a day while finalizing.
    • Maintenance still fails processing/migrating attempts after three days, and now fails finalizing ones after a day, so they can be retried.
  • Retry accepts any failed migration, whatever stage it failed in.
  • A redelivered job resumes a migration whose worker died. The worker takes the migration over with a new attempt, and the dead worker's late writes are refused.
  • Workers wait for V26. A worker that receives a migration for a project V26 has not reached yet leaves it pending and hands the job back to the queue. The stuck-migration sweep no longer throws on such projects.
  • Half-provisioned databases are recoverable again.
    • Any later attempt can take over a database that a failed migration left provisioning/failed: a retry, a new migration, or any migration after the failed one was deleted.
    • Only the owning migration's current, unfinished attempt keeps its databases.
  • Claim::reclaim() claims the next attempt of a failed migration without publishing it, for workers that retry in-process. retry() publishes that same claim.
  • Large migrations import everything again.
    • The report used to gain one entry per resource and overflowed its column at about 1,500 resources. From then on every progress write failed, and the sources abandoned the rest of each resource group.
    • Then the final write failed too, leaving the migration processing with no errors until the 3-day sweep.
    • This hit Appwrite, Firebase, Supabase and NHost imports, and Cloud backups of large schemas.
  • A migration whose final write cannot be stored still finishes. The worker retries it once without resourceData and statusCounters, and the migration ends failed or completed with its errors.

Platforms, attributes and databases

  • Platform endpoints reject blank values again, as on main.
    • The ten platform create/update actions are back to Text(n, requireNonBlank: true) and Hostname() with main's requireNonBlank check. The NonBlank wrapper is deleted.
    • The wrapper had let through a whitespace-only key/type/hostname on Web platforms, and Unicode-only blank values everywhere.
    • The 18 platform parameter examples (<NAME>, <APPLICATION_ID>, …) are back in the generated specs.
  • Inline attribute filters are checked the same way as on the per-type endpoints. databases.createCollection and tablesDB.createTable used to store each inline attribute's filters exactly as sent. They now accept only what the matching per-type endpoint sets: encrypt on string, varchar, text, mediumtext and longtext (not on the email, enum, ip or url formats, and on string and varchar only from a size of 150), datetime on datetime, and the type's own filter on point, linestring and polygon. A request with any other filter, a repeated filter, or a filters value that is not an array of strings gets 400 general_argument_invalid (Invalid filter for attribute 'name': subQueryAttributes), and no collection or table is created. Clients that send no filters, or only the filters above, are unaffected.
  • Updating a relationship without onDelete works again and keeps the stored action.
    • A rename or an empty body used to answer 500 (ForeignKeyAction::from(null)).
    • A rename no longer resets the reported onDelete to null.
  • An inline double attribute is stored with size 0 again, as the dedicated float endpoint and 1.9.x do.
  • New projects' collections, and project collections created at boot in shared-tables mode, get their permission rows. Both databases now come from the database factory with its permission hook.
  • Presences set over realtime are visible to their owner, and revoking one over realtime takes effect. Realtime now builds its console and project databases through the factory, one per call with its own authorization.
  • Cache invalidations from the boot, realtime and CLI tasks reach the servers again. They now build their databases through the factory and share its cache keyspace. The CLI's console database also drops undeclared attributes, as the servers' does.
  • MQTT reads users, sessions and projects from the same cache as the other servers.
    • MQTT built its console and project databases by hand. Their cached documents were keyed by the host the pooled connection dialled, where the factory's are keyed by pool name.
    • So when the HTTP server, the workers, the CLI or realtime updated a user, a session or a project, MQTT's cached copy was not refreshed until the 24-hour cache TTL ran out.
    • MQTT now builds both databases through the factory, one per call with its own authorization, as realtime does. The construction is in Appwrite\Mqtt\Databases.
    • The getCache, getConsoleDB and getProjectDB container entries and the connection-resources hook are unchanged.
    • Both sides shared one keyspace on main, so only unreleased feat-query-lib builds were affected. Nothing is migrated: MQTT's old cache entries are never read again and expire with the TTL.
  • Spatial support is read from the adapter's Feature\Spatial. It is no longer derived from four unrelated quirk capabilities.
  • sessions.latitude and sessions.longitude stay double (see the upgrade notes).

CI

  • The full database matrix keeps running after this PR merges.
    • The Tests / Matrix gate compared the utopia-php/database version string, which a branch constraint locks as dev-feat-query-lib on every update. So later pull requests would have run PostgreSQL/dedicated only.
    • It now compares each package's locked source commit for utopia-php/database, query, mongo, abuse, audit and migration.
    • A change to any of them runs MariaDB, PostgreSQL and MongoDB in dedicated and shared mode.

Commits

  • 046a86e (fix): reject blank platform values and keep their spec examples again
  • ba70ab8 (fix): keep a relationship's onDelete when an update leaves it out
  • 44e24f7 (fix): store an inline double with size 0 like the float endpoint
  • 8fd3a62 (fix): register the permission hook on the provisioning database
  • 4d04506 (fix): run the full database matrix whenever a database library moves
  • ad78604 (fix): read spatial support from the adapter's spatial feature
  • b16afaa (fix): keep the sessions geo attributes typed double
  • 5bf80a8 (fix): build the shared-tables boot database through the factory
  • fdc5396 (fix): register the permission hook on the boot database
  • 9e88e31 (fix): build realtime's databases through the factory
  • c951a90 (fix): build the CLI's platform database through the factory
  • a24b81e (fix): resolve the requested collection's public id without a catalog query
  • 864b751 (fix): meter nested relationship documents on document reads and writes as main did
  • f274148 (fix): stop queueing deleted resources on the unconsumed usage reduce channel
  • 2f66c01 (fix): stop re-emitting usage that the StatsResources gauges own
  • 3c03dbb (fix): attribute deployment usage to the function or site that owns it
  • 24324c1 (fix): validate relationship payloads and generate nested unique() ids again
  • 1909a71 (fix): resolve a list cursor the same way with or without joins
  • d05e86c (fix): answer query execution faults with 5xx, not 400
  • 4f1b5e4 fix(migrations): gate migration attempts on the V26 schema alone
  • 08e5336 fix(migrations): expire abandoned finalizing attempts and retry any failed stage
  • 2497ee6 feat(migrations): let a worker claim the next attempt of a failed migration
  • 1c89517 fix(migrations): resume an abandoned attempt when the queue redelivers it
  • 89e2f44 fix(migrations): keep deliveries pending until V26 reaches the project
  • 71dffd6 fix(migrations): recover databases whose provisioning attempt can no longer run
  • 495dea5 (fix): keep the migration report within its resourceData column
  • b8b090a (fix): retry a migration's terminal write without its report
  • 4a73b43 (test): give the migration report tests a project schema past V26
  • 65537d3 (fix): let a join read a collection the way listing it directly does
  • 67728dd (fix): take a joined list's page boundary only from rows the caller can read
  • e5dfb60 (test): pin join permissions to what listing the joined collection returns
  • 1f976fc (test): make the join leak checks able to fail
  • 9259d45 (test): pin joins and aggregates to what direct reads allow, over REST
  • f7601b1 (test): pin joins and aggregates to what direct reads allow, over GraphQL
  • 8594632 (fix): meter a cached list's related documents as its miss did
  • 8700db1 (fix): resolve related collections' public ids from the cached catalog
  • 40dff96 (refactor): keep the list cache field names together
  • 15a5bea (test): expect the migration report example in the report's own casing
  • a2ae0e1 (refactor): build MQTT's databases in Appwrite\Mqtt\Databases
  • d1370f5 (fix): share the servers' cache keyspace in MQTT
  • d9d7d04 (test): restore the database filters after each migration test
  • c657d12 (fix): accept only the endpoints' filters on inline attributes
  • 658439f chore: re-pin utopia-php/database, abuse and migration to their feat-query-lib heads
  • 2be4025 fix(databases): pass joined cursor values to the library unencoded
  • d422841 test: give the pooled MariaDB spatial case a real PDO

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Mar 26, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 3a2d3f82-e0fc-4e2b-a127-8f2577601506

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat-query-lib

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions

github-actions Bot commented Mar 26, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → feat-query-lib (after).

Metric Before After Change
🚀 Requests/sec 185.91 188.27 ⚪ +1.3%
⏱️ Latency P50 94.33 ms 91.62 ms ⚪ -2.9%
⏱️ Latency P95 215.75 ms 211.64 ms ⚪ -1.9%
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 91.62 211.64 11,742 188.27 -4.11
Account 168.25 325.52 618 10.24 -65.14
TablesDB 89.89 166.56 6,386 104.26 +6.05
Storage 82.61 190.43 3,090 52.77 +8.66
Functions 129.62 248.98 1,648 28.79 -12.03

Top API waits (after)

API request Max wait (ms)
account.name.update 468.87
storage.buckets.create 428.3
account.prefs.update 392.1
functions.variables.update 372.5
functions.create 369.67

@blacksmith-sh

This comment has been minimized.

@github-actions

github-actions Bot commented Mar 26, 2026 •

Copy link
Copy Markdown

🔄 PHP-Retry Summary

Flaky tests detected across commits:

Commit 5740cec - 1 flaky test
Test Retries Total Time Details
DatabaseServerTest::testCreateIndex 1 240.22s Logs
Commit 9555203 - 56 flaky tests
Test Retries Total Time Details
FunctionsConsoleClientTest::testCreateFunction 1 726ms Logs
FunctionsConsoleClientTest::testFunctionUsage 1 5ms Logs
FunctionsConsoleClientTest::testCreateFunctionVariable 1 5ms Logs
FunctionsConsoleClientTest::testListVariables 1 7ms Logs
FunctionsConsoleClientTest::testGetVariable 1 4ms Logs
FunctionsConsoleClientTest::testUpdateVariable 1 6ms Logs
FunctionsConsoleClientTest::testDeleteVariable 1 9ms Logs
FunctionsCustomClientTest::testCreateFunction 1 697ms Logs
FunctionsCustomClientTest::testCreateExecution 1 5ms Logs
FunctionsCustomClientTest::testCreateHeadExecution 1 5ms Logs
FunctionsCustomClientTest::testCreateCustomExecution 1 2.63s Logs
FunctionsCustomClientTest::testCreateExecutionNoDeployment 1 22ms Logs
FunctionsCustomClientTest::testSynchronousExecution 1 4.60s Logs
FunctionsCustomClientTest::testNonOverrideOfHeaders 1 4.60s Logs
FunctionsCustomClientTest::testListTemplates 1 5ms Logs
FunctionsCustomClientTest::testEventTriggerWithClientAuth 1 5.15s Logs
FunctionsCustomServerTest::testCreateCustomExecution with data set #0 1 9.31s Logs
FunctionsCustomServerTest::testCreateDeploymentFromCLI 1 8ms Logs
FunctionsCustomServerTest::testCreateFunctionAndDeploymentFromTemplate 1 19.94s Logs
FunctionsCustomServerTest::testCreateFunctionAndDeploymentFromTemplateBranch 1 7ms Logs
FunctionsCustomServerTest::testCreateFunctionAndDeploymentFromTemplateCommit 1 317ms Logs
FunctionsCustomServerTest::testCreateDeployment 1 3ms Logs
FunctionsCustomServerTest::testCancelDeploymentBuild 1 3ms Logs
FunctionsCustomServerTest::testCreateDeploymentLarge 1 2ms Logs
FunctionsCustomServerTest::testUpdateDeployment 1 2ms Logs
FunctionsCustomServerTest::testListDeployments 1 2ms Logs
FunctionsCustomServerTest::testGetDeployment 1 2ms Logs
FunctionsCustomServerTest::testCreateExecution 1 2ms Logs
FunctionsCustomServerTest::testListExecutions 1 2ms Logs
FunctionsCustomServerTest::testSyncCreateExecution 1 2ms Logs
FunctionsCustomServerTest::testGetExecution 1 2ms Logs
FunctionsCustomServerTest::testDeleteExecution 1 2ms Logs
FunctionsCustomServerTest::testUpdateSpecs 1 2ms Logs
FunctionsCustomServerTest::testDeleteDeployment 1 2ms Logs
FunctionsCustomServerTest::testDeleteFunction 1 2ms Logs
FunctionsCustomServerTest::testDeleteFunctionRulesCleanup 1 9.32s Logs
FunctionsCustomServerTest::testExecutionTimeout 1 18.63s Logs
FunctionsCustomServerTest::testCreateCustomExecutionBinaryResponse 1 18.63s Logs
FunctionsCustomServerTest::testCreateCustomExecutionBinaryRequest 1 18.64s Logs
FunctionsCustomServerTest::testEventTrigger 1 18.63s Logs
FunctionsCustomServerTest::testScopes 1 18.63s Logs
FunctionsCustomServerTest::testCookieExecution 1 18.63s Logs
FunctionsCustomServerTest::testFunctionsDomain 1 9.32s Logs
FunctionsCustomServerTest::testFunctionsDomainBinaryResponse 1 9.32s Logs
FunctionsCustomServerTest::testFunctionsDomainBinaryRequest 1 9.32s Logs
FunctionsCustomServerTest::testResponseFilters 1 4ms Logs
FunctionsCustomServerTest::testRequestFilters 1 18.61s Logs
FunctionsCustomServerTest::testFunctionLogging 1 3ms Logs
FunctionsCustomServerTest::testFunctionSpecifications 1 3ms Logs
FunctionsCustomServerTest::testDuplicateDeployment 1 18.62s Logs
FunctionsCustomServerTest::testUpdateDeploymentStatus 1 9.31s Logs
FunctionsCustomServerTest::testErrorPages 1 9.32s Logs
FunctionsCustomServerTest::testErrorPagesPermissions 1 9.31s Logs
FunctionsCustomServerTest::testErrorPagesEmptyBody 1 9.32s Logs
FunctionsCustomServerTest::testLogAndErrorTruncation 1 18.62s Logs
FunctionsCustomServerTest::testFunctionDeploymentRetention 1 3ms Logs
Commit 61a623f - 1 flaky test
Test Retries Total Time Details
FunctionsScheduleTest::testCreateScheduledAtExecution 1 4.74s Logs
Commit 4d85ab0 - 1 flaky test
Test Retries Total Time Details
VariablesConsoleClientTest::testProjectVariableInSite 1 144.32s Logs
Commit 48a0191 - 1 flaky test
Test Retries Total Time Details
AccountTest::testCreateAccountJWT 1 387ms Logs

Note: Flaky test results are tracked for the last 5 commits

@abnegate
abnegate force-pushed the feat-query-lib branch 3 times, most recently from 68b76df to 1b77a78 Compare April 2, 2026 08:59
@ChiragAgg5k
ChiragAgg5k changed the base branch from 1.9.x to main June 23, 2026 09:57
@abnegate
abnegate marked this pull request as ready for review August 14, 2026 05:14
@abnegate

Copy link
Copy Markdown
Member Author

@greptileai review

@greptile-apps

greptile-apps Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

[Critical risk] Migrates database query library across the entire codebase.

The PR does not appear safe to merge while large fractional integer-counter bounds can be applied incorrectly.

Fix All in Claude CodeFindings

  1. P1 Large Counter Bounds Lose Precision ▶
  2. P2 Test Pins Lookup Internals ▶
  3. P2 Column List Mirrors Implementation ▶
Fix with agent prompt
### Issue 1
src/Appwrite/Databases/Counter.php:115-120
When a transaction supplies a large fractional string as an integer attribute’s `max` or `min`, this float conversion can change the bound before it is applied. For example, `9007199254740993.5` can round to `9007199254740994`, allowing an increment past the maximum the caller specified. Determine the permitted integer without losing the string’s precision.

### Issue 2
tests/unit/Databases/CursorLookupTest.php:276-277
These assertions check whether the cursor contains an internal `cus.$id` field and whether the lookup reads a particular collection. The test already checks the resulting page below, so these checks could fail after a harmless change to how the lookup works. The repository requires tests to verify observable behavior rather than mirror implementation details; that requirement must be satisfied before merging.

```suggestion

```

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

### Issue 3
packages/usage/tests/MetricTest.php:undefined-618
The added `ordinal` expectation copies another value from `Metric::EVENT_COLUMNS` into an exact, ordered list in the test. The repository requires tests to verify observable behavior rather than mirror source code or configuration. A harmless change to the column representation would require updating both lists without showing whether event metrics still work. The new schema and index assertions below follow the same pattern. This requirement must be satisfied before merging.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

---

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

Summary

This PR migrates Appwrite’s database schemas, queries, hooks, and callers to the query-lib API, with corresponding dependency and test updates. Since the previous review, the only application change is a new locked utopia-php/database commit; no new actionable issue was established from that change.

Reviews (140) · Last reviewed commit: "chore(deps): re-pin utopia-php/database ..."

@abnegate

Copy link
Copy Markdown
Member Author

@greptileai review

18 similar comments
@abnegate

Copy link
Copy Markdown
Member Author

@greptileai review

@abnegate

Copy link
Copy Markdown
Member Author

@greptileai review

@abnegate

Copy link
Copy Markdown
Member Author

@greptileai review

@abnegate

Copy link
Copy Markdown
Member Author

@greptileai review

@abnegate

Copy link
Copy Markdown
Member Author

@greptileai review

@abnegate

Copy link
Copy Markdown
Member Author

@greptileai review

@abnegate

Copy link
Copy Markdown
Member Author

@greptileai review

@abnegate

Copy link
Copy Markdown
Member Author

@greptileai review

@abnegate

Copy link
Copy Markdown
Member Author

@greptileai review

@abnegate

Copy link
Copy Markdown
Member Author

@greptileai review

@abnegate

Copy link
Copy Markdown
Member Author

@greptileai review

@abnegate

Copy link
Copy Markdown
Member Author

@greptileai review

@abnegate

Copy link
Copy Markdown
Member Author

@greptileai review

@abnegate

Copy link
Copy Markdown
Member Author

@greptileai review

@abnegate

Copy link
Copy Markdown
Member Author

@greptileai review

@abnegate

Copy link
Copy Markdown
Member Author

@greptileai review

@abnegate

Copy link
Copy Markdown
Member Author

@greptileai review

@abnegate

Copy link
Copy Markdown
Member Author

@greptileai review

abnegate and others added 4 commits October 14, 2026 23:19
Main restored the released SDK parameter order on the messaging and
OAuth2 update endpoints, which conflicted with this branch's database 8
rewrite of the same param declarations. The resolution keeps main's
param and action-argument order while using the branch's
Database::getMaxUidLength() in place of getAdapter()->getMaxUIDLength().

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings the Joins query hook registered on the databases DB, the removal of
the manual join resolution in the document list and get routes, the uncached
joined list and the join permission e2e coverage.

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

TransactionState now overlays transaction writes per document id, so one-to-many
joined rows, joined alias columns and counts survive a list inside a transaction.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The Joins query hook implements Hook\Queries and relies on skipQueryHooks,
both introduced in 8.1.3.

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 A · See the inline comments. Summary

abnegate and others added 2 commits October 14, 2026 23:56
Collection ids may legally match database_<n>_collection_<n>. A join naming
such a collection must read that collection's own table, whether the name
collides with another collection's table or with no table at all, and
re-running the hook on its output must still be idempotent without registry
reads. A physical name no collection is called by keeps resolving through its
sequence, now after the public id lookup comes back empty.

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

Collection ids may legally match database_<n>_collection_<n>, so treating
every such identifier as a table name let a join silently read the
collection at that sequence, or come back not found, instead of the
collection the caller named. The registry is now asked for the identifier
as a public id first; only when no collection is called by it and it has
this database's table prefix with an all-digit sequence does the lookup fall
back to the sequence. The memo is still consulted before any read, so
re-running the hook on its own output stays idempotent without registry
reads, and a table name already produced is not reinterpreted as another
collection's public id.

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 A · See the inline comments. Summary

abnegate and others added 2 commits October 15, 2026 00:07
…name

The join hook memoized every table it produced as resolving to itself, so
once a read joined `shared` (table database_1_collection_2), a later join of
the collection whose public id is database_1_collection_2 — in the same
rewrite or a later read on the same handle — hit that entry and silently read
shared's table. Cover both orders, the re-run of the hook's own output, a
rewritten join changed afterwards, and a real SQLite cursor() paging a join
past its first batch, which exercises the library's own re-run of the hook.

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

Memoizing each produced table name as resolving to itself let it shadow a
collection whose public id is that same string, so a later join of that
public id read the wrong table. The string memo now only holds what a lookup
of the caller's identifier returned, public id first. The library re-runs the
hook on its own output (each cursor() page, resolveCursor, findOne), and those
re-runs pass the same join objects back, so joins the hook returned are
remembered by identity in a WeakMap together with the table they point at and
pass through untouched with no registry read; a join whose attribute changed
since is resolved again.

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 9 commits October 15, 2026 00:17
Bring in the description schema attribute (#14471) and the SDK parameter
order lock (#14469). The collection configs on this branch declare
attributes with typed Attribute value objects, so main's array-shaped
description entries are ported as Attribute::string(size: 1024, default: '')
in the same positions; the V25 steps already go through the typed
createAttributeFromCollection helpers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This branch adds createQuery to the databases, documentsDB and tablesDB
services. The lock from main only knows vectorsDB.createQuery, so the
new methods are appended with the same order vectorsDB already ships.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Main gained lean queue payloads (#14477): ProjectContext/UserContext in
queue messages, the worker resolving the console project from config, and
audits no longer shipping response bodies. The only conflict was the
worker projectContext resource signature; the branch's explicit
ProjectContext return type is kept alongside main's console-from-config
project resolution.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings in the 23 commits main gained since the last sync: the MQTT subscribe
gate that refuses a user topic whose row name is not the reserved filter and
addresses topics by id so lookups hit the primary key (#14460), the console
preview SDK flow (#14441) and the SDK docs audit (#14482).

MqttServerTest conflicted where the branch had added the reconnect regression
tests (blocked user, deleted session) next to main's rewrite of the
subscription tests. Both are kept: the branch's reconnect tests, then main's
membership-gated subscription tests addressed by topic id.

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

Main's subscribe-gate and unsubscribe tests seed their topics and subscribers
collections with the positional createCollection/createAttribute calls,
Database::VAR_STRING and the Helpers ID/Permission/Role classes, none of which
database 8 has. They now declare the collections with Collection::create and
typed Attribute::string columns and import Id, Permission and Role from
Utopia\Database, as the rest of the MQTT harness does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Bring in the Redis broker orphan-claim reap fix, queue message size telemetry, the V25 presence logs migration fix for upgraded projects, and the SDK docs updates so the database 8 adaptation stays mergeable against current main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
RequestTest registers namespace.methodA/methodB on every run without clearing Method's static registry, so ParametersTest, which throws on any duplicate-method error when it loads the controllers, failed whenever it ran after RequestTest in one process.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The console expiry test expired the shared cached console user's presence
and then ran maintenance, which only queues the cleanup job. The following
tests upsert a presence for that same user, and since there is one presence
per user the upsert refreshes the existing expired row in place, keeping
its id. When the Deletes worker later ran deleteExpiredPresences it found
the row while still expired and deleted it by id without re-checking the
expiresAt filter, removing the freshly refreshed presence and making the
next GET return 404 or the list return a total of 0.

Run the expiry test as a freshly signed-up console user whose session is
used only by this test, and restore the shared user in the cache, so the
background deletion can only ever touch a presence no other test uses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings in the console Supabase hero art change (939fa5e) so cloud can
re-pin server-ce to a head that contains the commit cloud main now pins.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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