Skip to content

fix(usage): migrate the usage schema without touching retention - #14553

Merged
abnegate merged 2 commits into
mainfrom
fix-usage-setup
Oct 15, 2026
Merged

abnegate merged 2 commits into
mainfrom
fix-usage-setup

Conversation

@abnegate

Copy link
Copy Markdown
Member

What does this PR do?

Fixes two usage bugs at their source, both found on cloud (appwrite-labs/cloud#6554): every usage events INSERT failed with Code: 16 ... No such column ordinal, and the workaround there patched the table from the worker at runtime.

Schema migration

  • A release that adds a usage column (here ordinal) only reached a deployment through Usage::setup(), which also re-applies the events and daily retention TTL. So rolling out a column meant applying a TTL nobody had reviewed.
  • A deployment that wraps its usage connection could not run it at all. Connection::setup() returned early for Connection::fromUsage(), so usage-setup printed "ClickHouse schemas are ready" and ran no DDL.

Changes:

  • Usage::migrate() creates and upgrades the schema (tables, daily view, columns, skip indexes, projections) and leaves the TTL alone. setup() is now migrate() followed by the retention TTL. Adapters inherit a migrate() that runs setup(), so third-party adapters still work. The ClickHouse adapter overrides it.
  • Connection::setup() now applies the schema on a wrapped connection too. A wrapped connection still skips the lazy readiness health check.

Accumulator double write

  • Accumulator::flush() passed the whole buffer to one addBatch() call. The adapter inserts in chunks of 1,000, so if a later chunk failed, every entry stayed buffered and the next flush wrote the earlier chunks again. The accumulator now sends one batch per addBatch() call and removes each batch from the buffer once it is written.

Test Plan

  • ClickHouseSchemaTest::testMigrateAddsMissingColumnsWithoutApplyingRetention (E2E, real ClickHouse) starts from a legacy events table with no dimension columns and no TTL, using an adapter configured with a 30-day retention. After migrate(), every event column (including ordinal) exists, neither the events table nor the daily table has a TTL, and an insert with an ordinal tag succeeds. A following setup() then applies the TTL to both tables.
  • AccumulatorTest::testRetryAfterAFailedBatchWritesEveryEntryOnce buffers 2,500 entries and fails the second batch. Only the first batch leaves the buffer, and after the retry each of the 2,500 entries has been written exactly once. Without the fix it fails: all 2,500 stay buffered and the first 1,000 are written twice.
  • Tests\Unit\Usage\ConnectionTest::testSetupAppliesTheSchemaThroughAWrappedConnection fails on main (the setup count is 0) and passes here. testWrappedConnectionIsReadyWithoutAHealthCheck covers the wrapped behaviour this PR keeps.
  • Locally: bin/monorepo check usage passes (Pint, Rector, PHPStan), and bin/monorepo test usage passes (unit 112 tests, E2E 273 tests on ClickHouse 25.11 and MariaDB). Pint and PHPStan pass on the server files.

Related PRs and Issues

  • appwrite-labs/cloud#6554 will run migrate() from its usage setup task in place of the worker's runtime schema repair.

Checklist

  • Have you read the Contributing Guidelines on issues?
  • If the PR includes a change to an API's metadata (desc, label, params, etc.), does it also include updated API specs and example docs? (No API changes.)

🤖 Generated with Claude Code

abnegate and others added 2 commits October 16, 2026 00:05
A release that adds a usage column, such as `ordinal`, only reached a
deployment through `setup()`, and `setup()` also re-applies the events and
daily TTL. A deployment that wraps its usage connection could not run it at
all: `Connection::setup()` returned early for `Connection::fromUsage()`, so
the `usage-setup` task reported the schema ready without running DDL, and the
events INSERT failed on the missing column.

- `Usage::migrate()` creates and upgrades the schema (tables, daily view,
  columns, skip indexes, projections) and leaves the TTL alone. `setup()` is
  `migrate()` followed by the retention TTL. Adapters inherit a `migrate()`
  that runs `setup()`, so third-party adapters keep working.
- `Connection::setup()` applies the schema on a wrapped connection too. A
  wrapped connection still skips the lazy readiness health check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`Accumulator::flush()` passed the whole buffer to one `addBatch()` call. The
adapter inserts it in chunks of 1,000, so when a later chunk failed the
exception left every entry buffered, and the next flush inserted the chunks
that had already been written a second time. The accumulator now writes one
batch per `addBatch()` call and drops each batch from the buffer as soon as it
is written.

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

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

Copy link
Copy Markdown

Review complete. No issues found — approved ✅.


This PR evolves packages/usage to separate schema migration from setup: Adapter::migrate() gains a policy-free default, the ClickHouse adapter overrides migrate() to add missing columns and indexes without touching retention TTL, and Usage exposes the migration path to callers. src/Appwrite/Usage/Connection.php wires this into the platform so usage storage can be migrated/initialized through the shared client lifecycle. Tests cover the accumulator, the ClickHouse schema migration behavior, and the new Connection wrapper.

Files Change
packages/usage/src/Adapter.php Adds migrate() to the adapter contract with a policy-free default
packages/usage/src/Adapter/ClickHouse.php Overrides migrate() to backfill columns/indexes without re-applying TTL retention
packages/usage/src/Accumulator.php, packages/usage/src/Usage.php Threads migration through usage writes and the public facade
src/Appwrite/Usage/Connection.php New wrapper integrating the usage adapter lifecycle with the platform
packages/usage/tests/*, tests/unit/Usage/ConnectionTest.php Unit and e2e coverage for accumulator, schema migration, and connection behavior

No findings met the review threshold; the verified candidates were below the confidence cutoff or informational only.

Reviewed commit: f837b65

@github-actions

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

19 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (12)
  • php.appwrite.secret-compare-timing (5)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

@ghost

ghost commented Oct 15, 2026

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The migration, wrapped-connection setup, and accumulator retry paths behave consistently with their intended contracts.

This change separates ClickHouse schema migration from retention setup, exposes migration through the usage API, and lets wrapped usage connections apply their schema. It also flushes accumulator entries in 1,000-item batches and removes successful batches from the buffer immediately.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 10
File Change
packages/usage/CHANGELOG.md Documents the new schema migration API and accumulator retry behavior.
packages/usage/README.md Shows the setup and migration APIs.
packages/usage/src/Accumulator.php Flushes event and gauge entries in bounded batches and clears each successful batch.
packages/usage/src/Adapter.php Adds a backward-compatible default migrate() implementation for adapters.
packages/usage/src/Adapter/ClickHouse.php Separates retention-free schema migration from setup-time TTL application.
packages/usage/src/Usage.php Exposes adapter migration through Usage.
packages/usage/tests/AccumulatorTest.php Covers retrying after a later batch fails without duplicate writes.
packages/usage/tests/E2E/Adapter/ClickHouseSchemaTest.php Verifies migration adds legacy columns without changing retention, then setup applies TTLs.
src/Appwrite/Usage/Connection.php Allows setup to apply schema through wrapped usage connections.
tests/unit/Usage/ConnectionTest.php Covers setup on wrapped connections and readiness without a health check.

Reviewed f837b65 · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟢 Tier S · Looks good to merge. Summary

@github-actions

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix-usage-setup (after).

Metric Before After Change
🚀 Requests/sec 182.98 182.58 ⚪ -0.2%
⏱️ Latency P50 94.88 ms 95.69 ms ⚪ +0.8%
⏱️ Latency P95 217.85 ms 217.8 ms ⚪ 0%
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 95.69 217.8 11,400 182.58 -0.04
Account 175.35 331.18 600 10.28 -9.02
TablesDB 93.18 170.34 6,200 101.98 -4.6
Storage 88.04 185.64 3,000 50.98 -7.1
Functions 137.67 259.07 1,600 27.92 -10.02

Top API waits (after)

API request Max wait (ms)
account.name.update 668.04
functions.create 416.98
tablesdb.rows.increment 411.08
tablesdb.rows.delete 409.75
functions.variables.create 399.27

@abnegate
abnegate merged commit 2d9e276 into main Oct 15, 2026
65 checks passed
@abnegate
abnegate deleted the fix-usage-setup branch October 15, 2026 11:55
abnegate added a commit that referenced this pull request Oct 15, 2026
Two gaps in migrate():

- ClickHouse refuses to change a column that a skip index covers (code 524,
  ALTER_OF_COLUMN_IS_FORBIDDEN). A table that #14553's migrate() had already
  indexed, such as `protocol` with `index-protocol`, aborted the
  convergence. migrate() now drops the indexes covering a drifted column,
  modifies the column, then adds the same indexes back and materializes them
  for existing parts. A run interrupted midway resumes on the next run.
- migrate() created a missing events or daily table without the retention
  TTL, so a table it created grew without bound. A table migrate() creates
  now carries the configured TTL in its CREATE TABLE. An existing table's TTL
  is still never altered; only setup() changes it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ChiragAgg5k ChiragAgg5k mentioned this pull request Oct 21, 2026
6 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant