Repository navigation
fix: delete the temporary profile when the browser stops - #94
Conversation
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 Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
… 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
…original failure when cleanup fails
|
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
The 4 failures on
What was checked:
So no link with the profile cleanup was found, but the sample is small and Runs:
|
…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.
|
Stability of the Ubuntu job after the follow-up commits (the earlier note listed 6 passed out of 10 on 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
The three failures named in the earlier note:
Runs on |
Problem
When no
userDataDiris given, kdriver creates akdriver_*profile in the temp directory (createTempDirectoryon 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.createdid not cover anything: the method was empty, the hook only ran at JVM exit, andstop()never called it.Change
cleanupTemporaryProfile()deletes the profile this browser created, and only that one:userDataDirthe caller supplied (Config.usesCustomDataDir);Config.createdTemporaryProfile(internal) is derived from the profile itself, soConfig.copy()carries it (a profile created before the browser copied its config, e.g. by readinguserDataDirfirst, is not leaked);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. Astop()from afinallyof a cancelled coroutine (or from inside the browser scope) still cleans up. A secondstop()is harmless. A profile that failed to start (startProcessthrows) is deleted too.detach()keeps the profile, since the browser still runs on it; its KDoc says so, and thatcleanupTemporaryProfile()deletes it once that browser has exited.stop()on a browser that died (crashed, killed from outside): the gracefulBrowser.closefails since nothing answers, which used to throw out ofstop()before the kill and the profile deletion; that failure (an I/O error, orConnectionClosedExceptiononce the connection gives up) is now logged andstop()goes on.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 bycreate(), which kept every browser ever created reachable until exit and missed browsers started throughDefaultBrowser(...).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'sstop()tries again.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.kotlin.io.path.deleteRecursively;unlinkat/fchmodatandopenwithO_NOFOLLOW_ANYfrom a canonical root on macOS, whereopenatis not exposed;/proc/self/fd/<fd>/<name>on Linux, where Kotlin/Native exposes no*atfunction, with the plain path as fallback without/proc); a directory it cannot list is made accessible through its descriptor (orfchmodat/ anO_PATHdescriptor), not by path. The profile is now created0700, like Chrome's own;FindFirstFileW/DeleteFileW/RemoveDirectoryWon\\?\extended-length paths, so entries beyond 260 characters are deleted too (clearing read-only attributes); an entry counts as gone only onERROR_FILE_NOT_FOUND/ERROR_PATH_NOT_FOUND;waitpid(WNOHANG)); before, an exited browser stayed a zombie andisAlive()(signal 0) stayed true, so everystop()waited the full 8 s.NSTask.isRunning.destroy()no longer closes the process handle beforeisAlive()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 forexitCodeOrNull().Platform coverage of the exit hook
stop()deletes the profilestop()addShutdownHookstays a no-op there (calling Kotlin fromatexitis not safe enough to ship blind, and signals bypass it anyway)Tests
jvmTestTemporaryProfileTest(real browser, likeBrowserTest):stop(); a secondstop()and repeatedcleanupTemporaryProfile()are harmless;userDataDiris kept with its content; a temporary profile created before the browser copied its config is deleted bystop(); 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;cleanupTemporaryProfile()on a running browser waits the bounded time, keeps the profile and logs a warning;create()failing after the launch stops the browser and deletes its profile;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;deleteTemporaryProfileretries 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).DefaultBrowser, a factory forcreate, the relaunch, one delete attempt): the public API is unchanged.macosTest/linuxTest/mingwTestTemporaryProfileTest: the profile is gone afterstop(), a second stop/cleanup is harmless (exercises each native delete implementation in CI).posixTestPosixDeleteRecursivelyTest(macOS and Linux native, defaultTMPDIR): 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.mingwTestWindowsDeleteRecursivelyTest: 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.commonMain/jvmMainis covered.Test stability on Ubuntu
testMultipleBrowsersDiffUserDataread 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 readsdocument.title(the target title is covered bytestUpdateTargetSetsTargetTitle).LookupBehaviourTest) ran their lookups right afterget():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 afterget(), which returns once the navigation has started; it now waits for the ready state to be complete.DOM.getDocument/DOM.getOuterHTMLinTabTest) 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 (maxFrameSizeignored) 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.TabTestis shared by macOS and Linux inposixTest.jvmTestprints 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
rm -rf "$TMPDIR"/kdriver_*while no kdriver process runs).killTreeisTerminateProcessonly); the delete retries cover the short window in which they still hold files.