Skip to content

fix(jobs): append a deployment's pending log callbacks in one write - #15881

Merged
TorstenDittmann merged 3 commits into
mainfrom
torsten/upbeat-bohr-brunmc
Nov 20, 2026
Merged

TorstenDittmann merged 3 commits into
mainfrom
torsten/upbeat-bohr-brunmc

Conversation

@TorstenDittmann

@TorstenDittmann TorstenDittmann commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Fixes the main source of Utopia\Lock\Exception\Contention: Failed to acquire distributed lock: jobs-deployment:… in the jobs worker (Cloud Sentry CLOUD-3QVY: ~72k events, about 90–150 per deployment of a chatty site build, spread over the build's 1–2 minutes).

Each log callback took the per-deployment lock on its own. Under it, it read the deployment, rewrote the whole buildLogs attribute (up to 1 MB), read it back and published it over realtime. That cost grows with the log, so a build streaming output queues callbacks on the lock faster than they drain. Every callback still waiting after LOCK_TIMEOUT (10s) throws Contention and goes back to the queue. Its lines then land out of order, or are lost once the retries run out. All 8 coroutines of a worker process can also end up waiting on one deployment's lock, which stalls every other deployment's callbacks on that process.

Log callbacks are now merged within each process:

  • Each log callback adds its lines to a per-process buffer keyed by the deployment's lock. The action instance is shared by every coroutine of the worker, so they all see the same buffer.
  • Callbacks for the same deployment queue on a per-process gate (a Channel(1)). Only one coroutine per process contends for the distributed lock at a time.
  • The coroutine holding the lock appends every pending callback's lines in one onLog() write and sends one realtime event. As before, dedupe markers for all events in the batch are saved in the same transaction. Events that are already marked, or repeated within the batch, are skipped.
  • The markers live in Redis, outside the transaction. If the transaction fails, the markers this batch wrote are deleted, so a redelivery appends the rolled-back lines instead of skipping them.
  • The other coroutines pass the gate, find their lines already applied and return without touching Redis.
  • If a write fails, the other callbacks' lines stay buffered, and the next coroutine through the gate applies them. A callback that gives up waiting removes its own lines from the buffer and is redelivered. If a batch had already taken those lines, the dedupe marker stops them being appended twice.

onLog() now takes the joined chunk and the list of event ids instead of one JobLog and one id. Both paths send their realtime event through a small broadcast() method. Nothing else changes: not the payload, the status transitions or any non-log callback.

Test Plan

  • pint --test and PHPStan (phpstan.neon) on the changed file: both pass locally.
  • Simulation: the real Jobs::log() / onLog() ran under Swoole 6 (PHP 8.4) against stub dependencies. It modelled 3 worker processes × 8 coroutines on one deployment, with a shared lock using the same backoff as Utopia\Lock\Distributed and a fixed DB write latency:
Scenario Path Elapsed DB writes Contention Lines missing / duplicated
300 callbacks, 80 ms writes old 29.7s 300 46 0 / 0
new 7.4s 74 0 0 / 0
+ 5 injected write failures, 50 redeliveries new 8.2s 75 0 (5 retried errors) 0 / 0
+ 5 dedupe-marker saves failing mid-batch new, without marker rollback 7.8s 77 0 11 / 0
new 7.8s 77 0 0 / 0
1000 callbacks, 200 ms writes old 213.7s 1000 429 0 / 0
new 52.6s 248 18 0 / 0

The buffer and gate maps were empty after each run, so nothing leaks. The contention left under the heaviest load comes from the shared lock itself: its polling is unfair between processes.

  • CI is green on the current head, including the Functions, Realtime and Webhooks e2e lanes, which exercise the log callback path end to end. The benchmark shows no regression.

Related PRs and Issues

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? No API metadata changes.

🤖 Generated with Claude Code

https://claude.ai/code/session_01F3M7ttqmi3HYfSr5f9kLt8

Every log callback took the per-deployment lock on its own and rewrote the
whole buildLogs attribute, so a build streaming output queued callbacks on
the lock faster than it drained. Those left waiting past LOCK_TIMEOUT threw
Contention and went back to the queue, landing their lines out of order.

Log callbacks now leave their lines in a per-process buffer and queue on a
per-deployment gate, so one coroutine per process contends for the lock and
appends every pending callback's lines in a single write. The others pass
the gate and return without touching the lock once their lines are in.
Dedupe markers for every event in the batch are saved in the same
transaction, so a redelivery of an applied callback is still skipped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01F3M7ttqmi3HYfSr5f9kLt8
Co-authored-by: Torsten Dittmann <[email protected]>
@appwrite

appwrite Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Code review

Commit Status Tier Verdict Details
09fde11 Reviewed Reviewed 🟢 S · Ready to merge ✅ Approved View review

Log callbacks for a deployment are buffered and serialized per process so pending chunks can be appended in one database write and broadcast in one realtime event. Event dedupe markers are recorded with the database transaction, and markers written by a batch are purged if that transaction fails so redelivery can apply the logs.

Latest changes: The newest commit routes the buffered-entry check through a private pending() method; the check remains equivalent to the previous isset condition.

Walkthrough (1)
File Change
src/Appwrite/Platform/Modules/Functions/Workers/Jobs.php Buffers and batches deployment log callbacks under a per-deployment gate, writes log chunks and event markers transactionally, broadcasts applied batches, and cleans up markers after a failed transaction.

Reviewed the commits since 0c93584

Tip

Comment @appwrite review to re-run, or mention @appwrite with a question.

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

🔵 Tier A · See the inline comments. Summary

@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Security rules

WARNING (1 new) — review signal only; does not fail the job.

php.appwrite.weak-secret-env-default (1)

Secret-like env var (SECRET, KEY, PASS, PASSWORD, TOKEN) read with a non-empty literal default. If the variable is unset the process silently runs with a shared, guessable value. Default to '' and fail or disable the feature when it is empty.

  • app/init/resources.php:354 — resource logs
    • What's wrong: _APP_USAGE_PASS falls back to 'appwrite' when unset, so every install that does not set it shares that value.
    • How to fix: Read System::getEnv('_APP_USAGE_PASS', '') and fail or disable the dependent connection when it is empty; keep the example value in .env / app/config/variables.php.
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.

The markers live in Redis, outside the database transaction. When a later
marker save or the commit failed, the append rolled back but the markers
already written stayed, so those callbacks were skipped on redelivery and
their lines lost. Purge the markers the batch wrote before rethrowing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01F3M7ttqmi3HYfSr5f9kLt8
Co-authored-by: Torsten Dittmann <[email protected]>
@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → torsten/upbeat-bohr-brunmc (after).

Metric Before After Change
🚀 Requests/sec 198.17 203.33 ⚪ +2.6%
⏱️ Latency P50 86 ms 85.53 ms ⚪ -0.6%
⏱️ Latency P95 207.25 ms 196.77 ms 🟢 -5.1%
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.53 196.77 12,597 203.33 -10.48
Account 155.58 298.98 663 11.07 -36.9
TablesDB 81.85 151.65 6,851 111.95 -16.09
Storage 80.9 188.13 3,315 56.5 -0.6
Functions 118.65 222.88 1,768 30.89 -16.68

Top API waits (after)

API request Max wait (ms)
storage.buckets.create 519.25
account.get 446.42
functions.variables.update 404.11
account.name.update 392.84
tablesdb.rows.delete 378.97

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

🟢 Tier S · Looks good to merge. Summary

PHPStan read the isset() right after the assignment as always true: it
cannot see other coroutines appending and removing the entry while this
one waits at the gate. The check now asks pending(), which names that.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01F3M7ttqmi3HYfSr5f9kLt8
Co-authored-by: Torsten Dittmann <[email protected]>
@TorstenDittmann
TorstenDittmann merged commit 6f16136 into main Nov 20, 2026
40 checks passed
@TorstenDittmann
TorstenDittmann deleted the torsten/upbeat-bohr-brunmc branch November 20, 2026 16:50
Arnav-1456 added a commit to Arnav-1456/appwrite that referenced this pull request Nov 20, 2026
A state callback (artifact/exit/complete) that cannot acquire the
per-deployment lock within LOCK_TIMEOUT (10s) threw Contention, and on
the Redis broker a rejection is final: the message was dead-lettered to
the failed list and never applied, while the jobs-service does not
resend (the ingest endpoint already answered 204). A lost exit or
complete callback could leave a deployment in building, and the failed
list grew by hundreds of entries per deploy day (issue appwrite#15745).

Contention is raised before the callback body runs, so a contended
message has applied nothing and is safe to requeue as-is: catch it,
publish the same envelope back onto v1-jobs through publisherForJobs,
and let the queue provide the spacing. Requeues are capped at
MAX_REQUEUES (3, i.e. four deliveries); beyond that the message is
dead-lettered on purpose via PermanentFailure, so a persistently stuck
lock cannot loop a message forever. A failed requeue enqueue surfaces as
a RuntimeException like the existing marker-save failures, instead of
losing the callback silently.

The envelope gains an attempts field (default 0) that only the worker
raises; the ingest endpoint and payloads already in queues are
unchanged. Log callbacks do not reach this path: appwrite#15881 gates them
behind a per-process batch so they no longer contend with each other.

Two e2e regression tests cover the contention path: one holds the
deployment lock while a real build streams its callbacks and asserts the
build completes after the release, the other holds the lock past the cap
and asserts a state callback dead-letters only after carrying the cap's
requeue count.
Arnav-1456 added a commit to Arnav-1456/appwrite that referenced this pull request Nov 20, 2026
A callback (log batch leader, artifact, exit, complete) that cannot
acquire the per-deployment lock within LOCK_TIMEOUT (10s) threw
Contention, and on the Redis broker a rejection is final: the message
was dead-lettered to the failed list and never applied, while the
jobs-service does not resend (the ingest endpoint already answered 204).
A lost exit or complete callback could leave a deployment in building,
and a lost log batch lost its lines - the failed list grew by hundreds
of entries per deploy day (issue appwrite#15745).

Contention is raised before the callback body runs, so a contended
message has applied nothing and is safe to requeue as-is: catch it (for
the state callbacks in the action body and for the gated log batch
leader in log()), publish the same envelope back onto v1-jobs through
publisherForJobs, and let the queue provide the spacing. A requeued log
callback re-adds its lines on the next delivery, and the batch dedupe
marker keeps them from appending twice. Requeues are capped at
MAX_REQUEUES (3, i.e. four deliveries); beyond that the message is
dead-lettered on purpose via PermanentFailure, so a persistently stuck
lock cannot loop a message forever. A failed requeue enqueue surfaces as
a RuntimeException like the existing marker-save failures, instead of
losing the callback silently.

The envelope gains an attempts field (default 0) that only the worker
raises; the ingest endpoint and payloads already in queues are
unchanged. Within one worker process log callbacks keep batching at
appwrite#15881's gate and no longer contend with each other at all.

Two e2e regression tests cover the contention path: one holds the
deployment lock while a real build streams its callbacks and asserts the
build completes after the release, the other holds the lock past the cap
and asserts a callback dead-letters only after carrying the cap's
requeue count.
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.

2 participants