Skip to content

move the taskkill and sysctl call-outs to in-process helpers - #19286

Merged
kevinushey merged 14 commits into
mainfrom
feature/native-process-tree-and-apple-silicon
Oct 28, 2026
Merged

kevinushey merged 14 commits into
mainfrom
feature/native-process-tree-and-apple-silicon

Conversation

@kevinushey

@kevinushey kevinushey commented Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #19285.

Follows the pattern from #19233 for the two remaining shell call-outs the survey in #19285 found worth moving in-process.

Stopping a Quarto job on Windows

QuartoJob::stop() ran taskkill /F /T /PID <pid> through runCommand and parsed stderr. It now calls a new core::system::terminateProcessTree(pid), which returns a proper Error:

  • Windows: takes one Toolhelp snapshot and walks it breadth-first from the root, opening each listed child before trusting it and keeping the handle until termination, so no pid can be recycled underneath the walk. A child is accepted only if the opened process's image name matches the listing (wide-character comparison, so CP932 names whose trailing byte is a backslash survive), the parent it records (via ntdll NtQueryInformationProcess) is the pid of the parent whose handle is held (that pid cannot be recycled while the handle is open), and it does not predate that parent (the orphan heuristic getSubprocesses() already uses). A child that refuses PROCESS_TERMINATE is opened for querying only so the walk still reaches its descendants; terminating it fails and is logged. The root is terminated first so it cannot spawn more, then the descendants. An already-exited process counts as success. Failures on descendants are logged; the result reflects the root only.

    Stated limitation: an intermediate that exits between the snapshot and being opened takes its subtree out of reach, because its descendants record only its pid, which may have gone to a new process by then, and terminating an unrelated process is the worse failure. A job object per launch in the child-process launcher would be the deterministic answer: terminate Windows child process trees through a per-launch job object #19287.

  • POSIX: collects the descendants with getChildProcesses() while the root is alive (once it exits they are reparented and unreachable from its pid), signals the root with SIGTERM (even if discovery failed), then the descendants, ignoring ESRCH. A pid <= 0 is rejected with EINVAL: kill() reads those as process groups or every process, and on macOS the children of pid 0 are the whole system. Signalling descendants by pid without pinning them is a follow-up: signal POSIX process-tree descendants without pid-reuse races #19302.

Also fixed on the way: processInfo(pid) on Linux split the whole /proc/<pid>/stat line on spaces, so a command name with a space shifted the parent-pid field and hid the process from getChildProcesses() (and so from terminateChildProcesses()). It now parses what follows the name's closing parenthesis, as ProcessInfo::creationTime() already did.

Apple silicon check in SessionRig.R

.rs.rig.machine() shelled out to /usr/sbin/sysctl -n hw.optional.arm64 to tell an x86_64 R under Rosetta from an Intel Mac. SessionRUtil.cpp now registers rs_isAppleSilicon (wrapping the existing core::system::isAppleSilicon(), FALSE off macOS), exposed as .rs.isAppleSilicon(), and rig.machine() uses it.

Tests

  • Win32SystemTests.cpp (compile and run only on the Windows CI job): terminateProcessTree takes a cmd.exe -> ping.exe tree, a process without descendants, an already-exited process, a descendant with a non-ASCII name (a copy of ping.exe named with U+30BD, launched through CreateProcessW), and a three-level tree whose middle process has a DACL denying PROCESS_TERMINATE; isListedProcess has deterministic cases for same-image pid reuse from another parent, another image, an orphan, and unqueryable fields; the ntdll parent-pid query is checked through a limited-access handle; and the walk over a stale listing stops at an intermediate that has exited.
  • PosixSystemTests.cpp: a forked child -> grandchild tree (the grandchild named worker thread on Linux, covering the /proc parse fix) with the grandchild's pid reported over a pipe and both processes in their own process group so cleanup is bounded on every path; both end with SIGTERM. On Linux the test makes itself a child subreaper so it can reap the grandchild itself. Also: a missing pid is an error.
  • test-rig.R: on macOS, .rs.isAppleSilicon() and .rs.rig.machine("x86_64") are checked against the sysctl oracle the shell call-out replaced; elsewhere .rs.isAppleSilicon() is FALSE.

Verified locally on an Apple silicon Mac, after merging main: the full PosixTests core suite (42 pass, 1 pre-existing skip) and r-scope rig|linter (357 pass, 1 pre-existing skip). The Windows tests need the Windows CI job.

No NEWS entry: there is no user-visible change.

QA Notes

On Windows, stop a running Quarto preview job from the Jobs pane and confirm the quarto/deno processes are gone (Task Manager) and nothing is logged about the stop. On an Apple silicon Mac with an x86_64 build of R, open a project whose renv lockfile asks for an R version that is not installed and confirm the warning bar offers an arm64 install.

Adds core::system::terminateProcessTree(pid): on Windows it opens the
root and every descendant it finds (so no pid can be recycled under it),
terminates the root first and then the descendants, treating an already
exited process as success; on POSIX it signals the root and the
descendants collected while the root was alive. Stopping a Quarto job on
Windows now calls it instead of running taskkill /F /T through a shell,
and gets a proper Error back.

Exposes core::system::isAppleSilicon() to R as .rs.isAppleSilicon(), and
uses it in .rs.rig.machine() instead of shelling out to sysctl.

Addresses #19285
@kevinushey kevinushey added this to the 2026.11 (Montauk Daisy) milestone Oct 26, 2026
The Windows tree walk now takes its own snapshot and opens every listed
child before checking it is the listed process: created after the
snapshot means the pid was recycled, created before its parent means an
orphan reporting a recycled parent pid. Either is dropped, so nothing is
terminated by pid alone.

The POSIX test reaps or kills both processes on every exit path, polls
waitpid() instead of blocking, restores the subreaper setting, and gives
the children an alarm as a safety net.
The Windows walk now also compares the opened process's image name with
the snapshot's, the one identity check that does not depend on the
clock, and the validation is detail::isListedProcess with unit tests
for a recycled pid, another image, an orphan, and unqueryable times.

processInfo(pid) split the whole /proc/<pid>/stat line on spaces, so a
command name with a space shifted the parent pid field and hid the
process from getChildProcesses(); it now parses what follows the name's
closing parenthesis, as creationTime() does. The POSIX terminator also
signals the root even when its descendants cannot be found.

The tree test learns the grandchild's pid over a pipe, so cleanup can
reach it even if discovery fails, and names it "worker thread" on Linux
to cover the parse fix.
…s group

The Windows walk enumerates with PROCESSENTRY32W and queries the image
name with QueryFullProcessImageNameW, comparing with CompareStringOrdinal:
in an ANSI code page such as CP932 a character's trailing byte can be a
backslash, which split the name wrongly and rejected a real descendant.

In the tree test the child puts itself and the grandchild in a process
group, so cleanup can kill and reap the grandchild even before its pid
was received; the grandchild reports its own pid after renaming itself,
so receipt means the regression precondition holds; and the pipe read
retries interrupted calls until a deadline.
openProcessTree() now reads a single Toolhelp snapshot into a parent to
children map and walks it breadth-first from the root, visiting each pid
once, so a tree that keeps spawning is terminated as listed rather than
chased through fresh snapshots. The tree test's cleanup also reaps the
child by pid, for the case where it never joined the process group. The
Windows fixture launches with CreateProcessW, and a test runs a copy of
ping.exe under a non-ASCII name through cmd.exe and checks the tree
termination takes it.
…om the parent

A descendant that denies PROCESS_TERMINATE is opened for querying alone,
so it is still validated and its own descendants reached; terminating it
fails and is logged. A test with a cmd.exe -> cmd.exe -> ping.exe tree
denies termination on the middle one and checks ping.exe still goes.

The tree test's parent also calls setpgid(child, child), so the group
exists before the timed pipe read however far the child has got.
The Windows walk no longer compares creation times with a wall-clock
snapshot time. The opened process must record the held parent as its
parent (NtQueryInformationProcess, ProcessBasicInformation): that pid
cannot be recycled while the parent's handle is open, so a process
recording it was spawned by it, and one recycled by any other parent is
rejected whatever the clock did. The image-name and orphan checks stay.
A test checks the parent pid is queryable through a limited-access
handle, the access the walk uses.
A listed process that is gone by the time it is opened no longer hides
the descendants it left behind: the walk continues to its listed
children, checked against the listed pid and the creation time of the
nearest ancestor still held. The snapshot and the walk are now
detail::listProcesses and detail::openProcessTree, so a test can list a
cmd.exe -> cmd.exe -> ping.exe tree, terminate the middle process, and
check the walk over the old listing still opens ping.exe.
A listed process that is gone by the time it is opened is skipped with
its subtree after all: its descendants record only its pid, which can
have gone to a new process by then, so nothing establishes that they
belong to the tree, and terminating an unrelated process is the worse
failure. The comment on openProcessTree says so and names a job object
per launch as the deterministic alternative. The test lists the three
level tree, terminates the middle process, closes every handle to it and
waits for the root to exit so that it is no longer openable, and checks
the orphan is left alone. tlhelp32.h in the tests now follows windows.h.
@github-actions

github-actions Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

All tests passed!

#################### 100% pass rate

Passed Failed Skipped Flaky
4476 0 239 2
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ auth-teardown 4 0 16 0
✅ desktop-linux 1120 0 43 1
✅ desktop-macos 1117 0 47 1
✅ desktop-windows 1120 0 50 0
✅ server-linux 1067 0 51 0
✅ setup 48 0 32 0
View / download the full report

View report online -- opens in the browser, no download needed. Available for 14 days.

Download playwright-report.zip -- extract and open index.html

Includes screenshots, traces, and step-by-step details for every test. Expires in 15 days.


All platforms - commit dbbffe0ac4d06f483174deede90c73edce37d462 - Run #1762

kevinushey added a commit that referenced this pull request Oct 27, 2026
…ns (#19296)

Two flakes from the PR #19286 e2e run (40398345386):

- code_suggestions 'ghost text accept' (Posit AI, Linux): every agent answer
  took 10s+ and the session cancelled the re-request at its 10s cutoff. The
  suggestion waits now skip as a service failure when a request was
  cancelled and every answer that did arrive was slow.
- shiny-app-r (Windows): the assistant built the tip choices with
  radioButtons(), which the button-only locator could not match. Match a
  button or radio by accessible name instead.
@kevinushey
kevinushey requested a review from gtritchie October 27, 2026 04:08

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Nothing here is blocking. The request-changes state is procedural.

Main items: no guard for pid <= 0 in the new POSIX terminateProcessTree() (on macOS a pid of 0 reaches every process), and an inaccurate comment about why the Windows walk lists before terminating. The rest are a design question about #19287, test hygiene, and small cleanups.

Comment thread src/cpp/core/system/PosixSystem.cpp Outdated
return terminateProcessTree(pid, SIGTERM);
}

Error terminateProcessTree(pid_t pid, int signal)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Nothing guards pid <= 0 here, and kill() treats those values specially: 0 is the caller's own process group, -1 is every process the user can signal. On macOS it is worse: proc_listchildpids(0, ...) returns launchd (pid 1) (checked on an Apple silicon Mac), so getChildProcesses(0) recurses through the whole system and every process found gets SIGTERM. No current caller passes 0 (QuartoJob checks pid_ > 0 and is Windows-only), but this is a new public API declared in System.hpp. Suggest returning EINVAL for pid <= 0, here and in the Windows version for symmetry.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in c052696: EINVAL for pid <= 0 on POSIX. I left Windows as is: PidType is a DWORD there, and OpenProcess(0) already fails with ERROR_INVALID_PARAMETER.

Comment thread src/cpp/core/system/PosixSystem.cpp Outdated

for (const ProcessInfo& process : descendants)
{
if (::kill(process.pid, signal) != 0 && errno != ESRCH)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Descendants are signalled by bare pid after the root has been signalled, and nothing pins those pids. If one exits after getChildProcesses() returns and its pid is reused, an unrelated process gets the signal. The window is short, and terminateChildProcesses() already has the same pattern, but the Windows half of this PR goes to some length to rule out exactly this. A pidfd on Linux (or re-checking the ppid just before kill()) would bring the two halves in line. Fine as a follow-up.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed, filed as #19302. The POSIX path has no production caller yet (the Quarto stop is Windows-only), so I'd rather do pidfd or a ppid re-check there than grow this PR.

Comment thread src/cpp/core/system/Win32System.cpp Outdated
return LAST_SYSTEM_ERROR();
CloseHandleOnExitScope closeRoot(&hRoot, ERROR_LOCATION);

// the descendants have to be found while the root is alive: once it has

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I don't think the reason given here holds. hRoot is held for the whole function, so the root's pid can't be recycled even after it exits. Its children still record that pid and still postdate it, so isListedProcess() would accept them. Only an intermediate whose handle nobody holds becomes unreachable. Listing before terminating is still sensible (it bounds the walk), but the comment gives the wrong reason.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

You're right: holding hRoot keeps its children reachable. The real reason is that terminating the root can make an intermediate exit (on a broken pipe, say) before its handle is held, which takes its subtree out of reach. The comment says that now (618e164).

// longer be established, and terminating an unrelated process would be the
// worse failure. A job object per launch would be the deterministic answer
// (#19287).
void openProcessTree(HANDLE hRoot,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Design question rather than a defect: this walk (snapshot, image name, ntdll parent pid, creation time) approximates tree membership and still has the exited-intermediate gap. A job object assigned when the quarto child is launched would give exact membership. ProcessOptions::terminateChildren (Process.hpp:120-126) already notes that Win32 needs CreateJobObject for this. I see #19287 tracks it. Is the interim heuristic, with its ntdll dependency and tests, worth carrying until then, or could #19287 be done first?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I'd keep it. It replaces taskkill /T, which walks the same snapshot by bare pid with no protection against pid reuse, so this is strictly safer, and it is green on Windows CI. #19287 changes the shared Win32ChildProcess launch path (suspended start, a job nested in the session's initJobObject job, terminate routing), and I'd like that reviewed on its own. When it lands, QuartoJob moves to it, and the walk can go if nothing else needs a pid-only kill.

EXPECT_EQ(WAIT_OBJECT_0, ::WaitForSingleObject(pi.hProcess, 5000));
EXPECT_EQ(WAIT_OBJECT_0, ::WaitForSingleObject(hGrandchild, 5000));

tempDir.remove();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This cleanup is skipped whenever an earlier ASSERT_* fails (e.g. WaitForSubprocesses() returning empty), which leaves the copied ソ.exe in %TEMP%. Its result is also ignored, and it can fail while the image is still mapped. A scope-exit cleanup that logs failures would cover both.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 618e164: RemoveOnExitScope, declared before the grandchild's handle so it runs after that closes; a failure to remove is logged.

TEST_F(Win32ProcessTest, TerminateProcessTreeTakesDescendants)
{
// cmd.exe -> ping.exe, a two-level tree
ASSERT_TRUE(StartProcess("cmd.exe /S /C \"ping -n 8 posit.co\" 1> nul"));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Nit: the new tests (here and at 621, 703, 762, 805, 814) ping posit.co, which needs DNS. Without DNS, ping exits immediately and the tree is gone before terminateProcessTree() runs. Some older tests in this file do the same, but the newer ones use ping -n 30 127.0.0.1, which avoids the network.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 618e164: the new tests use ping -n 30 127.0.0.1.

Comment thread src/cpp/core/system/PosixSystem.cpp Outdated
if (error)
return error;

std::size_t nameEnd = statStr.rfind(')');

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This repeats the parse in ProcessInfo::creationTime() below (read stat, rfind(')'), trim_copy, split). Could both use one helper that returns the fields after the command name, so a future fix lands in both places?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in c052696: both use readStatFieldsAfterName().

int signal);

// signal version of the terminateProcessTree() declared in System.hpp
Error terminateProcessTree(pid_t pid, int signal);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The only production caller of terminateProcessTree() is QuartoJob::stop(), inside #ifdef _WIN32, so this overload, the POSIX implementation, and the POSIX tests currently have no caller. Keeping the cross-platform API complete is a fair reason to keep the one-argument form, but is the signal overload needed?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Not needed; removed in c052696.

std::vector<SubprocInfo> getSubprocesses(PidType pid,
const FILETIME* pParentCreationTime);

struct OpenedProcess

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Minor: these redefine OpenedProcess and ProcessListing by hand. If either changes in Win32System.cpp only, the two translation units disagree on the layout. That is an ODR violation that still links, and openProcessTree() then fills a vector the test reads with the wrong layout. A small Win32 detail header shared by both files would prevent it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 618e164: Win32SystemDetail.hpp holds the declarations both files use, detail::getSubprocesses included.

kill() reads 0 as the caller's process group and -1 as every process it
can signal, and on macOS the children of pid 0 are the whole system, so
terminateProcessTree() now returns EINVAL for pid <= 0. The signal
overload had no caller and is gone. processInfo(pid) and
ProcessInfo::creationTime() share one helper for the fields that follow
the command name in /proc/<pid>/stat.
Win32SystemDetail.hpp declares what Win32SystemTests.cpp reaches into, so
the two cannot disagree on the layout of OpenedProcess or ProcessListing.
The comment on opening the tree before terminating it now gives the real
reason: terminating the root can make an intermediate exit before its
handle is held. The new tests ping the loopback address instead of
needing DNS, and the copied non-ASCII executable is removed on scope
exit, after the grandchild's handle closes, with failures logged.
…s-tree-and-apple-silicon

# Conflicts:
#	src/cpp/core/include/core/system/System.hpp
#	src/cpp/core/system/Win32SystemTests.cpp
#	src/cpp/session/modules/SessionRUtil.R
#	src/cpp/session/modules/SessionRUtil.cpp
The call runs in a child that leads its own process group and blocks
SIGTERM, so a pid that slipped through could reach nothing else and would
leave SIGTERM pending instead of ending the child. 0 and -1 reach beyond
any such group and are not exercised.

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks, all findings are addressed: the fixes look good, and deferring to #19302 and #19287 makes sense. One optional nit inline.


// declared before the grandchild's handle so it runs after that closes,
// and on every early return; a failure to remove is logged
RemoveOnExitScope removeTempDir(tempDir, ERROR_LOCATION);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Optional nit: this runs on every early return, but it can't succeed on one that happens after StartProcess() and before terminateProcessTree(), for example when ASSERT_EQ(1u, children.size()) fails. The copied exe is still running at that point, because the fixture's job is only closed in ~Win32ProcessTest(), which runs after this scope's locals have been destroyed. The removal then fails and is only logged, and the temp dir leaks. Calling CleanupProcess() before the scope ends (or a scope guard declared after this one that calls it) would close that gap. Fine to leave as is.

@kevinushey
kevinushey merged commit 15abfb5 into main Oct 28, 2026
47 checks passed
@kevinushey
kevinushey deleted the feature/native-process-tree-and-apple-silicon branch October 28, 2026 16:47
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.

move the remaining taskkill and sysctl call-outs to in-process C++ helpers

2 participants