Repository navigation
fix(#6936): send SIGINT into sandbox so cancelled runs report total_cost_usd #7208
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
4549445
43f5e6e
1ea267e
d708592
7262bad
e0399b7
d419f66
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -446,7 +446,11 @@ runs: | |
| if [[ -n "${MINT_URL}" ]]; then | ||
| MINT_FLAGS+=(--mint-url "${MINT_URL}") | ||
| fi | ||
| fullsend run "${AGENT}" \ | ||
| # exec replaces the shell so signals (SIGINT/SIGTERM from GHA | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [low] scope-authorization-partial Issue #6936's acceptance criteria explicitly ask to "verify the signal/cancellation lifecycle across the Review workflow, the fullsend action, ClaudeRuntime.Run, and the run finalization/telemetry writer" — this authorizes the substance of the changes to Suggested fix: Update the PR title/body to explicitly claim both the cost-estimation and signal/cancellation-lifecycle scopes, and update the body's "Files changed" list to include action.yml, internal/runtime/claude.go, and internal/sandbox/sandbox.go. |
||
| # cancellation) go directly to fullsend, preventing it from being | ||
| # orphaned and killed before its cleanup path can flush telemetry | ||
| # and metrics (#6936). | ||
| exec fullsend run "${AGENT}" \ | ||
| --fullsend-dir "${FULLSEND_DIR}" \ | ||
| --output-dir "${GITHUB_WORKSPACE}/output" \ | ||
| --target-repo "${TARGET_REPO}" \ | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -177,7 +177,9 @@ func (ClaudeRuntime) Run(ctx context.Context, params RunParams, printer *ui.Prin | |
| innerHandler(evt) | ||
| } | ||
|
|
||
| if parseErr := parseClaudeStream(r, handler); parseErr != nil { | ||
| parseErr := parseClaudeStream(r, handler) | ||
| fmt.Fprintf(os.Stderr, " stream ended: parseErr=%v ctxErr=%v cost=%.4f\n", parseErr, ctx.Err(), metrics.TotalCostUSD) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [low] leftover-debug-code Two new unconditional Suggested fix: Remove the leftover There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [low] logging-conventions fmt.Fprintf(os.Stderr, " stream ended: parseErr=%v ctxErr=%v cost=%.4f\n", ...) (line 181) and fmt.Fprintf(os.Stderr, " wait done: exitCode=%d waitErr=%v\n", ...) (line 193) execute unconditionally on every ClaudeRuntime.Run, including normal successful runs, adding stderr noise beyond the existing error-only " progress parser: %v\n" pattern. parseErr is also printed with a raw %v here (unsanitized) before being sanitized again on the error-handling path a few lines later. Suggested fix: Remove the unconditional diagnostic prints, or gate them behind an explicit debug/verbose flag if they are meant to persist as permanent diagnostics. |
||
| if parseErr != nil { | ||
| fmt.Fprintf(os.Stderr, " progress parser: %v\n", sanitizeOutput(parseErr.Error())) | ||
| cancel() | ||
| io.Copy(io.Discard, r) | ||
|
|
@@ -188,6 +190,7 @@ func (ClaudeRuntime) Run(ctx context.Context, params RunParams, printer *ui.Prin | |
| if execCmd.ProcessState != nil { | ||
| exitCode = execCmd.ProcessState.ExitCode() | ||
| } | ||
| fmt.Fprintf(os.Stderr, " wait done: exitCode=%d waitErr=%v\n", exitCode, waitErr) | ||
|
|
||
| if waitErr != nil && execCmd.ProcessState == nil { | ||
| return exitCode, fmt.Errorf("openshell exec failed: %w", waitErr) | ||
|
|
@@ -349,8 +352,10 @@ func buildRunCommand(params RunParams) string { | |
| envFile := sandbox.SandboxWorkspace + "/.env" | ||
| safe := strings.ReplaceAll(params.AgentBaseName, "'", "'\\''") | ||
|
|
||
| // exec replaces the shell so ExecStreamReader's PID file points to | ||
| // claude, not sh — required for the SIGINT-into-sandbox cancel mechanism. | ||
| parts := []string{ | ||
| fmt.Sprintf("cd %s && . %s && claude", params.RepoDir, envFile), | ||
| fmt.Sprintf("cd %s && . %s && exec claude", params.RepoDir, envFile), | ||
|
Comment on lines
+355
to
+358
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 3. Signal routing can regress untested buildRunCommand now relies on exec claude for correct signal delivery, but no modified Claude runtime test asserts that the generated command includes the shell replacement. If a later command refactor removes exec, existing tests still pass while the PID file targets the intermediate shell instead of the process that must flush final telemetry. Agent Prompt
Comment on lines
+355
to
+358
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 4. Runtime change skips guide review ClaudeRuntime.Run and buildRunCommand change an existing runtime backend's execution behavior, but the PR description does not state that docs/contributing/runtime-implementation.md was consulted. Because direct process execution participates in the documented egress-binary contract, reviewers cannot verify from the change record that the runtime checklist was evaluated. Agent Prompt
|
||
| "--print", | ||
| "--verbose", | ||
| "--output-format stream-json", | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -1360,24 +1360,84 @@ func ExecContext(ctx context.Context, sandboxName, command string, timeout time. | |
| return stdoutBuf.String(), stderrBuf.String(), exitCode, nil | ||
| } | ||
|
|
||
| // execPIDFile is the path inside the sandbox where the exec'd process PID | ||
| // is recorded so the cancel function can send SIGINT to it. | ||
| const execPIDFile = "/tmp/.fullsend_exec.pid" | ||
|
|
||
| // ExecStreamReader runs a command inside a sandbox, returning an io.ReadCloser for | ||
| // stdout so the caller can parse structured output. Stderr is forwarded to the | ||
| // given writer. The caller must read stdout to completion, then call cmd.Wait(). | ||
| // | ||
| // The parent context is used as the base for the timeout context, so | ||
| // cancelling the parent (e.g. on SIGTERM) terminates the subprocess. This | ||
| // allows CLI-level signal handling to propagate into long-running sandbox | ||
| // commands. | ||
| // cancelling the parent (e.g. on SIGTERM) terminates the subprocess. On | ||
| // context cancellation, a separate openshell exec call sends SIGINT to the | ||
| // in-sandbox process (identified by a PID file written at startup). This is | ||
| // necessary because SIGINT to the openshell CLI does not propagate through | ||
| // gRPC to in-sandbox processes. The openshell relay process is left running | ||
| // so it continues piping stdout (e.g. Claude Code's terminal result event | ||
| // with cost data). An 8-second WaitDelay allows the graceful shutdown to | ||
| // complete; after that Go kills the openshell process. | ||
| // | ||
| // stderrW must be safe for concurrent use: the cancel goroutine and the | ||
| // openshell subprocess both write to it simultaneously. | ||
| // | ||
| // The PID file path is a fixed singleton inside the sandbox. This function | ||
| // must not be called concurrently for the same sandbox. | ||
| func ExecStreamReader(ctx context.Context, sandboxName, command string, timeout time.Duration, stderrW io.Writer) (io.ReadCloser, *exec.Cmd, context.CancelFunc, error) { | ||
| ctx, cancel := context.WithTimeout(ctx, timeout) | ||
| timeoutSecs := fmt.Sprintf("%d", int(timeout.Seconds())) | ||
|
|
||
| // Prepend a PID-file write so the cancel function can target the | ||
| // in-sandbox process. Callers that use "exec" in their command (e.g. | ||
| // buildRunCommand) replace the shell, so the PID file points to the | ||
| // final process. | ||
| wrapped := fmt.Sprintf("echo $$ > %s; %s", execPIDFile, command) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 1. Three agents miss cancellation signals ExecStreamReader records the wrapper shell's $$ and later sends SIGINT only to that PID, but buildPiRunCommand launches Pi as a child without exec and the Codex builder uses a pipeline rather than replacing the shell as Claude does. Cancellation of Codex or the agents repository's Pi-based code, prioritize, and review agents can therefore leave the real agent running without flushing terminal output until the relay fallback timeout, WaitDelay, or sandbox teardown. Agent Prompt
|
||
|
|
||
| cmd := exec.CommandContext(ctx, "openshell", "sandbox", "exec", | ||
| "--name", sandboxName, | ||
| "--no-tty", | ||
| "--timeout", timeoutSecs, | ||
| "--", "sh", "-c", command, | ||
| "--", "sh", "-c", wrapped, | ||
| ) | ||
| // Put openshell in its own session so process-group-wide signals | ||
| // (SIGINT from GHA cancellation) don't kill it before cmd.Cancel | ||
| // has a chance to send SIGINT into the sandbox and relay the | ||
| // result event through stdout. | ||
| cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [medium] permission-expansion
Suggested fix: If There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [low] permission-expansion Setsid: true moves the openshell relay into a new session, and cmd.Cancel returns nil without ever signaling that host process directly — the only host-side kill is cmd.WaitDelay = 8s, with no Pdeathsig. If the parent fullsend process is SIGKILLed before WaitDelay fires, the relay can be reparented to init and keep running. An 8s WaitDelay also sits at or past GitHub Actions' own ~7.5s SIGINT-to-SIGKILL step window, so the intended force-kill of the relay may never run on a cancelled GHA job. Blast radius is limited to an already-sandboxed relay process (bounded by the existing --timeout, and torn down with the GHA VM), so this is a lifecycle-hardening gap rather than a genuine privilege expansion. Suggested fix: If Setsid is required, also set SysProcAttr.Pdeathsig = syscall.SIGKILL (Linux) so a killed parent cannot leave the relay orphaned. Shrink WaitDelay (or the internal 5s kill-exec timeout) so cleanup still fits inside GitHub Actions' cancellation budget. |
||
| cmd.Cancel = func() error { | ||
| fmt.Fprintf(stderrW, " sandbox cancel: sending SIGINT into %s\n", sandboxName) | ||
| // Send SIGINT to the in-sandbox process so it can flush final | ||
| // output (e.g. Claude Code's result event with total_cost_usd). | ||
| // A background context is required because the parent is already | ||
| // cancelled. The goroutine runs concurrently so Cancel returns | ||
| // immediately and WaitDelay starts without blocking. | ||
| killCtx, killCancel := context.WithTimeout(context.Background(), 5*time.Second) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [low] leftover-debug-code The Suggested fix: Remove the debug echo commands from |
||
| go func() { | ||
| defer killCancel() | ||
| killScript := fmt.Sprintf( | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [low] fail-open
Suggested fix: Validate that the PID file's content is a bare positive integer before using it (e.g. |
||
| "PID=$(cat %s 2>/dev/null); "+ | ||
| "if [ -z \"$PID\" ]; then echo \"sandbox-cancel: pid-file missing or empty\" >&2; exit 1; fi; "+ | ||
| "echo \"sandbox-cancel: pid=$PID\" >&2; "+ | ||
| "kill -INT $PID 2>&1; echo \"sandbox-cancel: kill=$?\" >&2", | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [medium] runtime-mechanism ExecStreamReader records Suggested fix: Either exec the payload in every ExecStreamReader caller (so $$ is always the runtime process, matching the Claude pattern) or deliver SIGINT to the recorded PID's process group (kill -INT -- -$PID) so wrapper-shell children receive it. Extend the cancellation test to a wrapping shell with a non-exec'd child and a pipeline child. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [low] fail-open ExecStreamReader's cancel script still treats the in-sandbox PID file as the sole SIGINT target. The new Suggested fix: Reject non-numeric PID file contents (e.g. case "$PID" in ''|[!0-9]) exit 1;; esac) before signaling, and use kill -INT -- "$PID". |
||
| execPIDFile) | ||
| killCmd := exec.CommandContext(killCtx, "openshell", "sandbox", "exec", //nolint:gosec // sandboxName is not user input | ||
| "--name", sandboxName, | ||
| "--no-tty", | ||
| "--timeout", "5", | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [medium] runtime-mechanism ExecStreamReader records Suggested fix: Either |
||
| "--", "sh", "-c", killScript, | ||
| ) | ||
| killCmd.Stdout = stderrW | ||
| killCmd.Stderr = stderrW | ||
| if err := killCmd.Run(); err != nil { | ||
| fmt.Fprintf(stderrW, " sandbox cancel: kill-exec failed: %v\n", err) | ||
| } | ||
| }() | ||
| // Do NOT signal the openshell relay process here. Openshell must | ||
| // stay alive to pipe claude's result event (with cost data) back | ||
| // through stdout. WaitDelay is the fallback if claude doesn't exit. | ||
| return nil | ||
| } | ||
| cmd.WaitDelay = 8 * time.Second | ||
| cmd.Stderr = stderrW | ||
|
|
||
| stdout, err := cmd.StdoutPipe() | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -303,6 +303,64 @@ func TestExecStreamReader_OpenshellNotInPath(t *testing.T) { | |
| assert.Error(t, err) | ||
| } | ||
|
|
||
| func TestExecStreamReader_SendsSIGINTOnCancel(t *testing.T) { | ||
| if runtime.GOOS == "windows" { | ||
| t.Skip("SIGINT not supported on Windows") | ||
| } | ||
|
|
||
| bin := t.TempDir() | ||
| script := filepath.Join(bin, "openshell") | ||
| // Fake openshell: pass-through that runs whatever comes after "--". | ||
| // This lets the cancel function's separate "openshell sandbox exec" | ||
| // call also go through the fake and execute the kill command. | ||
| require.NoError(t, os.WriteFile(script, []byte(`#!/bin/sh | ||
| while [ $# -gt 0 ]; do | ||
| if [ "$1" = "--" ]; then | ||
| shift | ||
| exec "$@" | ||
| fi | ||
| shift | ||
| done | ||
| echo "no -- found" >&2; exit 1 | ||
| `), 0o755)) | ||
| t.Setenv("PATH", bin+":/bin:/usr/bin") | ||
| defer os.Remove(execPIDFile) | ||
|
|
||
| ctx, cancel := context.WithCancel(context.Background()) | ||
| // The command traps SIGINT and flushes output, simulating Claude Code's | ||
| // graceful shutdown that emits the result event with cost data. | ||
| testCmd := "trap 'echo flushed-after-sigint; exit 0' INT; echo ready; while true; do :; done" | ||
| stdout, cmd, cleanup, err := ExecStreamReader(ctx, "test-sandbox", testCmd, 30*time.Second, os.Stderr) | ||
| require.NoError(t, err) | ||
| defer cleanup() | ||
|
|
||
| buf := make([]byte, 256) | ||
| n, err := stdout.Read(buf) | ||
| require.NoError(t, err) | ||
| assert.Contains(t, string(buf[:n]), "ready") | ||
|
|
||
| cancel() | ||
|
|
||
| var all []byte | ||
| for { | ||
| n, err = stdout.Read(buf) | ||
| if n > 0 { | ||
| all = append(all, buf[:n]...) | ||
| } | ||
| if err != nil { | ||
| break | ||
| } | ||
| } | ||
| assert.Contains(t, string(all), "flushed-after-sigint", | ||
| "in-sandbox process should receive SIGINT via the kill-exec mechanism and flush output") | ||
|
|
||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [low] test-idioms In TestExecStreamReader_SendsSIGINTOnCancel, waitErr := cmd.Wait() assigns the error to a named variable that is immediately discarded via _ = waitErr — dead code / unnecessary indirection that also misses an opportunity to assert the wait outcome. Suggested fix: Replace with _ = cmd.Wait() // wait for subprocess cleanup after cancellation, or assert the expected outcome. |
||
| waitErr := cmd.Wait() | ||
| _ = waitErr | ||
|
|
||
| assert.Equal(t, 8*time.Second, cmd.WaitDelay, | ||
| "WaitDelay should give the subprocess time to flush before force-kill") | ||
| } | ||
|
|
||
| func TestOsRootContainment(t *testing.T) { | ||
| dir := t.TempDir() | ||
|
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[medium] scope-creep
The PR title/body frame this change as cost estimation ('estimate USD cost on cancelled runs via historical rate cache'), but this revision also (1) replaces fullsend run with exec fullsend run so GHA signals reach the process directly, affecting every agent invocation through this action, not just cancelled Review runs, and (2) changes ExecStreamReader's default cancellation signal from SIGKILL to SIGINT + a 5s WaitDelay for all sandboxed CLI invocations (Claude, pi, Codex). GoReleaser builds release notes from PR titles (COMMITS.md), so a signal-handling behavior change hidden inside a cost-estimation title won't surface there, and the risk/moderate label similarly understates the process-lifecycle blast radius since ExecStreamReader is shared across all sandbox executions.
Suggested fix: Update the PR title/body to explicitly claim both scopes (cost estimation and graceful cancellation / signal delivery) so release notes and reviewers aren't misled, and re-evaluate the risk label given the shared blast radius. Splitting into two PRs is optional; retitling to reflect the actual scope is the minimum.