Repository navigation
fix(functions): never redeliver a message once the function has run - #14023
Conversation
A functions message that throws is rejected, and a broker that redelivers (JetStream) runs the function again. Three paths threw after the executor had been called: - the functions publish of the execution update event, which does not swallow its errors the way the webhook and realtime triggers do; - the rethrow of the executor error itself, although a timeout or a cut-off response cannot tell whether the function ran; - the event fan-out rethrowing the first subscriber failure, which re-runs every subscriber that already succeeded. After the executor is called the notifications are best-effort and the error stays on the execution record instead of being rethrown. The fan-out only retries while no subscriber has reached the executor. Failures before the executor still throw and are retried.
🟢 Tier S · Ready to mergeThe functions worker makes post-executor errors and notifications best-effort, while partial event fan-out retries skip subscribers already handled. Event IDs and a shared redelivery library provide retry bookkeeping, with unit and queue-retry integration coverage. CI also adds Semgrep rule checks and native-crash detection, and the functions E2E suite verifies optional totals for runtimes and specifications. Latest changes: The newest commits add Semgrep validation, scanning and reporting, native-crash checks in E2E jobs, and runtime/specification total-parameter coverage.
📂 Walkthrough · 7
Reviewed the commits since |
|
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
| // handled is recorded when the message fails, and a redelivery skips it. Messages | ||
| // published before events were named are named by their payload, which a Redis | ||
| // requeue keeps while it changes the pid. | ||
| $eventId = $functionMessage->eventId ?: \md5((string) \json_encode($payload)); |
There was a problem hiding this comment.
Identical legacy events share identity
For queued events without an eventId, two distinct events with identical serialized payloads get the same handled key. If the first event saves that key after a partial failure and the second event is retried within seven days, its subscriber is skipped even though it never ran for the second event.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Platform/Workers/Functions.php
Line: 177
Comment:
**Identical legacy events share identity**
For queued events without an `eventId`, two distinct events with identical serialized payloads get the same handled key. If the first event saves that key after a partial failure and the second event is retried within seven days, its subscriber is skipped even though it never ran for the second event.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.There was a problem hiding this comment.
This no longer applies after the later commits. Identity now comes only from the payload's eventId. A message without one (a legacy message) is never recorded or skipped: Redelivery logs redelivery.record.skipped and handles it as before, and its key falls back to pid:<message pid>, never to a payload hash. So two legacy messages with identical payloads can't share an identity, and neither can suppress the other.
Move the fan-out bookkeeping into Appwrite\Event\Redelivery (shared with the webhooks worker), unit-test that library, and replace the worker unit tests with an E2E test that fails the executor call and forces the retry through queue-retry.
|
|
||
| try { | ||
| // The executor goes away while the event is delivered: the worker's call to it fails. | ||
| $this->setExecutorRunning(false); |
There was a problem hiding this comment.
Shared executor disrupts tests
The Functions suite runs tests in parallel against the shared exc1 executor. If this test stops that container while another test needs it, the other test can fail or time out for an unrelated reason. The later queue-retry command also targets the global functions queue, so it can release failed jobs belonging to other tests.
Prompt To Fix With AI
This is a comment left during a code review.
Path: tests/e2e/Services/Functions/FunctionsCustomServerTest.php
Line: 2598
Comment:
**Shared executor disrupts tests**
The Functions suite runs tests in parallel against the shared `exc1` executor. If this test stops that container while another test needs it, the other test can fail or time out for an unrelated reason. The later `queue-retry` command also targets the global functions queue, so it can release failed jobs belonging to other tests.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.There was a problem hiding this comment.
Both points were valid, fixed in 0b93c6e and 19db7f0. The executor is never stopped now: one subscriber calls process.exit(1) mid-request, so the executor answers 500 and Executor::createExecution throws after the function ran, for that function alone. A second, succeeding subscriber covers the fan-out, and on main's worker the test fails with 'The retry ran the subscriber that succeeded a second time'. queue-retry is global, so the test is in a queueRetry group: the service paratest run excludes it, and it runs in its own e2e_grouped job where nothing else is in flight. That's the same mechanism as abuseEnabled, screenshots and antivirus. Measured today, the rest of the Functions suite leaves 0 failed jobs on that queue.
| public function testARecordTheCacheRefusedIsReportedAndTheRestAreStillWritten(): void | ||
| { | ||
| $adapter = new UnreliableCache(); | ||
| $adapter->refuseSaves = ['redelivery:webhooks:' . \md5('event-1:webhook-a')]; |
There was a problem hiding this comment.
This test builds its refusal key using the production cache prefix and hash expression. A harmless key-format change would break the test even if redelivery still worked. The exact cache-load-count assertion elsewhere in this file has the same problem. The repository instruction requires tests of observable behavior rather than assertions that mirror source code or configuration; this requirement must be satisfied 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: tests/unit/Event/RedeliveryTest.php
Line: 116
Comment:
**Test mirrors cache internals**
This test builds its refusal key using the production cache prefix and hash expression. A harmless key-format change would break the test even if redelivery still worked. The exact cache-load-count assertion elsewhere in this file has the same problem. The repository instruction requires tests of observable behavior rather than assertions that mirror source code or configuration; this requirement must be satisfied 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!
There was a problem hiding this comment.
…the record without its key
… by stopping the executor A subscriber that exits its runtime mid-request makes the executor answer with an error after the function ran, for that function alone. The shared executor stays up for the tests running beside it. A second, succeeding subscriber covers the fan-out: neither may run again when the queue is retried.
queue-retry re-drives every failed job in a queue, so its tests run in the grouped job, where no other test's jobs are in flight, and the service jobs exclude them.
|
Findings from the latest review summaries:
|
There was a problem hiding this comment.
Your trial has ended. Reactivate Greptile to resume code reviews.
|
Review complete. No issues found. The change makes the Functions worker resilient to broker redeliveries: a new
Reviewed commit: 19db7f0 |
Security rulesNo new WARNING or ERROR findings from security rules. 32 existing findings tracked in
|
Summary
Once the executor has been called, nothing in the functions worker may fail the message: a broker that redelivers (JetStream) would run the user's function again. After the executor, the notifications become best-effort and the error stays on the execution record instead of being rethrown. The event fan-out retries only the subscribers a failed delivery did not handle. Failures before the executor are still retried.
Part of appwrite-labs/cloud#5815, tracked in appwrite-labs/cloud#6214.
Why
Three paths threw after the function ran:
$publisherForFunctions->enqueue()of thefunctions.*.executions.*.updateevent. Unlike the webhook and realtime triggers, it does not swallow publish errors.throw new AppwriteException('Function execution failed: …'), even though a timeout or a cut-off response cannot tell whether the function ran.On Redis a thrown job lands on the failed list and nothing retries it, so this was invisible. On NATS it runs the function again. A cron-scheduled message carries no execution ID, so each redelivery also creates a second execution.
Evidence (Appwrite Cloud staging, functions on NATS, 7 days)
completedand then threwUtopia\NATS\Exception\ConnectionException: Connection closed by serverfrom a publish. 4 morefailedand then threw the same. Each one ran again on redelivery.6ab66ccc002625.73996143. Attempt 1 ran execution…5af9b2f(completed), then the update publish threw. Attempt 2, 300s later, ran execution…345227c3.Changes
execution.notify.erroron the span. The functions publish moves last, so its failure cannot skip the webhook or realtime.execution.error,execution.error.code) instead of being rethrown. The execution record still carriesfailedand the error text throughExecutionCompleted, which is dispatched in thefinallybeforehand.Func::fromEventstamps aneventId. Messages published before this change are named by a hash of their payload, which a Redis requeue keeps. On a partial failure the worker records each subscriber it handled in the cache (7 days) and then throws. The redelivery skips those subscribers and retries the rest, including after a failed page read. The record is written only on a failure and read only on a redelivery.Tests
FunctionsCustomServerTest::testEventExecutionIsNotRunAgainAfterTheExecutorFailed.queue-retry, then watches the executions for 15s. Watching for a set time is on purpose: nothing polls for a run that never happens.mainit recordsfailed, completed: the retry ran the function again. With the fix it staysfailed. The wholeFunctionsCustomServerTestclass passes locally (61 tests).Appwrite\Event\Redelivery, shared with the webhooks worker (fix(webhooks): retry only the endpoints that failed, under a stable delivery id #14025). It covers the event id, the per-target ids, the record written on failure, the lookup on redelivery, and the policy for an unreadable record.tests/unit/Event/RedeliveryTest.phphas 10 tests. A pre-executor failure of just one subscriber can't be induced end to end, because the API refuses the only case (an unsupported runtime).Not covered
execution.errorspan attribute instead.no available server503 means the function did not run, so it could be retried safely. It is recorded, not retried, which is also what happens on Redis today.