Skip to content

fix(usage): keep usage events when an insert fails - #14638

Merged
abnegate merged 5 commits into
mainfrom
fix/usage-requeue
Oct 19, 2026
Merged

abnegate merged 5 commits into
mainfrom
fix/usage-requeue

Conversation

@abnegate

@abnegate abnegate commented Oct 18, 2026 •

Copy link
Copy Markdown
Member

Problem

StatsUsage folds each message into an open batch and returns, so the queue acknowledges the message. Five seconds later a timer runs the insert. If the insert failed, flush() logged the error and dropped the batch, and every event in it was lost. This happened during a ClickHouse outage, a 5xx, or a rejected insert such as a missing column. appwrite-labs/cloud#6554 fixed this in cloud's worker and listed the server-ce worker as a known gap.

Fix

This follows the cloud worker's approach (src/Appwrite/Platform/Workers/StatsUsage.php):

  • A batch whose insert fails, or whose flush() returns false, is kept in $retained. Accumulator::flush() already removes each batch it writes, so a retry writes only what is left and never writes a batch twice.
  • While anything is retained, action() refuses each new message by throwing. The message is not acknowledged: on Redis it goes to the failed list, which queue-retry can replay, and on JetStream it is redelivered with backoff. Memory stays bounded because nothing new is accepted.
  • Retries are bounded:
    • A failed flush arms exactly one retry timer, after RETRY_DELAY_MS (5 s).
    • Any later attempt runs from action() on the next message, at most once per RETRY_DELAY_MS.
    • A stopping worker waits for at most one retry, which keeps it inside Docker's 10 s stop timeout.

Two trade-offs:

  • A retry after an ambiguous failure, such as a timeout after ClickHouse already applied the insert, can write the batch twice. The previous code dropped it instead. The ClickHouse adapter has no deduplication key, and cloud#6554 made the same choice.
  • If ClickHouse is still down when the worker stops, the retained batch is lost with the process. The open batch has the same best-effort limit.

Tests

API E2E: UsageCustomServerTest::testUsageEventsSurviveAFailedInsert

  • Adds a CHECK 0 = 1 constraint to projects_usage_events, so ClickHouse rejects every insert (Code 469).
  • Sends PATCH /users/:id/prefs and waits past the batch window, then drops the constraint.
  • Expects /v1/usage/events to count that PATCH.

Because the test breaks inserts for the whole stack, it is in the new usageOutage group. That group runs in its own e2e_grouped lane ("Usage Outage") and is excluded from the regular Usage run.

A unit test that drove action() under Swoole coroutines was dropped in review, because the unit suite must not run worker coroutines (AGENTS.md). The E2E is the regression test.

Before (main) After (this PR)
E2E testUsageEventsSurviveAFailedInsert, 8 s outage fails after 90 s: PATCH network.requests = 0. The worker logged Code: 469 ... VIOLATED_CONSTRAINT and dropped the batch. passes in 16 s
Same test with a 16 s outage (outlasts the timer retry; local only) — passes. The timer retry failed, then the retry from the next message wrote the event.
CI "Tests / E2E / Usage Outage (dedicated)" — passes
Pint, PHPStan, Rector pass

The before run used main's worker unchanged, on a local stack built from main.

🤖 Generated with Claude Code

StatsUsage acknowledged each message once its events were folded into the
open batch, then logged and discarded the batch if the insert failed, so a
ClickHouse outage or a rejected insert lost every event in it.

A batch whose insert fails is now retained. The worker retries it every
20 seconds and refuses new messages until it is written, so they stay in
the queue (failed list on Redis, redelivery with backoff on JetStream)
instead of being acknowledged into memory. The accumulator keeps only the
batches it could not write, so a retry never writes a batch twice. This
matches the cloud worker's handling in appwrite-labs/cloud#6554.

The outage E2E breaks every usage insert on its stack, so it runs in a
lane of its own.

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

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

Copy link
Copy Markdown

Review complete. 🟡 1 medium

💬 Inline comments (1)

🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 New unit test drives the worker against repo policy (StatsUsageTest.php:25) — tests/unit/Platform/Workers/StatsUsageTest.php:25-53 drives the StatsUsage worker's action() directly, including Swoole Coroutine::run and timers, from the shared unit suite.

This PR makes the stats-usage worker resilient to a ClickHouse outage: a failed flush retains the batch and schedules a delayed retry instead of losing metrics, with a shutdown path that flushes retained data. Supporting changes wire a new usageOutage e2e group into the CI lanes so the outage test is excluded from the default paratest run and executed only in its own lane, plus a fake ClickHouse server and unit coverage for the retry semantics.

Files Change
src/Appwrite/Platform/Workers/StatsUsage.php Adds batch retention, retry scheduling, and shutdown flush to the usage worker when the ClickHouse insert fails
.github/ci/e2e.json, .github/workflows/ci.yml Introduces the usageOutage group lane and excludes that group from the default paratest invocation
tests/e2e/Services/Usage/UsageCustomServerTest.php, tests/unit/Usage/ClickHouseServer.php, tests/unit/Platform/Workers/StatsUsageTest.php Adds the outage e2e test, a fake ClickHouse insert endpoint, and unit tests exercising retry and retention behavior

Reviewed commit: ee2454d

@ghost

ghost commented Oct 18, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

This PR retains failed usage-event batches in the StatsUsage worker and retries them while refusing new messages until they can be written. It adds an API regression test for ClickHouse insert failures and isolates that test in a dedicated Usage Outage E2E lane.

Latest changes: The newest worker change limits timer-based retries to one attempt and lets later messages trigger retries after the delay.

Verdict New comments Fixed Still open
💬 Commented 0 0 0

Note

Not approving while a bug finding is open: Retry retained batches even when no new message arrives

📂 Walkthrough · 4
File Change
src/Appwrite/Platform/Workers/StatsUsage.php Retains failed batches, refuses messages while they remain, and applies timer- and message-triggered retries.
tests/e2e/Services/Usage/UsageCustomServerTest.php Adds an API regression test that forces ClickHouse inserts to fail and checks that usage events are written after recovery.
.github/ci/e2e.json Adds a dedicated Usage Outage E2E lane for the stack-wide ClickHouse failure test.
.github/workflows/ci.yml Excludes the outage test group from the regular Usage E2E run.

Reviewed the commits since 8e22307 · 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 A · Looks good to merge. Summary

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

@luxor-code-review luxor-code-review Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Adds ClickHouse-outage retry handling to the stats-usage worker plus a dedicated CI lane and tests; two moderate robustness findings around retry-timer shutdown and test-layer policy.

Key findings

@github-actions

github-actions Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/usage-requeue (after).

Metric Before After Change
🚀 Requests/sec 217.27 221.25 ⚪ +1.8%
⏱️ Latency P50 78.35 ms 79.39 ms ⚪ +1.3%
⏱️ Latency P95 193.19 ms 178.83 ms 🟢 -7.4%
Per-scenario breakdown & investigation details

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

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 79.39 178.83 13,680 221.25 -14.36
Account 149.76 281.78 720 12.29 -10.86
TablesDB 79.23 150.83 7,440 122.79 -2.54
Storage 67.81 153.91 3,600 61.62 -13.55
Functions 108.6 208.6 1,920 33.46 -14.93

Top API waits (after)

API request Max wait (ms)
account.name.update 530.99
functions.variables.update 352.06
account.prefs.update 351.6
tablesdb.rows.create 341.17
functions.create 322.1

abnegate and others added 3 commits October 19, 2026 12:24
Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	tests/e2e/Services/Usage/UsageCustomServerTest.php
A stopping worker waits for its pending retry timer, so a 20s retry
outlived Docker's 10s stop timeout and the container was killed with
the retained batch still in memory. Retrying every 5s keeps a pending
retry inside the same budget the flush window already respects.

The worker unit test drove action() inside Swoole coroutines in the
shared unit process, which the test boundaries rule out; the usage
outage E2E covers the same behaviour through the real worker, so the
test and its ClickHouse stand-in go, along with the constant seams
they needed.

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

A retry that failed re-armed its own timer, so during an outage that
outlived shutdown the worker kept its event loop alive past Docker's stop
timeout and was killed. Only the flush that fails now arms a retry
timer. Later attempts run on the next message once the retry delay has
passed, so a stopping worker waits for at most one retry.

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
abnegate merged commit d44428c into main Oct 19, 2026
122 checks passed
@abnegate
abnegate deleted the fix/usage-requeue branch October 19, 2026 00:03
@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