Skip to content

fix: format datetime fields in the response model - #14295

Merged
ChiragAgg5k merged 3 commits into
mainfrom
fix/response-datetime-tz
Oct 9, 2026
Merged

ChiragAgg5k merged 3 commits into
mainfrom
fix/response-datetime-tz

Conversation

@ChiragAgg5k

@ChiragAgg5k ChiragAgg5k commented Oct 9, 2026 •

Copy link
Copy Markdown
Member

Summary

A synchronous function execution (POST /v1/functions/{functionId}/executions with async=false) returns $createdAt and $updatedAt in the database format 2026-10-09 10:00:00.123, while GET /v1/functions/{functionId}/executions/{executionId} returns the documented ISO 8601 format 2026-10-09T10:00:00.123+00:00. The queued async response (202) has the same problem. Because the api shutdown hook copies $response->getPayload() into the event, the functions.*.executions.*.create webhook, realtime and function-event payloads carry the raw format too.

Root cause: Executions/Create.php builds the execution as an in-memory Document with DateTime::now() and outputs it without a database round-trip. Normally the database datetime filter (DateTime::formatTz on decode) produces the timezone format on read, and Response::output() copies values as-is, ignoring Model::TYPE_DATETIME. Every endpoint that answered with an in-memory datetime needed its own inline DateTime::formatTz() to look right.

Fix: Response::output() now normalises every rule of type Model::TYPE_DATETIME (including array rules) to Y-m-d\TH:i:s.vP via DateTime::formatTz(). It only converts strings in the database format (space at offset 10), so it is cheap and idempotent: values already carrying the T separator, null, '' and non-strings are returned unchanged (formatTz('') would otherwise turn an empty value into "now"). It runs inside output(), which sets $this->payload, so getPayload() and every event built from it get the formatted values. It runs after the sensitive-field masking, so masked values stay ''.

Why not a response filter

src/Appwrite/Utopia/Response/Filters/V16..V24 are API-version compatibility shims that only run for clients pinned to an older X-Appwrite-Response-Format. This is the current contract of TYPE_DATETIME (documented example 2020-10-15T06:38:00.000+00:00) and has to hold for every client and for event payloads, so it belongs in the model output itself.

Removed inline calls

File Value Why it is safe
app/controllers/api/account.php ($createSession, used by PUT /account/sessions/magic-url, PUT /account/sessions/phone, POST /account/sessions/token) session expire Only used for the cookie timestamp ((new \DateTime($expire))->getTimestamp() is format-agnostic, both strings are in the same default timezone) and the response attribute.
app/controllers/api/account.php (PATCH /account/sessions/:sessionId) session expire, providerAccessTokenExpiry Persisted with updateDocument (the datetime filter encodes either format), then output through Response::output() for both the event payload and the response. User::sessionVerify() normalises both sides before comparing.
app/controllers/api/account.php (GET /account/sessions/oauth2/:provider/redirect) token / session expire Token is stored with createDocument; session expire feeds the cookie timestamp and the event payload, which goes through Response::output(). The endpoint itself redirects.
app/controllers/api/account.php (POST /account/tokens/email, POST /account/tokens/phone, POST /account/recovery/otp, POST /account/verifications/phone, POST /account/verifications/email/otp) token expire Only stored; the response and event use the document returned by createDocument, which is already decoded. Not used in any email/SMS template or URL.
src/Appwrite/Platform/Modules/Account/Http/Account/MFA/Challenges/Create.php challenge expire Only stored; response uses the createDocument result. Not used in the SMS/email content.
src/Appwrite/Platform/Modules/Users/Http/Users/Sessions/Create.php session expire Only stored; response and event use the createDocument result.
src/Appwrite/Platform/Modules/Users/Http/Users/Tokens/Create.php token expire Only stored; response and event use the createDocument result.

Functions/Http/Executions/Create.php needed no code change: its in-memory DateTime::now() values are now formatted by the response.

Kept on purpose

  • Comparisons against database-decoded (timezone format) values. String comparison between Y-m-d H:i:s and Y-m-d\TH:i:s would break: app/controllers/general.php:151, app/controllers/shared/api.php (209, 409, 430, 775, 800, 1143), app/controllers/shared/api/auth.php (26, 43-45), app/init/realtime/connection.php:301, app/init/resources/request.php (574, 1143), src/Appwrite/Auth/Key.php (206, 237, 273), src/Appwrite/Auth/Passkey/Challenges.php:61, Account/MFA/Challenges/Update.php:109, Account/Passkeys/Create.php:184, Messaging/Messages/Delete.php:77, Presences/HTTP/Get.php:63, Presences/HTTP/Update.php:145, Storage/Buckets/Files/Preview/Get.php:355, Users/MFA/Challenges/Get.php:72, Tasks/ScheduleMessages.php:77, Workers/Functions.php:411, Utopia/Database/Documents/User.php (123, 149, 173).
  • Values placed in email links, which client apps parse: expire query parameter of magic URL (POST /account/tokens/magic-url, account.php:2635), recovery (POST /account/recovery, account.php:4154) and email verification (POST /account/verifications/email, account.php:4917).
  • Cookie-only values that never reach a response: account.php:1169 (email/password session), account.php:1346 (anonymous session), general.php:1665 (preview cookie), Account/Sessions/IdToken/Create.php:264. These are not response workarounds, so they are out of scope here.
  • Realtime message timestamp (app/realtime.php 554, 592, Messaging/Adapter/Realtime.php:550): not a response model.
  • Execution/Store.php:858: the ClickHouse execution store normalising what it reads back, the same role the database datetime filter plays.
  • Response/Filters/V16.php (82, 83): version shim output.

Follow-ups noticed, not changed here: the functions worker builds the executions.*.update event payload with Model::filter() instead of Response::output(), so its datetimes do not get this normalisation. Messaging/Messages/Delete.php:77 compares DateTime::now() (database format) with a formatTz value, which is wrong on the same calendar day.

Tests

E2E only, extending existing test methods. Assertions use the existing \DateTime::createFromFormat('Y-m-d\TH:i:s.uP', ...) pattern from the account tests.

  • FunctionsCustomServerTest::testSyncCreateExecution: sync create response $createdAt / $updatedAt are ISO 8601. Fails without the fix.
  • FunctionsCustomServerTest::testListExecutionsWithinCreatedAtWindow: sync (201) and async (202) create responses are ISO 8601. The test's own workaround that converted the 202 $createdAt from database format before comparing is removed. Fails without the fix.
  • ProjectWebhooks/WebhooksCustomServerTest::testExecutions: the functions.*.executions.*.create webhook payload has ISO 8601 $createdAt / $updatedAt equal to the response. Fails without the fix.
  • AccountCustomClientTest::testSessionAlert: POST /account/tokens/email and POST /account/sessions/token expire.
  • AccountCustomClientTest::testConvertAnonymousAccountOAuth2: PATCH /account/sessions/current expire and providerAccessTokenExpiry. Fails with the removal and without the central fix.
  • AccountCustomClientTest::testRefreshEmailPasswordSession already asserted expire of PATCH /account/sessions/:sessionId, and fails with the removal and without the central fix.
  • AccountCustomClientTest: testCreatePhone (POST /account/tokens/phone), testCreateEmailVerificationOTP (POST /account/verifications/email/otp), testCreateRecoveryOTP (POST /account/recovery/otp), testRegenerateMFARecoveryCodesRequiresRecentChallenge (POST /account/mfa/challenges); testPhoneVerification already had the strict assertion for POST /account/verifications/phone.
  • AccountCustomServerTest::testCreateTokenWithSessionsKey: POST /account/tokens/email and POST /account/recovery/otp with an API key.
  • UsersBase::testCreateSession, UsersBase::testCreateToken: expire.

The assertions for round-tripped values (tokens, challenges, users sessions/tokens) also pass on the base commit, because those responses already came from createDocument. They guard the removals.

Verification

  • composer lint (Pint) on the changed files: passed.
  • composer analyze (PHPStan, phpstan.neon) on the changed source files: no errors.
  • composer refactor:check (Rector) on the changed tests: no changes.
  • Local docker stack from this branch, full suites: tests/e2e/Services/Account OK (162 tests, 2953 assertions, 3 skipped), tests/e2e/Services/Users OK (68 tests, 941 assertions), tests/e2e/Services/ProjectWebhooks OK (82 tests, 8353 assertions), tests/e2e/Services/Functions OK (88 tests, 2322 assertions). The warnings come from code this PR does not touch: WebhooksBase::getWebhookSignature() reads data on an empty request while the executions.*.update assertion is retried, and the functions run reports the expected 500 page printed by testErrorPagesEmptyBody.
  • With Response.php reverted to main (removals kept) and the container restarted, these fail as expected: testSyncCreateExecution, testListExecutionsWithinCreatedAtWindow, WebhooksCustomServerTest::testExecutions, testRefreshEmailPasswordSession, testConvertAnonymousAccountOAuth2.

Closes #14296

Documents built in memory (a synchronous execution, a queued async
execution) never pass through the database datetime filter, so they
were returned, and copied into event payloads, in the database format
without a timezone. Response::output() now normalises every
TYPE_DATETIME rule to ISO 8601 with offset.
These calls only existed to give in-memory values the documented
format in API responses and event payloads, which Response::output()
now guarantees. Comparisons, email link parameters and cookie-only
values keep their formatTz.
@luxor-code-review

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

Copy link
Copy Markdown

Review complete. No blocking issues — approved ✅; 1 nitpick below.

🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 assertNotFalse(createFromFormat) passes on null values (AccountCustomClientTest.php:2361) — The newly added assertions use assertNotFalse(\DateTime::createFromFormat('Y-m-d\TH:i:s.uP', $value)), which cannot fail on null: PHPUnit's assertNotFalse only rejects boolean false, so a missing datetime key emitted as null passes the check (tests/e2e/Services/Account/AccountCustomClientTest.php:2361).

The change centralizes datetime output formatting: DateTime::addSeconds() results are now persisted in the raw DB format at the creation sites, and Response::output() gains a formatDatetime() pass that converts any in-memory Y-m-d H:i:s.v datetime to ISO 8601 for every TYPE_DATETIME model field. E2E suites add DateTime::createFromFormat('Y-m-d\TH:i:s.uP', ...) assertions locking the ISO 8601 wire contract for tokens, sessions, MFA challenges, executions, and webhook payloads.

Files Change
app/controllers/api/account.php, src/Appwrite/Platform/Modules/Account/Http/Account/MFA/Challenges/Create.php, src/Appwrite/Platform/Modules/Users/Http/Users/Sessions/Create.php, src/Appwrite/Platform/Modules/Users/Http/Users/Tokens/Create.php Drop formatTz() around DateTime::addSeconds() so raw DB-format expiry values are persisted and validated directly.
src/Appwrite/Utopia/Response.php Add formatDatetime() normalization pass in output() for TYPE_DATETIME model attributes, restoring the ISO 8601 wire format.
tests/e2e/Services/Account/*Test.php, tests/e2e/Services/Users/UsersBase.php, tests/e2e/Services/Functions/FunctionsCustomServerTest.php, tests/e2e/Services/ProjectWebhooks/WebhooksCustomServerTest.php Add ISO 8601 parse assertions on $createdAt/$updatedAt/expire fields and remove the now-redundant $iso() helper.

Reviewed commit: d99fdb2

@ghost

ghost commented Oct 9, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

Response model output now formats database-style datetime strings as ISO 8601, and the account/session/token creation paths no longer pre-format values that are persisted or output through the model. E2E coverage was expanded for execution responses, webhook payloads, and account and user expiry fields.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 10
File Change
src/Appwrite/Utopia/Response.php Normalize datetime model fields in response payloads.
app/controllers/api/account.php Remove inline datetime formatting from account session and token flows.
src/Appwrite/Platform/Modules/Account/Http/Account/MFA/Challenges/Create.php Leave challenge expiry formatting to response output.
src/Appwrite/Platform/Modules/Users/Http/Users/Sessions/Create.php Leave session expiry formatting to response output.
src/Appwrite/Platform/Modules/Users/Http/Users/Tokens/Create.php Leave token expiry formatting to response output.
tests/e2e/Services/Account/AccountCustomClientTest.php Assert ISO 8601 expiry values in account flows.
tests/e2e/Services/Account/AccountCustomServerTest.php Assert ISO 8601 expiry values in server-side token flows.
tests/e2e/Services/Functions/FunctionsCustomServerTest.php Assert ISO 8601 timestamps on synchronous and queued execution responses.
tests/e2e/Services/ProjectWebhooks/WebhooksCustomServerTest.php Assert execution webhook timestamps match the response format.
tests/e2e/Services/Users/UsersBase.php Assert ISO 8601 expiry values for created user sessions and tokens.

Merged main (3e483dc); no changes to this PR's code since d99fdb2 · 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 9, 2026

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

32 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (17)
  • php.appwrite.permissive-write-permission (8)
  • 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 9, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/response-datetime-tz (after).

Metric Before After Change
🚀 Requests/sec 198.15 197.07 ⚪ -0.5%
⏱️ Latency P50 87.1 ms 88.01 ms ⚪ +1.1%
⏱️ Latency P95 208.76 ms 207.19 ms ⚪ -0.8%
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.01 207.19 12,540 197.07 -1.57
Account 168.68 332.1 660 11.02 -1.14
TablesDB 85.27 166.85 6,820 109.76 +7.56
Storage 79.42 170.1 3,300 54.87 +1.09
Functions 124.8 250.56 1,760 30 -5.2

Top API waits (after)

API request Max wait (ms)
account.name.update 474.54
account.prefs.update 447.41
functions.create 433.65
storage.files.create 381.09
functions.variables.update 380.73

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.

Format datetime fields in the response model

1 participant