Repository navigation
feat: a browser context manager -- relaunch on crash, recycle blue/green, shed load - #14
Merged
Merged
Conversation
…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
force-pushed
the
feat/browser-manager
branch
from
September 19, 2026 21:24
3f4b873 to
a810e84
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
/healthkept sayingok.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()plusconnect(), notlaunch(). 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.
lease.lostsignal aborted, so an in-flight lookup fails asbrowser_unavailable, not as whichever Playwright error happened to be pending.BROWSER_MAX_RELAUNCH_FAILURESfailures in a row (default 5), the pool callsonFatalandindex.tsexits 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.
/proc/<pid>/smaps_rollup, because RSS double-counts the shared pages every renderer maps.Overload → shed. A queued caller waits at most
POOL_WAIT_CAP_MS, then gets a 503 withRetry-After: 5:overloadedif every context was busy;browser_unavailableif 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
overloadedandbrowser_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.sleevenote_browser_generations{state};sleevenote_browser_age_secondsandsleevenote_browser_memory_bytes, both absent, not 0, while there is nothing to report;sleevenote_browser_launches_total{reason};sleevenote_browser_launch_failures_total.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:
newContexthas no timeout. The reviewer SIGSTOPped the browser straight afterconnect(): relaunch, recycle, startup andclose()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 reachesonFatalat 175 s.docker stoplooked like a crash.launchServerinstalls its own SIGTERM/SIGINT/SIGHUP handlers by default, and they closed Chromium before our shutdown ran. They are off now.browser_unavailableif it did.Verification
214 passed / 9 skipped (156 at the branch point),
tsc --noEmitclean. 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:
The flakiest-looking ones had 3 stability runs each, with no flakes.
Live smoke against real Spotify: 3/3.
Before this deploys
init: trueon 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_periodof about 60 s. A shutdown that lands during a hung launch can take about 40 s, and Docker's default is 10 s.crack-sleevenotesurfaces them asErrorCode::Unrecognized, preserved verbatim and never mapped onto a known failure. The user still hears back withinPOOL_WAIT_CAP_MS(20 s) rather than after today's 150 s 504.Known follow-ups, not in this PR
overloadeduntil 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.browser_deaths_totalcounter. A crash that a recycle's launch adopts is counted as a recycle today.lostcheck.🤖 Generated with Claude Code
https://claude.ai/code/session_01F8PrF3gizKqXCStjCuWL3d