Skip to content

feat: a browser context manager -- relaunch on crash, recycle blue/green, shed load - #14

Merged
cycle-five merged 22 commits into
masterfrom
feat/browser-manager
Sep 19, 2026
Merged

cycle-five merged 22 commits into
masterfrom
feat/browser-manager

Conversation

@cycle-five

Copy link
Copy Markdown
Owner

Implements docs/superpowers/specs/2026-09-19-browser-context-manager-design.md. Bumps to 0.5.0.

Stacked on #13 (0.4.1). This PR targets #13's branch, so the diff shows only the manager. Once #13 merges, I'll rebase this onto master and retarget it.

Why

#13 made the pool take a context back from a holder that hangs. That left the browser itself unmanaged. On the bots VM:

  • One Chromium had been alive for 10+ days. Nothing checked its health and nothing recycled it, while renderers accumulated.
  • A crashed browser failed every request until someone restarted the container, and /health kept saying ok.
  • Excess callers waited up to the whole 150 s budget just to queue, then got the same 504 as a genuinely stuck extraction.

Off-the-shelf pools were ruled out in #13, for the same reason here: none of them owns the browser process.

The design

Own Chromium as a process. It is launched with chromium.launchServer() plus connect(), not launch(). That hands back a pid, an exit event, and a SIGKILL. Measured after a SIGKILL: exit is seen at +5 ms, disconnect at +14 ms.

Generations. A generation is one browser and its contexts. Its states are starting → serving → draining → closed, and exactly one generation serves at a time.

  • Crash → relaunch.

    • Every lease on the dead browser has its new lease.lost signal aborted, so an in-flight lookup fails as browser_unavailable, not as whichever Playwright error happened to be pending.
    • The pool relaunches with a 1 s, 2 s, 4 s … backoff, capped at 30 s.
    • After BROWSER_MAX_RELAUNCH_FAILURES failures in a row (default 5), the pool calls onFatal and index.ts exits non-zero, so the container restart policy gives it a clean start. A service that answers 503 forever is an outage nobody is told about.
  • Aging → blue/green recycle.

    • Three triggers: age (6 h), leases served (1000), or the PSS of the browser's process tree (2048 MB). PSS is read from /proc/<pid>/smaps_rollup, because RSS double-counts the shared pages every renderer maps.
    • The replacement is launched and filled before anything moves, then the old generation drains. No caller waits on a recycle. The cost is about 2× browser memory for a few seconds.
    • A failed recycle leaves the old browser serving, and never escalates.
  • Overload → shed. A queued caller waits at most POOL_WAIT_CAP_MS, then gets a 503 with Retry-After: 5:

    • overloaded if every context was busy;
    • browser_unavailable if no browser was serving.

    The default follows the budget, min(20 s, budget/2). A key with a stale cache entry still serves that entry rather than a 503.

Wire and metrics

  • Two new 503 codes, overloaded and browser_unavailable. Both are transient, and neither says anything about Spotify's page, which is why they are not 502s. Coalesced waiters get the same code.
  • New metrics:
    • sleevenote_browser_generations{state};
    • sleevenote_browser_age_seconds and sleevenote_browser_memory_bytes, both absent, not 0, while there is nothing to report;
    • sleevenote_browser_launches_total{reason};
    • sleevenote_browser_launch_failures_total.
  • New env vars (README table): BROWSER_MAX_AGE_MS, BROWSER_MAX_LEASES, BROWSER_MAX_MEMORY_MB, BROWSER_CHECK_INTERVAL_MS, BROWSER_CLOSE_TIMEOUT_MS, BROWSER_MAX_RELAUNCH_FAILURES, POOL_WAIT_CAP_MS. All have defaults. createPool(cfg) is unchanged.

What the whole-branch review caught

Nine tasks were each reviewed on their own. A final review of the whole branch then reproduced a Critical against real Chromium that no single task owned:

  • A Chromium that is alive but hung while being set up wedged the pool at 503 forever and never escalated. newContext has no timeout. The reviewer SIGSTOPped the browser straight after connect(): relaunch, recycle, startup and close() all hung. The whole fill is now bounded (FILL_TIMEOUT_MS, 30 s), and a hung browser is SIGKILLed. Probed with production constants, a wedged relaunch now reaches onFatal at 175 s.
  • A crash loop never backed off. A browser that launched fine and then died soon after reset the failure count, so it was relaunched forever. A generation that dies within 60 s of launch now counts as a failed relaunch, and a spec ruling records the change.
  • Every docker stop looked like a crash. launchServer installs its own SIGTERM/SIGINT/SIGHUP handlers by default, and they closed Chromium before our shutdown ran. They are off now.
  • A crash during playlist paging was served as a short 200, which cracktunes caches for up to 30 days, since it opts into partial listings. A swallowed page-call failure now checks whether the browser died, and throws browser_unavailable if it did.

Verification

  • 214 passed / 9 skipped (156 at the branch point), tsc --noEmit clean. Every new test was seen failing first, then sabotaged. Where a sabotage could not be made to fail, it is recorded rather than forced.

  • The lifecycle tests run against real Chromium, never a fake browser:

    • SIGKILL of the serving pid;
    • a SIGSTOP-wedged browser during setup;
    • a crash during a recycle;
    • a crash loop escalating;
    • drain-not-revoke checked with pid liveness.

    The flakiest-looking ones had 3 stability runs each, with no flakes.

  • Live smoke against real Spotify: 3/3.

Before this deploys

  • init: true on the sleevenote service in both homelab stacks. It was already needed (fix(pool): a lease ends at its deadline, whether or not its holder returns it #13). It matters more now: a relaunch leaves children behind in a process that keeps running, where a crash used to end the process.
  • stop_grace_period of about 60 s. A shutdown that lands during a hung launch can take about 40 s, and Docker's default is 10 s.
  • cracktunes should map the two new codes. Until it does, crack-sleevenote surfaces them as ErrorCode::Unrecognized, preserved verbatim and never mapped onto a known failure. The user still hears back within POOL_WAIT_CAP_MS (20 s) rather than after today's 150 s 504.

Known follow-ups, not in this PR

  • A browser that hangs while serving still sheds as overloaded until its 6 h age recycle. In 0.4.1 it never recovered. The fix is to recycle when a serving browser runs short of contexts, which needs a new launch reason.
  • A browser_deaths_total counter. A crash that a recycle's launch adopts is counted as a recycle today.
  • An isolated test for the 1 s grace wait on its own; today it is tested only as a pair with the plain lost check.
  • A warning when that grace wait expires with no death, to show on TuneTitan how often a healthy lookup pays the second.

🤖 Generated with Claude Code

https://claude.ai/code/session_01F8PrF3gizKqXCStjCuWL3d

…and load shedding

The 0.4.1 fix stops a stuck lease from starving the pool. It does nothing
for the browser, which the pool launches once and trusts for the life of the
process. A Chromium crash is a permanent outage, one browser lives as long
as the container (1.27 GB three hours into a production run), and an excess
caller waits the whole 150 s budget just to queue.

The design gives the pool generations of browsers, launched with
launchServer() so the manager holds the real OS process. It recycles them
blue/green on age, leases served or PSS, relaunches with backoff after a
crash and escalates to a process exit, and sheds load with a queue wait
cap, answered as a 503 in two distinct kinds.

Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
… carries the pid

Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
procmem, then BrowserProcess, then config. Then the pool's rewrite over
generations, in the order the spec builds its behaviour: crash, recycle,
wait cap. Then the HTTP surface and startup wiring, and last the docs and
0.5.0. The spec gains the one race the plan found: a Playwright call can
reject before the pool hears the browser died, so a failure that is not our
own verdict waits up to 1s for the lost signal.

Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
… memory

Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
…t cap

Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
… backoff, escalate

Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
…jected at give-up

Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
…memory

Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
…vailable

Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
…t on a browser that will not relaunch

Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
…est self-contained

Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
… citations

Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
…e pool at 503

launchServer() and connect() had LAUNCH_TIMEOUT_MS, but the fill after
them -- newContext, newPage, route -- had no bound. A Chromium that is alive
but not answering held it forever: a relaunch never failed, so it never
escalated; a recycle never finished, so close() never did; at startup
createPool() never resolved. The final review proved all three by SIGSTOPping
a browser straight after connect: 503 forever, and no exit.

The fill now races FILL_TIMEOUT_MS (30s; a real fill takes well under 1s).
Past it the launch fails, and launchGeneration's close() SIGKILLs the browser,
which rejects the calls still pending on it.

Folded in, the same code:
- close() waits for a relaunch in flight, as it already did for a recycle,
  so the relaunched Chromium cannot outlive it. A relaunch that fails after
  close() is neither counted nor escalated: onFatal exits 1. The backoff
  sleep wakes on close(), or close() would wait out up to 30s of it.
- onDeath empties the dead generation and clears `serving` before aborting
  the leases' `lost`, so a listener that acquires at once queues for the
  relaunch instead of getting a context on the dead browser.
- relaunch() gets a .catch that routes to onFatal, not an unhandled rejection.
- observer.launched runs inside launchGeneration's try (M5): an observer
  that throws fails the launch and closes its browser instead of leaking it.
- the startupGen comment names the real cause, microsoft/TypeScript#9998 (M3).

Test hooks: afterConnect(pid), where a test SIGSTOPs the browser -- the
reviewer's technique, as a fixture -- and fillTimeoutMs.

Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
launchServer() defaults handleSIGTERM, handleSIGINT and handleSIGHUP to true,
and createPool() registers those handlers before index.ts registers its own.
On `docker stop`, Playwright closed Chromium first: the pool saw a serving
browser die, counted launches_total{reason="crash"}, warned, and relaunched
mid-drain -- and in-flight lookups died ahead of shutdownSequence's "close
HTTP first". All three are now off. Playwright's `exit` handler is installed
regardless, so a Node that exits without close() still kills the browser; the
test pins that too.

Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
relaunchFailures was reset at every promote. A browser that fills and then
dies soon after -- an OOM, a crash on its first navigation, pid pressure
from zombies -- was relaunched at once, forever: no backoff, and onFatal
never called, while the service answered mostly 503. A container restart is
exactly what clears that state.

Per the final review's ruling, which amends the spec: "consecutive failures"
now counts launches that failed OR serving generations that died before
STABLE_AFTER_MS (60s; test hook stableAfterMs). The count resets once the
serving generation has served that long -- on the tick, where checkRecycle
already runs, and at its death by its own age -- never at promote.

An early death increments the count and logs a [pool] line naming the
generation and its age. At the limit it gives up exactly as a failed launch
does (waiters rejected, then onFatal); otherwise relaunch() sleeps
backoff(count) before its first attempt. It does not call launchFailed():
that counter means launches that failed, and the death already shows as the
next launches_total{reason="crash"}. A death after the window resets the
count and relaunches at once, as before.

Four existing tests pass stableAfterMs 0: their subject is failed launches,
and without it the startup browser's own death would count toward the limit.

Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
… a short listing

recordResponses' window loop catches every failed page.evaluate -- "Browser
closed" included -- warns, breaks, and returns a normal capture, and
runExtraction checked `lost` only on a throw. A crash mid-pagination went out
as `complete: false`: a 200 to a caller that opts into partial listings
(cracktunes does, crack-core/src/sources/sleevenote.rs), cached at TTL_ALBUM
or TTL_PLAYLIST for up to 30 days, and a 502 extraction_incomplete that
blamed Spotify to a strict caller.

Capture gains `pageCallFailed`, set by every catch in recordResponses that
swallows a page call: the window loop, and the response body read. The body
read is split from its parse, as response.json() does inside, so a JSON
content-type that is not JSON stays a non-event and only a failed read
flags. runExtraction, before judging or normalizing, grace-waits on `lost`
when the flag is set and throws `lost.reason` if it aborted; and it looks at
`lost` once more before the successful return.

Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
…cycle backoff, a drain that opens nothing

Three behaviours the task reviews found unguarded (F5), each now shown to
fail when its code is deleted:
- A crash during a recycle launch. The recycle's browser is held at
  afterConnect until the pool has seen the serving browser die; the recycle
  must adopt the slot alone, so launches are exactly startup and
  recycle_age, and liveContexts() recovers to POOL_SIZE. Deleting relaunch's
  wait on launchInFlight adds a 'crash' launch.
- The recycle backoff. The failed-recycle test holds the clock inside
  backoff(1) for 300ms and expects no second attempt; two injected failures
  make a premature retry fail on the next tick instead of after a real launch.
- A lease ending in a draining generation opens nothing there (spec §2).
  The observable is the draining browser's own newContext(), spied: deleting
  releaseRecord's first non-serving branch calls it once per lease.

Also:
- M2: the memory test's fake reports 100 MB for the first browser only, and
  the test now checks that no third browser launches.
- M1: a failed recycle's log says the old generation keeps serving only when
  it does.

Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
- M4: BrowserUnavailableError, PoolOverloadedError and PoolClosedError set
  `name` the way ExtractionError does, so a log line reads
  `BrowserUnavailableError: ...` rather than a bare `Error: ...`. Nothing on
  the wire reads `name`: the route and the relay classify by instanceof.
- M6: index.ts's onFatal logs the first line of the error only, as extract.ts
  does -- Playwright folds a multi-line call log into `message`. It now says
  "the pool gave up on the browser", since a crash loop reaches it as well
  as a relaunch that cannot launch.

Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
… mid-pagination

The spec is amended where the final review ruled (M8):
- a launch is bounded end to end: FILL_TIMEOUT_MS joins LAUNCH_TIMEOUT_MS,
  a constant, not a knob;
- "consecutive failures" counts a serving browser that dies inside
  STABLE_AFTER_MS, resets on the tick or at a death by age, and never at
  promote; an early death is not a launchFailed();
- a shutdown is not a crash (Playwright's signal handlers are off), and
  close() waits for a launch in flight;
- D6: runExtraction checks `lost` after the capture and before the return
  too, so a crash mid-pagination is not a short listing;
- the drain bound is PRODUCE_BUDGET_MS + CONTEXT_CLOSE_TIMEOUT_MS +
  2 x BROWSER_CLOSE_TIMEOUT_MS, since close(ms) can take up to 2 x ms;
- BROWSER_MAX_LEASES=3 starts its recycle when the third lease is released,
  not "on the fourth lease".

design-notes gains the fill bound and the shutdown paragraph, and its crash
paragraph the stability window (M9); its link to the spec now resolves from
docs/ (M7). The README's BROWSER_MAX_RELAUNCH_FAILURES row says what counts.

Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
@cycle-five
cycle-five changed the base branch from fix/pool-lease-deadline to master September 19, 2026 21:24
@cycle-five
cycle-five merged commit a3bb9a6 into master Sep 19, 2026
2 checks passed
@cycle-five
cycle-five deleted the feat/browser-manager branch September 19, 2026 21:28
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