Skip to content

fix(sites): make screenshot capture deterministic and diagnosable - #13315

Merged
HarshMN2345 merged 7 commits into
mainfrom
fix/screenshot-reliability
Oct 29, 2026
Merged

HarshMN2345 merged 7 commits into
mainfrom
fix/screenshot-reliability

Conversation

@HarshMN2345

Copy link
Copy Markdown
Member

Context

Investigating screenshot failures in production turned up three separate causes behind the same Screenshot capturing failed message. This PR covers the ones that live in this repo. The browser service dying is handled separately in appwrite/docker-browser#17.

1. The deployment domain was picked non-deterministically

findOne on rules had no ordering, so the domain was whichever row the adapter returned first:

$rule = $dbForPlatform->findOne('rules', [
    Query::equal("projectInternalId", [$project->getSequence()]),
    Query::equal("type", ["deployment"]),
    Query::equal('deploymentInternalId', [$deployment->getSequence()]),
]);

In production 200,411 of 308,919 deployments (65%) carry more than one type=deployment rule, and the candidates are not equivalent. On one deployment I tested, one domain served in 0.64s while the other returned a persistent 503 backend read error — same deployment, same build. The capture that picked the second one failed after 30s having received nothing.

Now ordered by $sequence, and the chosen rule.domain and rule.trigger are recorded on the span so the next occurrence is diagnosable from logs instead of requiring a live reproduction.

2. The timeout layers were all equal, so none had headroom

The client to the browser used _APP_SITES_TIMEOUT, which caps a site's own request — an unrelated concern that also happens to default to 30. The browser's navigation timeout defaults to 30s too, and we never sent one.

Server-side the sequence is navigate → settle (3–5s, per framework) → render → PNG encode at 1.5×. With both budgets at 30s, the client aborts captures the browser would have completed, and because both deadlines land together the browser can never report why. Every such failure looked identical: Operation timed out after 30025 milliseconds with 0 bytes received.

  • _APP_BROWSER_TIMEOUT, default 90s, replaces the borrowed _APP_SITES_TIMEOUT
  • an explicit 60s navigation budget is sent to the browser (its accepted max is 120000)

Each layer now exceeds the one below it.

3. The failure message said nothing, and sometimes said the wrong thing

Screenshot capturing failed. Deployment will continue. carried no reason. Worse, it was shown for failures where the spans recorded screenshot.count: 2 — both screenshots captured fine and only the S3 upload failed. The log now includes the reason.

4. Capture duration was never measured

Added a worker.screenshots.capture.duration histogram, tagged by theme. Light and dark are recorded separately on purpose: the first capture pays the site's cold start and the second finds it warm, so a combined number hides the thing worth watching. Only a success/failure counter existed before, so how close captures run to the ceiling was invisible.

Verification

php -l, composer lint and PHPStan level 4 pass on the changed files. Full composer analyze and the E2E suite were not run.

Review notes

  • Query::orderAsc('$sequence') is valid per Database::INTERNAL_ATTRIBUTES but has no precedent in this repo. The filter is selective and limited to 1, so I would not expect a filesort, but it was not executed against a real rules table.
  • Ascending order picks the oldest rule, which on the deployment I tested is the working one. That is one data point. If the trigger=deployment domains turn out to be the unreliable ones generally, preferring by trigger explicitly would be better than relying on creation order.

The screenshot worker resolved a deployment's domain with findOne and no
order, so on deployments carrying several rules the domain was whichever the
adapter returned first and an unreachable one failed some captures but not
others. Order by $sequence and record the chosen domain and trigger on the
span.

The HTTP client to the browser shared _APP_SITES_TIMEOUT, which caps a site's
own request, so its budget equalled the browser's navigation default and left
nothing for the settle, render and encode that follow. Give it
_APP_BROWSER_TIMEOUT at 90s and send an explicit 60s navigation budget, so
each layer exceeds the one below and the browser can report its own errors.

Report the failure reason in the deployment log instead of a bare 'Screenshot
capturing failed', which was shown even when the capture succeeded and only
the upload failed, and record per-capture duration so cold start is visible.
@greptile-apps

greptile-apps Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR makes screenshot processing more deterministic and diagnosable.

  • Selects deployment rules in sequence order and adds rule details to tracing.
  • Introduces separate browser client and navigation timeout budgets.
  • Improves failure logging and adds per-theme capture-duration telemetry.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

Filename Overview
src/Appwrite/Platform/Modules/Functions/Workers/Screenshots.php Orders deployment-rule selection, enriches tracing and failure logs, and adds per-theme capture-duration telemetry.
src/Appwrite/Screenshots/Client.php Sends an explicit 60-second navigation timeout to the browser service.
app/init/resources.php Configures the screenshot client from the new browser-specific timeout setting.
docker-compose.yml Passes the browser timeout setting into the dedicated screenshots worker.
tests/unit/Screenshots/ClientTest.php Updates request-shape coverage for the explicit browser navigation timeout.

Reviews (3): Last reviewed commit: "fix(sites): keep the existing screenshot..." | Re-trigger Greptile


// The first capture pays the site's cold start and the second
// finds it warm, so record them separately rather than as a total.
$this->recordDuration($duration, \microtime(true) - $captureStart, $theme);

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 Capture durations exclude failures

When Screenshots\Client::create() throws for a timeout, HTTP error, or invalid response, control skips recordDuration() and the failure path records only the counter. The histogram therefore excludes the slowest failed captures and cannot show elapsed time for the production failures it was added to diagnose.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Platform/Modules/Functions/Workers/Screenshots.php
Line: 177

Comment:
**Capture durations exclude failures**

When `Screenshots\Client::create()` throws for a timeout, HTTP error, or invalid response, control skips `recordDuration()` and the failure path records only the counter. The histogram therefore excludes the slowest failed captures and cannot show elapsed time for the production failures it was added to diagnose.

---

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

@github-actions

github-actions Bot commented Aug 24, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/screenshot-reliability (after).

Metric Before After Change
🚀 Requests/sec 159.83 162.96 ⚪ +2%
⏱️ Latency P50 107.04 ms 107.85 ms ⚪ +0.8%
⏱️ Latency P95 254.65 ms 248.54 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 107.85 248.54 10,260 162.96 -6.1
Account 196.68 365.22 540 9.43 -84.11
TablesDB 103.68 185.81 5,580 91.98 -10.14
Storage 100.34 233.65 2,700 46.03 +1.02
Functions 151.55 290.15 1,440 25.36 +2.99

Top API waits (after)

API request Max wait (ms)
account.name.update 562.12
account.prefs.update 548.53
functions.create 517.56
storage.buckets.create 487.44
functions.variables.update 454.17

@ghost

ghost commented Oct 5, 2026 •

Copy link
Copy Markdown

🔵 Tier A · Mergeable after minor fixes

The new deterministic rule-selection behavior lacks regression coverage despite existing screenshot E2E tests.

The screenshot worker now selects deployment rules in sequence order and records the selected domain and trigger on its span. It also measures capture duration separately for light and dark themes and includes exception details in deployment failure logs.

Verdict New comments Fixed Still open
✅ Approved 0 0 1
Fix with agent prompt
### Issue 1
src/Appwrite/Platform/Modules/Functions/Workers/Screenshots.php:114
**Cover deterministic rule selection with a regression test**

The existing `testSiteScreenshot` E2E test checks screenshot output but does not distinguish which of multiple deployment rules is selected, so removing this ordering would still pass. Please add an E2E regression with distinguishable rule candidates that verifies the intended selection through observable capture behavior, especially since this query has not been exercised against a real rules table.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
📂 Walkthrough · 1
File Change
src/Appwrite/Platform/Modules/Functions/Workers/Screenshots.php Adds deterministic rule ordering, rule diagnostics, per-theme duration metrics, and failure reasons in logs.
⏳ Still open from earlier reviews · 1

Merged main (0f1e945); no changes to this PR's code since dabfb3e · 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

Query::equal("projectInternalId", [$project->getSequence()]),
Query::equal("type", ["deployment"]),
Query::equal('deploymentInternalId', [$deployment->getSequence()]),
Query::orderAsc('$sequence'),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cover deterministic rule selection with a regression test

The existing testSiteScreenshot E2E test checks screenshot output but does not distinguish which of multiple deployment rules is selected, so removing this ordering would still pass. Please add an E2E regression with distinguishable rule candidates that verifies the intended selection through observable capture behavior, especially since this query has not been exercised against a real rules table.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Platform/Modules/Functions/Workers/Screenshots.php
Line: 114

Comment:
**Cover deterministic rule selection with a regression test**

The existing `testSiteScreenshot` E2E test checks screenshot output but does not distinguish which of multiple deployment rules is selected, so removing this ordering would still pass. Please add an E2E regression with distinguishable rule candidates that verifies the intended selection through observable capture behavior, especially since this query has not been exercised against a real rules table.

---

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.

…t worker

findOne already breaks ties on $sequence ascending when no unique order is
given, so the rule pick was never left to the adapter. The explicit order
emits the same ORDER BY and needs no comment.
@github-actions

github-actions Bot commented Oct 8, 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.

@HarshMN2345
HarshMN2345 merged commit 04ca9ae into main Oct 29, 2026
38 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