Skip to content

fix(functions): never redeliver a message once the function has run - #14023

Merged
levivannoort merged 9 commits into
mainfrom
fix/functions-no-duplicate-runs
Oct 7, 2026
Merged

levivannoort merged 9 commits into
mainfrom
fix/functions-no-duplicate-runs

Conversation

@levivannoort

@levivannoort levivannoort commented Sep 30, 2026 •

Copy link
Copy Markdown
Member

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:

  1. $publisherForFunctions->enqueue() of the functions.*.executions.*.update event. Unlike the webhook and realtime triggers, it does not swallow publish errors.
  2. throw new AppwriteException('Function execution failed: …'), even though a timeout or a cut-off response cannot tell whether the function ran.
  3. The event fan-out rethrowing the first subscriber failure, which redelivers the event to every subscriber that already succeeded.

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)

  • 70 scheduled runs completed and then threw Utopia\NATS\Exception\ConnectionException: Connection closed by server from a publish. 4 more failed and then threw the same. Each one ran again on redelivery.
  • 35 rethrows of the executor error ("no available server" ×34).
  • Example: message 6ab66ccc002625.73996143. Attempt 1 ran execution …5af9b2f (completed), then the update publish threw. Attempt 2, 300s later, ran execution …345227c3.

Changes

  • The notifications after the executor are wrapped, with failures recorded as execution.notify.error on the span. The functions publish moves last, so its failure cannot skip the webhook or realtime.
  • The executor error is recorded on the span (execution.error, execution.error.code) instead of being rethrown. The execution record still carries failed and the error text through ExecutionCompleted, which is dispatched in the finally beforehand.
  • Fan-out: Func::fromEvent stamps an eventId. 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.
  • Fan-out, degraded cache: if a record can't be written, the failure goes on the span and the message is not retried. If a record can't be read, the subscriber is skipped. Either way a lost run is preferred over running user code twice.

Tests

  • E2E: FunctionsCustomServerTest::testEventExecutionIsNotRunAgainAfterTheExecutorFailed.
    • It stops the executor container while an event is delivered, restores it, forces the retry with queue-retry, then watches the executions for 15s. Watching for a set time is on purpose: nothing polls for a run that never happens.
    • Against main it records failed, completed: the retry ran the function again. With the fix it stays failed. The whole FunctionsCustomServerTest class passes locally (61 tests).
  • Unit: the fan-out bookkeeping lives in a small library, 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.php has 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).
  • The worker unit tests this PR first added are removed, per AGENTS.md.
  • Pint, Rector (tests config) and PHPStan are clean on the changed files.

Not covered

  • The record of handled subscribers lives in the cache. If it is evicted before the redelivery, that message falls back to the behaviour before this PR (every subscriber re-runs). A durable record is tracked in appwrite-labs/cloud#6220.
  • Alerting on worker errors no longer sees executor failures. Alert on the execution.error span attribute instead.
  • A Traefik no available server 503 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.
  • No E2E. The redelivery itself happens in the broker.

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

ghost commented Sep 30, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

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

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 7
File Change
.github/workflows/ci.yml Isolate queue-retry tests and add Semgrep reporting and native-crash checks.
src/Appwrite/Event/Message/Func.php Generate and serialize an event ID for function-trigger events.
src/Appwrite/Event/Redelivery.php Track handled subscribers across retries with consumer isolation and cache-failure policies.
src/Appwrite/Platform/Workers/Functions.php Retry only unhandled subscribers and suppress post-executor notification and execution-error rethrows.
tests/e2e/Services/Functions/FunctionsCustomServerTest.php Cover successful/crashing subscriber retries and optional runtime/specification totals.
tests/resources/functions/crash/index.js Provide a function fixture that exits during execution.
tests/unit/Event/RedeliveryTest.php Cover event identity, target tracking, legacy messages and cache failures.

Reviewed the commits since 19db7f0 · 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

@greptile-apps

greptile-apps Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 2/5

[Critical risk] Changes how function execution events are retried after failures.

The PR is not safe to merge until the new E2E test can run without disrupting parallel tests and the outstanding legacy-event identity issue is addressed.

Fix All in Claude CodeFindings

  1. P1 Docker command cannot run ▶
  2. P1 Shared executor disrupts tests ▶
  3. P1 Identical legacy events share identity ▶
  4. P2 Test mirrors cache internals ▶
Fix with agent prompt
### Issue 1
tests/e2e/Services/Functions/FunctionsCustomServerTest.php:2634
The E2E suite runs inside the `appwrite` container, which has no Docker socket mount. When this test runs in the repository’s Compose environment, `docker stop exc1` cannot reach the Docker daemon. The exit-code assertion fails before the test exercises an executor failure.

### Issue 2
tests/e2e/Services/Functions/FunctionsCustomServerTest.php:2598
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.

### Issue 3
src/Appwrite/Platform/Workers/Functions.php:undefined-177
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.

### Issue 4
tests/unit/Event/RedeliveryTest.php:116
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.

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!

---

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

Summary

The PR prevents post-executor failures from redelivering functions and introduces per-subscriber handled records for partially failed event fan-out.

  • The latest changes extract handled-record logic into Redelivery, replace worker-action unit tests with library tests, and add an executor-failure E2E test.
  • The new E2E test needs a runnable, isolated executor-failure setup before it can reliably validate that behavior.

Reviews (4) · Last reviewed commit: "test(functions): cover the executor-fail..."

@github-actions

github-actions Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/functions-no-duplicate-runs (after).

Metric Before After Change
🚀 Requests/sec 199.27 204.1 ⚪ +2.4%
⏱️ Latency P50 87.45 ms 85.38 ms ⚪ -2.4%
⏱️ Latency P95 201.1 ms 196.2 ms ⚪ -2.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 85.38 196.2 12,654 204.1 -4.9
Account 160.99 302.79 666 11.03 -15.12
TablesDB 83.72 160.78 6,882 112.42 -4.21
Storage 77.04 169.11 3,330 56.48 +6.77
Functions 121.5 232 1,776 30.82 -11.23

Top API waits (after)

API request Max wait (ms)
functions.create 444.21
tablesdb.rows.increment 428.99
tablesdb.rows.get 428.85
account.name.update 408.15
account.prefs.update 379.71

@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 B · 1 blocking finding to address. Summary

// 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));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Fix in Claude Code Fix in Codex

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@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 B · See the inline comments. Summary

Comment thread tests/unit/Event/RedeliveryTest.php Resolved

try {
// The executor goes away while the event is delivered: the worker's call to it fails.
$this->setExecutorRunning(false);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Fix in Claude Code Fix in Codex

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment thread tests/unit/Event/RedeliveryTest.php Outdated
public function testARecordTheCacheRefusedIsReportedAndTheRestAreStillWritten(): void
{
$adapter = new UnreliableCache();
$adapter->refuseSaves = ['redelivery:webhooks:' . \md5('event-1:webhook-a')];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 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)

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!

Fix in Claude Code Fix in Codex

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in c3362ea / 9274a9b: the fake now refuses a write by its position in the order, not by rebuilding the key. The first-delivery test no longer counts reads: it uses a cache whose reads throw, with handledWhenUnknown: true, so it would answer 'handled' if it read at all, and asserts it doesn't.

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

Copy link
Copy Markdown
Member Author

Findings from the latest review summaries:

  • Identical legacy events (valid, fixed in c3362ea): a message without an eventId is no longer named by its payload. It isn't tracked at all: no record and no skip. Its fan-out then behaves as it did before this PR, and a partial failure after a subscriber ran is recorded rather than retried. Only messages queued before this deploy lack an eventId. testAMessageWithoutAnEventIdIsNotTracked fails on the previous library.
  • Evictable cache (a real limit, stated rather than fixed): the handled-subscriber record lives in the cache. If it is evicted before the redelivery, that one message degrades to what every redelivery did before this PR: all subscribers run again. The record is written right before the failure and read at the next delivery, minutes later on the functions backoff, so under allkeys-lru it is among the most recently used keys when eviction would pick. A durable record would mean a platform-database write on the failure path. I'd rather do that as a follow-up if eviction shows up in practice (redelivery.lookup.error / skipped counts are on the span).

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Your trial has ended. Reactivate Greptile to resume code reviews.

@levivannoort

Copy link
Copy Markdown
Member Author

@tenki-reviewer

@luxor-code-review

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

Copy link
Copy Markdown

Review complete. No issues found.


The change makes the Functions worker resilient to broker redeliveries: a new Redelivery helper tracks which event subscribers were already handled, and the worker consults it before re-executing user code after a queue redelivery. A crash runtime fixture and a new e2e test exercise the executor-failure path end to end.

Files Change
src/Appwrite/Event/Redelivery.php, src/Appwrite/Event/Message/Func.php New redelivery-tracking helper and eventId field on the Func queue message payload.
src/Appwrite/Platform/Workers/Functions.php Fan-out loop records handled subscribers and skips already-handled targets on redelivery.
tests/unit/Event/RedeliveryTest.php, tests/resources/functions/crash/index.js Unit coverage for the helper and a crashing function fixture.
tests/e2e/Services/Functions/FunctionsCustomServerTest.php, .github/workflows/ci.yml New queueRetry e2e test and a dedicated isolated CI matrix entry for it.

Reviewed commit: 19db7f0

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

@levivannoort
levivannoort merged commit 5327983 into main Oct 7, 2026
98 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.

1 participant