Skip to content

fix(queue): ship lean project and user contexts instead of whole documents - #14477

Merged
ChiragAgg5k merged 7 commits into
mainfrom
refactor/lean-queue-payloads
Oct 14, 2026
Merged

ChiragAgg5k merged 7 commits into
mainfrom
refactor/lean-queue-payloads

Conversation

@ChiragAgg5k

@ChiragAgg5k ChiragAgg5k commented Oct 14, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Queue messages serialized whole Documents with getArrayCopy(): the full project (keys, webhooks, platforms, templates, decrypted SMTP/OAuth secrets), the full user (sessions with secrets, tokens, memberships, targets, password hash), and the audit payload (the whole HTTP response). Workers re-fetch the project by $id and read at most five user fields, so almost all of it was dead weight. On 2026-10-13 a single ~138MB v1-audits job sat in the queue for 14h and OOMKilled every worker-audits pod that reserved it (~360 restarts).

before: { project: <full doc>, user: <full doc + sessions>, payload: <response body>, ... }
after:  { project: ProjectContext, user: UserContext, payload: [], ... }
Change Where
UserContext ($id, $sequence, name, email, type); database added to ProjectContext Event/Message
project → ProjectContext Build, Func, Mail, Messaging, Database, Delete, Jobs, Migration, Execution(s), ExecutionCancelled, StatsResources
user → UserContext Audit (user, impersonatorUser), Func, webhook/event trim
user dropped (never read) Database, Messaging
audits.payload defaults to false; S3 audits send [] shared/api.php, S3/Base.php
Console project resolved from config in workers, not from the payload app/init/worker/message.php

Kept full on purpose: Delete document (row is gone before publish), Func http function (vars used directly), Migration migration (working state), Execution records, and every customer-facing payload (webhook body, function event body, realtime).

Benchmark

5,598 real jobs sampled from fra1 queue replicas, decoded with the new fromArray() and re-encoded with toArray(), weighted by 1.28h of queue throughput.

Queue Jobs/day Before GiB/day After GiB/day Saved
v1-audits 6.3M 98.7 3.5 96%
v1-executions 3.7M 23.2 4.2 82%
v1-functions 1.3M 12.9 5.7 56%
v1-webhooks 0.5M 8.5 6.7 22%
v1-stats-resources 0.2M 1.1 0.0 96%
deletes, mails, database, messaging small 1.1 0.2 79–97%
All document-carrying queues 147.4 22.1 85%

v1-stats-usage (119 GiB/day of metrics) is unaffected. Every sampled old-format job decodes with the new classes, so in-flight jobs survive the deploy.

Test Plan

  • composer lint, phpstan and the existing unit suite pass; ProjectContextTest now expects database.
  • CertificatesDomainValidationTest passed only with _APP_DOMAIN set; it now pins the validation domain.
  • Benchmark above: every sampled old-format job decodes with the new classes.
  • E2E to watch: Functions, Webhooks, Databases/TablesDB, Messaging, Account, Teams, Migrations, Projects, Realtime, Usage.

Related PRs and Issues

  • Job size telemetry: feat(queue): record consumed message size and log large messages #14480 (queue Server, no re-encode).
  • Cloud follow-up (must ship with the bump): drop user: from DatabaseMessage in the four Delete.php actions, return the injected console project in cloud's worker message.php, trim cloud messages (threats, growth, ZDT, dedicated databases).

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?

Related: #14478

@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟡 2 medium

💬 Inline comments (2)

  • 🟡 Restore audits.payload default of true — api.php:1063
  • 🟡 Avoid double json_encode when sizing queue payloads — Telemetry.php:75
🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 S3 audit events now enqueue empty payload (Base.php:505) — enqueueAudit changed the AuditMessage payload from $resource->getArrayCopy() to [], so bucket/file audit events are enqueued with no resource data (src/Appwrite/Platform/Modules/S3/Http/S3/Base.php:505).

The PR replaces full user/project document serialization in queue and event messages with lean ProjectContext and UserContext DTOs, wraps queue publishers with a new PublisherTelemetry payload-size histogram, and substitutes a fresh console project document in worker message init. The audits.payload route-label default is flipped from true to false, and the S3 module now enqueues audits with an empty payload.

Files Change
src/Appwrite/Event/Message/* New/updated message DTOs (ProjectContext, UserContext) that whitelist ~7 fields and drop empty strings; user removed from Database/Messaging messages
src/Appwrite/Event/Event.php trimPayload() now serializes a slim user context into every event payload
app/init/worker/message.php, app/init/resources.php, app/realtime.php Console project resolution and telemetry-wrapped publisher wiring
src/Appwrite/Utopia/Queue/Publisher/Telemetry.php New payload-size histogram decorator over queue publishers
app/controllers/shared/api.php, src/Appwrite/Platform/Modules/S3/Http/S3/Base.php Audit payload capture default flipped off; S3 audits enqueue empty payloads
tests/unit/** Unit tests for the new messages, telemetry publisher, and workers

Note: a few scans hit their step limits before publishing, but their verified conclusions were recovered and adjudicated; coverage across all 52 changed files is intact.

Reviewed commit: 41d93d0

@ghost

ghost commented Oct 14, 2026 •

Copy link
Copy Markdown

🔵 Tier A · Mergeable after minor fixes

The previously reported minor test gap remains: the new project database field is not asserted through fromArray().

This change serializes compact project and user contexts in queue messages, reduces audit payload retention, and resolves console projects from worker configuration. It also removes unused user fields from database and messaging queue messages and updates related unit-test setup.

Verdict New comments Fixed Still open
✅ Approved 0 0 1
Fix with agent prompt
### Issue 1
tests/unit/Event/Message/ProjectContextTest.php:33
**Keep a round-trip assertion for the database field**

This assertion only covers `fromDocument()->toArray()`; if `fromArray()` stops restoring `database`, the test still passes. The removed round-trip test covered this field, and workers decode queued project contexts with `fromArray()`, so retaining that assertion would protect the queue contract.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
📂 Walkthrough · 8
File Change
app/controllers/shared/api.php, src/Appwrite/Platform/Modules/S3/Http/S3/Base.php Disable audit payload capture by default and omit the S3 resource body from audit jobs.
app/init/worker/message.php Resolve console project data from configuration and retain project-context decoding.
src/Appwrite/Event/Event.php Trim event project and user data to queue-safe context fields.
src/Appwrite/Event/Message/*.php Serialize compact project and user contexts and remove unused database/messaging user data.
src/Appwrite/Event/Message/UserContext.php Add a compact serializable user context.
src/Appwrite/Platform/Modules/Databases/Http/Databases/**/*.php Remove unused user fields from database queue messages.
tests/unit/Event/Message/ProjectContextTest.php Include the database value in the project-context serialization expectation.
tests/unit/Workers/CertificatesDomainValidationTest.php Pin the certificate validation domain in the test message.
⏳ Still open from earlier reviews · 1

Reviewed 61f44f4 · 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

github-actions Bot commented Oct 14, 2026 •

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.

@github-actions

github-actions Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → refactor/lean-queue-payloads (after).

⚠️ Before benchmark did not complete — change column unavailable.

Metric Before After Change
🚀 Requests/sec n/a 195.65 n/a
⏱️ Latency P50 n/a 88.89 ms n/a
⏱️ Latency P95 n/a 208.43 ms n/a
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 88.89 208.43 12,540 195.65 n/a
Account 174.02 329.43 660 10.98 n/a
TablesDB 86.38 160.58 6,820 109.58 n/a
Storage 80.18 175.92 3,300 54.72 n/a
Functions 126.54 247.29 1,760 29.81 n/a

Top API waits (after)

API request Max wait (ms)
functions.create 495.3
account.name.update 483.04
account.prefs.update 482.13
functions.delete 427.89
functions.variables.update 410.29

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

This PR slims queue message payloads via new ProjectContext/UserContext DTOs and adds a telemetry histogram around queue publishers, but silently disables audit payload capture for all endpoints.

Key findings

  • 🟡 Restore audits.payload default of true — api.php:1063
  • 🟡 Avoid double json_encode when sizing queue payloads — Telemetry.php:75

Comment thread app/controllers/shared/api.php Resolved
@ChiragAgg5k
ChiragAgg5k force-pushed the refactor/lean-queue-payloads branch from 45b1467 to dd88996 Compare October 14, 2026 11:56

@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

…text

Queue publishers route jobs on the project database DSN, so the lean project context has to carry it instead of the whole project document. UserContext replaces whole user documents (sessions, tokens, memberships, targets) in queue payloads with the identity fields workers actually read. Empty fields are dropped on serialization so an empty context stays an empty Document for isEmpty() checks.
No consumer reads the audit payload (cloud Activity writes data '' and CE has no audits worker), yet every audited route attached the full response body by default. That is how a single v1-audits job reached 138MB and OOMKilled workers. Routes can still opt in via the audits.payload label.
…ayload

Workers used the console project document straight from the message payload, so publishers had to ship the full console document. Resolving it from the console resource (copied per job so the shared instance and its nested documents are never mutated) lets publishers send lean console context, while Deletes still reads auths.duration from the configured console project.
Workers re-fetch the project by $id, so keys, webhooks, templates and secrets copied into these messages went unread and inflated jobs (2026-10-13 v1-audits OOM).
Queue messages carried whole user Documents (sessions, tokens, memberships, targets, password hash), which let a single v1-audits job reach 138MB and OOMKill workers. Consumers only read $id, $sequence, name, email and type (cloud Activity for audits, the Functions worker for the execution JWT and user headers), so Audit and Func now serialize users through UserContext and projects through ProjectContext.

The Databases and Messaging workers never read user, so both messages drop the property entirely; no CE caller passes it.
The webhooks worker reads only the user id for X-Appwrite-Webhook-User-Id; the full user with sessions and secrets rode every webhook job.
Without _APP_DOMAIN the worker treats every rule as the main domain and skips DNS validation, so the test only passed where the docker env set it.
@ChiragAgg5k
ChiragAgg5k force-pushed the refactor/lean-queue-payloads branch from dd88996 to 61f44f4 Compare October 14, 2026 12:07
@ChiragAgg5k
ChiragAgg5k merged commit 8635df5 into main Oct 14, 2026
63 checks passed
@ChiragAgg5k
ChiragAgg5k deleted the refactor/lean-queue-payloads branch October 14, 2026 12:29
abnegate added a commit that referenced this pull request Oct 14, 2026
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]>
eldadfux added a commit that referenced this pull request Oct 14, 2026
Follows main's lean queue payloads (#14477): function, webhook, event,
delete and audit messages carry ProjectContext and UserContext instead of
whole documents, and audits record no payload unless the route asks.

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