Skip to content

fix(events): preserve object shapes in event payloads - #13650

Merged
HarshMN2345 merged 8 commits into
mainfrom
codex/fix-function-event-json-6360
Oct 28, 2026
Merged

HarshMN2345 merged 8 commits into
mainfrom
codex/fix-function-event-json-6360

Conversation

@HarshMN2345

@HarshMN2345 HarshMN2345 commented Sep 14, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Fixes #6360. When a user with empty preferences is deleted, the API prepares prefs: {}, but the queue decodes JSON objects into associative arrays. Every consumer that re-encodes the decoded payload then emits prefs: [], which breaks typed SDK consumers. This happened in three places: Function event data, webhook bodies and realtime frames. All three now keep JSON object shapes, so {} stays {}.

  • Functions: Func keeps the original JSON in the existing function-message body when an associative decode/re-encode would change its shape. The worker passes that body as the event data when present.
  • Webhooks: Webhook::preparePayload() adds a body to the queued message under the same condition. The worker delivers and signs that body when present.
  • Realtime: when the array decode changed the published JSON, the frame's payload is re-read from the published message as objects. If that read fails, the frame keeps the decoded arrays. Unchanged payloads skip the re-decode.

Empty lists remain lists, and nested objects and numeric-key objects retain their JSON types.

The queue codec itself is unchanged; nothing under packages/queue is touched. The fix only adds the original JSON next to the existing payload.

Rolling deploys and older messages: the legacy payload stays in every message. Older workers read only events, payload, user and project, so they ignore body and behave as before. New workers fall back to encoding the payload when body is empty, which covers messages queued before the deploy. Only affected payloads carry both representations, which increases their queue size; ordinary payloads keep their existing size.

The e2e signature helpers (Scope, ProjectWebhooks and Webhooks tests) now sign the raw delivered body instead of re-encoding the decoded data. Re-encoding turned {} back into [], so the old helpers only matched while the server also sent []. The same applies to receivers: one that hashes the raw request body is unaffected, but one that re-encodes the decoded JSON before hashing (as these helpers did) will now get a mismatch on payloads with empty objects.

Test Plan

All local runs used throwaway containers built from appwrite-dev:oauth-callback with this branch's code mounted, on network appwrite.

  • API container: --add-host appwrite:127.0.0.1; mounts src, app, packages, tests and phpunit.xml read-only; env from docker inspect appwrite.
  • Worker container: php app/worker.php webhooks,functions,executions,builds; env from docker inspect appwrite-worker.
  • Queue routing: the queue names are already env-overridable, so both containers got _APP_WEBHOOK_QUEUE_NAME, _APP_FUNCTIONS_QUEUE_NAME, _APP_EXECUTIONS_QUEUE_NAME and _APP_BUILDS_QUEUE_NAME set to private names. The worker's startup table and spans confirmed it processed the private webhooks, functions and executions jobs.
  • Extra env: this branch needs _APP_ALLOWED_INTERNAL_ADDRESSES (new SSRF policy) and a few other new vars that the shared stack lacks. Their values came from the branch's committed .env.
  • Writable fixture folder: tests/resources/functions/timeout was overlaid with a scratch copy because the deployment tests write code.tar.gz there.

Unit tests:

  • tests/unit/Event: OK, 26 tests / 311 assertions (includes FuncTest, which covers empty objects, empty lists, nested mixed shapes, numeric-key objects, an unchanged 70KB payload and older messages without a body).
  • tests/unit/Platform/Workers/WebhooksTest.php: OK, 3 / 26.
  • tests/unit/Platform/Workers/FunctionsTest.php: OK, 5 / 62.
  • packages/queue/tests/CodecTest.php: OK, 11 / 16.

E2E with the fix:

  • ProjectWebhooks/WebhooksCustomClientTest: 40 tests, 38 pass, 2 errors (testCreateTeamMembership, testUpdateTeamMembership). Same result on a second run.
  • ProjectWebhooks/WebhooksCustomServerTest: 42 tests, 41 pass, 1 error (testCreateTeamMembership). Same result on a second run.
  • All three errors are environmental: getLastEmail() cannot resolve the maildev host, which does not exist on that network. --display-warnings showed only that cause.
  • Services/Webhooks (WebhooksConsoleClientTest + WebhooksCustomServerTest): OK, 133 tests / 1005 assertions.
  • FunctionsCustomServerTest --filter testEventTriggerPreservesEmptyPreferences (deletes a user and checks the triggered Function receives prefs: {}): OK, 1 test / 43 assertions, with the functions and executions jobs going through the branch worker.

Same branch code with the old signature helpers:

  • Client suite: 8 failures, all at the signature asserts (CustomClientTest:107/176/505/566/628, Base:1449/1488/1576) in testCreateAccount, testDeleteAccount, testUpdateAccountName/Password/Email, testCreateTeam, testUpdateTeam, testDeleteTeam, plus the same 2 maildev errors.
  • Server suite: 6 failures at signature asserts (CustomServerTest:519/603/641, Base:1449/1488/1576) in testCreateUser, testUpdateUserStatus, testDeleteUser, testCreateTeam/UpdateTeam/DeleteTeam, plus 1 maildev error.
  • Services/Webhooks: 4 failures (testSecretRotationZeroDowntime and testCreateWebhookWithCustomSecret in both classes, at the signature asserts at WebhooksBase:815/910).
  • All of these pass with the fix.

Delivered bodies: request-catcher deliveries from the client-suite run carried "prefs":{} 34 times and "prefs":[] 0 times.

Realtime: a realtime server running this branch and one running code without this fix were subscribed to the same account event. This branch's frame carried "prefs":{}; the other carried "prefs":[]. A PHP check of the realtime logic showed that a NUL-prefixed key falls back to the arrays with no warnings, a numeric-key object stays an object, and an unchanged payload skips the re-decode.

Static checks: Pint --test, php -l on all 11 changed PHP files, node --check on the event-handler fixture and git diff --check pass.

Earlier, at 0b578fb61f (Functions fix only), GitHub Actions passed the Functions suite (82 tests, 1,909 assertions), along with Unit and Checks. Functions job. The new FuncTest regression fails against the pre-change Func class and passes with this patch.

Not verified:

  • Old/new deploy mix was not run end to end for webhooks. The rolling-deploy behaviour above comes from reading the code.
  • The 3 team-membership tests that need maildev never got past the mail step, so their webhook checks were not exercised.
  • Builds go through the Jobs service and the shared v1-jobs queue, so they ran on the shared stack's code, not this branch. That path is unchanged by this branch.
  • The dev image's vendor has utopia-php/database 7.3.11 while the branch requires ^7.4.0. That only affects relationship-delete events, which these suites don't depend on.
  • The Function event regression was not re-run without the Func fix; the earlier CI run above already showed it.
  • PHPStan was not run at this head; the earlier level-4 run covered only the 0b578fb61f changes.

Related PRs and Issues

Checklist

  • Read the contributing guidelines.
  • API metadata is unchanged; regenerated specs and examples are not needed.

@github-actions

github-actions Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → codex/fix-function-event-json-6360 (after).

Metric Before After Change
🚀 Requests/sec 197.86 202.92 ⚪ +2.6%
⏱️ Latency P50 86.38 ms 85.7 ms ⚪ -0.8%
⏱️ Latency P95 209.02 ms 196.42 ms 🟢 -6%
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 85.7 196.42 12,597 202.92 -12.6
Account 151.51 289.63 663 11 -7.61
TablesDB 81.29 150.89 6,851 111.96 -3.58
Storage 83.8 194.2 3,315 56.25 +1
Functions 115.54 229.58 1,768 30.78 -43.4

Top API waits (after)

API request Max wait (ms)
account.name.update 522.8
storage.buckets.create 432
account.prefs.update 368.38
tablesdb.rows.create 358.95
functions.variables.update 354.97

# Conflicts:
#	src/Appwrite/Platform/Workers/Functions.php
The signature checks re-encoded the decoded request data, which only
matches the delivered bytes while no empty object is involved: `{}`
decodes to an array and comes back as `[]`. Keep the raw body next to the
decoded data and sign that instead.
The webhooks worker re-encoded the payload it decoded from the queue, so an
empty object such as `prefs: {}` was delivered as `[]`. When that round trip
would change the JSON, the message now also carries the original JSON as
`body`, using the same rule as function events, and the worker sends it.
Messages without a body are encoded from the payload as before.
The realtime server decodes published events into arrays, so an empty
object such as `prefs: {}` reached subscribers as `[]`. When decoding
changed the published JSON, the payload is re-read as objects for the
frame, falling back to the arrays if that decode fails.
@HarshMN2345 HarshMN2345 changed the title fix(functions): preserve object shapes in queued event payloads fix(events): preserve object shapes in event payloads Oct 6, 2026
…ent-json-6360

Webhook::preparePayload() now adds both the eventId from main and the
original JSON body, which is only set when decoding the payload into
arrays would change its shape.

# Conflicts:
#	src/Appwrite/Event/Webhook.php
@github-actions

github-actions Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

6 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (3)
  • php.appwrite.secret-compare-timing (1)
  • 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.

# Conflicts:
#	src/Appwrite/Event/Webhook.php
#	tests/e2e/Services/Functions/FunctionsCustomServerTest.php
@HarshMN2345
HarshMN2345 marked this pull request as ready for review October 28, 2026 13:07
@luxor-code-review

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

Copy link
Copy Markdown

Review complete. No issues found — approved ✅.


This change fixes a JSON round-trip fidelity bug where re-encoding queue messages through `json_decode(..., true)` turned empty objects into arrays, breaking webhook signatures and payload shape for consumers like function logs.

Files Change
`src/Appwrite/Event/Message/Func.php`, `src/Appwrite/Event/Webhook.php` Capture the original encoded body at publish time and pass it through the queue envelope so consumers can use the exact published bytes.
`src/Appwrite/Platform/Workers/Functions.php`, `src/Appwrite/Platform/Workers/Webhooks.php` Prefer the preserved raw body over re-encoding decoded arrays when executing functions and signing webhook deliveries.
`app/realtime.php` Detect payload shape drift between the published bytes and the re-encoded event, restoring the original object-typed `data.payload` for realtime frames.
`tests/e2e/Scopes/Scope.php`, `tests/e2e/Services/Webhooks/`, `tests/e2e/Services/ProjectWebhooks/` Store raw request bytes in test helpers and compute webhook signatures over them, matching what the server delivers.
`tests/e2e/Services/Functions/FunctionsCustomServerTest.php`, `tests/unit/Event/Message/FuncTest.php`, `tests/resources/functions/event-handler/index.js` Add regression coverage asserting empty-object prefs are preserved through execution logs and queue message bodies.

Reviewed commit: 7a137ae

@ghost

ghost commented Oct 28, 2026 •

Copy link
Copy Markdown

🔵 Tier A · Mergeable after minor fixes

A because the changed realtime shape-preservation path has no committed regression assertion.

Preserves JSON object-versus-array shapes through function events, webhook deliveries, and realtime frames while leaving the queue codec unchanged. Updates webhook test helpers to sign delivered bytes and adds a Function event regression test.

Verdict New comments Fixed Still open
✅ Approved 1 0 0
Finding Where
🟡 Add a realtime regression assertion for empty objects app/realtime.php:831
Fix with agent prompt
### Issue 1
app/realtime.php:831
**Add a realtime regression assertion for empty objects**

This branch can regress to array-shaped payloads without failing the committed tests: the existing realtime tests decode frames associatively and do not check empty-object shape, while the new regression covers only the Function path. Please add an assertion against a raw realtime frame containing empty `prefs` (or decode that frame as objects).

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
📂 Walkthrough · 12
File Change
app/realtime.php Re-reads changed realtime payloads as objects before building frames.
src/Appwrite/Event/Message/Func.php Carries original JSON when queue decoding would change payload shape.
src/Appwrite/Event/Webhook.php Adds original JSON to webhook queue messages when shape changes.
src/Appwrite/Platform/Workers/Functions.php Uses preserved event JSON as Function event data when available.
src/Appwrite/Platform/Workers/Webhooks.php Delivers preserved webhook JSON when available.
tests/e2e/Scopes/Scope.php Retains raw webhook request bytes for signature checks.
tests/e2e/Services/Functions/FunctionsCustomServerTest.php Adds an end-to-end empty-preferences Function event regression.
tests/e2e/Services/ProjectWebhooks/WebhooksBase.php Updates webhook signature helpers to use raw delivered bytes.
tests/e2e/Services/ProjectWebhooks/WebhooksCustomClientTest.php Uses raw delivered bytes in webhook signature assertions.
tests/e2e/Services/Webhooks/WebhooksBase.php Uses raw delivered bytes for webhook signature assertions.
tests/resources/functions/event-handler/index.js Logs the serialized event body for the Function regression test.
tests/unit/Event/Message/FuncTest.php Tests preserved object shapes, unchanged payloads, and legacy messages.

Reviewed 7a137ae · 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

Comment thread app/realtime.php
// Decoding into arrays turns objects such as `prefs: {}` into `[]`, so when that
// changed the published JSON, the payload is re-read as objects for the frame.
if ($receivers !== [] && \json_encode($event) !== $payload) {
$data['payload'] = \json_decode($payload)->data->payload ?? $data['payload'];

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Add a realtime regression assertion for empty objects

This branch can regress to array-shaped payloads without failing the committed tests: the existing realtime tests decode frames associatively and do not check empty-object shape, while the new regression covers only the Function path. Please add an assertion against a raw realtime frame containing empty prefs (or decode that frame as objects).

Prompt To Fix With AI
This is a comment left during a code review.
Path: app/realtime.php
Line: 831

Comment:
**Add a realtime regression assertion for empty objects**

This branch can regress to array-shaped payloads without failing the committed tests: the existing realtime tests decode frames associatively and do not check empty-object shape, while the new regression covers only the Function path. Please add an assertion against a raw realtime frame containing empty `prefs` (or decode that frame as objects).

---

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

🟡 Minor · testing · Reply if this doesn't apply.

@HarshMN2345
HarshMN2345 merged commit 4c7015f into main Oct 28, 2026
66 checks passed
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.

🐛 Bug Report: User object empty prefs field is an array instead of an object

1 participant