diff --git a/action.yml b/action.yml index 9ed38708da..6c21e5ebaf 100644 --- a/action.yml +++ b/action.yml @@ -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 + # 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}" \ diff --git a/internal/cli/run.go b/internal/cli/run.go index 8eaafc2757..e733078ebe 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -3711,11 +3711,11 @@ func transcriptErrorMessage(te agentruntime.TranscriptError) string { // artifact upload step (if: always()) captures the partial usage data // (#6936). // -// NOTE: TotalCostUSD will be zero in the persisted metrics because dollar -// cost is only available from the terminal ResultEvent, which a cancelled -// run never emits. Token counts (input, output, cache_read, cache_creation) -// are captured via the deferred TokensEvent and will be non-zero. See #6936 -// for background. +// NOTE: TotalCostUSD is now reported by the SIGINT-into-sandbox +// mechanism (#6936): on cancellation, SIGINT is sent to the in-sandbox +// claude process, which flushes its ResultEvent (with cost data) before +// exiting. If the SIGINT delivery fails, TotalCostUSD falls back to +// zero — token counts are still captured via the deferred TokensEvent. // // cancelled is false when ctx is still live, in which case the caller's // normal control flow continues unchanged; the other return values are diff --git a/internal/runtime/claude.go b/internal/runtime/claude.go index aeeb06ea88..69fdfc5c83 100644 --- a/internal/runtime/claude.go +++ b/internal/runtime/claude.go @@ -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) + 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), "--print", "--verbose", "--output-format stream-json", diff --git a/internal/sandbox/sandbox.go b/internal/sandbox/sandbox.go index 906deb45fb..27dd0c8ff4 100644 --- a/internal/sandbox/sandbox.go +++ b/internal/sandbox/sandbox.go @@ -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) + 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} + 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) + go func() { + defer killCancel() + killScript := fmt.Sprintf( + "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", + execPIDFile) + killCmd := exec.CommandContext(killCtx, "openshell", "sandbox", "exec", //nolint:gosec // sandboxName is not user input + "--name", sandboxName, + "--no-tty", + "--timeout", "5", + "--", "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() diff --git a/internal/sandbox/sandbox_test.go b/internal/sandbox/sandbox_test.go index a9867e809e..b72fd9c7f2 100644 --- a/internal/sandbox/sandbox_test.go +++ b/internal/sandbox/sandbox_test.go @@ -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") + + 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()