Skip to content

fix: delete the temporary profile when the browser stops - #94

Merged
nathanfallet merged 26 commits into
mainfrom
fix/cleanup-temp-profile
Nov 21, 2026
Merged

nathanfallet merged 26 commits into
mainfrom
fix/cleanup-temp-profile

Conversation

@nathanfallet

@nathanfallet nathanfallet commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Problem

When no userDataDir is given, kdriver creates a kdriver_* profile in the temp directory (createTempDirectory on the JVM, $TMPDIR/kdriver_<random> on POSIX (chmod-ing a subdirectory it cannot list), %TEMP%\kdriver_<random> on Windows) and never deletes it: DefaultBrowser.cleanupTemporaryProfile() was a TODO. On a host that starts browsers all day this left thousands of profile directories (41 GB, ~500 more per day).

The existing call in the shutdown hook of DefaultBrowser.create did not cover anything: the method was empty, the hook only ran at JVM exit, and stop() never called it.

Change

  • cleanupTemporaryProfile() deletes the profile this browser created, and only that one:
    • never a userDataDir the caller supplied (Config.usesCustomDataDir);
    • a temporary profile is deleted by the browser that runs on it, whichever copy of the config created it: Config.createdTemporaryProfile (internal) is derived from the profile itself, so Config.copy() carries it (a profile created before the browser copied its config, e.g. by reading userDataDir first, is not leaked);
    • only once the browser process has exited, with a bounded wait (5 s), since Chrome keeps writing to the profile while it shuts down; if the process is still alive it leaves the profile and logs a warning;
    • retrying for ~5 s when a file is still locked (Windows, antivirus);
    • idempotent: once deleted, further calls do nothing.
  • stop() runs every step even if an earlier one fails or is cancelled (graceful close, then, non-cancellable, the kill, the connection and HTTP client closes and the profile deletion, then the scope cancellation), and rethrows the first failure with the others suppressed: a close that throws no longer leaves the process running and the profile on disk. A stop() from a finally of a cancelled coroutine (or from inside the browser scope) still cleans up. A second stop() is harmless. A profile that failed to start (startProcess throws) is deleted too.
  • detach() keeps the profile, since the browser still runs on it; its KDoc says so, and that cleanupTemporaryProfile() deletes it once that browser has exited.
  • stop() on a browser that died (crashed, killed from outside): the graceful Browser.close fails since nothing answers, which used to throw out of stop() before the kill and the profile deletion; that failure (an I/O error, or ConnectionClosedException once the connection gives up) is now logged and stop() goes on.
  • Host exit without stop(): one process-wide shutdown hook (StartedBrowsers) stops the browsers kdriver launched and has not stopped, which deletes their profiles. A browser it only connected to (browserUrl, or host and port) is never closed on exit, as before. It replaces the per-browser hook added by create(), which kept every browser ever created reachable until exit and missed browsers started through DefaultBrowser(...).start(). A browser leaves the registry when it is stopped (with its profile gone) or detached.
  • create() failing after the launch (e.g. target discovery throws) now stops the browser: the caller never gets the instance, so it could not. Whether it launched is what decides (not the pid, which a start that already stopped the browser has cleared), so such a browser stays for the exit hook when its profile could not be deleted. A kill that fails keeps the process, so the exit hook's stop() tries again.
  • Restart path (start() on a dead process): the new browser runs on the same profile, so it takes over deleting it; if the relaunch fails, the profile is deleted since nothing runs on it anymore. The relaunch also clears the host and port assigned to the dead process: before, the new browser inherited them, took the connect-existing branch and timed out on the dead port instead of launching a browser.
  • Recursive deletion per platform, never following symbolic links or junctions (a link inside the profile is removed, not its target), on the I/O dispatcher:
    • JVM: kotlin.io.path.deleteRecursively;
    • POSIX native: every directory is opened without following links and its entries are reached from that descriptor only, so an entry swapped for a link during the walk is unlinked, never followed nor chmod-ed through (unlinkat/fchmodat and open with O_NOFOLLOW_ANY from a canonical root on macOS, where openat is not exposed; /proc/self/fd/<fd>/<name> on Linux, where Kotlin/Native exposes no *at function, with the plain path as fallback without /proc); a directory it cannot list is made accessible through its descriptor (or fchmodat / an O_PATH descriptor), not by path. The profile is now created 0700, like Chrome's own;
    • Windows native: FindFirstFileW/DeleteFileW/RemoveDirectoryW on \\?\ extended-length paths, so entries beyond 260 characters are deleted too (clearing read-only attributes); an entry counts as gone only on ERROR_FILE_NOT_FOUND/ERROR_PATH_NOT_FOUND;
    • JS cannot launch a browser, so nothing there.
  • Process liveness, which the wait depends on:
    • Linux native: the child is now reaped (waitpid(WNOHANG)); before, an exited browser stayed a zombie and isAlive() (signal 0) stayed true, so every stop() waited the full 8 s.
    • macOS native: NSTask.isRunning.
    • Windows native: destroy() no longer closes the process handle before isAlive() reads it (undefined result); the handle stays open for as long as the process object is used and is closed by a cleaner once it is unreachable (no thread can race another onto a closed handle, and a detached process's handle is released too); the exit code is cached for exitCodeOrNull().

Platform coverage of the exit hook

Platform stop() deletes the profile Exit without stop()
JVM yes yes (JVM shutdown hook, normal exit and SIGTERM/SIGINT; not SIGKILL)
macOS / Linux native yes no: addShutdownHook stays a no-op there (calling Kotlin from atexit is not safe enough to ship blind, and signals bypass it anyway)
Windows native yes no, same reason
JS n/a (cannot launch a browser) n/a

Tests

  • jvmTest TemporaryProfileTest (real browser, like BrowserTest):
    • the temporary profile is gone after stop(); a second stop() and repeated cleanupTemporaryProfile() are harmless;
    • a custom userDataDir is kept with its content; a temporary profile created before the browser copied its config is deleted by stop(); a config copy keeps a temporary profile temporary and a custom one custom;
    • stop() deletes the profile and kills the process even when the graceful close or the connection close throws, and still reports that failure;
    • detach() keeps the browser running and its profile, out of the exit hook; cleanupTemporaryProfile() deletes it once that browser has exited;
    • the exit hook leaves a browser kdriver only connected to;
    • cleanupTemporaryProfile() on a running browser waits the bounded time, keeps the profile and logs a warning;
    • a process that cannot be launched leaves no profile; create() failing after the launch stops the browser and deletes its profile;
    • a failed delete in stop() logs a warning and keeps the browser registered, then the exit hook (StartedBrowsers.stopAll()) deletes the profile; the exit hook stops running browsers, and still stops the others when one fails to stop;
    • stop() on a browser that died still deletes its profile;
    • restart on a dead process launches a new process on the same profile and hands its deletion over; a failed relaunch deletes the profile;
    • deleteTemporaryProfile retries with a delay between attempts, stops at the first success and gives up after the last one (virtual time); deletion removes nested content, does not follow symbolic links, is true for a missing directory, and gives up on an entry it cannot delete (POSIX).
  • Test seams are internal only (logger, release timeout and delete function of DefaultBrowser, a factory for create, the relaunch, one delete attempt): the public API is unchanged.
  • macosTest / linuxTest / mingwTest TemporaryProfileTest: the profile is gone after stop(), a second stop/cleanup is harmless (exercises each native delete implementation in CI).
  • posixTest PosixDeleteRecursivelyTest (macOS and Linux native, default TMPDIR): nested content, directories it cannot list or empty at first, a link inside the profile (its target neither deleted nor chmod-ed), a root that is itself a link, a missing root. The lstat/chmod race itself cannot be triggered deterministically; the walk no longer has a step between a check and a use by path.
  • mingwTest WindowsDeleteRecursivelyTest: a tree nested past 300 characters is deleted; doubled separators; an unreachable path is not reported gone; the extended-length form of drive, UNC, already-extended, device and relative paths.
  • Kover on the JVM: every added or changed line in commonMain / jvmMain is covered.

Test stability on Ubuntu

  • testMultipleBrowsersDiffUserData read the title after an idle wait, which a slow runner could pass before the page had loaded (the title was still the URL); waiting for the target to report the title still failed now and then, the target title staying the URL 30 s after the load, and example.com pages could themselves take that long. It now loads three local pages, waits for each document's ready state, and reads document.title (the target title is covered by testUpdateTargetSetsTargetTitle).
  • The lookup tests (LookupBehaviourTest) ran their lookups right after get(): select("li[", timeout = 0) could find no document yet and time out instead of getting the browser's error. They wait for the ready state first.
  • testGetContentGetsHtmlContent (JVM, macOS and Linux native) read the document right after get(), which returns once the navigation has started; it now waits for the ready state to be complete.
  • Linux native: a CDP command could get no answer (30 s timeout on DOM.getDocument / DOM.getOuterHTML in TabTest) once another browser had run and stopped in the same process. The cause is in Ktor's Curl WebSocket client, not in the tests: Ktor goes from 3.4.0 to 3.4.3, a patch bump in its own commit. The 3.4.1 to 3.4.3 Curl fixes are KTOR-9331 (segfaults with WebSockets), KTOR-9327 (maxFrameSize ignored) and KTOR-9274 (link errors). The evidence is empirical: on 3.4.0 the Linux native tests failed on all 3 runs once the ready-state wait was in, and on 3.4.3 they passed on every run since (counts in the stability comment). Correction to the message of commit 7fbe24c: KTOR-9540 and KTOR-9527, named there, come in releases after 3.4.3, not in this bump.
  • The native TabTest is shared by macOS and Linux in posixTest.
  • jvmTest prints kdriver's warnings and errors (slf4j-simple at the warn level): a browser that fails to start logs its fate, the last connection error and its stderr, which the no-op SLF4J default dropped.

Not in this PR

  • Profiles already leaked by earlier versions are not swept: this only stops new ones from piling up. They can be removed by hand (rm -rf "$TMPDIR"/kdriver_* while no kdriver process runs).
  • The Windows native target still does not kill the browser's child processes (killTree is TerminateProcess only); the delete retries cover the short window in which they still hold files.

nathanfallet and others added 3 commits November 18, 2026 19:57
When no userDataDir is given, kdriver creates a kdriver_* profile in the temp
directory, and cleanupTemporaryProfile() was a TODO: every browser left its
profile on disk (thousands of directories, tens of GB on a busy host).

- cleanupTemporaryProfile() deletes the profile this browser created, never a
  custom userDataDir nor a temporary one inherited through Config.copy(). It
  waits (bounded) for the browser process to exit first, and retries briefly
  when a file is still locked.
- stop() calls it after the process is gone, non-cancellably and before
  cancelling the browser scope; a second stop() or cleanup does nothing.
- One process-wide shutdown hook (LaunchedBrowsers) stops the browsers still
  running when the JVM exits, which deletes their profiles. It replaces the
  per-browser hook in create(), which kept every browser reachable forever and
  missed browsers started with DefaultBrowser(...).start().
- Recursive deletion per platform, never following symbolic links or
  junctions: kotlin.io.path on the JVM, lstat/readdir on POSIX,
  FindFirstFileW on Windows.
- Process liveness fixes the wait depends on: reap the child on Linux native
  (a zombie looked alive forever), use NSTask.isRunning on macOS, and keep the
  Windows process handle open after destroy() so isAlive() stays accurate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Stop on JVM exit every started browser, connect-existing ones included, as
  the per-browser hook of create() did (registry renamed StartedBrowsers).
- create() stops the browser when start() fails after launching it: the
  caller never gets the instance, so it could not.
- stop() does not wait another 5 s for a process it has just waited for.
- Windows: close the process handle once the process is seen to exit
  (atomically), instead of leaking it; exit code cached for exitCodeOrNull.
- Linux: never reset the reaped flag; ECHILD from a racing waitpid means
  exited too.
- POSIX delete: chmod a profile subdirectory before listing it, so one
  without read/search permission can still be emptied.
- Restart hands the profile over under the new browser's mutex; kdoc says
  the exit hook is JVM only.

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

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

codecov Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.14563% with 5 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
.../kotlin/dev/kdriver/core/browser/DefaultBrowser.kt 93.24% 1 Missing and 4 partials ⚠️

📢 Thoughts on this report? Let us know!

nathanfallet and others added 10 commits November 18, 2026 20:24
… a moment

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- StartedBrowsers.stopAll runs each stop in a supervisor scope with an
  exception handler, instead of catching Exception: a browser that fails
  to stop still does not keep the others running, and cancellation still
  propagates.
- Windows Process.isAlive reads the exit code through a helper and
  returns once.
- Native TemporaryProfileTest: camelCase test name and KDoc, as detekt
  requires outside the excluded test source sets.
New JVM tests, with internal seams only (no public API change): the
logger, the release timeout and the profile deletion of DefaultBrowser,
a factory for DefaultBrowser.create, the relaunch of a dead browser, and
one delete attempt of deleteTemporaryProfile.

- a profile inherited through Config.copy() is never deleted;
- a process still running after the bounded wait keeps its profile and
  logs a warning;
- a profile is deleted when the process cannot be launched, and when
  create() fails after the launch (the browser is stopped too);
- a failed delete in stop() logs a warning and keeps the browser
  registered, so the exit hook deletes the profile later;
- deleteTemporaryProfile retries with a delay between attempts, stops at
  the first success, and gives up after the last attempt;
- the exit hook stops the other browsers when one fails to stop;
- stop() on a browser that died still deletes its profile;
- restart on a dead process: the profile is handed over to the new
  browser, or deleted when the relaunch fails.

The restart test found that a restarted browser never launched a
process: it inherited the host and port assigned to the dead one, took
the connect-existing branch, and timed out on the dead port. The relaunch
now clears them so the new browser gets a port of its own.

It also found that stop() on a browser that had died threw from the
graceful Browser.close (nothing answers anymore), before reaching the
kill and the profile deletion: a crashed browser kept its profile. An
I/O failure of that close is now logged and stop() goes on.
…osed

The connection layer reports a browser that no longer answers as
ConnectionClosedException (a RuntimeException) once every send attempt
has failed, not only as an IOException: stop() must go on to the kill
and the profile deletion in both cases. Both are now covered by tests on
a connection whose Browser.close fails.
Full parameter documentation for deleteTemporaryProfile, error() in a
test double, and a line wrapped under the length limit.
On the Windows CI a browser stopped right after its start left its
profile locked for more than the 2 seconds of retries, so stop() kept
the profile until the exit hook. Retries cost nothing when the first
attempt succeeds. The test that caught it now lists what is left of the
profile when it fails.
…er custom dir restart and never-started stop
@nathanfallet

Copy link
Copy Markdown
Member Author

CI note on the Ubuntu job, so the failures are not mistaken for something else.

Ubuntu has failed on this branch since the last pushes, each time on a different test. To check whether the cleanup is involved, the same Ubuntu job (JVM tests, plus the Linux native tests when the JVM ones pass) was run by hand on throwaway branches, none of them pushed to main:

Code Runs Result
main (9d0a01b) 7 7 passed
d3e6a4c (this branch, before the last three commits) 3 3 passed
d3800f4 (this branch) 10 6 passed, 4 failed

The 4 failures on d3800f4:

  • BrowserTest.testBrowserScanBotDetection: "Failed to connect to browser" on the first Chrome launch of the JVM run (also failed twice on the PR run itself);
  • BrowserTest.testMultipleBrowsersDiffUserData: the title is read as the URL before the page has loaded (the failure also seen on earlier heads);
  • TabTest.testGetContentGetsHtmlContent on linuxX64: CDP command timeout, with a Vulkan error from Chrome in the log;
  • one run that failed in 15 s on Gradle plugin resolution, unrelated to the code.

What was checked:

  • between d3e6a4c and d3800f4 only the failure paths of create(), start() and restart() changed; a successful start is the same code;
  • no browser process is left after the JVM tests (0 Chrome processes in the 3 runs that listed them), so the later native tests are not slowed by leftovers.

So no link with the profile cleanup was found, but the sample is small and main did not fail once in 7 runs, so this is not proven either way. macOS and Windows pass, and CodeFactor and codecov/patch (97.67 %) pass.

Runs:

  • main: 44802500673, 44802504502, 44802510045, 44805367607, 44805377250, 44805387193, 44805396643
  • d3e6a4c: 44803922063, 44803931578, 44803942730
  • d3800f4: 44803927079, 44803937289, 44803946802, 44805362351, 44805372658, 44805382322, 44805392046, 44807296950, 44807301784, 44807307628

…t kdriver's warnings in JVM tests

get() returns once the navigation has started, while the target's title is
still its URL and the document may still be loading. testMultipleBrowsersDiffUserData
read the title after an idle wait, which a slow runner could pass before the
page parsed its <title>; it now waits for the target to report the expected
title (subscribed to targetInfoChanged before reading the current one, with a
timeout, no fixed sleep). testGetContentGetsHtmlContent (JVM, macOS, Linux)
now reads the document once its ready state is complete.

slf4j-simple at the warn level in jvmTest: a browser that fails to start logs
its fate, the last connection error and its stderr, which SLF4J's no-op
default dropped, leaving only "Failed to connect to browser".
… copy keep its temporary profile a temporary one

stop() ran its steps one after the other: a graceful close that threw (with
anything but the I/O errors it already tolerated), a failed kill or a failed
connection close skipped the rest, leaving the process running and the
profile on disk. Every step now runs even if an earlier one failed or was
cancelled; the kill, client closes and profile deletion run non-cancellable,
the scope is cancelled last, and the first failure is rethrown with the
others suppressed.

Config.copy() did not carry whether the profile is a temporary one kdriver
created, so a profile created before the browser copied its config (for
instance by reading userDataDir first) was never deleted. It is now derived
from the profile itself (set, and not given by the caller), so every copy
agrees, and the browser running on it deletes it. The restart path no longer
needs to hand the profile over explicitly.

detach() keeps the temporary profile, since the browser still runs on it:
said in its KDoc, with how to delete it once that browser has exited, and
tested.
A profile nests deep enough (extensions, caches) to pass 260 characters,
which the plain-path wide functions refuse, so those entries were left. The
walk now uses the \\?\ extended-length form (UNC paths as \\?\UNC\...),
which needs no system setting; relative and device paths are left as is.
The walk checked an entry with lstat, then chmod-ed, listed and removed it
by path: an entry replaced by a symbolic link in between had its target's
mode changed, and could be listed and emptied. Each directory is now opened
without following links and its children are reached from that descriptor
only: the *at functions on macOS (with O_NOFOLLOW_ANY, since openat is not
exposed there), /proc/self/fd on Linux, where Kotlin/Native exposes none of
them (falling back to the path without /proc). A directory is made
accessible through its descriptor, or through fchmodat / an O_PATH
descriptor when it cannot be read, so a link is never chmod-ed through.

The temporary profile is now created owner-only (0700, like Chrome's own),
not 0777 minus the umask, so no other user can add entries to it.

posixTest covers the native walk on macOS and Linux: nested content,
unreadable directories, links (never followed, target mode unchanged), a
root that is itself a link, a missing root.
…xits

start() registered every browser with the exit hook, including one reached
through browserUrl or a host and port, so the hook sent Browser.close to a
browser that may be shared or owned by something else. The old per-browser
hook skipped it (stopped is true without a process). Only a browser kdriver
launched is registered now.
Each delete attempt walks the whole profile with blocking file system calls,
up to 26 times when a file stays locked; it ran on the caller's dispatcher,
blocking a small one (a UI thread, a single-threaded loop) for the walk.
…object is used

The handle was closed by whichever thread first saw the exit in isAlive(),
while destroy() or another isAlive() could still be about to use it: a
TerminateProcess or GetExitCodeProcess on a closed, possibly reused, handle.
It is now closed by a cleaner once the object is unreachable, which also
releases it after detach(), where nothing ever saw the exit. The temporary
profile directory no longer doubles the separator when TEMP ends with one.
On Linux native (Curl engine) a CDP command could get no answer (a 30 s
command timeout in TabTest.testGetContentGetsHtmlContent, on DOM.getDocument
or DOM.getOuterHTML) once another browser had run and stopped in the same
process. Ktor 3.4.1 to 3.4.3 fix several Curl WebSocket bugs, among them a
WebSocket cancellation that could cancel a new request reusing the same
easy handle (KTOR-9540) and a freeze on large responses (KTOR-9527). With
3.4.0 the Linux native tests failed on every run of this branch since the
ready state wait was added; with 3.4.3 they pass.
…t hook, and retry a failed kill

create() chose between stop() and detach() on the pid, which stop() clears:
a start that stopped the browser itself (no answer on the debug port) and
then threw got detached, which took it off the exit hook even when its
profile could not be deleted or its process could not be killed. It now
asks whether the instance launched a process. A kill that fails no longer
forgets the process either, so the exit hook's stop() tries again.

The KDoc now says the profile is deleted by the browser kdriver launches on
it: a browser it only connects to never owns a profile.
…for the page in lookup tests

testMultipleBrowsersDiffUserData loaded example.com/one, /two and /three:
on a CI run one of them was still loading after 30 s, so the test measured
the runner's network, not the browsers. It now loads three local pages and
waits for their titles.

The lookup tests ran their lookups right after get(), which returns once
the navigation has started: select("li[", timeout = 0) could find no
document yet and time out instead of getting the browser's error. They now
wait for the page's ready state first.
…wsersDiffUserData

Waiting for the target to report the title still failed on CI (on Ubuntu
and Windows): the page had its URL as target title 30 s after get(), on a
local file. The test now waits for the document's ready state, as the other
page tests do, and reads document.title; the propagation of the title into
the target info is covered by testUpdateTargetSetsTargetTitle.
Fewer returns in isAlive (Windows), openDirectory and withCanonicalParent
(POSIX), a named check instead of indexes for drive paths, the DirectoryAccess
actuals named after it, and KDoc and named constants in the native tests.
@nathanfallet

Copy link
Copy Markdown
Member Author

Stability of the Ubuntu job after the follow-up commits (the earlier note listed 6 passed out of 10 on d3800f4).

The Ubuntu runs below used the same code as the PR head, on throwaway branches with a workflow that can be dispatched and only runs on Ubuntu (JVM tests, then Linux native tests). None of them were pushed to main, and all have been deleted.

Code Runs Result
733fe74 (PR head) 1 PR run (3 OS) + 6 Ubuntu 7 of 7 passed on Ubuntu; macOS and Windows passed
769f970 1 PR run (3 OS) + 6 Ubuntu 7 of 7 passed
c084b26 1 PR run + 6 Ubuntu 5 of 7 passed: testMultipleBrowsersDiffUserData timed out waiting for a page title, and a lookup test ran before the page had loaded. Both are fixed in da5de06 and 769f970
c99af80 (Ktor 3.4.3) 1 (3 OS) + 6 Ubuntu 7 of 7 passed
Ktor 3.4.0 with the ready-state wait 3 3 failed on Linux native (TabTest, CDP command timeout)

The three failures named in the earlier note:

  • Page title read before the page loaded (testMultipleBrowsersDiffUserData): the cause was in the test. It now loads local pages, waits for the ready state and reads document.title.
  • "Failed to connect to browser" on the first launch: did not happen in any of the roughly 40 Ubuntu runs since. jvmTest now prints kdriver's warnings and errors, so if it happens again, the log will show the browser's fate, the last connection error and its stderr. Until now SLF4J's no-op default dropped them.
  • CDP timeout on Linux native: the cause is the Ktor Curl WebSocket client, not the tests. It is gone with Ktor 3.4.3; see the PR description.

Runs on 733fe74: 44909757104 (PR), 44909755238, 44909757853, 44909760249, 44909762670, 44909765356, 44909767860.
Runs on 769f970: 44908198345 (PR), 44908200093, 44908202748, 44908205127, 44908207647, 44908210147, 44908212481.

@nathanfallet
nathanfallet merged commit e0773e5 into main Nov 21, 2026
5 checks passed
@nathanfallet
nathanfallet deleted the fix/cleanup-temp-profile branch November 21, 2026 15:00
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