Skip to content

feat: add self-hosted usage service - #13286

Merged
ChiragAgg5k merged 24 commits into
mainfrom
feat/usage-oss
Aug 24, 2026
Merged

ChiragAgg5k merged 24 commits into
mainfrom
feat/usage-oss

Conversation

@ChiragAgg5k

@ChiragAgg5k ChiragAgg5k commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds the generic Usage service to self-hosted Appwrite, backed by a private single-node ClickHouse instance.

  • enables self-hosted usage collection by default through _APP_USAGE_STATS=enabled, with an explicit disabled no-op path
  • keeps existing v1-stats-usage and v1-stats-resources queue contracts and DI names
  • adds tenant-scoped event and gauge ingestion using project sequence as the server-derived tenant
  • adds GET /v1/usage/events and GET /v1/usage/gauges with usage.read, filtering/grouping/bucket budgets, last|max, and empty-series responses
  • adds idempotent schema setup at boot, schema-aware health, resource snapshots, realtime concurrency sampling, and tenant purge on project deletion
  • adds default private ClickHouse 26.4.3-alpine Compose wiring, persistent storage, authentication, healthcheck, and combined/separate worker/task registration
  • pins utopia-php/usage ^0.14.0 (baeef33bbcb673265550c83fe437cfa5c400a1e0)

Architecture

Appwrite\\Usage\\Context now captures generic request/resource metadata while preserving its existing API and Cloud subclass compatibility. Legacy Usage and StatsResources payload envelopes remain readable; dimensions are additive fields inside metric/gauge rows.

country is stored lowercased and filter values are folded the same way through Context::normalizeCountry(). ClickHouse compares case-sensitively, so before this an equal("country", ["US"]) filter returned an empty series.

Appwrite\\Usage\\Connection owns a lifecycle-local pooled ClickHouse client and the shared projects_* namespace. Request reads bind Utopia\\Usage\\Tenant to the authenticated project's sequence; tenant is never request-controlled.

The existing publishers feed one consumer per stable queue. Inserts intentionally retain Cloud's current best-effort, non-idempotent behavior; arbitrary insert retries or deduplication were not added. Schema-not-ready is treated separately and fails message handling before insert, making the failure visible rather than acknowledging a missing-schema write.

Schema setup runs from app/http.php at boot, alongside the platform and project databases, on the same retry ladder. Giving up logs a warning rather than blocking boot: reads and ingestion both gate on Connection::isReady(), so they stay correct while the schema is missing. The usage-setup CLI task is retained for repair without a restart. There is deliberately no one-shot setup container -- no other schema in the repo has one, and gating the API on it let analytics storage take the API down.

Health probes connectivity plus the raw event, daily aggregate, and gauge objects. Raw events and daily aggregates have a 180-day TTL; gauges remain unlimited per the approved retention policy.

Cloud compatibility

Generic Usage module, worker, and task registration is gated to _APP_EDITION=self-hosted, preventing duplicate Cloud routes and competing queue consumers before downstream adoption.

The read endpoints are built to be subclassed rather than copied. Dimension/filter/interval constants and the query helpers are protected and read through static::, so an override actually takes effect. Entitlement is an injected usagePolicy object: the self-hosted implementation allows everything, since self-hosted has no plans, addons, or reseller namespaces, and Cloud binds a subclass carrying its plan-history, premium-geo, and affiliate rules. It is injected rather than hung off the action because actions are shared across coroutines, so per-request state cannot live on $this. This lets the Cloud PR delete its duplicated copies of both endpoints instead of maintaining them in parallel.

Verified directly against the current Cloud checkout:

  • Appwrite\\Cloud\\Usage\\Context loads against the enriched parent
  • Appwrite\\Cloud\\Event\\Message\\Usage retains constructor compatibility
  • existing Cloud queue names, publisher resource names, and optional message extension seams are unchanged

Cloud-only policy remains downstream: billing/legacy dual-write, affiliates and console_* tenants, premium geo, team billing dimensions, plan history, WAF/dedicated database metrics, Audit ClickHouse, and multi-region infrastructure.

ClickHouse operations

Default Compose includes authenticated clickhouse/clickhouse-server:26.4.3-alpine on the internal appwrite network only, with no published ports, a persistent /var/lib/clickhouse volume, authenticated SELECT 1 healthcheck, and raised nofile.

External _APP_CONNECTIONS_DB_USAGE remains supported. _APP_USAGE_PASS is used to bootstrap the bundled user; on an existing volume operators must run ALTER USER before changing the environment and DSN because image initialization does not rotate persisted credentials.

Live checks performed:

  • ClickHouse reached authenticated healthy state with no host port publication
  • usage-setup succeeded repeatedly
  • dropping projects_usage_gauges made schema health return healthy=false, schemaReady=false; rerunning setup repaired it
  • real event/gauge inserts and tenant-scoped reads returned event 3 and gauge 7
  • physical schema showed TTL on events/daily and unlimited gauges

Validation

Library unit tests were dropped in c88c65d8 and have been restored and extended:

  • tests/unit/Usage — concurrency flooring, country fold, isReady TTL / cache expiry, parseFilterQueries, late-bound bucket budget, catalogued disabled / not-ready exceptions
  • tests/unit/Event/Message/UsageTest.php — legacy and dimensioned payload envelopes
  • tests/unit/Workers/StatsUsageTest.php — tenant resolution and disabled no-op (adapted to Accumulator + getDatabasesDB)

E2E (tests/e2e/Services/Usage is already in the CI matrix and is now also listed in phpunit.xml):

  • empty-series / flat aggregate / scope smoke (skipped when _APP_USAGE_STATS=disabled)
  • invalid queries[] returns general_query_invalid (400), not 500
  • _APP_USAGE_STATS=disabled returns catalogued general_usage_disabled (403), not 500 — skipped on the default enabled CI stack

Queue-to-API ingest and tenant isolation are not in this suite. This repo has no existing usage-worker E2E harness, and this CI job does not run a dedicated ingest path. Inventing one would be fake coverage.

Review-fix follow-ups also landed:

  • $usage in the api init/shutdown hooks is typed as Appwrite\\Usage\\Context; the redundant instanceof guards are gone
  • GENERAL_USAGE_DISABLED is 403 (service-disabled neighbor). Schema-not-ready is a distinct GENERAL_USAGE_NOT_READY 503, so a missing catalog row cannot become an undefined-index 500
  • advertised Cloud interval / bucket constants are read through static::

This branch was rebased onto latest origin/main.

Why this PR is draft

The focused implementation checks are green, but queue-to-API ingestion still needs a real worker harness before this is merge-ready. Remaining before marking ready:

  • add/execute queue-to-API event and gauge ingestion with polling
  • add/execute cross-project tenant isolation
  • add/execute project deletion and post-delete queued-message coverage
  • complete/verify all generic per-resource storage/database/collection/document gauges expected by Console
  • add an Appwrite-owned schema version/checksum ledger and drift validation beyond required-object readiness
  • validate previous-stable upgrade, persisted credential rotation, backup/restore, and constrained-resource behavior
  • decide least-privilege migration versus runtime ClickHouse credentials for production guidance

Best-effort insert loss/duplication remains intentional and must stay observable/documented. Dimensioned sparse aggregate=max retains Cloud's current no-carry-forward limitation.

Required follow-up dependencies

  1. Cloud PR: adopt the upstream generic module/workers/models while retaining Cloud-only billing, affiliate/console namespace, premium geo, plan, team, dual-write, regional, and dedicated database behavior. Test against this exact Appwrite SHA and keep one consumer per queue.
  2. Console/Vibes PR: enable usageStats for self-hosted only when backend readiness is exposed, replace the current hardcoded self-hosted-off profile, and complete the site usage surface decision.
  3. SDK/spec generation: regenerate server/client specs from these method labels, including gauge aggregate=last|max, and update the Console SDK dependency in lockstep.

No merge is requested until those gates and downstream compatibility checks pass.

@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@github-actions

github-actions Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → feat/usage-oss (after).

Metric Before After Change
🚀 Requests/sec 233.69 198.73 🔴 -15%
⏱️ Latency P50 64.32 ms 75.31 ms 🔴 +17.1%
⏱️ Latency P95 198.95 ms 241.65 ms 🔴 +21.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 75.31 241.65 12,540 198.73 +42.7
Account 124.98 336.82 660 10.97 +62.47
TablesDB 73.39 235.85 6,820 110.35 +48.1
Storage 66.29 219.22 3,300 55.41 +40.19
Functions 106.16 261.43 1,760 30.15 +26.01

Top API waits (after)

API request Max wait (ms)
tablesdb.rows.delete 861.24
tablesdb.rows.list 770.51
storage.files.update 727.65
storage.buckets.delete 699.12
tablesdb.rows.decrement 691.04

@ChiragAgg5k
ChiragAgg5k marked this pull request as ready for review August 20, 2026 12:44
@greptile-apps

greptile-apps Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR adds a self-hosted usage service backed by ClickHouse, including tenant-scoped ingestion and query APIs.

  • Adds usage event and gauge workers, scheduled resource snapshots, readiness checks, and schema setup.
  • Registers ClickHouse deployment configuration, usage API models, health reporting, and worker/task entrypoints.
  • Integrates usage cleanup with project and team deletion, though final-sweep recovery remains unresolved.

Confidence Score: 4/5

The PR is not yet safe to merge because a failed post-delete usage sweep can permanently retain late usage rows after their project mapping is removed.

The readiness-cache and team pre-purge issues are addressed, but the delete worker still catches and suppresses final-sweep failures after deleting project records, leaving queued late-arriving usage data without a retry or reconciliation path.

Files Needing Attention: src/Appwrite/Platform/Workers/Deletes.php

Important Files Changed

Filename Overview
src/Appwrite/Usage/Connection.php Adds lifecycle-local ClickHouse setup and schema-aware readiness with a 15-second positive cache, resolving the prior permanent-cache behavior.
src/Appwrite/Platform/Workers/Deletes.php Adds pre-delete tenant capture and purge coverage for project and team deletion, but still suppresses final-sweep failures after deleting the tenant mapping.
src/Appwrite/Platform/Workers/StatsUsage.php Adds tenant-scoped event ingestion from queued project context with intentionally best-effort writes.
src/Appwrite/Platform/Workers/StatsResources.php Adds tenant-scoped resource-gauge ingestion with project identity validation and readiness gating.
src/Appwrite/Platform/Modules/Usage/Http/Events/XList.php Adds tenant-bound usage-event querying with metric, dimension, filter, interval, and bucket controls.
src/Appwrite/Platform/Modules/Usage/Http/Gauges/XList.php Adds tenant-bound gauge querying with last/max aggregation and bounded response controls.
docker-compose.yml Adds private persistent ClickHouse wiring and combined/separate usage worker and task configuration.

Reviews (8): Last reviewed commit: "fix(usage): span the swallowed post-dele..." | Re-trigger Greptile

Comment thread src/Appwrite/Usage/Connection.php Resolved
Comment thread app/controllers/general.php Resolved
Comment thread app/controllers/general.php Resolved
Every other schema in self-hosted Appwrite is created at boot by
app/http.php -- platform DB, project DB, shared-tables metadata, bucket
collections -- with a retry ladder and an already-exists skip. Usage was
the only one with its own container, and Cloud has no equivalent: there
an operator runs the setup script by hand against the migration endpoint.

Gating `appwrite` on `service_completed_successfully` also meant an
unhealthy ClickHouse stopped the API from starting at all, which lets
analytics storage take down the core API. The gating was inconsistent
too: only the dev override waited on the one-shot, so in the shipped
compose it was an orphan sitting at Exited (0), which reads as a failure.

Call Connection::setup() from the existing boot block instead. It retries
on the same 15x2s ladder as the databases above so a cold start wins the
race against ClickHouse, then gives up with a warning rather than
blocking boot. Reads and ingestion already gate on Connection::isReady(),
so both stay correct while the schema is missing.

Keep bin/usage-setup and the CLI task -- they repair a dropped table
without a restart, the closest analogue to Cloud's manual script -- and
put its retry on the same ladder.
Cloud has to enforce plan history limits, the premium geo addon, and its
affiliate metric carve-out on the same two endpoints, and today it does
that by keeping a full copy of both actions. The copies have already
drifted behind this branch's gauge fixes, so the duplication is actively
losing correctness rather than merely costing lines.

Make the upstream actions subclassable instead:

- widen the dimension/filter/interval constants and the query helpers from
  private to protected
- read them through `static::` so an override actually takes effect --
  `self::` binds to the defining class and would silently ignore Cloud
- inject a `usagePolicy` object the actions consult before querying. The
  self-hosted implementation allows everything, since self-hosted has no
  plans, addons, or reseller namespaces. Cloud binds a subclass that
  carries the checks its endpoints do today.

The policy is injected rather than hung off the action because actions are
shared across coroutines, so per-request state cannot live on `$this`.

Also fold `country` filters through Context::normalizeCountry() on the way
in. Writes have always stored the column lowercased, readers did not fold
the filter, and ClickHouse compares case-sensitively -- so
`equal("country", ["US"])` returned an empty series. Both sides now share
one rule, with a unit test pinning them together.
Cloud carried these two constants with the rationale attached; upstream
now owns them, so bring the reasoning along rather than leaving bare
values here and a duplicate definition there.
Cloud's stats-resources task carries a near-verbatim copy of this fold --
same method names, same three constants, same values -- so the two editions
each own an arithmetic they should agree on. They had already diverged:
Cloud opens its first window at `_APP_STATS_RESOURCES_INTERVAL` unfloored,
so an interval below the 300s bucket size yields a window that closes
before any whole bucket has elapsed and samples nothing at all.

Subclassing does not work here: this task injects `usageConnection`, which
Cloud's container does not define, and inject() is positional and cannot be
dropped by a subclass. The fold is a well-defined domain concept and takes
only a Usage instance, so it becomes Appwrite\Usage\Concurrency and both
editions call it.

Task drops 157 -> 63 lines. The flooring fix lives in the shared code, with
a unit test that fails on the old unfloored behaviour.
The suite was added with the endpoints but never wired into the E2E
matrix, so it has not run in CI once -- the endpoints were only ever
covered by whatever ran locally.

ClickHouse is in the default compose profile, so `compose up --wait`
already starts it; the job needs no other setup. Marked functional so
paratest parallelizes the single class per method, matching the other
one-class suites.
Two real defects the project-wide scan caught:

- app/http.php annotated $usageConnection with an aliased class name that
  PHPStan would not resolve in that docblock, so isEnabled() and setup()
  were both calls on an unknown type. Use the fully-qualified name and drop
  the now-unused alias.
- the test fake bound $queued by reference before checking isset(), which
  created the array key as a side effect and made the guard always true.
  Read through the key instead and shift in place.

Also return the Context setters to `static` rather than `self`, so a
subclass can chain them. Cloud adds a team dimension on top of this class
and chains its own setter after a dozen inherited ones; with `self` the
chain degrades to the base type halfway through and the subclass method is
unreachable. That is what kept Cloud's copy of every setter alive.
Three of the five _APP_EDITION checks this branch added were the wrong
mechanism for what they were guarding.

The one in Platform\Appwrite was simply dead: Cloud composes Core() plus
its own modules through Appwrite\Cloud\Platform\Appwrite and never
instantiates this class, so the guard could not fire there.

The two in the shared Core services were load-bearing but env-dependent.
Cloud registers its own stats-usage and stats-resources, and Core is added
first, so without a guard getWorkerAction() would hand Cloud the generic
worker instead of its billing-aware one -- silently, and only when
_APP_EDITION happened to be unset.

Move both registrations into the Usage module's own Services/Workers.php
and Services/Tasks.php, which is where Databases and Functions already keep
theirs. Cloud never registers that module, so the collision cannot occur
regardless of environment. Verified with _APP_EDITION unset: Cloud drops
from three duplicated usage actions to none, and usage-setup is no longer
registered there at all, which matches Cloud provisioning its schema
out-of-band.

The remaining two guards stay, for reasons that are not registration:
Deletes would begin purging Cloud's usage rows on project deletion, and
Schedule would run a second usage loop alongside Cloud's own scheduler.
Removes the unit tests this branch introduced. The e2e suite covers the
usage endpoints, and tests/unit/Usage/Fakes/Adapter.php only existed to
serve them.

Also allow utopia-php/usage ^0.14.0 rather than pinning 0.14.0 exactly, so
patch releases come in without a lock edit. The lock still resolves 0.14.0;
only its content hash changed.

RegistrationTest keeps its Usage service entry -- that is not new coverage,
it is the existing duplicate-worker assertion following the registration
move.
Cloud's merged entitlement work asserts access, geo dimensions and history
at three different points, and it has to: access is checked before the
request is parsed so an unauthorised caller is refused rather than told
whether their query was valid, while the geo gate needs the parsed filters
and the history check needs the resolved window.

A single assert() could only run after parsing, which turned that 401 into a
400. Match the three-call shape so Cloud can inherit the query unchanged.

Gauges asserts history only, as Cloud's does -- it has no geo dimensions and
no metric carve-out.
Cloud's version of this class, merged in appwrite-labs/cloud#5399, typed
these; keep that when the two converge here.
vibes 0.6.0 includes appwrite/vibes#155, which enables the usage screens
against the endpoints this branch adds. Older console builds have no UI for
them.
ClickHouse readiness was cached forever after the first success, so later
outages were treated as healthy and usage writes were dropped. Team-owned
project deletes also never reached the tenant purge path.
The self-hosted stats-resources worker only counted rows, so the console's
storage charts — which read the unified `storage` gauge Cloud writes per
bucket, database, function, and site — stayed empty. Port Cloud's
collectUnifiedStorage projection: per-resource storage bytes plus the
files/collections/documents/deployments/builds companions and project
totals, with explicit service/resourceType/resourceId tags.

Flat dimensioned gauge aggregates also returned time: null, which crashes
the console's top-resources parser; the window end now stands in, matching
the flat max-aggregate precedent.
Team deletion removed the platform project records inside the action and
purged ClickHouse afterwards, but retries reconstruct tenant sequences
from those records — a purge failure after the delete left the tenants
unrecoverable. Purge first, so a failure fails the message while a retry
can still resolve the mapping, and sweep again after the delete for rows
that landed in between (best-effort, logged). A purge returning false now
also fails the message instead of being silently acknowledged.
@cursor
cursor Bot force-pushed the feat/usage-oss branch 2 times, most recently from 20e89c6 to 63f810f Compare August 24, 2026 03:45
Type the request usage context, split disabled vs schema-not-ready
catalog errors, and late-bind overridable interval constants.

Co-authored-by: Chirag Aggarwal <[email protected]>
@cursor
cursor Bot force-pushed the feat/usage-oss branch from 63f810f to ef6bfa2 Compare August 24, 2026 03:46
Keep the best-effort Console::error, and add Span attributes so a
failed sweep is visible on the worker span, not only stdout.

Co-authored-by: Chirag Aggarwal <[email protected]>
@ChiragAgg5k
ChiragAgg5k merged commit dadc4aa into main Aug 24, 2026
45 checks passed
lohanidamodar pushed a commit that referenced this pull request Sep 12, 2026
StatsUsage and StatsResources became ClickHouse-only in #13286, so nothing
writes the project-DB or logs-DB `stats` collection any more. Remove the
definition from both collection sets and everything that existed only to
prune it.

Removing the definition makes the sweeper a hazard rather than dead weight:
new projects get no `stats` metadata row, so deleteByGroup('stats', ...)
would throw. deleteUsageStats() and both its dispatch sites go, taking
DELETE_TYPE_USAGE, the hourlyUsageRetentionDatetime message field, the
maintenance scheduling and _APP_MAINTENANCE_RETENTION_USAGE_HOURLY with them.

The logs collection set is now empty but the file and the getLogsDB plumbing
stay: the database itself is still created and other editions merge their own
collections into that set.

Also sweeps the Usage* response models that no endpoint returns any more, and
the V19 filter arms that reshaped two of them. UsageDataPoint, UsageMetric,
UsageEventList and UsageGaugeList are the live ClickHouse models and stay.

The spec test that pinned "a list of a sub-model emits array + $ref items, not
allOf" used UsageProject as its fixture; re-point it at UsageMetric/UsageDataPoint
rather than lose the generator guarantee typed SDKs depend on.

Migrations are untouched. Utopia resolves a collection from the database
metadata table, not from this config, so V20's createDocument('stats', ...)
still works on the <=1.5.x installs those migrations run against.
lohanidamodar pushed a commit that referenced this pull request Sep 12, 2026
StatsUsage and StatsResources became ClickHouse-only in #13286, so nothing
writes the project-DB or logs-DB `stats` collection any more. Remove the
definition from both collection sets and everything that existed only to
prune it.

Removing the definition makes the sweeper a hazard rather than dead weight:
new projects get no `stats` metadata row, so deleteByGroup('stats', ...)
would throw. deleteUsageStats() and both its dispatch sites go, taking
DELETE_TYPE_USAGE, the hourlyUsageRetentionDatetime message field, the
maintenance scheduling and _APP_MAINTENANCE_RETENTION_USAGE_HOURLY with them.

The logs collection set is now empty but the file and the getLogsDB plumbing
stay: the database itself is still created and other editions merge their own
collections into that set.

No API surface changes. The Usage* response models that are still returned
somewhere keep their classes, constants and registrations; only the ones with
no referee left in any edition go: UsageFunction(s), UsageSite,
UsageDocumentsDB(s) and UsageVectorsDB(s), along with the two V19 filter arms
that reshaped responses nothing emits.

The spec test that pinned "a list of a sub-model emits array + $ref items, not
allOf" used UsageProject as its fixture; re-point it at UsageMetric/UsageDataPoint
so the generator guarantee typed SDKs depend on keeps its regression net.

Migrations are untouched. Utopia resolves a collection from the database
metadata table, not from this config, so V20's createDocument('stats', ...)
still works on the <=1.5.x installs those migrations run against.
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.

4 participants