Skip to content

chore: absorb usage into packages/usage - #13956

Merged
ChiragAgg5k merged 286 commits into
mainfrom
chore/absorb-usage
Sep 28, 2026
Merged

ChiragAgg5k merged 286 commits into
mainfrom
chore/absorb-usage

Conversation

@ChiragAgg5k

Copy link
Copy Markdown
Member

Summary

Moves utopia-php/usage into packages/usage so Appwrite loads it directly. Wave 4 of #13828, following the playbook in rfc/monorepo.md. usage is a standalone repository, so it gets the full playbook. The mirror head (6340f12) is the 0.16.6 release Appwrite already locks, so there is no version gap and Appwrite runs the same code.

Important

Merge with a merge commit, not a squash. A squash drops the git-subtree-* annotation and orphans the package from its mirror.

Commits

Commit What
Add 'packages/usage/' from commit '6340f12…' Subtree import from the mirror main with full history
chore(usage): mirror plumbing mirror.yml replaces tests.yml, linter.yml, codeql-analysis.yml; pint.json and composer.lock removed; hoisted QA stripped from composer.json; README banner; CONTRIBUTING.md now points at appwrite/appwrite
refactor: load usage from packages/ Root wiring, step A shape, QA config, RFC baseline line

What changed

Area Change
Root composer.json Autoload, autoload-dev and replace entries added; utopia-php/usage: ^0.16.6 removed from require
Hoisting Nothing new: psr/http-client is already in the root require; client and query are in packages/; database is still vendored and required by the root. No ext-* requirement (ext-curl is only a suggest, and the root already requires it)
composer.lock Only utopia-php/usage removed (+1/−54, content hash)
src/ src/Usage/* moved up to src/. Otherwise Pint only: import order, new Foo()->bar(), and return null; → return; in SQL::getAttribute()
Unit tier tests/ Pure tests (Accumulator, Metric, Sample, SampleWatermark, Tenant, UsageQuery, Adapter/ClickHouseColumnType) under Utopia\Usage\Tests\
tests/E2E/ Every test that needs ClickHouse or MariaDB (the ClickHouse adapter suites, DatabaseTest, the UsageBase trait), under Utopia\Usage\Tests\E2E\. The ClickHouse benchmark harness moves to tests/E2E/Benchmark (own bench suite, excluded from e2e)
Tests Namespaces Utopia\Tests\{Usage,Adapter,Benchmark} → Utopia\Usage\Tests\…; eight @dataProvider annotations become #[DataProvider] attributes (PHPUnit 12 ignores the annotations, which upstream's PHPUnit 9 read); Rector and Pint cleanups
phpunit.xml PHPUnit 12; unit, e2e and bench suites; env defaults point the e2e tier at the compose host ports
docker-compose.yml Project utopia-usage, services only (MariaDB 13316, ClickHouse HTTP 18223), tmpfs storage. The in-container usage app service and its Dockerfile are gone: the e2e tier runs on the host, and the Dockerfile copied the removed composer.lock
phpstan.neon Standalone, level max over src and tests, with phpstan-baseline.neon holding 1 finding: the Pint return; above against ?array. Added to the RFC phase 8 list
rector.php Standalone; skips the 13 rules that would rewrite src (constructor promotion, readonly, typed constants, closure and arrow-fn types, str_contains, array_any, ??, catch variables, new without parentheses), scoped to src only

Appwrite uses the package in app/init/resources/request.php, Usage/Http/{Action,Events/XList,Gauges/XList}.php, Workers/{Deletes,StatsResources,StatsUsage}.php, Appwrite/Usage/{Concurrency,Connection}.php and tests/unit/Usage/ConcurrencyTest.php.

Validation

Check Result
bin/monorepo validate all packages valid
bin/monorepo check usage Rector, Pint, PHPStan level max (with baseline) pass
bin/monorepo test usage unit 119 tests / 481 assertions OK
bin/monorepo test usage e2e 259 tests / 1237 assertions OK against ClickHouse 25.11 and MariaDB 10.7 (5 deprecations: UsageBase exercises the deprecated Query::contains(), as upstream does)
vendor/bin/phpunit --testsuite packages in appwrite/appwrite:2.3.0 Completes: 8825 tests. 6 errors, none in usage: 5 agents DiffCheckTest (the worktree's .git is outside the container mount) and 1 client Swoole connection-reset flake
… --testsuite packages --filter 'Utopia\\Usage\\Tests' in appwrite/appwrite:2.3.0 119 tests / 481 assertions OK
vendor/bin/phpunit tests/unit/Usage in appwrite/appwrite:2.3.0 10 tests OK
Host PHPStan on the 10 Appwrite files above No errors
Utopia\Usage\Adapter\ClickHouse resolves to packages/usage/src/Adapter/ClickHouse.php; no vendor/utopia-php/usage
composer validate --no-check-publish valid (existing utopia-php/platform exact-version warning)
composer lint passes
bin/monorepo split usage --dry-run acbaa10, fast-forward of the mirror head 6340f12 (+2 commits)
git diff --check clean

The benchmark harness (composer bench, not part of either tier) does not pass upstream either: GaugesBench seeds a resource column the gauges table no longer has, and EventsBench expects daily routing where the adapter now picks split. Left as imported.

Mirror state

Ruleset Existing main ruleset (id 22178136) had org admins and repo role 5 as bypass actors and required 1 approval, so the split app could not push. absorb normalised it: the split app (4016286) is now the only always-bypass actor and 0 approvals are required
Classic branch protection on main None, so Split should push without intervention

After merge

Step
Merge with a merge commit A squash orphans the package from its mirror
Confirm Split The Split run for usage is green and the mirror fast-forwards from 6340f12
Triage mirror issues and PRs Port what is still wanted here, then close each with a pointer (see below)
Monorepo PRs None: usage never lived in utopia-php/monorepo

Open on utopia-php/usage:

# Type Title Author
utopia-php/usage#42 PR feat!: support utopia-php/database 8 and PHP 8.5 @abnegate
utopia-php/usage#31 Issue Failed flush retries re-insert already-committed rows (duplicate usage events) @loks0n
utopia-php/usage#30 PR feat: add type and outcome event dimensions @lohanidamodar
utopia-php/usage#16 PR refactor(usage): collapse the Usage facade into the adapter base, rename it Usage @loks0n
utopia-php/usage#11 PR Extract multitenancy into a SharedTables decorator with safe withTenant scoping @loks0n

🤖 Generated with Claude Code

…ods; update ClickHouse and Database adapters to support new query types and improve handling of array values
- Introduced logCounter method to log individual usage counter metrics with upsert behavior.
- Added logBatchCounter method to log multiple usage counter metrics in batch, allowing for individual entries without aggregation.
- Updated logBatch method to accept a batch size parameter for better control over batch processing.
- Enhanced Usage class to support new logging methods and batch size functionality.
- Implemented tests for new methods, including scenarios for batch sizes, counter behavior, and metrics with tags.
…s, update parsing logic, and add comprehensive tests.
…nd OFFSET application; update test documentation
…se method for improved readability and maintainability
- Introduced increment and set methods for metrics, replacing log and logCounter.
- Added in-memory buffers for increment and counter metrics with automatic flushing.
- Implemented collect and collectSet methods for deferred metric accumulation.
- Enhanced flush logic to handle both increment and set metrics, clearing buffers post-flush.
- Added configuration options for flush thresholds and intervals.
- Updated tests to reflect changes in metric logging and buffer management.
ArnabChatterjee20k and others added 11 commits September 10, 2026 10:50
…858a)

The prior commit inadvertently committed a locally-regenerated lock that
resolved a broken utopia-php/client combination (undefined array_last() in
the Curl adapter). Restore the lock to its pre-session state.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QssJBktSLWpuEuWzVB23do
…ith ZSTD

These store raw, un-normalized caller input (full Accept/Accept-Language
headers, arbitrary query-key names), so their distinct count is unbounded.
Revert them from LowCardinality + set(0) back to Nullable(String) +
bloom_filter (equality lookups without a cardinality bet) and add
CODEC(ZSTD(3)) to compress the high-entropy text. protocol/timeZone/
weatherCode remain LowCardinality + set(0) (genuinely bounded).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QssJBktSLWpuEuWzVB23do
Adds an ipReputation dimension to the events schema, ready to populate later.
It holds a bounded IP-reputation verdict (clean/low/suspicious/block), so it
is typed LowCardinality(Nullable(String)) with a set(0) equality index, like
protocol/country. Column is nullable and unpopulated until the producer is
ready.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QssJBktSLWpuEuWzVB23do
feat(tests): add tests for low and high cardinality request attribute…
client 0.5 moved Utopia\Client under Utopia\Client\Client and keeps
the old name only as an alias until its next major. Require ^0.5 and
import the new name so client can drop the alias.
refactor: use utopia-php/client 0.5's names
…a0e40d'

git-subtree-dir: packages/usage
git-subtree-mainline: 1bc79bd
git-subtree-split: 6340f12
@ChiragAgg5k ChiragAgg5k added the absorb History-preserving package absorption; merge commit required label Sep 28, 2026
@ghost

ghost commented Sep 28, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The new Audit wiring matches the package namespaces and the root dependency setup; I found no concrete issue in these changes.

This PR moves Utopia Usage into packages/usage and loads it directly through Appwrite’s Composer autoloader, with package tests, QA configuration, and mirror plumbing. Earlier follow-up commits also wired in the Platform package. The latest commits switch Audit to the local packages/audit copy and record its PHPStan baseline in the monorepo RFC.

Latest changes: The newest commits add Audit source and test autoload mappings, replace the external Audit dependency, and document Audit’s five PHPStan baseline findings.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 7
File Change
composer.json, composer.lock Load absorbed Usage, Platform, and Audit packages from local source and replace their external dependencies.
packages/usage/ Import Usage source and tests with standalone unit/E2E suites, QA configuration, compose services, and mirror plumbing.
packages/platform/ Import Platform source and tests with package QA, documentation, and mirror configuration.
packages/audit/ Provide the local Audit source, tests, and package configuration used by the new root autoload mappings.
rfc/monorepo.md Record package PHPStan baselines, including the newly documented Audit findings.
composer.json Autoloads usage source and tests directly and replaces the external dependency.
packages/usage/tests/Adapter/ClickHouseColumnTypeTest.php Adds a standalone unit test for ClickHouse dimension column types.

Reviewed the commits since 7cfe648 · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@greptile-apps

greptile-apps Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

[High risk] Absorbs external usage package into monorepo.

The PR should not merge until the repository’s regular-expression requirement is satisfied; the two earlier findings also remain open.

Fix All in Claude CodeFindings

  1. P2 Prohibited regular expressions ▶
  2. P2 Tests depend on private implementation ▶
  3. P2 Security Test databases exposed on network ▶
Fix with agent prompt
### Issue 1
packages/usage/src/SampleWatermark.php:29
The watermark validation uses `preg_match()`. The repository instruction says not to add regular expressions; use string functions or an existing validator unless the PR explains why neither works. The ClickHouse adapter also uses regular expressions for identifier validation and SQL rewriting. Please satisfy this requirement 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!

### Issue 2
packages/usage/tests/Adapter/ClickHouseColumnTypeTest.php:undefined-32
The new unit test calls the adapter’s private `getColumnType()` method and checks exact SQL type strings. A harmless internal refactor could break it without changing the schema ClickHouse creates. The same pattern appears in `MetricTest`, which derives an expected count from `Metric::EVENT_COLUMNS`, and `UsageQueryTest`, which asserts configuration constants. The repository requires tests of observable behavior and leaves syntax and schema checks to linters. Please satisfy that requirement 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!

### Issue 3
packages/usage/docker-compose.yml:6-7
If a developer or CI host is reachable from another machine and its firewall permits these ports, the unrestricted MariaDB and ClickHouse port bindings let a peer connect using the fixed passwords in this file and read or modify test data. Bind both published ports to loopback for host-run tests.

**How this was verified:** Both database ports have unrestricted host bindings, and the same Compose file supplies their login credentials.

---

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

Summary

The PR moves the usage library into packages/usage, replaces the vendored Composer dependency with in-tree autoloading, and adds standalone package tests and tooling. The post-review merge introduces no additional usage-code changes; the audit files visible in the linear diff were already in the base.

Reviews (4) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..."

namespace: 'utopia_usage_coltype',
);

$this->getColumnType = new ReflectionMethod(ClickHouseAdapter::class, 'getColumnType');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Tests depend on private implementation The new unit test calls the adapter’s private getColumnType() method and checks exact SQL type strings. A harmless internal refactor could break it without changing the schema ClickHouse creates. The same pattern appears in MetricTest, which derives an expected count from Metric::EVENT_COLUMNS, and UsageQueryTest, which asserts configuration constants. The repository requires tests of observable behavior and leaves syntax and schema checks to linters. Please satisfy that requirement before merging.

Context Used: Call out and harshly judge implementation-coupled tests. We don't mirror source code, configuration, or version pins in assertions. We test observable behavior; use linters for syntax and schema checks. (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/usage/tests/Adapter/ClickHouseColumnTypeTest.php
Line: 32

Comment:
**Tests depend on private implementation** The new unit test calls the adapter’s private `getColumnType()` method and checks exact SQL type strings. A harmless internal refactor could break it without changing the schema ClickHouse creates. The same pattern appears in `MetricTest`, which derives an expected count from `Metric::EVENT_COLUMNS`, and `UsageQueryTest`, which asserts configuration constants. The repository requires tests of observable behavior and leaves syntax and schema checks to linters. Please satisfy that requirement before merging.

**Context Used:** Call out and harshly judge implementation-coupled tests. We don't mirror source code, configuration, or version pins in assertions. We test observable behavior; use linters for syntax and schema checks. ([source](https://app.greptile.com/review/custom-context?memory=instruction-0))

---

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

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!

Fix in Claude Code Fix in Codex

Comment on lines +6 to +7
ports:
- "13316:3306"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 security Test databases exposed on network If a developer or CI host is reachable from another machine and its firewall permits these ports, the unrestricted MariaDB and ClickHouse port bindings let a peer connect using the fixed passwords in this file and read or modify test data. Bind both published ports to loopback for host-run tests.

How this was verified: Both database ports have unrestricted host bindings, and the same Compose file supplies their login credentials.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/usage/docker-compose.yml
Line: 6-7

Comment:
**Test databases exposed on network** If a developer or CI host is reachable from another machine and its firewall permits these ports, the unrestricted MariaDB and ClickHouse port bindings let a peer connect using the fixed passwords in this file and read or modify test data. Bind both published ports to loopback for host-run tests.

**How this was verified:** Both database ports have unrestricted host bindings, and the same Compose file supplies their login credentials.

---

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

Fix in Claude Code Fix in Codex

@github-actions

github-actions Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → chore/absorb-usage (after).

Metric Before After Change
🚀 Requests/sec 190.59 194.78 ⚪ +2.2%
⏱️ Latency P50 90.42 ms 89.3 ms ⚪ -1.2%
⏱️ Latency P95 211.76 ms 205.96 ms ⚪ -2.7%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 89.3 205.96 12,369 194.78 -5.8
Account 173.24 319.67 651 10.84 -8.4
TablesDB 87.35 166.05 6,727 108.28 -0.91
Storage 81.03 175.93 3,255 54.03 -6.15
Functions 125.7 239.97 1,736 29.49 -16.15

Top API waits (after)

API request Max wait (ms)
account.name.update 437.81
functions.variables.update 428.56
account.prefs.update 402.45
tablesdb.rows.create 389.89
account.get 370.78

@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

}

foreach ($entries as $entry) {
if (preg_match('/^[a-f0-9]{32}:[a-f0-9]{64}:[a-f0-9]{64}$/', $entry) !== 1) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Prohibited regular expressions The watermark validation uses preg_match(). The repository instruction says not to add regular expressions; use string functions or an existing validator unless the PR explains why neither works. The ClickHouse adapter also uses regular expressions for identifier validation and SQL rewriting. Please satisfy this requirement before merging.

Context Used: CLAUDE.md (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/usage/src/SampleWatermark.php
Line: 29

Comment:
**Prohibited regular expressions** The watermark validation uses `preg_match()`. The repository instruction says not to add regular expressions; use string functions or an existing validator unless the PR explains why neither works. The ClickHouse adapter also uses regular expressions for identifier validation and SQL rewriting. Please satisfy this requirement before merging.

**Context Used:** CLAUDE.md ([source](https://github.com/appwrite/appwrite/blob/main/CLAUDE.md))

---

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

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!

Fix in Claude Code Fix in Codex

@ChiragAgg5k
ChiragAgg5k merged commit e276a2b into main Sep 28, 2026
52 checks passed
abnegate added a commit that referenced this pull request Sep 29, 2026
utopia-php/usage#42 moved usage onto utopia-php/database 8: typed
Attribute and Index models for the schema, the event ordinal dimension,
PHP 8.5. Main absorbed usage into packages/usage (#13956) and the
mirror closed #42 in favour of a change here, so this applies #42's
final head (bf9ab997fa) to the package: every line it changed, in the
package layout, with its tests. The package requires database ^8.0
with dev stability until 8.0.0 is tagged, because bin/monorepo check
and test resolve it from Packagist, where it exists only as
8.0.x-dev; the mirror's branch alias does not apply to a split
package.

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

absorb History-preserving package absorption; merge commit required

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants