Skip to content

fix(capture): refuse excess captures with 503 instead of killing accepted ones - #34

Open
abnegate wants to merge 6 commits into
mainfrom
fix/capture-admission-control
Open

abnegate wants to merge 6 commits into
mainfrom
fix/capture-admission-control

Conversation

@abnegate

@abnegate abnegate commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Symptom

Root cause

A 507 from this service is mostly a load signal, not a verdict on the page. The memory guard kills whichever capture started last, not the one using the memory.

Confirmed from the code trace and the reproduction below:

  • Bun.serve (src/server.ts) hands every request straight to its route. Nothing bounds concurrency, and every request opens its own browser context.
  • MemoryGuard.check (src/utils/memory.ts) reads the cgroup working set. Over limit × MEMORY_BUDGET, it closes the newest open capture, whatever that capture's own size, and the screenshot and report routes answer that capture with 507.
  • appwrite captures the light and dark themes of each deployment concurrently, so every job is at least two captures.
  • fix: close the newest capture when memory nears the container limit #26's own measurement shows it: three concurrent captures of the same page under --memory 2g returned 200, 507, 200.

Inferred, not confirmed:

  • Production sizing: 2 browser replicas at 2 GiB, and screenshot workers running several coroutines per pod across several pods. This comes from local clones of the deploy config, which may be stale.

Telemetry: Grafana sits behind Cloudflare Access and was not reachable from this session, so there is no Loki or Prometheus correlation for the incident window. The cause above rests on the code trace, the #26 measurement, the config and the calibrated reproduction in this PR.

Fix

  • Admission control (src/utils/admission.ts). Only POST /v1/screenshots and POST /v1/reports are admitted this way.
    • Slots default to floor((limit × MEMORY_BUDGET − baseline) / CAPTURE_MEMORY), at least 1. The baseline is measured at startup, after Chromium launches.
    • A memory check also runs on every admission. It counts already-admitted captures at their estimate, so a capture that has not grown yet still reserves its room.
    • Anything that does not fit gets a typed 503 with Retry-After, before any browser context opens.
  • 507 now means the page itself crossed the budget. That is a capture that had been alone for 3 s and started while the browser was under budget. A capture evicted under load gets a retryable 503 with Retry-After.
  • SSRF refusals return 403 via a typed BlockedUrlError, instead of a 400 the caller had to string-match.
  • Health answers 503 when the browser is idle and still over budget, so a liveness probe can restart a pod that cannot recover by itself.
  • Aborted requests close their context, so a caller timeout frees the slot at once.
  • New env vars: CAPTURE_SLOTS (derived by default), CAPTURE_MEMORY (256 MiB), RETRY_AFTER (5 s). They are documented in the README with an error table.
  • There is no queue on purpose. The caller's 60 s HTTP timeout already roughly equals the navigation timeout plus sleep, so time spent waiting in a queue would turn into caller timeouts. Rejecting immediately with Retry-After leaves the backoff to the caller.

Proof

Recovery tests (bun test tests/recovery) run against a 1 GiB container. BASE is appwrite/browser:base, built from 58d03d5. Fix is this branch.

Test BASE Fix
Heavy load, 12 staggered captures 9–11×200 + 1–3×507 (accepted captures killed) 1×200 + 11×503, no 507
Slots (CAPTURE_SLOTS=2, RETRY_AFTER=7, 6 concurrent) 6×200 2×200 + 4×503 with Retry-After: 7
Memory clause (CAPTURE_MEMORY=1024, 3 concurrent) 3×200 1×200 + 2×503
Derived slots, clients retrying 3× 507s are terminal 0×507; 4–6 of 12 finish, the rest end on a retryable 503
Baseline over budget (MEMORY_BUDGET=0.05) 507 503 with Retry-After; idle health 503
Client aborts its capture (CAPTURE_SLOTS=1) context left open, no abort logged context closed, next capture 200
Lone page that grows past the budget 507 507

BASE, heavy load:

error: expect(received).toEqual(expected)
-   503, ... (11×)
+   200, ... (10×)
+   507,
(fail) E2E Tests - admission under heavy load > should refuse captures that do not fit instead of killing accepted ones with 507
Derived slots null: 9/12 completed, attempts 9x200 3x507, finals 9x200 3x507
 1 pass
 6 fail

Fix:

Derived slots 2: 6/12 completed, attempts 6x200 24x503, finals 6x200 6x503
 9 pass
 0 fail
Ran 9 tests across 3 files.

Unit tests on BASE plus the new tests fail because the module and exports are missing. On the fix they all pass:

BASE: error: Cannot find module '../../src/utils/admission.js'
      SyntaxError: Export named 'BlockedUrlError' not found in module 'src/utils/ssrf.ts'
      SyntaxError: Export named 'Closure' not found in module 'src/utils/memory.ts'
      96 pass, 4 fail, 3 errors
Fix:  152 pass, 0 fail

The e2e suite passes on the fix (27/27), including SSRF returning 403 for a private first hop.

Decisions for Jake

  1. Default CAPTURE_MEMORY = 256 MiB trades throughput for safety. In the 1 GiB test, the fix completed fewer captures within the 3-attempt retry window than BASE did (4–6 vs 9–11 of 12), but none failed permanently. Production may want a chart override.
  2. Reports (Lighthouse) share the screenshot estimate, even though they are heavier. appwrite has no caller for /v1/reports today.
  3. appwrite now treats a 403 from any intermediary as permanent. A proxy or WAF answering 403 in front of the browser would abandon the capture instead of retrying it.

Release order

  1. Release this image.
  2. Bump the browser tag in appwrite (docker-compose.yml, composeData.ts) and in the cloud chart.
  3. Deploy the appwrite PR: fix(screenshots): retry a browser at capacity and abandon only page refusals appwrite#15508.

Supersedes

Together with appwrite/appwrite#15508, this supersedes appwrite/appwrite#15424.

🤖 Generated with Claude Code

abnegate and others added 6 commits November 12, 2026 16:50
…rest with 503

Nothing bounded concurrency. Every request opened its own browser
context, so a burst crossed the memory budget together and the guard
closed accepted captures with a permanent 507 for memory other pages
were using.

Admission now runs before any context opens. POST /v1/screenshots and
POST /v1/reports share a pool of CAPTURE_SLOTS; past it, or when one
more CAPTURE_MEMORY estimate would not fit in the budget on top of the
larger of the working set and the startup baseline plus one estimate
per capture in flight, the request gets 503 with Retry-After
(RETRY_AFTER) and has done no work, so a retry is safe. Counting
admitted captures at their estimate matters because a capture admitted
a moment ago has not grown yet. An idle browser always admits one
capture so a high baseline cannot lock the service out. There is no
queue: waiting would eat into the caller's own timeout. /v1/test and
/v1/health are not gated, because captures load /v1/test themselves.

Slots default to what fits in the budget above the startup baseline.
config/admission imports ./browser.js itself so that baseline is read
after Chromium has launched; otherwise it misses idle Chromium and
over-admits, whatever order config/index exports in.

/v1/health answers 503 when nothing is in flight, no capture has been
released for 2 s, and usage is still over the budget, so a liveness
probe restarts a browser whose idle memory has crept past the point
where any capture could run. The 2 s grace lets a just-closed page
drain before health counts it.

A client that goes away now has its context closed at once, so the
capture fails fast and frees its slot instead of holding it until the
page finishes. Failures map to responses in one function, status codes
come from one enum, and a context.close() that throws is logged rather
than replacing the response; the capture and egress guard are released
after it either way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…lone

Admission keeps bursts out, but the guard still closes the newest
capture whenever the working set crosses the budget, and it answered
every such closure 507. A 507 tells the caller the page itself is too
big and not to retry, which was false for a capture closed while
neighbours, memory still draining from a closed neighbour, or a
baseline already over budget were using the memory.

A closure now records why. It is Exceeded (507) only when the capture
has been the sole tracked one for QUIET_MS (3 s; the clock restarts on
every track and release) and usage was under the budget when it was
tracked, so the page alone took the browser over. Every other closure
is Evicted and answered 503 with Retry-After and a message saying the
capture can be retried. Routes already release a capture only after
its context has closed, so a closed page whose memory is still draining
keeps the survivor from looking alone, and its release restarts the
solitude clock.

SETTLE_MS and QUIET_MS are exported so tests do not copy them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
assertAllowedUrl threw a plain Error for a private host or a non-http(s)
scheme, so the routes answered 400 and a caller could only tell an SSRF
refusal from a malformed request by matching the message. A refused
navigation already answered 403. The up-front check now throws
BlockedUrlError, which maps to 403 the same way, so callers classify by
status. A URL that cannot be parsed stays a plain Error and a 400.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Admission, the guard's 507 rule and the failure mapping decide whether a
caller retries, and none of it had tests. These pin the contract:

- Admission refuses excess captures with CapacityError (503 plus
  Retry-After) on the slot count and on the memory clause, counts
  admitted captures at their estimate, always admits an idle browser,
  and admit() releases the slot whether the handler resolves or throws.
- Health fails only when idle over the budget, and not while a released
  capture's memory drains.
- deriveSlots, createAdmission and the env parsers size slots from the
  startup baseline and accept only positive integers.
- The guard marks a closure Exceeded only for a capture alone past the
  quiet window that was tracked under the budget; a survivor of an
  eviction, of a released neighbour, or of an over-budget baseline is
  Evicted. Closed but unreleased captures still count.
- failureResponse covers every row of the README status table.
- SSRF refusals throw BlockedUrlError, while a malformed URL does not.

The guard tests use real timers and a fake reader with wide margins
around the 100 ms poll, the settle delay and the quiet window, so the
memory file takes several seconds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The unit tests use a fake memory reader, so nothing showed that a real
container under concurrent load refuses captures up front instead of
letting the guard close accepted ones with 507. These container tests
run against appwrite/browser:local, or the image in BROWSER_IMAGE so the
same suite can be pointed at a BASE build to show the red run:

- slots: CAPTURE_SLOTS=2 and 6 concurrent captures give 2x200 and 4x503
  with Retry-After, no guard closure, and "Chromium started!" logged
  before the "Admission:" line, so the baseline includes idle Chromium.
- memory clause: CAPTURE_MEMORY=1024 at 1 GiB admits one of three.
- heavy: CAPTURE_MEMORY=512 at 1 GiB (one slot), 12 staggered
  3840x2160 @3x clipped captures.
- derived: default CAPTURE_MEMORY and derived slots (2 at 1 GiB), the
  same 12 captures, each client retrying like the Appwrite screenshot
  client: up to 3 attempts, waiting Retry-After plus up to 50% jitter.
- a 507 only for a page that grows past the budget alone, after the
  3 s solitude window and in 16 MiB steps the 100 ms poll sees before
  the kernel OOM-kills Chromium; an over-budget baseline evicts with
  503 and Retry-After and reports idle /v1/health unhealthy.
- an abandoned capture with CAPTURE_SLOTS=1 frees its slot for the
  next request.

Calibration at 1 GiB with the default budget (870 MiB): baseline
112-147 MiB, one heavy capture adds 90-108 MiB, so CAPTURE_MEMORY=512
yields one slot for any baseline up to 358 MiB.

Status mix for the 12 heavy captures:
- BASE (no admission): 9-11x200 plus 1-3x507; the 507s are terminal.
- fix, one slot: 1x200 plus 11x503, no 507.
- fix, derived slots with retrying clients: 4-6 of 12 completed, zero
  507s on any attempt, and every other client ended on a retryable 503
  with Retry-After. 12 captures of about 9.5 s through 2 slots need
  about 57 s, longer than the clients' retry window, so not all finish.

Containers count any health answer as started, since an over-budget
container never answers 200, and container removal gets its own hook
timeout because docker rm -f of a running Chromium can outlast bun's
5 s default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…slow shutdown

The unit CONNECT helper resolved on the first chunk that held the end of
the 200 header. The egress guard writes that header and then pipes the
upstream bytes separately, so whether "pong" arrived in the same chunk
depended on TCP timing; on Bun 1.4 it arrives in a second chunk every
time, which made "establishes a tunnel to a reachable host" fail on
every run. The helper now collects everything and settles once the
socket closes, which follows both an orderly end and an error.

The integration afterAll closes the browser, and with branded Chrome
(channel chrome, Chrome 157) on macOS that takes 12-30 s even with no
proxy and no page open, while headless-shell closes in under 0.1 s.
The cause is Chrome's own shutdown, not the egress guard: closing the
guard first did not change it (3/5 runs still over 5 s). bun's 5 s
default hook timeout therefore failed the teardown on every run, BASE
included. The hook now gets 60 s, as a named constant.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@appwrite

appwrite Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

🔵 Tier A · Mergeable after minor fixes

The admission guard can still misclassify an overlapping request during context creation as an isolated capture, yielding a permanent 507 in that uncommon pressure case.

This change adds admission control for screenshot and report captures, returns retryable 503 responses when capacity is exhausted, and distinguishes memory evictions from captures classified as exceeding the budget. It also adds request-abort cleanup, memory-aware health reporting, typed SSRF refusals, and supporting documentation and tests.

Verdict New comments Fixed Still open
💬 Commented 1 0 0

Note

Not approving while a bug finding is open: Pending admitted captures are missing from the solitude check

Finding Where
🟡 Pending admitted captures are missing from the solitude check src/utils/memory.ts:155
Fix with agent prompt
### Issue 1
src/utils/memory.ts:155
**Pending admitted captures are missing from the solitude check**

A request is admitted before either route finishes `browser.newContext()`, but it is not added to `tracked` until afterward (`screenshots.ts:52-53`, `reports.ts:48-50`). If memory crosses the budget while that second context is still being created and the existing capture has already been alone for 3 seconds, this check can mark and close the existing capture as `Exceeded`, returning a permanent 507 for overlapping work instead of a retryable eviction.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
📂 Walkthrough · 9
File Change
README.md Documents admission settings, capture error statuses, and memory-aware health behavior.
src/config/admission.ts, src/config/index.ts, src/server.ts Initializes admission after Chromium startup and applies it to screenshot and report routes.
src/routes/health.ts, src/routes/reports.ts, src/routes/screenshots.ts Adds memory-aware health status, abort cleanup, and centralized capture failure responses.
src/utils/abort.ts, src/utils/admission.ts, src/utils/failure.ts, src/utils/status.ts Adds abort handling, admission controls, failure mapping, and shared HTTP status values.
src/utils/memory.ts Tracks capture closure reasons and distinguishes eviction from isolated memory-budget exceedance.
src/utils/router.ts, src/utils/ssrf.ts Exports the route handler type and introduces typed SSRF refusals.
tests/e2e/ssrf.test.ts, tests/integration/egress.test.ts, tests/unit/egress.test.ts, tests/unit/ssrf.test.ts Updates SSRF expectations, shutdown timing, CONNECT response handling, and SSRF error type coverage.
tests/recovery/admission.test.ts, tests/recovery/container.ts, tests/recovery/memory.test.ts Adds container-level admission, retry, abort, and memory-recovery coverage.
tests/unit/admission.test.ts, tests/unit/failure.test.ts, tests/unit/memory.test.ts Adds unit coverage for admission decisions, failure mapping, memory guard behavior, and configuration parsing.

Reviewed bef3f1f · Details · 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

Comment thread src/utils/memory.ts
newest.exceeded = true;
this.settledAt = Date.now() + SETTLE_MS;
const exceeded =
this.tracked.length === 1 &&

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pending admitted captures are missing from the solitude check

A request is admitted before either route finishes browser.newContext(), but it is not added to tracked until afterward (screenshots.ts:52-53, reports.ts:48-50). If memory crosses the budget while that second context is still being created and the existing capture has already been alone for 3 seconds, this check can mark and close the existing capture as Exceeded, returning a permanent 507 for overlapping work instead of a retryable eviction.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/utils/memory.ts
Line: 155

Comment:
**Pending admitted captures are missing from the solitude check**

A request is admitted before either route finishes `browser.newContext()`, but it is not added to `tracked` until afterward (`screenshots.ts:52-53`, `reports.ts:48-50`). If memory crosses the budget while that second context is still being created and the existing capture has already been alone for 3 seconds, this check can mark and close the existing capture as `Exceeded`, returning a permanent 507 for overlapping work instead of a retryable eviction.

---

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

🟡 Minor · bug · Reply if this doesn't apply.

@github-actions

Copy link
Copy Markdown

Docker Image Stats

Metric Value
Image Size 833MB
Memory Usage 110MiB
Cold Start Time 1.04s
Screenshot Time 1.26s

Screenshot benchmark: Average of 3 runs on https://appwrite.io

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